@tscircuit/eval 0.0.517 → 0.0.518

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,7 @@ var Hht=Object.create;var Fx=Object.defineProperty;var qht=Object.getOwnProperty
5
5
  `);for(O=I=0;I<xt.length&&!xt[I].includes("DetermineComponentFrameRoot");)I++;for(;O<It.length&&!It[O].includes("DetermineComponentFrameRoot");)O++;if(I===xt.length||O===It.length)for(I=xt.length-1,O=It.length-1;1<=I&&0<=O&&xt[I]!==It[O];)O--;for(;1<=I&&0<=O;I--,O--)if(xt[I]!==It[O]){if(I!==1||O!==1)do if(I--,O--,0>O||xt[I]!==It[O]){var zt=`
6
6
  `+xt[I].replace(" at new "," at ");return m.displayName&&zt.includes("<anonymous>")&&(zt=zt.replace("<anonymous>",m.displayName)),zt}while(1<=I&&0<=O);break}}}finally{CE=!1,Error.prepareStackTrace=w}return(w=m?m.displayName||m.name:"")?U(w):""}function W(m){switch(m.tag){case 26:case 27:case 5:return U(m.type);case 16:return U("Lazy");case 13:return U("Suspense");case 19:return U("SuspenseList");case 0:case 15:return X(m.type,!1);case 11:return X(m.type.render,!1);case 1:return X(m.type,!0);case 31:return U("Activity");default:return""}}function et(m){try{var y="";do y+=W(m),m=m.return;while(m);return y}catch(w){return`
7
7
  Error generating stack: `+w.message+`
8
- `+w.stack}}function nt(m,y){if(typeof m=="object"&&m!==null){var w=xz.get(m);return w!==void 0?w:(y={value:m,source:y,stack:et(y)},xz.set(m,y),y)}return{value:m,source:y,stack:et(y)}}function mt(m,y){sm[om++]=xx,sm[om++]=gx,gx=m,xx=y}function G(m,y,w){gs[xs++]=_a,gs[xs++]=ya,gs[xs++]=bh,bh=m;var I=_a;m=ya;var O=32-ns(I)-1;I&=~(1<<O),w+=1;var z=32-ns(y)+O;if(30<z){var K=O-O%5;z=(I&(1<<K)-1).toString(32),I>>=K,O-=K,_a=1<<32-ns(y)+O|w<<O|I,ya=z+m}else _a=1<<z|w<<O|I,ya=m}function tt(m){m.return!==null&&(mt(m,1),G(m,1,0))}function J(m){for(;m===gx;)gx=sm[--om],sm[om]=null,xx=sm[--om],sm[om]=null;for(;m===bh;)bh=gs[--xs],gs[xs]=null,ya=gs[--xs],gs[xs]=null,_a=gs[--xs],gs[xs]=null}function ht(m,y){_(Cc,y),_(Hy,m),_(Ki,null),m=ypt(y),d(Ki),_(Ki,m)}function pt(){d(Ki),d(Hy),d(Cc)}function St(m){m.memoizedState!==null&&_(bx,m);var y=Ki.current,w=gpt(y,m.type);y!==w&&(_(Hy,m),_(Ki,w))}function Mt(m){Hy.current===m&&(d(Ki),d(Hy)),bx.current===m&&(d(bx),fa?xh._currentValue=em:xh._currentValue2=em)}function ot(m){var y=Error(i(418,""));throw Z(nt(y,m)),IE}function Y(m,y){if(!ys)throw Error(i(175));mht(m.stateNode,m.type,m.memoizedProps,y,m)||ot(m)}function H(m){for(Sr=m.return;Sr;)switch(Sr.tag){case 5:case 13:Co=!1;return;case 27:case 3:Co=!0;return;default:Sr=Sr.return}}function it(m){if(!ys||m!==Sr)return!1;if(!_n)return H(m),_n=!0,!1;var y=m.tag;if(wi?y!==3&&y!==27&&(y!==5||oz(m.type)&&!fx(m.type,m.memoizedProps))&&Si&&ot(m):y!==3&&(y!==5||oz(m.type)&&!fx(m.type,m.memoizedProps))&&Si&&ot(m),H(m),y===13){if(!ys)throw Error(i(316));if(m=m.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(i(317));Si=ght(m)}else Si=wi&&y===27?aht(m.type,Si):Sr?sz(m.stateNode):null;return!0}function ut(){ys&&(Si=Sr=null,_n=!1)}function yt(){var m=vh;return m!==null&&(Lr===null?Lr=m:Lr.push.apply(Lr,m),vh=null),m}function Z(m){vh===null?vh=[m]:vh.push(m)}function at(m,y){return m===y&&(m!==0||1/m===1/y)||m!==m&&y!==y}function Et(m,y,w){fa?(_(vx,y._currentValue),y._currentValue=w):(_(vx,y._currentValue2),y._currentValue2=w)}function Ft(m){var y=vx.current;fa?m._currentValue=y:m._currentValue2=y,d(vx)}function Ot(m,y,w){for(;m!==null;){var I=m.alternate;if((m.childLanes&y)!==y?(m.childLanes|=y,I!==null&&(I.childLanes|=y)):I!==null&&(I.childLanes&y)!==y&&(I.childLanes|=y),m===w)break;m=m.return}}function Ie(m,y,w,I){var O=m.child;for(O!==null&&(O.return=m);O!==null;){var z=O.dependencies;if(z!==null){var K=O.child;z=z.firstContext;t:for(;z!==null;){var ct=z;z=O;for(var xt=0;xt<y.length;xt++)if(ct.context===y[xt]){z.lanes|=w,ct=z.alternate,ct!==null&&(ct.lanes|=w),Ot(z.return,w,m),I||(K=null);break t}z=ct.next}}else if(O.tag===18){if(K=O.return,K===null)throw Error(i(341));K.lanes|=w,z=K.alternate,z!==null&&(z.lanes|=w),Ot(K,w,m),K=null}else K=O.child;if(K!==null)K.return=O;else for(K=O;K!==null;){if(K===m){K=null;break}if(O=K.sibling,O!==null){O.return=K.return,K=O;break}K=K.return}O=K}}function Se(m,y,w,I){m=null;for(var O=y,z=!1;O!==null;){if(!z){if((O.flags&524288)!==0)z=!0;else if((O.flags&262144)!==0)break}if(O.tag===10){var K=O.alternate;if(K===null)throw Error(i(387));if(K=K.memoizedProps,K!==null){var ct=O.type;rs(O.pendingProps.value,K.value)||(m!==null?m.push(ct):m=[ct])}}else if(O===bx.current){if(K=O.alternate,K===null)throw Error(i(387));K.memoizedState.memoizedState!==O.memoizedState.memoizedState&&(m!==null?m.push(xh):m=[xh])}O=O.return}m!==null&&Ie(y,m,w,I),y.flags|=262144}function Kt(m){for(m=m.firstContext;m!==null;){var y=m.context;if(!rs(fa?y._currentValue:y._currentValue2,m.memoizedValue))return!0;m=m.next}return!1}function le(m){wh=m,ga=null,m=m.dependencies,m!==null&&(m.firstContext=null)}function Jt(m){return Ii(wh,m)}function qn(m,y){return wh===null&&le(m),Ii(m,y)}function Ii(m,y){var w=fa?y._currentValue:y._currentValue2;if(y={context:y,memoizedValue:w,next:null},ga===null){if(m===null)throw Error(i(308));ga=y,m.dependencies={lanes:0,firstContext:y},m.flags|=524288}else ga=ga.next=y;return w}function Nr(){return{controller:new Dht,data:new Map,refCount:0}}function Gs(m){m.refCount--,m.refCount===0&&jht(Bht,function(){m.controller.abort()})}function Ar(m){m!==am&&m.next===null&&(am===null?wx=am=m:am=am.next=m),Sx=!0,NE||(NE=!0,ky())}function ko(m,y){if(!AE&&Sx){AE=!0;do for(var w=!1,I=wx;I!==null;){if(!y)if(m!==0){var O=I.pendingLanes;if(O===0)var z=0;else{var K=I.suspendedLanes,ct=I.pingedLanes;z=(1<<31-ns(42|m)+1)-1,z&=O&~(K&~ct),z=z&201326741?z&201326741|1:z?z|2:0}z!==0&&(w=!0,Ff(I,z))}else z=en,z=v(I,I===Rn?z:0,I.cancelPendingCommit!==null||I.timeoutHandle!==gh),(z&3)===0||S(I,z)||(w=!0,Ff(I,z));I=I.next}while(w);AE=!1}}function Af(){Rf()}function Rf(){Sx=NE=!1;var m=0;cm!==0&&(Ept()&&(m=cm),cm=0);for(var y=Zs(),w=null,I=wx;I!==null;){var O=I.next,z=Of(I,y);z===0?(I.next=null,w===null?wx=O:w.next=O,O===null&&(am=w)):(w=I,(m!==0||(z&3)!==0)&&(Sx=!0)),I=O}ko(m,!1)}function Of(m,y){for(var w=m.suspendedLanes,I=m.pingedLanes,O=m.expirationTimes,z=m.pendingLanes&-62914561;0<z;){var K=31-ns(z),ct=1<<K,xt=O[K];xt===-1?((ct&w)===0||(ct&I)!==0)&&(O[K]=P(ct,y)):xt<=y&&(m.expiredLanes|=ct),z&=~ct}if(y=Rn,w=en,w=v(m,m===y?w:0,m.cancelPendingCommit!==null||m.timeoutHandle!==gh),I=m.callbackNode,w===0||m===y&&(bn===2||bn===9)||m.cancelPendingCommit!==null)return I!==null&&I!==null&&TE(I),m.callbackNode=null,m.callbackPriority=0;if((w&3)===0||S(m,w)){if(y=w&-w,y===m.callbackPriority)return y;switch(I!==null&&TE(I),B(w)){case 2:case 8:w=Lht;break;case 32:w=EE;break;case 268435456:w=Fht;break;default:w=EE}return I=Lf.bind(null,m),w=yx(w,I),m.callbackPriority=y,m.callbackNode=w,y}return I!==null&&I!==null&&TE(I),m.callbackPriority=2,m.callbackNode=null,2}function Lf(m,y){if(Ji!==0&&Ji!==5)return m.callbackNode=null,m.callbackPriority=0,null;var w=m.callbackNode;if(Xy(!0)&&m.callbackNode!==w)return null;var I=en;return I=v(m,m===Rn?I:0,m.cancelPendingCommit!==null||m.timeoutHandle!==gh),I===0?null:(v$(m,I,y),Of(m,Zs()),m.callbackNode!=null&&m.callbackNode===w?Lf.bind(null,m):null)}function Ff(m,y){if(Xy())return null;v$(m,y,!0)}function ky(){Rpt?Opt(function(){(Qe&6)!==0?yx(yz,Af):Rf()}):yx(yz,Af)}function ih(){return cm===0&&(cm=T()),cm}function Ty(m,y){if(qy===null){var w=qy=[];RE=0,lm=ih(),um={status:"pending",value:void 0,then:function(I){w.push(I)}}}return RE++,y.then($f,$f),y}function $f(){if(--RE===0&&qy!==null){um!==null&&(um.status="fulfilled");var m=qy;qy=null,lm=0,um=null;for(var y=0;y<m.length;y++)(0,m[y])()}}function Ey(m,y){var w=[],I={status:"pending",value:null,reason:null,then:function(O){w.push(O)}};return m.then(function(){I.status="fulfilled",I.value=y;for(var O=0;O<w.length;O++)(0,w[O])(y)},function(O){for(I.status="rejected",I.reason=O,O=0;O<w.length;O++)(0,w[O])(void 0)}),I}function rh(){var m=Sh.current;return m!==null?m:Rn.pooledCache}function fc(m,y){y===null?_(Sh,Sh.current):_(Sh,y.pool)}function zf(){var m=rh();return m===null?null:{parent:fa?ei._currentValue:ei._currentValue2,pool:m}}function mc(m,y){if(rs(m,y))return!0;if(typeof m!="object"||m===null||typeof y!="object"||y===null)return!1;var w=Object.keys(m),I=Object.keys(y);if(w.length!==I.length)return!1;for(I=0;I<w.length;I++){var O=w[I];if(!Yht.call(y,O)||!rs(m[O],y[O]))return!1}return!0}function Df(m){return m=m.status,m==="fulfilled"||m==="rejected"}function _c(){}function jf(m,y,w){switch(w=m[w],w===void 0?m.push(y):w!==y&&(y.then(_c,_c),y=w),y.status){case"fulfilled":return y.value;case"rejected":throw m=y.reason,Yf(m),m;default:if(typeof y.status=="string")y.then(_c,_c);else{if(m=Rn,m!==null&&100<m.shellSuspendCounter)throw Error(i(482));m=y,m.status="pending",m.then(function(I){if(y.status==="pending"){var O=y;O.status="fulfilled",O.value=I}},function(I){if(y.status==="pending"){var O=y;O.status="rejected",O.reason=I}})}switch(y.status){case"fulfilled":return y.value;case"rejected":throw m=y.reason,Yf(m),m}throw pm=y,Zy}}function Bf(){if(pm===null)throw Error(i(459));var m=pm;return pm=null,m}function Yf(m){if(m===Zy||m===Px)throw Error(i(483))}function yc(){for(var m=hm,y=LE=hm=0;y<m;){var w=bs[y];bs[y++]=null;var I=bs[y];bs[y++]=null;var O=bs[y];bs[y++]=null;var z=bs[y];if(bs[y++]=null,I!==null&&O!==null){var K=I.pending;K===null?O.next=O:(O.next=K.next,K.next=O),I.pending=O}z!==0&&Xf(w,O,z)}}function gc(m,y,w,I){bs[hm++]=m,bs[hm++]=y,bs[hm++]=w,bs[hm++]=I,LE|=I,m.lanes|=I,m=m.alternate,m!==null&&(m.lanes|=I)}function sh(m,y,w,I){return gc(m,y,w,I),xc(m)}function To(m,y){return gc(m,null,null,y),xc(m)}function Xf(m,y,w){m.lanes|=w;var I=m.alternate;I!==null&&(I.lanes|=w);for(var O=!1,z=m.return;z!==null;)z.childLanes|=w,I=z.alternate,I!==null&&(I.childLanes|=w),z.tag===22&&(m=z.stateNode,m===null||m._visibility&1||(O=!0)),m=z,z=z.return;return m.tag===3?(z=m.stateNode,O&&y!==null&&(O=31-ns(w),m=z.hiddenUpdates,I=m[O],I===null?m[O]=[y]:I.push(y),y.lane=w|536870912),z):null}function xc(m){if(50<ng)throw ng=0,GE=null,Error(i(185));for(var y=m.return;y!==null;)m=y,y=m.return;return m.tag===3?m.stateNode:null}function oh(m){m.updateQueue={baseState:m.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ah(m,y){m=m.updateQueue,y.updateQueue===m&&(y.updateQueue={baseState:m.baseState,firstBaseUpdate:m.firstBaseUpdate,lastBaseUpdate:m.lastBaseUpdate,shared:m.shared,callbacks:null})}function ms(m){return{lane:m,tag:0,payload:null,callback:null,next:null}}function _s(m,y,w){var I=m.updateQueue;if(I===null)return null;if(I=I.shared,(Qe&2)!==0){var O=I.pending;return O===null?y.next=y:(y.next=O.next,O.next=y),I.pending=y,y=xc(m),Xf(m,null,w),y}return gc(m,I,y,w),xc(m)}function ca(m,y,w){if(y=y.updateQueue,y!==null&&(y=y.shared,(w&4194048)!==0)){var I=y.lanes;I&=m.pendingLanes,w|=I,y.lanes=w,A(m,w)}}function ch(m,y){var w=m.updateQueue,I=m.alternate;if(I!==null&&(I=I.updateQueue,w===I)){var O=null,z=null;if(w=w.firstBaseUpdate,w!==null){do{var K={lane:w.lane,tag:w.tag,payload:w.payload,callback:null,next:null};z===null?O=z=K:z=z.next=K,w=w.next}while(w!==null);z===null?O=z=y:z=z.next=y}else O=z=y;w={baseState:I.baseState,firstBaseUpdate:O,lastBaseUpdate:z,shared:I.shared,callbacks:I.callbacks},m.updateQueue=w;return}m=w.lastBaseUpdate,m===null?w.firstBaseUpdate=y:m.next=y,w.lastBaseUpdate=y}function la(){if(FE){var m=um;if(m!==null)throw m}}function ua(m,y,w,I){FE=!1;var O=m.updateQueue;Ic=!1;var z=O.firstBaseUpdate,K=O.lastBaseUpdate,ct=O.shared.pending;if(ct!==null){O.shared.pending=null;var xt=ct,It=xt.next;xt.next=null,K===null?z=It:K.next=It,K=xt;var zt=m.alternate;zt!==null&&(zt=zt.updateQueue,ct=zt.lastBaseUpdate,ct!==K&&(ct===null?zt.firstBaseUpdate=It:ct.next=It,zt.lastBaseUpdate=xt))}if(z!==null){var Xt=O.baseState;K=0,zt=It=xt=null,ct=z;do{var Ht=ct.lane&-536870913,Fe=Ht!==ct.lane;if(Fe?(en&Ht)===Ht:(I&Ht)===Ht){Ht!==0&&Ht===lm&&(FE=!0),zt!==null&&(zt=zt.next={lane:0,tag:ct.tag,payload:ct.payload,callback:null,next:null});t:{var Ss=m,ig=ct;Ht=y;var Th=w;switch(ig.tag){case 1:if(Ss=ig.payload,typeof Ss=="function"){Xt=Ss.call(Th,Xt,Ht);break t}Xt=Ss;break t;case 3:Ss.flags=Ss.flags&-65537|128;case 0:if(Ss=ig.payload,Ht=typeof Ss=="function"?Ss.call(Th,Xt,Ht):Ss,Ht==null)break t;Xt=fE({},Xt,Ht);break t;case 2:Ic=!0}}Ht=ct.callback,Ht!==null&&(m.flags|=64,Fe&&(m.flags|=8192),Fe=O.callbacks,Fe===null?O.callbacks=[Ht]:Fe.push(Ht))}else Fe={lane:Ht,tag:ct.tag,payload:ct.payload,callback:ct.callback,next:null},zt===null?(It=zt=Fe,xt=Xt):zt=zt.next=Fe,K|=Ht;if(ct=ct.next,ct===null){if(ct=O.shared.pending,ct===null)break;Fe=ct,ct=Fe.next,Fe.next=null,O.lastBaseUpdate=Fe,O.shared.pending=null}}while(!0);zt===null&&(xt=Xt),O.baseState=xt,O.firstBaseUpdate=It,O.lastBaseUpdate=zt,z===null&&(O.shared.lanes=0),Rc|=K,m.lanes=K,m.memoizedState=Xt}}function Uf(m,y){if(typeof m!="function")throw Error(i(191,m));m.call(y)}function Vf(m,y){var w=m.callbacks;if(w!==null)for(m.callbacks=null,m=0;m<w.length;m++)Uf(w[m],y)}function Gf(m,y){m=ba,_(Tx,m),_(dm,y),ba=m|y.baseLanes}function lh(){_(Tx,ba),_(dm,dm.current)}function uh(){ba=Tx.current,d(dm),d(Tx)}function Fn(){throw Error(i(321))}function ph(m,y){if(y===null)return!1;for(var w=0;w<y.length&&w<m.length;w++)if(!rs(m[w],y[w]))return!1;return!0}function hh(m,y,w,I,O,z){return Nc=z,je=y,y.memoizedState=null,y.updateQueue=null,y.lanes=0,ye.H=m===null||m.memoizedState===null?vz:wz,Ph=!1,z=w(I,O),Ph=!1,fm&&(z=K0(y,w,I,O)),Z0(m),z}function Z0(m){ye.H=Cx;var y=Pn!==null&&Pn.next!==null;if(Nc=0,mi=Pn=je=null,Ex=!1,Ky=0,mm=null,y)throw Error(i(300));m===null||Ai||(m=m.dependencies,m!==null&&Kt(m)&&(Ai=!0))}function K0(m,y,w,I){je=m;var O=0;do{if(fm&&(mm=null),Ky=0,fm=!1,25<=O)throw Error(i(301));if(O+=1,mi=Pn=null,m.updateQueue!=null){var z=m.updateQueue;z.lastEffect=null,z.events=null,z.stores=null,z.memoCache!=null&&(z.memoCache.index=0)}ye.H=Uht,z=y(w,I)}while(fm);return z}function IT(){var m=ye.H,y=m.useState()[0];return y=typeof y.then=="function"?dh(y):y,m=m.useState()[0],(Pn!==null?Pn.memoizedState:null)!==m&&(je.flags|=1024),y}function My(){var m=Mx!==0;return Mx=0,m}function Cy(m,y,w){y.updateQueue=m.updateQueue,y.flags&=-2053,m.lanes&=~w}function Iy(m){if(Ex){for(m=m.memoizedState;m!==null;){var y=m.queue;y!==null&&(y.pending=null),m=m.next}Ex=!1}Nc=0,mi=Pn=je=null,fm=!1,Ky=Mx=0,mm=null}function cr(){var m={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return mi===null?je.memoizedState=mi=m:mi=mi.next=m,mi}function ti(){if(Pn===null){var m=je.alternate;m=m!==null?m.memoizedState:null}else m=Pn.next;var y=mi===null?je.memoizedState:mi.next;if(y!==null)mi=y,Pn=m;else{if(m===null)throw je.alternate===null?Error(i(467)):Error(i(310));Pn=m,m={memoizedState:Pn.memoizedState,baseState:Pn.baseState,baseQueue:Pn.baseQueue,queue:Pn.queue,next:null},mi===null?je.memoizedState=mi=m:mi=mi.next=m}return mi}function Ny(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function dh(m){var y=Ky;return Ky+=1,mm===null&&(mm=[]),m=jf(mm,m,y),y=je,(mi===null?y.memoizedState:mi.next)===null&&(y=y.alternate,ye.H=y===null||y.memoizedState===null?vz:wz),m}function Wf(m){if(m!==null&&typeof m=="object"){if(typeof m.then=="function")return dh(m);if(m.$$typeof===Tc)return Jt(m)}throw Error(i(438,String(m)))}function Ay(m){var y=null,w=je.updateQueue;if(w!==null&&(y=w.memoCache),y==null){var I=je.alternate;I!==null&&(I=I.updateQueue,I!==null&&(I=I.memoCache,I!=null&&(y={data:I.data.map(function(O){return O.slice()}),index:0})))}if(y==null&&(y={data:[],index:0}),w===null&&(w=Ny(),je.updateQueue=w),w.memoCache=y,w=y.data[y.index],w===void 0)for(w=y.data[y.index]=Array(m),I=0;I<m;I++)w[I]=dpt;return y.index++,w}function Ws(m,y){return typeof y=="function"?y(m):y}function Hf(m){var y=ti();return Ry(y,Pn,m)}function Ry(m,y,w){var I=m.queue;if(I===null)throw Error(i(311));I.lastRenderedReducer=w;var O=m.baseQueue,z=I.pending;if(z!==null){if(O!==null){var K=O.next;O.next=z.next,z.next=K}y.baseQueue=O=z,I.pending=null}if(z=m.baseState,O===null)m.memoizedState=z;else{y=O.next;var ct=K=null,xt=null,It=y,zt=!1;do{var Xt=It.lane&-536870913;if(Xt!==It.lane?(en&Xt)===Xt:(Nc&Xt)===Xt){var Ht=It.revertLane;if(Ht===0)xt!==null&&(xt=xt.next={lane:0,revertLane:0,action:It.action,hasEagerState:It.hasEagerState,eagerState:It.eagerState,next:null}),Xt===lm&&(zt=!0);else if((Nc&Ht)===Ht){It=It.next,Ht===lm&&(zt=!0);continue}else Xt={lane:0,revertLane:It.revertLane,action:It.action,hasEagerState:It.hasEagerState,eagerState:It.eagerState,next:null},xt===null?(ct=xt=Xt,K=z):xt=xt.next=Xt,je.lanes|=Ht,Rc|=Ht;Xt=It.action,Ph&&w(z,Xt),z=It.hasEagerState?It.eagerState:w(z,Xt)}else Ht={lane:Xt,revertLane:It.revertLane,action:It.action,hasEagerState:It.hasEagerState,eagerState:It.eagerState,next:null},xt===null?(ct=xt=Ht,K=z):xt=xt.next=Ht,je.lanes|=Xt,Rc|=Xt;It=It.next}while(It!==null&&It!==y);if(xt===null?K=z:xt.next=ct,!rs(z,m.memoizedState)&&(Ai=!0,zt&&(w=um,w!==null)))throw w;m.memoizedState=z,m.baseState=K,m.baseQueue=xt,I.lastRenderedState=z}return O===null&&(I.lanes=0),[m.memoizedState,I.dispatch]}function Oy(m){var y=ti(),w=y.queue;if(w===null)throw Error(i(311));w.lastRenderedReducer=m;var I=w.dispatch,O=w.pending,z=y.memoizedState;if(O!==null){w.pending=null;var K=O=O.next;do z=m(z,K.action),K=K.next;while(K!==O);rs(z,y.memoizedState)||(Ai=!0),y.memoizedState=z,y.baseQueue===null&&(y.baseState=z),w.lastRenderedState=z}return[z,I]}function Q7(m,y,w){var I=je,O=ti(),z=_n;if(z){if(w===void 0)throw Error(i(407));w=w()}else w=y();var K=!rs((Pn||O).memoizedState,w);K&&(O.memoizedState=w,Ai=!0),O=O.queue;var ct=nF.bind(null,I,O,m);if(Ly(2048,8,ct,[m]),O.getSnapshot!==y||K||mi!==null&&mi.memoizedState.tag&1){if(I.flags|=2048,qf(9,J0(),eF.bind(null,I,O,w,y),null),Rn===null)throw Error(i(349));z||(Nc&124)!==0||tF(I,y,w)}return w}function tF(m,y,w){m.flags|=16384,m={getSnapshot:y,value:w},y=je.updateQueue,y===null?(y=Ny(),je.updateQueue=y,y.stores=[m]):(w=y.stores,w===null?y.stores=[m]:w.push(m))}function eF(m,y,w,I){y.value=w,y.getSnapshot=I,iF(y)&&rF(m)}function nF(m,y,w){return w(function(){iF(y)&&rF(m)})}function iF(m){var y=m.getSnapshot;m=m.value;try{var w=y();return!rs(m,w)}catch{return!0}}function rF(m){var y=To(m,2);y!==null&&ts(y,m,2)}function NT(m){var y=cr();if(typeof m=="function"){var w=m;if(m=w(),Ph){j(!0);try{w()}finally{j(!1)}}}return y.memoizedState=y.baseState=m,y.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ws,lastRenderedState:m},y}function sF(m,y,w,I){return m.baseState=w,Ry(m,Pn,typeof I=="function"?I:Ws)}function Uut(m,y,w,I,O){if(tx(m))throw Error(i(485));if(m=y.action,m!==null){var z={payload:O,action:m,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(K){z.listeners.push(K)}};ye.T!==null?w(!0):z.isTransition=!1,I(z),w=y.pending,w===null?(z.next=y.pending=z,oF(y,z)):(z.next=w.next,y.pending=w.next=z)}}function oF(m,y){var w=y.action,I=y.payload,O=m.state;if(y.isTransition){var z=ye.T,K={};ye.T=K;try{var ct=w(O,I),xt=ye.S;xt!==null&&xt(K,ct),aF(m,y,ct)}catch(It){AT(m,y,It)}finally{ye.T=z}}else try{z=w(O,I),aF(m,y,z)}catch(It){AT(m,y,It)}}function aF(m,y,w){w!==null&&typeof w=="object"&&typeof w.then=="function"?w.then(function(I){cF(m,y,I)},function(I){return AT(m,y,I)}):cF(m,y,w)}function cF(m,y,w){y.status="fulfilled",y.value=w,lF(y),m.state=w,y=m.pending,y!==null&&(w=y.next,w===y?m.pending=null:(w=w.next,y.next=w,oF(m,w)))}function AT(m,y,w){var I=m.pending;if(m.pending=null,I!==null){I=I.next;do y.status="rejected",y.reason=w,lF(y),y=y.next;while(y!==I)}m.action=null}function lF(m){m=m.listeners;for(var y=0;y<m.length;y++)(0,m[y])()}function uF(m,y){return y}function pF(m,y){if(_n){var w=Rn.formState;if(w!==null){t:{var I=je;if(_n){if(Si){var O=sht(Si,Co);if(O){Si=sz(O),I=oht(O);break t}}ot(I)}I=!1}I&&(y=w[0])}}w=cr(),w.memoizedState=w.baseState=y,I={pending:null,lanes:0,dispatch:null,lastRenderedReducer:uF,lastRenderedState:y},w.queue=I,w=CF.bind(null,je,I),I.dispatch=w,I=NT(!1);var z=FT.bind(null,je,!1,I.queue);return I=cr(),O={state:y,dispatch:null,action:m,pending:null},I.queue=O,w=Uut.bind(null,je,O,z,w),O.dispatch=w,I.memoizedState=m,[y,w,!1]}function hF(m){var y=ti();return dF(y,Pn,m)}function dF(m,y,w){if(y=Ry(m,y,uF)[0],m=Hf(Ws)[0],typeof y=="object"&&y!==null&&typeof y.then=="function")try{var I=dh(y)}catch(K){throw K===Zy?Px:K}else I=y;y=ti();var O=y.queue,z=O.dispatch;return w!==y.memoizedState&&(je.flags|=2048,qf(9,J0(),Vut.bind(null,O,w),null)),[I,z,m]}function Vut(m,y){m.action=y}function fF(m){var y=ti(),w=Pn;if(w!==null)return dF(y,w,m);ti(),y=y.memoizedState,w=ti();var I=w.queue.dispatch;return w.memoizedState=m,[y,I,!1]}function qf(m,y,w,I){return m={tag:m,create:w,deps:I,inst:y,next:null},y=je.updateQueue,y===null&&(y=Ny(),je.updateQueue=y),w=y.lastEffect,w===null?y.lastEffect=m.next=m:(I=w.next,w.next=m,m.next=I,y.lastEffect=m),m}function J0(){return{destroy:void 0,resource:void 0}}function mF(){return ti().memoizedState}function Q0(m,y,w,I){var O=cr();I=I===void 0?null:I,je.flags|=m,O.memoizedState=qf(1|y,J0(),w,I)}function Ly(m,y,w,I){var O=ti();I=I===void 0?null:I;var z=O.memoizedState.inst;Pn!==null&&I!==null&&ph(I,Pn.memoizedState.deps)?O.memoizedState=qf(y,z,w,I):(je.flags|=m,O.memoizedState=qf(1|y,z,w,I))}function _F(m,y){Q0(8390656,8,m,y)}function yF(m,y){Ly(2048,8,m,y)}function gF(m,y){return Ly(4,2,m,y)}function xF(m,y){return Ly(4,4,m,y)}function bF(m,y){if(typeof y=="function"){m=m();var w=y(m);return function(){typeof w=="function"?w():y(null)}}if(y!=null)return m=m(),y.current=m,function(){y.current=null}}function vF(m,y,w){w=w!=null?w.concat([m]):null,Ly(4,4,bF.bind(null,y,m),w)}function RT(){}function wF(m,y){var w=ti();y=y===void 0?null:y;var I=w.memoizedState;return y!==null&&ph(y,I[1])?I[0]:(w.memoizedState=[m,y],m)}function SF(m,y){var w=ti();y=y===void 0?null:y;var I=w.memoizedState;if(y!==null&&ph(y,I[1]))return I[0];if(I=m(),Ph){j(!0);try{m()}finally{j(!1)}}return w.memoizedState=[I,y],I}function OT(m,y,w){return w===void 0||(Nc&1073741824)!==0?m.memoizedState=y:(m.memoizedState=w,m=b$(),je.lanes|=m,Rc|=m,w)}function PF(m,y,w,I){return rs(w,y)?w:dm.current!==null?(m=OT(m,w,I),rs(m,y)||(Ai=!0),m):(Nc&42)===0?(Ai=!0,m.memoizedState=w):(m=b$(),je.lanes|=m,Rc|=m,y)}function kF(m,y,w,I,O){var z=ma();Ni(z!==0&&8>z?z:8);var K=ye.T,ct={};ye.T=ct,FT(m,!1,y,w);try{var xt=O(),It=ye.S;if(It!==null&&It(ct,xt),xt!==null&&typeof xt=="object"&&typeof xt.then=="function"){var zt=Ey(xt,I);Fy(m,y,zt,Qr(m))}else Fy(m,y,I,Qr(m))}catch(Xt){Fy(m,y,{then:function(){},status:"rejected",reason:Xt},Qr())}finally{Ni(z),ye.T=K}}function TF(m){var y=m.memoizedState;if(y!==null)return y;y={memoizedState:em,baseState:em,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ws,lastRenderedState:em},next:null};var w={};return y.next={memoizedState:w,baseState:w,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ws,lastRenderedState:w},next:null},m.memoizedState=y,m=m.alternate,m!==null&&(m.memoizedState=y),y}function LT(){return Jt(xh)}function EF(){return ti().memoizedState}function MF(){return ti().memoizedState}function Gut(m){for(var y=m.return;y!==null;){switch(y.tag){case 24:case 3:var w=Qr();m=ms(w);var I=_s(y,m,w);I!==null&&(ts(I,y,w),ca(I,y,w)),y={cache:Nr()},m.payload=y;return}y=y.return}}function Wut(m,y,w){var I=Qr();w={lane:I,revertLane:0,action:w,hasEagerState:!1,eagerState:null,next:null},tx(m)?IF(y,w):(w=sh(m,y,w,I),w!==null&&(ts(w,m,I),NF(w,y,I)))}function CF(m,y,w){var I=Qr();Fy(m,y,w,I)}function Fy(m,y,w,I){var O={lane:I,revertLane:0,action:w,hasEagerState:!1,eagerState:null,next:null};if(tx(m))IF(y,O);else{var z=m.alternate;if(m.lanes===0&&(z===null||z.lanes===0)&&(z=y.lastRenderedReducer,z!==null))try{var K=y.lastRenderedState,ct=z(K,w);if(O.hasEagerState=!0,O.eagerState=ct,rs(ct,K))return gc(m,y,O,0),Rn===null&&yc(),!1}catch{}finally{}if(w=sh(m,y,O,I),w!==null)return ts(w,m,I),NF(w,y,I),!0}return!1}function FT(m,y,w,I){if(I={lane:2,revertLane:ih(),action:I,hasEagerState:!1,eagerState:null,next:null},tx(m)){if(y)throw Error(i(479))}else y=sh(m,w,I,2),y!==null&&ts(y,m,2)}function tx(m){var y=m.alternate;return m===je||y!==null&&y===je}function IF(m,y){fm=Ex=!0;var w=m.pending;w===null?y.next=y:(y.next=w.next,w.next=y),m.pending=y}function NF(m,y,w){if((w&4194048)!==0){var I=y.lanes;I&=m.pendingLanes,w|=I,y.lanes=w,A(m,w)}}function ex(m){var y=Jy;return Jy+=1,_m===null&&(_m=[]),jf(_m,m,y)}function $y(m,y){y=y.props.ref,m.ref=y!==void 0?y:null}function nx(m,y){throw y.$$typeof===ppt?Error(i(525)):(m=Object.prototype.toString.call(y),Error(i(31,m==="[object Object]"?"object with keys {"+Object.keys(y).join(", ")+"}":m)))}function AF(m){var y=m._init;return y(m._payload)}function RF(m){function y(gt,dt){if(m){var vt=gt.deletions;vt===null?(gt.deletions=[dt],gt.flags|=16):vt.push(dt)}}function w(gt,dt){if(!m)return null;for(;dt!==null;)y(gt,dt),dt=dt.sibling;return null}function I(gt){for(var dt=new Map;gt!==null;)gt.key!==null?dt.set(gt.key,gt):dt.set(gt.index,gt),gt=gt.sibling;return dt}function O(gt,dt){return gt=da(gt,dt),gt.index=0,gt.sibling=null,gt}function z(gt,dt,vt){return gt.index=vt,m?(vt=gt.alternate,vt!==null?(vt=vt.index,vt<dt?(gt.flags|=67108866,dt):vt):(gt.flags|=67108866,dt)):(gt.flags|=1048576,dt)}function K(gt){return m&&gt.alternate===null&&(gt.flags|=67108866),gt}function ct(gt,dt,vt,$t){return dt===null||dt.tag!==6?(dt=pE(vt,gt.mode,$t),dt.return=gt,dt):(dt=O(dt,vt),dt.return=gt,dt)}function xt(gt,dt,vt,$t){var ce=vt.type;return ce===tm?zt(gt,dt,vt.props.children,$t,vt.key):dt!==null&&(dt.elementType===ce||typeof ce=="object"&&ce!==null&&ce.$$typeof===Ec&&AF(ce)===dt.type)?(dt=O(dt,vt.props),$y(dt,vt),dt.return=gt,dt):(dt=px(vt.type,vt.key,vt.props,null,gt.mode,$t),$y(dt,vt),dt.return=gt,dt)}function It(gt,dt,vt,$t){return dt===null||dt.tag!==4||dt.stateNode.containerInfo!==vt.containerInfo||dt.stateNode.implementation!==vt.implementation?(dt=hE(vt,gt.mode,$t),dt.return=gt,dt):(dt=O(dt,vt.children||[]),dt.return=gt,dt)}function zt(gt,dt,vt,$t,ce){return dt===null||dt.tag!==7?(dt=yh(vt,gt.mode,$t,ce),dt.return=gt,dt):(dt=O(dt,vt),dt.return=gt,dt)}function Xt(gt,dt,vt){if(typeof dt=="string"&&dt!==""||typeof dt=="number"||typeof dt=="bigint")return dt=pE(""+dt,gt.mode,vt),dt.return=gt,dt;if(typeof dt=="object"&&dt!==null){switch(dt.$$typeof){case hx:return vt=px(dt.type,dt.key,dt.props,null,gt.mode,vt),$y(vt,dt),vt.return=gt,vt;case Qf:return dt=hE(dt,gt.mode,vt),dt.return=gt,dt;case Ec:var $t=dt._init;return dt=$t(dt._payload),Xt(gt,dt,vt)}if(dx(dt)||l(dt))return dt=yh(dt,gt.mode,vt,null),dt.return=gt,dt;if(typeof dt.then=="function")return Xt(gt,ex(dt),vt);if(dt.$$typeof===Tc)return Xt(gt,qn(gt,dt),vt);nx(gt,dt)}return null}function Ht(gt,dt,vt,$t){var ce=dt!==null?dt.key:null;if(typeof vt=="string"&&vt!==""||typeof vt=="number"||typeof vt=="bigint")return ce!==null?null:ct(gt,dt,""+vt,$t);if(typeof vt=="object"&&vt!==null){switch(vt.$$typeof){case hx:return vt.key===ce?xt(gt,dt,vt,$t):null;case Qf:return vt.key===ce?It(gt,dt,vt,$t):null;case Ec:return ce=vt._init,vt=ce(vt._payload),Ht(gt,dt,vt,$t)}if(dx(vt)||l(vt))return ce!==null?null:zt(gt,dt,vt,$t,null);if(typeof vt.then=="function")return Ht(gt,dt,ex(vt),$t);if(vt.$$typeof===Tc)return Ht(gt,dt,qn(gt,vt),$t);nx(gt,vt)}return null}function Fe(gt,dt,vt,$t,ce){if(typeof $t=="string"&&$t!==""||typeof $t=="number"||typeof $t=="bigint")return gt=gt.get(vt)||null,ct(dt,gt,""+$t,ce);if(typeof $t=="object"&&$t!==null){switch($t.$$typeof){case hx:return gt=gt.get($t.key===null?vt:$t.key)||null,xt(dt,gt,$t,ce);case Qf:return gt=gt.get($t.key===null?vt:$t.key)||null,It(dt,gt,$t,ce);case Ec:var $n=$t._init;return $t=$n($t._payload),Fe(gt,dt,vt,$t,ce)}if(dx($t)||l($t))return gt=gt.get(vt)||null,zt(dt,gt,$t,ce,null);if(typeof $t.then=="function")return Fe(gt,dt,vt,ex($t),ce);if($t.$$typeof===Tc)return Fe(gt,dt,vt,qn(dt,$t),ce);nx(dt,$t)}return null}function Ss(gt,dt,vt,$t){for(var ce=null,$n=null,Te=dt,on=dt=0,Oi=null;Te!==null&&on<vt.length;on++){Te.index>on?(Oi=Te,Te=null):Oi=Te.sibling;var an=Ht(gt,Te,vt[on],$t);if(an===null){Te===null&&(Te=Oi);break}m&&Te&&an.alternate===null&&y(gt,Te),dt=z(an,dt,on),$n===null?ce=an:$n.sibling=an,$n=an,Te=Oi}if(on===vt.length)return w(gt,Te),_n&&mt(gt,on),ce;if(Te===null){for(;on<vt.length;on++)Te=Xt(gt,vt[on],$t),Te!==null&&(dt=z(Te,dt,on),$n===null?ce=Te:$n.sibling=Te,$n=Te);return _n&&mt(gt,on),ce}for(Te=I(Te);on<vt.length;on++)Oi=Fe(Te,gt,on,vt[on],$t),Oi!==null&&(m&&Oi.alternate!==null&&Te.delete(Oi.key===null?on:Oi.key),dt=z(Oi,dt,on),$n===null?ce=Oi:$n.sibling=Oi,$n=Oi);return m&&Te.forEach(function(Fc){return y(gt,Fc)}),_n&&mt(gt,on),ce}function ig(gt,dt,vt,$t){if(vt==null)throw Error(i(151));for(var ce=null,$n=null,Te=dt,on=dt=0,Oi=null,an=vt.next();Te!==null&&!an.done;on++,an=vt.next()){Te.index>on?(Oi=Te,Te=null):Oi=Te.sibling;var Fc=Ht(gt,Te,an.value,$t);if(Fc===null){Te===null&&(Te=Oi);break}m&&Te&&Fc.alternate===null&&y(gt,Te),dt=z(Fc,dt,on),$n===null?ce=Fc:$n.sibling=Fc,$n=Fc,Te=Oi}if(an.done)return w(gt,Te),_n&&mt(gt,on),ce;if(Te===null){for(;!an.done;on++,an=vt.next())an=Xt(gt,an.value,$t),an!==null&&(dt=z(an,dt,on),$n===null?ce=an:$n.sibling=an,$n=an);return _n&&mt(gt,on),ce}for(Te=I(Te);!an.done;on++,an=vt.next())an=Fe(Te,gt,on,an.value,$t),an!==null&&(m&&an.alternate!==null&&Te.delete(an.key===null?on:an.key),dt=z(an,dt,on),$n===null?ce=an:$n.sibling=an,$n=an);return m&&Te.forEach(function(Wht){return y(gt,Wht)}),_n&&mt(gt,on),ce}function Th(gt,dt,vt,$t){if(typeof vt=="object"&&vt!==null&&vt.type===tm&&vt.key===null&&(vt=vt.props.children),typeof vt=="object"&&vt!==null){switch(vt.$$typeof){case hx:t:{for(var ce=vt.key;dt!==null;){if(dt.key===ce){if(ce=vt.type,ce===tm){if(dt.tag===7){w(gt,dt.sibling),$t=O(dt,vt.props.children),$t.return=gt,gt=$t;break t}}else if(dt.elementType===ce||typeof ce=="object"&&ce!==null&&ce.$$typeof===Ec&&AF(ce)===dt.type){w(gt,dt.sibling),$t=O(dt,vt.props),$y($t,vt),$t.return=gt,gt=$t;break t}w(gt,dt);break}else y(gt,dt);dt=dt.sibling}vt.type===tm?($t=yh(vt.props.children,gt.mode,$t,vt.key),$t.return=gt,gt=$t):($t=px(vt.type,vt.key,vt.props,null,gt.mode,$t),$y($t,vt),$t.return=gt,gt=$t)}return K(gt);case Qf:t:{for(ce=vt.key;dt!==null;){if(dt.key===ce)if(dt.tag===4&&dt.stateNode.containerInfo===vt.containerInfo&&dt.stateNode.implementation===vt.implementation){w(gt,dt.sibling),$t=O(dt,vt.children||[]),$t.return=gt,gt=$t;break t}else{w(gt,dt);break}else y(gt,dt);dt=dt.sibling}$t=hE(vt,gt.mode,$t),$t.return=gt,gt=$t}return K(gt);case Ec:return ce=vt._init,vt=ce(vt._payload),Th(gt,dt,vt,$t)}if(dx(vt))return Ss(gt,dt,vt,$t);if(l(vt)){if(ce=l(vt),typeof ce!="function")throw Error(i(150));return vt=ce.call(vt),ig(gt,dt,vt,$t)}if(typeof vt.then=="function")return Th(gt,dt,ex(vt),$t);if(vt.$$typeof===Tc)return Th(gt,dt,qn(gt,vt),$t);nx(gt,vt)}return typeof vt=="string"&&vt!==""||typeof vt=="number"||typeof vt=="bigint"?(vt=""+vt,dt!==null&&dt.tag===6?(w(gt,dt.sibling),$t=O(dt,vt),$t.return=gt,gt=$t):(w(gt,dt),$t=pE(vt,gt.mode,$t),$t.return=gt,gt=$t),K(gt)):w(gt,dt)}return function(gt,dt,vt,$t){try{Jy=0;var ce=Th(gt,dt,vt,$t);return _m=null,ce}catch(Te){if(Te===Zy||Te===Px)throw Te;var $n=e(29,Te,null,gt.mode);return $n.lanes=$t,$n.return=gt,$n}finally{}}}function bc(m){var y=m.alternate;_(Pi,Pi.current&1),_(vs,m),Io===null&&(y===null||dm.current!==null||y.memoizedState!==null)&&(Io=m)}function OF(m){if(m.tag===22){if(_(Pi,Pi.current),_(vs,m),Io===null){var y=m.alternate;y!==null&&y.memoizedState!==null&&(Io=m)}}else vc(m)}function vc(){_(Pi,Pi.current),_(vs,vs.current)}function pa(m){d(vs),Io===m&&(Io=null),d(Pi)}function ix(m){for(var y=m;y!==null;){if(y.tag===13){var w=y.memoizedState;if(w!==null&&(w=w.dehydrated,w===null||wE(w)||SE(w)))return y}else if(y.tag===19&&y.memoizedProps.revealOrder!==void 0){if((y.flags&128)!==0)return y}else if(y.child!==null){y.child.return=y,y=y.child;continue}if(y===m)break;for(;y.sibling===null;){if(y.return===null||y.return===m)return null;y=y.return}y.sibling.return=y.return,y=y.sibling}return null}function $T(m,y,w,I){y=m.memoizedState,w=w(I,y),w=w==null?y:fE({},y,w),m.memoizedState=w,m.lanes===0&&(m.updateQueue.baseState=w)}function LF(m,y,w,I,O,z,K){return m=m.stateNode,typeof m.shouldComponentUpdate=="function"?m.shouldComponentUpdate(I,z,K):y.prototype&&y.prototype.isPureReactComponent?!mc(w,I)||!mc(O,z):!0}function FF(m,y,w,I){m=y.state,typeof y.componentWillReceiveProps=="function"&&y.componentWillReceiveProps(w,I),typeof y.UNSAFE_componentWillReceiveProps=="function"&&y.UNSAFE_componentWillReceiveProps(w,I),y.state!==m&&$E.enqueueReplaceState(y,y.state,null)}function fh(m,y){var w=y;if("ref"in y){w={};for(var I in y)I!=="ref"&&(w[I]=y[I])}if(m=m.defaultProps){w===y&&(w=fE({},w));for(var O in m)w[O]===void 0&&(w[O]=m[O])}return w}function rx(m,y){try{var w=m.onUncaughtError;w(y.value,{componentStack:y.stack})}catch(I){setTimeout(function(){throw I})}}function $F(m,y,w){try{var I=m.onCaughtError;I(w.value,{componentStack:w.stack,errorBoundary:y.tag===1?y.stateNode:null})}catch(O){setTimeout(function(){throw O})}}function zT(m,y,w){return w=ms(w),w.tag=3,w.payload={element:null},w.callback=function(){rx(m,y)},w}function zF(m){return m=ms(m),m.tag=3,m}function DF(m,y,w,I){var O=w.type.getDerivedStateFromError;if(typeof O=="function"){var z=I.value;m.payload=function(){return O(z)},m.callback=function(){$F(y,w,I)}}var K=w.stateNode;K!==null&&typeof K.componentDidCatch=="function"&&(m.callback=function(){$F(y,w,I),typeof O!="function"&&(Oc===null?Oc=new Set([this]):Oc.add(this));var ct=I.stack;this.componentDidCatch(I.value,{componentStack:ct!==null?ct:""})})}function Hut(m,y,w,I,O){if(w.flags|=32768,I!==null&&typeof I=="object"&&typeof I.then=="function"){if(y=w.alternate,y!==null&&Se(y,w,O,!0),w=vs.current,w!==null){switch(w.tag){case 13:return Io===null?aE():w.alternate===null&&ni===0&&(ni=3),w.flags&=-257,w.flags|=65536,w.lanes=O,I===kx?w.flags|=16384:(y=w.updateQueue,y===null?w.updateQueue=new Set([I]):y.add(I),lE(m,I,O)),!1;case 22:return w.flags|=65536,I===kx?w.flags|=16384:(y=w.updateQueue,y===null?(y={transitions:null,markerInstances:null,retryQueue:new Set([I])},w.updateQueue=y):(w=y.retryQueue,w===null?y.retryQueue=new Set([I]):w.add(I)),lE(m,I,O)),!1}throw Error(i(435,w.tag))}return lE(m,I,O),aE(),!1}if(_n)return y=vs.current,y!==null?((y.flags&65536)===0&&(y.flags|=256),y.flags|=65536,y.lanes=O,I!==IE&&(m=Error(i(422),{cause:I}),Z(nt(m,w)))):(I!==IE&&(y=Error(i(423),{cause:I}),Z(nt(y,w))),m=m.current.alternate,m.flags|=65536,O&=-O,m.lanes|=O,I=nt(I,w),O=zT(m.stateNode,I,O),ch(m,O),ni!==4&&(ni=2)),!1;var z=Error(i(520),{cause:I});if(z=nt(z,w),tg===null?tg=[z]:tg.push(z),ni!==4&&(ni=2),y===null)return!0;I=nt(I,w),w=y;do{switch(w.tag){case 3:return w.flags|=65536,m=O&-O,w.lanes|=m,m=zT(w.stateNode,I,m),ch(w,m),!1;case 1:if(y=w.type,z=w.stateNode,(w.flags&128)===0&&(typeof y.getDerivedStateFromError=="function"||z!==null&&typeof z.componentDidCatch=="function"&&(Oc===null||!Oc.has(z))))return w.flags|=65536,O&=-O,w.lanes|=O,O=zF(O),DF(O,m,w,I),ch(w,O),!1}w=w.return}while(w!==null);return!1}function Zi(m,y,w,I){y.child=m===null?Sz(y,null,w,I):ym(y,m.child,w,I)}function jF(m,y,w,I,O){w=w.render;var z=y.ref;if("ref"in I){var K={};for(var ct in I)ct!=="ref"&&(K[ct]=I[ct])}else K=I;return le(y),I=hh(m,y,w,K,z,O),ct=My(),m!==null&&!Ai?(Cy(m,y,O),ha(m,y,O)):(_n&&ct&&tt(y),y.flags|=1,Zi(m,y,I,O),y.child)}function BF(m,y,w,I,O){if(m===null){var z=w.type;return typeof z=="function"&&!uE(z)&&z.defaultProps===void 0&&w.compare===null?(y.tag=15,y.type=z,YF(m,y,z,I,O)):(m=px(w.type,null,I,y,y.mode,O),m.ref=y.ref,m.return=y,y.child=m)}if(z=m.child,!VT(m,O)){var K=z.memoizedProps;if(w=w.compare,w=w!==null?w:mc,w(K,I)&&m.ref===y.ref)return ha(m,y,O)}return y.flags|=1,m=da(z,I),m.ref=y.ref,m.return=y,y.child=m}function YF(m,y,w,I,O){if(m!==null){var z=m.memoizedProps;if(mc(z,I)&&m.ref===y.ref)if(Ai=!1,y.pendingProps=I=z,VT(m,O))(m.flags&131072)!==0&&(Ai=!0);else return y.lanes=m.lanes,ha(m,y,O)}return DT(m,y,w,I,O)}function XF(m,y,w){var I=y.pendingProps,O=I.children,z=m!==null?m.memoizedState:null;if(I.mode==="hidden"){if((y.flags&128)!==0){if(I=z!==null?z.baseLanes|w:w,m!==null){for(O=y.child=m.child,z=0;O!==null;)z=z|O.lanes|O.childLanes,O=O.sibling;y.childLanes=z&~I}else y.childLanes=0,y.child=null;return UF(m,y,I,w)}if((w&536870912)!==0)y.memoizedState={baseLanes:0,cachePool:null},m!==null&&fc(y,z!==null?z.cachePool:null),z!==null?Gf(y,z):lh(),OF(y);else return y.lanes=y.childLanes=536870912,UF(m,y,z!==null?z.baseLanes|w:w,w)}else z!==null?(fc(y,z.cachePool),Gf(y,z),vc(y),y.memoizedState=null):(m!==null&&fc(y,null),lh(),vc(y));return Zi(m,y,O,w),y.child}function UF(m,y,w,I){var O=rh();return O=O===null?null:{parent:fa?ei._currentValue:ei._currentValue2,pool:O},y.memoizedState={baseLanes:w,cachePool:O},m!==null&&fc(y,null),lh(),OF(y),m!==null&&Se(m,y,I,!0),null}function sx(m,y){var w=y.ref;if(w===null)m!==null&&m.ref!==null&&(y.flags|=4194816);else{if(typeof w!="function"&&typeof w!="object")throw Error(i(284));(m===null||m.ref!==w)&&(y.flags|=4194816)}}function DT(m,y,w,I,O){return le(y),w=hh(m,y,w,I,void 0,O),I=My(),m!==null&&!Ai?(Cy(m,y,O),ha(m,y,O)):(_n&&I&&tt(y),y.flags|=1,Zi(m,y,w,O),y.child)}function VF(m,y,w,I,O,z){return le(y),y.updateQueue=null,w=K0(y,I,w,O),Z0(m),I=My(),m!==null&&!Ai?(Cy(m,y,z),ha(m,y,z)):(_n&&I&&tt(y),y.flags|=1,Zi(m,y,w,z),y.child)}function GF(m,y,w,I,O){if(le(y),y.stateNode===null){var z=rm,K=w.contextType;typeof K=="object"&&K!==null&&(z=Jt(K)),z=new w(I,z),y.memoizedState=z.state!==null&&z.state!==void 0?z.state:null,z.updater=$E,y.stateNode=z,z._reactInternals=y,z=y.stateNode,z.props=I,z.state=y.memoizedState,z.refs={},oh(y),K=w.contextType,z.context=typeof K=="object"&&K!==null?Jt(K):rm,z.state=y.memoizedState,K=w.getDerivedStateFromProps,typeof K=="function"&&($T(y,w,K,I),z.state=y.memoizedState),typeof w.getDerivedStateFromProps=="function"||typeof z.getSnapshotBeforeUpdate=="function"||typeof z.UNSAFE_componentWillMount!="function"&&typeof z.componentWillMount!="function"||(K=z.state,typeof z.componentWillMount=="function"&&z.componentWillMount(),typeof z.UNSAFE_componentWillMount=="function"&&z.UNSAFE_componentWillMount(),K!==z.state&&$E.enqueueReplaceState(z,z.state,null),ua(y,I,z,O),la(),z.state=y.memoizedState),typeof z.componentDidMount=="function"&&(y.flags|=4194308),I=!0}else if(m===null){z=y.stateNode;var ct=y.memoizedProps,xt=fh(w,ct);z.props=xt;var It=z.context,zt=w.contextType;K=rm,typeof zt=="object"&&zt!==null&&(K=Jt(zt));var Xt=w.getDerivedStateFromProps;zt=typeof Xt=="function"||typeof z.getSnapshotBeforeUpdate=="function",ct=y.pendingProps!==ct,zt||typeof z.UNSAFE_componentWillReceiveProps!="function"&&typeof z.componentWillReceiveProps!="function"||(ct||It!==K)&&FF(y,z,I,K),Ic=!1;var Ht=y.memoizedState;z.state=Ht,ua(y,I,z,O),la(),It=y.memoizedState,ct||Ht!==It||Ic?(typeof Xt=="function"&&($T(y,w,Xt,I),It=y.memoizedState),(xt=Ic||LF(y,w,xt,I,Ht,It,K))?(zt||typeof z.UNSAFE_componentWillMount!="function"&&typeof z.componentWillMount!="function"||(typeof z.componentWillMount=="function"&&z.componentWillMount(),typeof z.UNSAFE_componentWillMount=="function"&&z.UNSAFE_componentWillMount()),typeof z.componentDidMount=="function"&&(y.flags|=4194308)):(typeof z.componentDidMount=="function"&&(y.flags|=4194308),y.memoizedProps=I,y.memoizedState=It),z.props=I,z.state=It,z.context=K,I=xt):(typeof z.componentDidMount=="function"&&(y.flags|=4194308),I=!1)}else{z=y.stateNode,ah(m,y),K=y.memoizedProps,zt=fh(w,K),z.props=zt,Xt=y.pendingProps,Ht=z.context,It=w.contextType,xt=rm,typeof It=="object"&&It!==null&&(xt=Jt(It)),ct=w.getDerivedStateFromProps,(It=typeof ct=="function"||typeof z.getSnapshotBeforeUpdate=="function")||typeof z.UNSAFE_componentWillReceiveProps!="function"&&typeof z.componentWillReceiveProps!="function"||(K!==Xt||Ht!==xt)&&FF(y,z,I,xt),Ic=!1,Ht=y.memoizedState,z.state=Ht,ua(y,I,z,O),la();var Fe=y.memoizedState;K!==Xt||Ht!==Fe||Ic||m!==null&&m.dependencies!==null&&Kt(m.dependencies)?(typeof ct=="function"&&($T(y,w,ct,I),Fe=y.memoizedState),(zt=Ic||LF(y,w,zt,I,Ht,Fe,xt)||m!==null&&m.dependencies!==null&&Kt(m.dependencies))?(It||typeof z.UNSAFE_componentWillUpdate!="function"&&typeof z.componentWillUpdate!="function"||(typeof z.componentWillUpdate=="function"&&z.componentWillUpdate(I,Fe,xt),typeof z.UNSAFE_componentWillUpdate=="function"&&z.UNSAFE_componentWillUpdate(I,Fe,xt)),typeof z.componentDidUpdate=="function"&&(y.flags|=4),typeof z.getSnapshotBeforeUpdate=="function"&&(y.flags|=1024)):(typeof z.componentDidUpdate!="function"||K===m.memoizedProps&&Ht===m.memoizedState||(y.flags|=4),typeof z.getSnapshotBeforeUpdate!="function"||K===m.memoizedProps&&Ht===m.memoizedState||(y.flags|=1024),y.memoizedProps=I,y.memoizedState=Fe),z.props=I,z.state=Fe,z.context=xt,I=zt):(typeof z.componentDidUpdate!="function"||K===m.memoizedProps&&Ht===m.memoizedState||(y.flags|=4),typeof z.getSnapshotBeforeUpdate!="function"||K===m.memoizedProps&&Ht===m.memoizedState||(y.flags|=1024),I=!1)}return z=I,sx(m,y),I=(y.flags&128)!==0,z||I?(z=y.stateNode,w=I&&typeof w.getDerivedStateFromError!="function"?null:z.render(),y.flags|=1,m!==null&&I?(y.child=ym(y,m.child,null,O),y.child=ym(y,null,w,O)):Zi(m,y,w,O),y.memoizedState=z.state,m=y.child):m=ha(m,y,O),m}function WF(m,y,w,I){return ut(),y.flags|=256,Zi(m,y,w,I),y.child}function jT(m){return{baseLanes:m,cachePool:zf()}}function BT(m,y,w){return m=m!==null?m.childLanes&~w:0,y&&(m|=ws),m}function HF(m,y,w){var I=y.pendingProps,O=!1,z=(y.flags&128)!==0,K;if((K=z)||(K=m!==null&&m.memoizedState===null?!1:(Pi.current&2)!==0),K&&(O=!0,y.flags&=-129),K=(y.flags&32)!==0,y.flags&=-33,m===null){if(_n){if(O?bc(y):vc(y),_n){var ct=Si,xt;(xt=ct)&&(ct=fht(ct,Co),ct!==null?(y.memoizedState={dehydrated:ct,treeContext:bh!==null?{id:_a,overflow:ya}:null,retryLane:536870912,hydrationErrors:null},xt=e(18,null,null,0),xt.stateNode=ct,xt.return=y,y.child=xt,Sr=y,Si=null,xt=!0):xt=!1),xt||ot(y)}if(ct=y.memoizedState,ct!==null&&(ct=ct.dehydrated,ct!==null))return SE(ct)?y.lanes=32:y.lanes=536870912,null;pa(y)}return ct=I.children,I=I.fallback,O?(vc(y),O=y.mode,ct=ox({mode:"hidden",children:ct},O),I=yh(I,O,w,null),ct.return=y,I.return=y,ct.sibling=I,y.child=ct,O=y.child,O.memoizedState=jT(w),O.childLanes=BT(m,K,w),y.memoizedState=zE,I):(bc(y),YT(y,ct))}if(xt=m.memoizedState,xt!==null&&(ct=xt.dehydrated,ct!==null)){if(z)y.flags&256?(bc(y),y.flags&=-257,y=XT(m,y,w)):y.memoizedState!==null?(vc(y),y.child=m.child,y.flags|=128,y=null):(vc(y),O=I.fallback,ct=y.mode,I=ox({mode:"visible",children:I.children},ct),O=yh(O,ct,w,null),O.flags|=2,I.return=y,O.return=y,I.sibling=O,y.child=I,ym(y,m.child,null,w),I=y.child,I.memoizedState=jT(w),I.childLanes=BT(m,K,w),y.memoizedState=zE,y=O);else if(bc(y),SE(ct))K=iht(ct).digest,I=Error(i(419)),I.stack="",I.digest=K,Z({value:I,source:null,stack:null}),y=XT(m,y,w);else if(Ai||Se(m,y,w,!1),K=(w&m.childLanes)!==0,Ai||K){if(K=Rn,K!==null&&(I=w&-w,I=(I&42)!==0?1:R(I),I=(I&(K.suspendedLanes|w))!==0?0:I,I!==0&&I!==xt.retryLane))throw xt.retryLane=I,To(m,I),ts(K,m,I),kz;wE(ct)||aE(),y=XT(m,y,w)}else wE(ct)?(y.flags|=192,y.child=m.child,y=null):(m=xt.treeContext,ys&&(Si=uht(ct),Sr=y,_n=!0,vh=null,Co=!1,m!==null&&(gs[xs++]=_a,gs[xs++]=ya,gs[xs++]=bh,_a=m.id,ya=m.overflow,bh=y)),y=YT(y,I.children),y.flags|=4096);return y}return O?(vc(y),O=I.fallback,ct=y.mode,xt=m.child,z=xt.sibling,I=da(xt,{mode:"hidden",children:I.children}),I.subtreeFlags=xt.subtreeFlags&65011712,z!==null?O=da(z,O):(O=yh(O,ct,w,null),O.flags|=2),O.return=y,I.return=y,I.sibling=O,y.child=I,I=O,O=y.child,ct=m.child.memoizedState,ct===null?ct=jT(w):(xt=ct.cachePool,xt!==null?(z=fa?ei._currentValue:ei._currentValue2,xt=xt.parent!==z?{parent:z,pool:z}:xt):xt=zf(),ct={baseLanes:ct.baseLanes|w,cachePool:xt}),O.memoizedState=ct,O.childLanes=BT(m,K,w),y.memoizedState=zE,I):(bc(y),w=m.child,m=w.sibling,w=da(w,{mode:"visible",children:I.children}),w.return=y,w.sibling=null,m!==null&&(K=y.deletions,K===null?(y.deletions=[m],y.flags|=16):K.push(m)),y.child=w,y.memoizedState=null,w)}function YT(m,y){return y=ox({mode:"visible",children:y},m.mode),y.return=m,m.child=y}function ox(m,y){return m=e(22,m,null,y),m.lanes=0,m.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null},m}function XT(m,y,w){return ym(y,m.child,null,w),m=YT(y,y.pendingProps.children),m.flags|=2,y.memoizedState=null,m}function qF(m,y,w){m.lanes|=y;var I=m.alternate;I!==null&&(I.lanes|=y),Ot(m.return,y,w)}function UT(m,y,w,I,O){var z=m.memoizedState;z===null?m.memoizedState={isBackwards:y,rendering:null,renderingStartTime:0,last:I,tail:w,tailMode:O}:(z.isBackwards=y,z.rendering=null,z.renderingStartTime=0,z.last=I,z.tail=w,z.tailMode=O)}function ZF(m,y,w){var I=y.pendingProps,O=I.revealOrder,z=I.tail;if(Zi(m,y,I.children,w),I=Pi.current,(I&2)!==0)I=I&1|2,y.flags|=128;else{if(m!==null&&(m.flags&128)!==0)t:for(m=y.child;m!==null;){if(m.tag===13)m.memoizedState!==null&&qF(m,w,y);else if(m.tag===19)qF(m,w,y);else if(m.child!==null){m.child.return=m,m=m.child;continue}if(m===y)break t;for(;m.sibling===null;){if(m.return===null||m.return===y)break t;m=m.return}m.sibling.return=m.return,m=m.sibling}I&=1}switch(_(Pi,I),O){case"forwards":for(w=y.child,O=null;w!==null;)m=w.alternate,m!==null&&ix(m)===null&&(O=w),w=w.sibling;w=O,w===null?(O=y.child,y.child=null):(O=w.sibling,w.sibling=null),UT(y,!1,O,w,z);break;case"backwards":for(w=null,O=y.child,y.child=null;O!==null;){if(m=O.alternate,m!==null&&ix(m)===null){y.child=O;break}m=O.sibling,O.sibling=w,w=O,O=m}UT(y,!0,w,null,z);break;case"together":UT(y,!1,null,null,void 0);break;default:y.memoizedState=null}return y.child}function ha(m,y,w){if(m!==null&&(y.dependencies=m.dependencies),Rc|=y.lanes,(w&y.childLanes)===0)if(m!==null){if(Se(m,y,w,!1),(w&y.childLanes)===0)return null}else return null;if(m!==null&&y.child!==m.child)throw Error(i(153));if(y.child!==null){for(m=y.child,w=da(m,m.pendingProps),y.child=w,w.return=y;m.sibling!==null;)m=m.sibling,w=w.sibling=da(m,m.pendingProps),w.return=y;w.sibling=null}return y.child}function VT(m,y){return(m.lanes&y)!==0?!0:(m=m.dependencies,!!(m!==null&&Kt(m)))}function qut(m,y,w){switch(y.tag){case 3:ht(y,y.stateNode.containerInfo),Et(y,ei,m.memoizedState.cache),ut();break;case 27:case 5:St(y);break;case 4:ht(y,y.stateNode.containerInfo);break;case 10:Et(y,y.type,y.memoizedProps.value);break;case 13:var I=y.memoizedState;if(I!==null)return I.dehydrated!==null?(bc(y),y.flags|=128,null):(w&y.child.childLanes)!==0?HF(m,y,w):(bc(y),m=ha(m,y,w),m!==null?m.sibling:null);bc(y);break;case 19:var O=(m.flags&128)!==0;if(I=(w&y.childLanes)!==0,I||(Se(m,y,w,!1),I=(w&y.childLanes)!==0),O){if(I)return ZF(m,y,w);y.flags|=128}if(O=y.memoizedState,O!==null&&(O.rendering=null,O.tail=null,O.lastEffect=null),_(Pi,Pi.current),I)break;return null;case 22:case 23:return y.lanes=0,XF(m,y,w);case 24:Et(y,ei,m.memoizedState.cache)}return ha(m,y,w)}function KF(m,y,w){if(m!==null)if(m.memoizedProps!==y.pendingProps)Ai=!0;else{if(!VT(m,w)&&(y.flags&128)===0)return Ai=!1,qut(m,y,w);Ai=(m.flags&131072)!==0}else Ai=!1,_n&&(y.flags&1048576)!==0&&G(y,xx,y.index);switch(y.lanes=0,y.tag){case 16:t:{m=y.pendingProps;var I=y.elementType,O=I._init;if(I=O(I._payload),y.type=I,typeof I=="function")uE(I)?(m=fh(I,m),y.tag=1,y=GF(null,y,I,m,w)):(y.tag=0,y=DT(null,y,I,m,w));else{if(I!=null){if(O=I.$$typeof,O===_E){y.tag=11,y=jF(null,y,I,m,w);break t}else if(O===xE){y.tag=14,y=BF(null,y,I,m,w);break t}}throw y=u(I)||I,Error(i(306,y,""))}}return y;case 0:return DT(m,y,y.type,y.pendingProps,w);case 1:return I=y.type,O=fh(I,y.pendingProps),GF(m,y,I,O,w);case 3:t:{if(ht(y,y.stateNode.containerInfo),m===null)throw Error(i(387));var z=y.pendingProps;O=y.memoizedState,I=O.element,ah(m,y),ua(y,z,null,w);var K=y.memoizedState;if(z=K.cache,Et(y,ei,z),z!==O.cache&&Ie(y,[ei],w,!0),la(),z=K.element,ys&&O.isDehydrated)if(O={element:z,isDehydrated:!1,cache:K.cache},y.updateQueue.baseState=O,y.memoizedState=O,y.flags&256){y=WF(m,y,z,w);break t}else if(z!==I){I=nt(Error(i(424)),y),Z(I),y=WF(m,y,z,w);break t}else for(ys&&(Si=lht(y.stateNode.containerInfo),Sr=y,_n=!0,vh=null,Co=!0),w=Sz(y,null,z,w),y.child=w;w;)w.flags=w.flags&-3|4096,w=w.sibling;else{if(ut(),z===I){y=ha(m,y,w);break t}Zi(m,y,z,w)}y=y.child}return y;case 26:if(qs)return sx(m,y),m===null?(w=cz(y.type,null,y.pendingProps,null))?y.memoizedState=w:_n||(y.stateNode=Tht(y.type,y.pendingProps,Cc.current,y)):y.memoizedState=cz(y.type,m.memoizedProps,y.pendingProps,m.memoizedState),null;case 27:if(wi)return St(y),m===null&&wi&&_n&&(I=y.stateNode=fz(y.type,y.pendingProps,Cc.current,Ki.current,!1),Sr=y,Co=!0,Si=pht(y.type,I,Si)),Zi(m,y,y.pendingProps.children,w),sx(m,y),m===null&&(y.flags|=4194304),y.child;case 5:return m===null&&_n&&(Sht(y.type,y.pendingProps,Ki.current),(O=I=Si)&&(I=hht(I,y.type,y.pendingProps,Co),I!==null?(y.stateNode=I,Sr=y,Si=cht(I),Co=!1,O=!0):O=!1),O||ot(y)),St(y),O=y.type,z=y.pendingProps,K=m!==null?m.memoizedProps:null,I=z.children,fx(O,z)?I=null:K!==null&&fx(O,K)&&(y.flags|=32),y.memoizedState!==null&&(O=hh(m,y,IT,null,null,w),fa?xh._currentValue=O:xh._currentValue2=O),sx(m,y),Zi(m,y,I,w),y.child;case 6:return m===null&&_n&&(Pht(y.pendingProps,Ki.current),(m=w=Si)&&(w=dht(w,y.pendingProps,Co),w!==null?(y.stateNode=w,Sr=y,Si=null,m=!0):m=!1),m||ot(y)),null;case 13:return HF(m,y,w);case 4:return ht(y,y.stateNode.containerInfo),I=y.pendingProps,m===null?y.child=ym(y,null,I,w):Zi(m,y,I,w),y.child;case 11:return jF(m,y,y.type,y.pendingProps,w);case 7:return Zi(m,y,y.pendingProps,w),y.child;case 8:return Zi(m,y,y.pendingProps.children,w),y.child;case 12:return Zi(m,y,y.pendingProps.children,w),y.child;case 10:return I=y.pendingProps,Et(y,y.type,I.value),Zi(m,y,I.children,w),y.child;case 9:return O=y.type._context,I=y.pendingProps.children,le(y),O=Jt(O),I=I(O),y.flags|=1,Zi(m,y,I,w),y.child;case 14:return BF(m,y,y.type,y.pendingProps,w);case 15:return YF(m,y,y.type,y.pendingProps,w);case 19:return ZF(m,y,w);case 31:return I=y.pendingProps,w=y.mode,I={mode:I.mode,children:I.children},m===null?(w=ox(I,w),w.ref=y.ref,y.child=w,w.return=y,y=w):(w=da(m.child,I),w.ref=y.ref,y.child=w,w.return=y,y=w),y;case 22:return XF(m,y,w);case 24:return le(y),I=Jt(ei),m===null?(O=rh(),O===null&&(O=Rn,z=Nr(),O.pooledCache=z,z.refCount++,z!==null&&(O.pooledCacheLanes|=w),O=z),y.memoizedState={parent:I,cache:O},oh(y),Et(y,ei,O)):((m.lanes&w)!==0&&(ah(m,y),ua(y,null,null,w),la()),O=m.memoizedState,z=y.memoizedState,O.parent!==I?(O={parent:I,cache:I},y.memoizedState=O,y.lanes===0&&(y.memoizedState=y.updateQueue.baseState=O),Et(y,ei,I)):(I=z.cache,Et(y,ei,I),I!==O.cache&&Ie(y,[ei],w,!0))),Zi(m,y,y.pendingProps.children,w),y.child;case 29:throw y.pendingProps}throw Error(i(156,y.tag))}function Jr(m){m.flags|=4}function JF(m,y){if(m!==null&&m.child===y.child)return!1;if((y.flags&16)!==0)return!0;for(m=y.child;m!==null;){if((m.flags&13878)!==0||(m.subtreeFlags&13878)!==0)return!0;m=m.sibling}return!1}function GT(m,y,w,I){if(lr)for(w=y.child;w!==null;){if(w.tag===5||w.tag===6)vE(m,w.stateNode);else if(!(w.tag===4||wi&&w.tag===27)&&w.child!==null){w.child.return=w,w=w.child;continue}if(w===y)break;for(;w.sibling===null;){if(w.return===null||w.return===y)return;w=w.return}w.sibling.return=w.return,w=w.sibling}else if(Mc)for(var O=y.child;O!==null;){if(O.tag===5){var z=O.stateNode;w&&I&&(z=iz(z,O.type,O.memoizedProps)),vE(m,z)}else if(O.tag===6)z=O.stateNode,w&&I&&(z=rz(z,O.memoizedProps)),vE(m,z);else if(O.tag!==4){if(O.tag===22&&O.memoizedState!==null)z=O.child,z!==null&&(z.return=O),GT(m,O,!0,!0);else if(O.child!==null){O.child.return=O,O=O.child;continue}}if(O===y)break;for(;O.sibling===null;){if(O.return===null||O.return===y)return;O=O.return}O.sibling.return=O.return,O=O.sibling}}function QF(m,y,w,I){var O=!1;if(Mc)for(var z=y.child;z!==null;){if(z.tag===5){var K=z.stateNode;w&&I&&(K=iz(K,z.type,z.memoizedProps)),ez(m,K)}else if(z.tag===6)K=z.stateNode,w&&I&&(K=rz(K,z.memoizedProps)),ez(m,K);else if(z.tag!==4){if(z.tag===22&&z.memoizedState!==null)O=z.child,O!==null&&(O.return=z),QF(m,z,!0,!0),O=!0;else if(z.child!==null){z.child.return=z,z=z.child;continue}}if(z===y)break;for(;z.sibling===null;){if(z.return===null||z.return===y)return O;z=z.return}z.sibling.return=z.return,z=z.sibling}return O}function t$(m,y){if(Mc&&JF(m,y)){m=y.stateNode;var w=m.containerInfo,I=tz();QF(I,y,!1,!1),m.pendingChildren=I,Jr(y),nht(w,I)}}function WT(m,y,w,I){if(lr)m.memoizedProps!==I&&Jr(y);else if(Mc){var O=m.stateNode,z=m.memoizedProps;if((m=JF(m,y))||z!==I){var K=Ki.current;z=eht(O,w,z,I,!m,null),z===O?y.stateNode=O:(q$(z,w,I,K)&&Jr(y),y.stateNode=z,m?GT(z,y,!1,!1):Jr(y))}else y.stateNode=O}}function HT(m,y,w){if(Cpt(y,w)){if(m.flags|=16777216,!K$(y,w))if(k$())m.flags|=8192;else throw pm=kx,OE}else m.flags&=-16777217}function e$(m,y){if(Mht(y)){if(m.flags|=16777216,!dz(y))if(k$())m.flags|=8192;else throw pm=kx,OE}else m.flags&=-16777217}function ax(m,y){y!==null&&(m.flags|=4),m.flags&16384&&(y=m.tag!==22?k():536870912,m.lanes|=y,bm|=y)}function zy(m,y){if(!_n)switch(m.tailMode){case"hidden":y=m.tail;for(var w=null;y!==null;)y.alternate!==null&&(w=y),y=y.sibling;w===null?m.tail=null:w.sibling=null;break;case"collapsed":w=m.tail;for(var I=null;w!==null;)w.alternate!==null&&(I=w),w=w.sibling;I===null?y||m.tail===null?m.tail=null:m.tail.sibling=null:I.sibling=null}}function Zn(m){var y=m.alternate!==null&&m.alternate.child===m.child,w=0,I=0;if(y)for(var O=m.child;O!==null;)w|=O.lanes|O.childLanes,I|=O.subtreeFlags&65011712,I|=O.flags&65011712,O.return=m,O=O.sibling;else for(O=m.child;O!==null;)w|=O.lanes|O.childLanes,I|=O.subtreeFlags,I|=O.flags,O.return=m,O=O.sibling;return m.subtreeFlags|=I,m.childLanes=w,y}function Zut(m,y,w){var I=y.pendingProps;switch(J(y),y.tag){case 31:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Zn(y),null;case 1:return Zn(y),null;case 3:return w=y.stateNode,I=null,m!==null&&(I=m.memoizedState.cache),y.memoizedState.cache!==I&&(y.flags|=2048),Ft(ei),pt(),w.pendingContext&&(w.context=w.pendingContext,w.pendingContext=null),(m===null||m.child===null)&&(it(y)?Jr(y):m===null||m.memoizedState.isDehydrated&&(y.flags&256)===0||(y.flags|=1024,yt())),t$(m,y),Zn(y),null;case 26:if(qs){w=y.type;var O=y.memoizedState;return m===null?(Jr(y),O!==null?(Zn(y),e$(y,O)):(Zn(y),HT(y,w,I))):O?O!==m.memoizedState?(Jr(y),Zn(y),e$(y,O)):(Zn(y),y.flags&=-16777217):(lr?m.memoizedProps!==I&&Jr(y):WT(m,y,w,I),Zn(y),HT(y,w,I)),null}case 27:if(wi){if(Mt(y),w=Cc.current,O=y.type,m!==null&&y.stateNode!=null)lr?m.memoizedProps!==I&&Jr(y):WT(m,y,O,I);else{if(!I){if(y.stateNode===null)throw Error(i(166));return Zn(y),null}m=Ki.current,it(y)?Y(y,m):(m=fz(O,I,w,m,!0),y.stateNode=m,Jr(y))}return Zn(y),null}case 5:if(Mt(y),w=y.type,m!==null&&y.stateNode!=null)WT(m,y,w,I);else{if(!I){if(y.stateNode===null)throw Error(i(166));return Zn(y),null}m=Ki.current,it(y)?Y(y,m):(O=vpt(w,I,Cc.current,m,y),GT(O,y,!1,!1),y.stateNode=O,q$(O,w,I,m)&&Jr(y))}return Zn(y),HT(y,y.type,y.pendingProps),null;case 6:if(m&&y.stateNode!=null)w=m.memoizedProps,lr?w!==I&&Jr(y):Mc&&(w!==I?(y.stateNode=Z$(I,Cc.current,Ki.current,y),Jr(y)):y.stateNode=m.stateNode);else{if(typeof I!="string"&&y.stateNode===null)throw Error(i(166));if(m=Cc.current,w=Ki.current,it(y)){if(!ys)throw Error(i(176));if(m=y.stateNode,w=y.memoizedProps,I=null,O=Sr,O!==null)switch(O.tag){case 27:case 5:I=O.memoizedProps}_ht(m,w,y,I)||ot(y)}else y.stateNode=Z$(I,m,w,y)}return Zn(y),null;case 13:if(I=y.memoizedState,m===null||m.memoizedState!==null&&m.memoizedState.dehydrated!==null){if(O=it(y),I!==null&&I.dehydrated!==null){if(m===null){if(!O)throw Error(i(318));if(!ys)throw Error(i(344));if(O=y.memoizedState,O=O!==null?O.dehydrated:null,!O)throw Error(i(317));yht(O,y)}else ut(),(y.flags&128)===0&&(y.memoizedState=null),y.flags|=4;Zn(y),O=!1}else O=yt(),m!==null&&m.memoizedState!==null&&(m.memoizedState.hydrationErrors=O),O=!0;if(!O)return y.flags&256?(pa(y),y):(pa(y),null)}if(pa(y),(y.flags&128)!==0)return y.lanes=w,y;if(w=I!==null,m=m!==null&&m.memoizedState!==null,w){I=y.child,O=null,I.alternate!==null&&I.alternate.memoizedState!==null&&I.alternate.memoizedState.cachePool!==null&&(O=I.alternate.memoizedState.cachePool.pool);var z=null;I.memoizedState!==null&&I.memoizedState.cachePool!==null&&(z=I.memoizedState.cachePool.pool),z!==O&&(I.flags|=2048)}return w!==m&&w&&(y.child.flags|=8192),ax(y,y.updateQueue),Zn(y),null;case 4:return pt(),t$(m,y),m===null&&kpt(y.stateNode.containerInfo),Zn(y),null;case 10:return Ft(y.type),Zn(y),null;case 19:if(d(Pi),O=y.memoizedState,O===null)return Zn(y),null;if(I=(y.flags&128)!==0,z=O.rendering,z===null)if(I)zy(O,!1);else{if(ni!==0||m!==null&&(m.flags&128)!==0)for(m=y.child;m!==null;){if(z=ix(m),z!==null){for(y.flags|=128,zy(O,!1),m=z.updateQueue,y.updateQueue=m,ax(y,m),y.subtreeFlags=0,m=w,w=y.child;w!==null;)D$(w,m),w=w.sibling;return _(Pi,Pi.current&1|2),y.child}m=m.sibling}O.tail!==null&&Zs()>eg&&(y.flags|=128,I=!0,zy(O,!1),y.lanes=4194304)}else{if(!I)if(m=ix(z),m!==null){if(y.flags|=128,I=!0,m=m.updateQueue,y.updateQueue=m,ax(y,m),zy(O,!0),O.tail===null&&O.tailMode==="hidden"&&!z.alternate&&!_n)return Zn(y),null}else 2*Zs()-O.renderingStartTime>eg&&w!==536870912&&(y.flags|=128,I=!0,zy(O,!1),y.lanes=4194304);O.isBackwards?(z.sibling=y.child,y.child=z):(m=O.last,m!==null?m.sibling=z:y.child=z,O.last=z)}return O.tail!==null?(y=O.tail,O.rendering=y,O.tail=y.sibling,O.renderingStartTime=Zs(),y.sibling=null,m=Pi.current,_(Pi,I?m&1|2:m&1),y):(Zn(y),null);case 22:case 23:return pa(y),uh(),I=y.memoizedState!==null,m!==null?m.memoizedState!==null!==I&&(y.flags|=8192):I&&(y.flags|=8192),I?(w&536870912)!==0&&(y.flags&128)===0&&(Zn(y),y.subtreeFlags&6&&(y.flags|=8192)):Zn(y),w=y.updateQueue,w!==null&&ax(y,w.retryQueue),w=null,m!==null&&m.memoizedState!==null&&m.memoizedState.cachePool!==null&&(w=m.memoizedState.cachePool.pool),I=null,y.memoizedState!==null&&y.memoizedState.cachePool!==null&&(I=y.memoizedState.cachePool.pool),I!==w&&(y.flags|=2048),m!==null&&d(Sh),null;case 24:return w=null,m!==null&&(w=m.memoizedState.cache),y.memoizedState.cache!==w&&(y.flags|=2048),Ft(ei),Zn(y),null;case 25:return null;case 30:return null}throw Error(i(156,y.tag))}function Kut(m,y){switch(J(y),y.tag){case 1:return m=y.flags,m&65536?(y.flags=m&-65537|128,y):null;case 3:return Ft(ei),pt(),m=y.flags,(m&65536)!==0&&(m&128)===0?(y.flags=m&-65537|128,y):null;case 26:case 27:case 5:return Mt(y),null;case 13:if(pa(y),m=y.memoizedState,m!==null&&m.dehydrated!==null){if(y.alternate===null)throw Error(i(340));ut()}return m=y.flags,m&65536?(y.flags=m&-65537|128,y):null;case 19:return d(Pi),null;case 4:return pt(),null;case 10:return Ft(y.type),null;case 22:case 23:return pa(y),uh(),m!==null&&d(Sh),m=y.flags,m&65536?(y.flags=m&-65537|128,y):null;case 24:return Ft(ei),null;case 25:return null;default:return null}}function n$(m,y){switch(J(y),y.tag){case 3:Ft(ei),pt();break;case 26:case 27:case 5:Mt(y);break;case 4:pt();break;case 13:pa(y);break;case 19:d(Pi);break;case 10:Ft(y.type);break;case 22:case 23:pa(y),uh(),m!==null&&d(Sh);break;case 24:Ft(ei)}}function Dy(m,y){try{var w=y.updateQueue,I=w!==null?w.lastEffect:null;if(I!==null){var O=I.next;w=O;do{if((w.tag&m)===m){I=void 0;var z=w.create,K=w.inst;I=z(),K.destroy=I}w=w.next}while(w!==O)}}catch(ct){xn(y,y.return,ct)}}function wc(m,y,w){try{var I=y.updateQueue,O=I!==null?I.lastEffect:null;if(O!==null){var z=O.next;I=z;do{if((I.tag&m)===m){var K=I.inst,ct=K.destroy;if(ct!==void 0){K.destroy=void 0,O=y;var xt=w,It=ct;try{It()}catch(zt){xn(O,xt,zt)}}}I=I.next}while(I!==z)}}catch(zt){xn(y,y.return,zt)}}function i$(m){var y=m.updateQueue;if(y!==null){var w=m.stateNode;try{Vf(y,w)}catch(I){xn(m,m.return,I)}}}function r$(m,y,w){w.props=fh(m.type,m.memoizedProps),w.state=m.memoizedState;try{w.componentWillUnmount()}catch(I){xn(m,y,I)}}function jy(m,y){try{var w=m.ref;if(w!==null){switch(m.tag){case 26:case 27:case 5:var I=Uy(m.stateNode);break;case 30:I=m.stateNode;break;default:I=m.stateNode}typeof w=="function"?m.refCleanup=w(I):w.current=I}}catch(O){xn(m,y,O)}}function Eo(m,y){var w=m.ref,I=m.refCleanup;if(w!==null)if(typeof I=="function")try{I()}catch(O){xn(m,y,O)}finally{m.refCleanup=null,m=m.alternate,m!=null&&(m.refCleanup=null)}else if(typeof w=="function")try{w(null)}catch(O){xn(m,y,O)}else w.current=null}function s$(m){var y=m.type,w=m.memoizedProps,I=m.stateNode;try{Upt(I,y,w,m)}catch(O){xn(m,m.return,O)}}function qT(m,y,w){try{Vpt(m.stateNode,m.type,w,y,m)}catch(I){xn(m,m.return,I)}}function o$(m){return m.tag===5||m.tag===3||(qs?m.tag===26:!1)||(wi?m.tag===27&&nm(m.type):!1)||m.tag===4}function ZT(m){t:for(;;){for(;m.sibling===null;){if(m.return===null||o$(m.return))return null;m=m.return}for(m.sibling.return=m.return,m=m.sibling;m.tag!==5&&m.tag!==6&&m.tag!==18;){if(wi&&m.tag===27&&nm(m.type)||m.flags&2||m.child===null||m.tag===4)continue t;m.child.return=m,m=m.child}if(!(m.flags&2))return m.stateNode}}function KT(m,y,w){var I=m.tag;if(I===5||I===6)m=m.stateNode,y?Wpt(w,m,y):Ypt(w,m);else if(I!==4&&(wi&&I===27&&nm(m.type)&&(w=m.stateNode,y=null),m=m.child,m!==null))for(KT(m,y,w),m=m.sibling;m!==null;)KT(m,y,w),m=m.sibling}function cx(m,y,w){var I=m.tag;if(I===5||I===6)m=m.stateNode,y?Gpt(w,m,y):Bpt(w,m);else if(I!==4&&(wi&&I===27&&nm(m.type)&&(w=m.stateNode),m=m.child,m!==null))for(cx(m,y,w),m=m.sibling;m!==null;)cx(m,y,w),m=m.sibling}function a$(m,y,w){m=m.containerInfo;try{nz(m,w)}catch(I){xn(y,y.return,I)}}function c$(m){var y=m.stateNode,w=m.memoizedProps;try{Iht(m.type,w,y,m)}catch(I){xn(m,m.return,I)}}function Jut(m,y){for(xpt(m.containerInfo),Ri=y;Ri!==null;)if(m=Ri,y=m.child,(m.subtreeFlags&1024)!==0&&y!==null)y.return=m,Ri=y;else for(;Ri!==null;){m=Ri;var w=m.alternate;switch(y=m.flags,m.tag){case 0:break;case 11:case 15:break;case 1:if((y&1024)!==0&&w!==null){y=void 0;var I=m,O=w.memoizedProps;w=w.memoizedState;var z=I.stateNode;try{var K=fh(I.type,O,I.elementType===I.type);y=z.getSnapshotBeforeUpdate(K,w),z.__reactInternalSnapshotBeforeUpdate=y}catch(ct){xn(I,I.return,ct)}}break;case 3:(y&1024)!==0&&lr&&tht(m.stateNode.containerInfo);break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((y&1024)!==0)throw Error(i(163))}if(y=m.sibling,y!==null){y.return=m.return,Ri=y;break}Ri=m.return}}function l$(m,y,w){var I=w.flags;switch(w.tag){case 0:case 11:case 15:Sc(m,w),I&4&&Dy(5,w);break;case 1:if(Sc(m,w),I&4)if(m=w.stateNode,y===null)try{m.componentDidMount()}catch(K){xn(w,w.return,K)}else{var O=fh(w.type,y.memoizedProps);y=y.memoizedState;try{m.componentDidUpdate(O,y,m.__reactInternalSnapshotBeforeUpdate)}catch(K){xn(w,w.return,K)}}I&64&&i$(w),I&512&&jy(w,w.return);break;case 3:if(Sc(m,w),I&64&&(m=w.updateQueue,m!==null)){if(y=null,w.child!==null)switch(w.child.tag){case 27:case 5:y=Uy(w.child.stateNode);break;case 1:y=w.child.stateNode}try{Vf(m,y)}catch(K){xn(w,w.return,K)}}break;case 27:wi&&y===null&&I&4&&c$(w);case 26:case 5:Sc(m,w),y===null&&I&4&&s$(w),I&512&&jy(w,w.return);break;case 12:Sc(m,w);break;case 13:Sc(m,w),I&4&&p$(m,w),I&64&&(m=w.memoizedState,m!==null&&(m=m.dehydrated,m!==null&&(w=spt.bind(null,w),rht(m,w))));break;case 22:if(I=w.memoizedState!==null||xa,!I){y=y!==null&&y.memoizedState!==null||hi,O=xa;var z=hi;xa=I,(hi=y)&&!z?Pc(m,w,(w.subtreeFlags&8772)!==0):Sc(m,w),xa=O,hi=z}break;case 30:break;default:Sc(m,w)}}function u$(m){var y=m.alternate;y!==null&&(m.alternate=null,u$(y)),m.child=null,m.deletions=null,m.sibling=null,m.tag===5&&(y=m.stateNode,y!==null&&Mpt(y)),m.stateNode=null,m.return=null,m.dependencies=null,m.memoizedProps=null,m.memoizedState=null,m.pendingProps=null,m.stateNode=null,m.updateQueue=null}function Hs(m,y,w){for(w=w.child;w!==null;)JT(m,y,w),w=w.sibling}function JT(m,y,w){if(is&&typeof is.onCommitFiberUnmount=="function")try{is.onCommitFiberUnmount(Wy,w)}catch{}switch(w.tag){case 26:if(qs){hi||Eo(w,y),Hs(m,y,w),w.memoizedState?uz(w.memoizedState):w.stateNode&&hz(w.stateNode);break}case 27:if(wi){hi||Eo(w,y);var I=_i,O=Or;nm(w.type)&&(_i=w.stateNode,Or=!1),Hs(m,y,w),mz(w.stateNode),_i=I,Or=O;break}case 5:hi||Eo(w,y);case 6:if(lr){if(I=_i,O=Or,_i=null,Hs(m,y,w),_i=I,Or=O,_i!==null)if(Or)try{qpt(_i,w.stateNode)}catch(z){xn(w,y,z)}else try{Hpt(_i,w.stateNode)}catch(z){xn(w,y,z)}}else Hs(m,y,w);break;case 18:lr&&_i!==null&&(Or?wht(_i,w.stateNode):vht(_i,w.stateNode));break;case 4:lr?(I=_i,O=Or,_i=w.stateNode.containerInfo,Or=!0,Hs(m,y,w),_i=I,Or=O):(Mc&&a$(w.stateNode,w,tz()),Hs(m,y,w));break;case 0:case 11:case 14:case 15:hi||wc(2,w,y),hi||wc(4,w,y),Hs(m,y,w);break;case 1:hi||(Eo(w,y),I=w.stateNode,typeof I.componentWillUnmount=="function"&&r$(w,y,I)),Hs(m,y,w);break;case 21:Hs(m,y,w);break;case 22:hi=(I=hi)||w.memoizedState!==null,Hs(m,y,w),hi=I;break;default:Hs(m,y,w)}}function p$(m,y){if(ys&&y.memoizedState===null&&(m=y.alternate,m!==null&&(m=m.memoizedState,m!==null&&(m=m.dehydrated,m!==null))))try{bht(m)}catch(w){xn(y,y.return,w)}}function Qut(m){switch(m.tag){case 13:case 19:var y=m.stateNode;return y===null&&(y=m.stateNode=new Tz),y;case 22:return m=m.stateNode,y=m._retryCache,y===null&&(y=m._retryCache=new Tz),y;default:throw Error(i(435,m.tag))}}function QT(m,y){var w=Qut(m);y.forEach(function(I){var O=opt.bind(null,m,I);w.has(I)||(w.add(I),I.then(O,O))})}function wr(m,y){var w=y.deletions;if(w!==null)for(var I=0;I<w.length;I++){var O=w[I],z=m,K=y;if(lr){var ct=K;t:for(;ct!==null;){switch(ct.tag){case 27:if(wi){if(nm(ct.type)){_i=ct.stateNode,Or=!1;break t}break}case 5:_i=ct.stateNode,Or=!1;break t;case 3:case 4:_i=ct.stateNode.containerInfo,Or=!0;break t}ct=ct.return}if(_i===null)throw Error(i(160));JT(z,K,O),_i=null,Or=!1}else JT(z,K,O);z=O.alternate,z!==null&&(z.return=null),O.return=null}if(y.subtreeFlags&13878)for(y=y.child;y!==null;)h$(y,m),y=y.sibling}function h$(m,y){var w=m.alternate,I=m.flags;switch(m.tag){case 0:case 11:case 14:case 15:wr(y,m),Rr(m),I&4&&(wc(3,m,m.return),Dy(3,m),wc(5,m,m.return));break;case 1:wr(y,m),Rr(m),I&512&&(hi||w===null||Eo(w,w.return)),I&64&&xa&&(m=m.updateQueue,m!==null&&(I=m.callbacks,I!==null&&(w=m.shared.hiddenCallbacks,m.shared.hiddenCallbacks=w===null?I:w.concat(I))));break;case 26:if(qs){var O=Ks;if(wr(y,m),Rr(m),I&512&&(hi||w===null||Eo(w,w.return)),I&4){I=w!==null?w.memoizedState:null;var z=m.memoizedState;w===null?z===null?m.stateNode===null?m.stateNode=kht(O,m.type,m.memoizedProps,m):pz(O,m.type,m.stateNode):m.stateNode=lz(O,z,m.memoizedProps):I!==z?(I===null?w.stateNode!==null&&hz(w.stateNode):uz(I),z===null?pz(O,m.type,m.stateNode):lz(O,z,m.memoizedProps)):z===null&&m.stateNode!==null&&qT(m,m.memoizedProps,w.memoizedProps)}break}case 27:if(wi){wr(y,m),Rr(m),I&512&&(hi||w===null||Eo(w,w.return)),w!==null&&I&4&&qT(m,m.memoizedProps,w.memoizedProps);break}case 5:if(wr(y,m),Rr(m),I&512&&(hi||w===null||Eo(w,w.return)),lr){if(m.flags&32){O=m.stateNode;try{Q$(O)}catch(zt){xn(m,m.return,zt)}}I&4&&m.stateNode!=null&&(O=m.memoizedProps,qT(m,O,w!==null?w.memoizedProps:O)),I&1024&&(DE=!0)}break;case 6:if(wr(y,m),Rr(m),I&4&&lr){if(m.stateNode===null)throw Error(i(162));I=m.memoizedProps,w=w!==null?w.memoizedProps:I,O=m.stateNode;try{Xpt(O,w,I)}catch(zt){xn(m,m.return,zt)}}break;case 3:if(qs?(Eht(),O=Ks,Ks=PE(y.containerInfo),wr(y,m),Ks=O):wr(y,m),Rr(m),I&4){if(lr&&ys&&w!==null&&w.memoizedState.isDehydrated)try{xht(y.containerInfo)}catch(zt){xn(m,m.return,zt)}if(Mc){I=y.containerInfo,w=y.pendingChildren;try{nz(I,w)}catch(zt){xn(m,m.return,zt)}}}DE&&(DE=!1,d$(m));break;case 4:qs?(w=Ks,Ks=PE(m.stateNode.containerInfo),wr(y,m),Rr(m),Ks=w):(wr(y,m),Rr(m)),I&4&&Mc&&a$(m.stateNode,m,m.stateNode.pendingChildren);break;case 12:wr(y,m),Rr(m);break;case 13:wr(y,m),Rr(m),m.child.flags&8192&&m.memoizedState!==null!=(w!==null&&w.memoizedState!==null)&&(XE=Zs()),I&4&&(I=m.updateQueue,I!==null&&(m.updateQueue=null,QT(m,I)));break;case 22:O=m.memoizedState!==null;var K=w!==null&&w.memoizedState!==null,ct=xa,xt=hi;if(xa=ct||O,hi=xt||K,wr(y,m),hi=xt,xa=ct,Rr(m),I&8192&&(y=m.stateNode,y._visibility=O?y._visibility&-2:y._visibility|1,O&&(w===null||K||xa||hi||mh(m)),lr)){t:if(w=null,lr)for(y=m;;){if(y.tag===5||qs&&y.tag===26){if(w===null){K=w=y;try{z=K.stateNode,O?Zpt(z):Jpt(K.stateNode,K.memoizedProps)}catch(zt){xn(K,K.return,zt)}}}else if(y.tag===6){if(w===null){K=y;try{var It=K.stateNode;O?Kpt(It):Qpt(It,K.memoizedProps)}catch(zt){xn(K,K.return,zt)}}}else if((y.tag!==22&&y.tag!==23||y.memoizedState===null||y===m)&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===m)break t;for(;y.sibling===null;){if(y.return===null||y.return===m)break t;w===y&&(w=null),y=y.return}w===y&&(w=null),y.sibling.return=y.return,y=y.sibling}}I&4&&(I=m.updateQueue,I!==null&&(w=I.retryQueue,w!==null&&(I.retryQueue=null,QT(m,w))));break;case 19:wr(y,m),Rr(m),I&4&&(I=m.updateQueue,I!==null&&(m.updateQueue=null,QT(m,I)));break;case 30:break;case 21:break;default:wr(y,m),Rr(m)}}function Rr(m){var y=m.flags;if(y&2){try{if(lr){for(var w,I=m.return;I!==null;){if(o$(I)){w=I;break}I=I.return}if(w==null)throw Error(i(160));switch(w.tag){case 27:if(wi){var O=w.stateNode,z=ZT(m);cx(m,z,O);break}case 5:var K=w.stateNode;w.flags&32&&(Q$(K),w.flags&=-33);var ct=ZT(m);cx(m,ct,K);break;case 3:case 4:var xt=w.stateNode.containerInfo,It=ZT(m);KT(m,It,xt);break;default:throw Error(i(161))}}}catch(zt){xn(m,m.return,zt)}m.flags&=-3}y&4096&&(m.flags&=-4097)}function d$(m){if(m.subtreeFlags&1024)for(m=m.child;m!==null;){var y=m;d$(y),y.tag===5&&y.flags&1024&&Apt(y.stateNode),m=m.sibling}}function Sc(m,y){if(y.subtreeFlags&8772)for(y=y.child;y!==null;)l$(m,y.alternate,y),y=y.sibling}function mh(m){for(m=m.child;m!==null;){var y=m;switch(y.tag){case 0:case 11:case 14:case 15:wc(4,y,y.return),mh(y);break;case 1:Eo(y,y.return);var w=y.stateNode;typeof w.componentWillUnmount=="function"&&r$(y,y.return,w),mh(y);break;case 27:wi&&mz(y.stateNode);case 26:case 5:Eo(y,y.return),mh(y);break;case 22:y.memoizedState===null&&mh(y);break;case 30:mh(y);break;default:mh(y)}m=m.sibling}}function Pc(m,y,w){for(w=w&&(y.subtreeFlags&8772)!==0,y=y.child;y!==null;){var I=y.alternate,O=m,z=y,K=z.flags;switch(z.tag){case 0:case 11:case 15:Pc(O,z,w),Dy(4,z);break;case 1:if(Pc(O,z,w),I=z,O=I.stateNode,typeof O.componentDidMount=="function")try{O.componentDidMount()}catch(It){xn(I,I.return,It)}if(I=z,O=I.updateQueue,O!==null){var ct=I.stateNode;try{var xt=O.shared.hiddenCallbacks;if(xt!==null)for(O.shared.hiddenCallbacks=null,O=0;O<xt.length;O++)Uf(xt[O],ct)}catch(It){xn(I,I.return,It)}}w&&K&64&&i$(z),jy(z,z.return);break;case 27:wi&&c$(z);case 26:case 5:Pc(O,z,w),w&&I===null&&K&4&&s$(z),jy(z,z.return);break;case 12:Pc(O,z,w);break;case 13:Pc(O,z,w),w&&K&4&&p$(O,z);break;case 22:z.memoizedState===null&&Pc(O,z,w),jy(z,z.return);break;case 30:break;default:Pc(O,z,w)}y=y.sibling}}function tE(m,y){var w=null;m!==null&&m.memoizedState!==null&&m.memoizedState.cachePool!==null&&(w=m.memoizedState.cachePool.pool),m=null,y.memoizedState!==null&&y.memoizedState.cachePool!==null&&(m=y.memoizedState.cachePool.pool),m!==w&&(m!=null&&m.refCount++,w!=null&&Gs(w))}function eE(m,y){m=null,y.alternate!==null&&(m=y.alternate.memoizedState.cache),y=y.memoizedState.cache,y!==m&&(y.refCount++,m!=null&&Gs(m))}function Mo(m,y,w,I){if(y.subtreeFlags&10256)for(y=y.child;y!==null;)f$(m,y,w,I),y=y.sibling}function f$(m,y,w,I){var O=y.flags;switch(y.tag){case 0:case 11:case 15:Mo(m,y,w,I),O&2048&&Dy(9,y);break;case 1:Mo(m,y,w,I);break;case 3:Mo(m,y,w,I),O&2048&&(m=null,y.alternate!==null&&(m=y.alternate.memoizedState.cache),y=y.memoizedState.cache,y!==m&&(y.refCount++,m!=null&&Gs(m)));break;case 12:if(O&2048){Mo(m,y,w,I),m=y.stateNode;try{var z=y.memoizedProps,K=z.id,ct=z.onPostCommit;typeof ct=="function"&&ct(K,y.alternate===null?"mount":"update",m.passiveEffectDuration,-0)}catch(xt){xn(y,y.return,xt)}}else Mo(m,y,w,I);break;case 13:Mo(m,y,w,I);break;case 23:break;case 22:z=y.stateNode,K=y.alternate,y.memoizedState!==null?z._visibility&2?Mo(m,y,w,I):By(m,y):z._visibility&2?Mo(m,y,w,I):(z._visibility|=2,Zf(m,y,w,I,(y.subtreeFlags&10256)!==0)),O&2048&&tE(K,y);break;case 24:Mo(m,y,w,I),O&2048&&eE(y.alternate,y);break;default:Mo(m,y,w,I)}}function Zf(m,y,w,I,O){for(O=O&&(y.subtreeFlags&10256)!==0,y=y.child;y!==null;){var z=m,K=y,ct=w,xt=I,It=K.flags;switch(K.tag){case 0:case 11:case 15:Zf(z,K,ct,xt,O),Dy(8,K);break;case 23:break;case 22:var zt=K.stateNode;K.memoizedState!==null?zt._visibility&2?Zf(z,K,ct,xt,O):By(z,K):(zt._visibility|=2,Zf(z,K,ct,xt,O)),O&&It&2048&&tE(K.alternate,K);break;case 24:Zf(z,K,ct,xt,O),O&&It&2048&&eE(K.alternate,K);break;default:Zf(z,K,ct,xt,O)}y=y.sibling}}function By(m,y){if(y.subtreeFlags&10256)for(y=y.child;y!==null;){var w=m,I=y,O=I.flags;switch(I.tag){case 22:By(w,I),O&2048&&tE(I.alternate,I);break;case 24:By(w,I),O&2048&&eE(I.alternate,I);break;default:By(w,I)}y=y.sibling}}function _h(m){if(m.subtreeFlags&gm)for(m=m.child;m!==null;)m$(m),m=m.sibling}function m$(m){switch(m.tag){case 26:_h(m),m.flags&gm&&(m.memoizedState!==null?Cht(Ks,m.memoizedState,m.memoizedProps):J$(m.type,m.memoizedProps));break;case 5:_h(m),m.flags&gm&&J$(m.type,m.memoizedProps);break;case 3:case 4:if(qs){var y=Ks;Ks=PE(m.stateNode.containerInfo),_h(m),Ks=y}else _h(m);break;case 22:m.memoizedState===null&&(y=m.alternate,y!==null&&y.memoizedState!==null?(y=gm,gm=16777216,_h(m),gm=y):_h(m));break;default:_h(m)}}function _$(m){var y=m.alternate;if(y!==null&&(m=y.child,m!==null)){y.child=null;do y=m.sibling,m.sibling=null,m=y;while(m!==null)}}function Yy(m){var y=m.deletions;if((m.flags&16)!==0){if(y!==null)for(var w=0;w<y.length;w++){var I=y[w];Ri=I,g$(I,m)}_$(m)}if(m.subtreeFlags&10256)for(m=m.child;m!==null;)y$(m),m=m.sibling}function y$(m){switch(m.tag){case 0:case 11:case 15:Yy(m),m.flags&2048&&wc(9,m,m.return);break;case 3:Yy(m);break;case 12:Yy(m);break;case 22:var y=m.stateNode;m.memoizedState!==null&&y._visibility&2&&(m.return===null||m.return.tag!==13)?(y._visibility&=-3,lx(m)):Yy(m);break;default:Yy(m)}}function lx(m){var y=m.deletions;if((m.flags&16)!==0){if(y!==null)for(var w=0;w<y.length;w++){var I=y[w];Ri=I,g$(I,m)}_$(m)}for(m=m.child;m!==null;){switch(y=m,y.tag){case 0:case 11:case 15:wc(8,y,y.return),lx(y);break;case 22:w=y.stateNode,w._visibility&2&&(w._visibility&=-3,lx(y));break;default:lx(y)}m=m.sibling}}function g$(m,y){for(;Ri!==null;){var w=Ri;switch(w.tag){case 0:case 11:case 15:wc(8,w,y);break;case 23:case 22:if(w.memoizedState!==null&&w.memoizedState.cachePool!==null){var I=w.memoizedState.cachePool.pool;I!=null&&I.refCount++}break;case 24:Gs(w.memoizedState.cache)}if(I=w.child,I!==null)I.return=w,Ri=I;else t:for(w=m;Ri!==null;){I=Ri;var O=I.sibling,z=I.return;if(u$(I),I===w){Ri=null;break t}if(O!==null){O.return=z,Ri=O;break t}Ri=z}}}function nE(m){var y=Ppt(m);if(y!=null){if(typeof y.memoizedProps["data-testname"]!="string")throw Error(i(364));return y}if(m=Lpt(m),m===null)throw Error(i(362));return m.stateNode.current}function iE(m,y){var w=m.tag;switch(y.$$typeof){case Ix:if(m.type===y.value)return!0;break;case Nx:t:{for(y=y.value,m=[m,0],w=0;w<m.length;){var I=m[w++],O=I.tag,z=m[w++],K=y[z];if(O!==5&&O!==26&&O!==27||!Gy(I)){for(;K!=null&&iE(I,K);)z++,K=y[z];if(z===y.length){y=!0;break t}else for(I=I.child;I!==null;)m.push(I,z),I=I.sibling}}y=!1}return y;case Ax:if((w===5||w===26||w===27)&&zpt(m.stateNode,y.value))return!0;break;case Ox:if((w===5||w===6||w===26||w===27)&&(m=$pt(m),m!==null&&0<=m.indexOf(y.value)))return!0;break;case Rx:if((w===5||w===26||w===27)&&(m=m.memoizedProps["data-testname"],typeof m=="string"&&m.toLowerCase()===y.value.toLowerCase()))return!0;break;default:throw Error(i(365))}return!1}function rE(m){switch(m.$$typeof){case Ix:return"<"+(u(m.value)||"Unknown")+">";case Nx:return":has("+(rE(m)||"")+")";case Ax:return'[role="'+m.value+'"]';case Ox:return'"'+m.value+'"';case Rx:return'[data-testname="'+m.value+'"]';default:throw Error(i(365))}}function x$(m,y){var w=[];m=[m,0];for(var I=0;I<m.length;){var O=m[I++],z=O.tag,K=m[I++],ct=y[K];if(z!==5&&z!==26&&z!==27||!Gy(O)){for(;ct!=null&&iE(O,ct);)K++,ct=y[K];if(K===y.length)w.push(O);else for(O=O.child;O!==null;)m.push(O,K),O=O.sibling}}return w}function sE(m,y){if(!Vy)throw Error(i(363));m=nE(m),m=x$(m,y),y=[],m=Array.from(m);for(var w=0;w<m.length;){var I=m[w++],O=I.tag;if(O===5||O===26||O===27)Gy(I)||y.push(I.stateNode);else for(I=I.child;I!==null;)m.push(I),I=I.sibling}return y}function Qr(){if((Qe&2)!==0&&en!==0)return en&-en;if(ye.T!==null){var m=lm;return m!==0?m:ih()}return Tpt()}function b$(){ws===0&&(ws=(en&536870912)===0||_n?T():536870912);var m=vs.current;return m!==null&&(m.flags|=32),ws}function ts(m,y,w){(m===Rn&&(bn===2||bn===9)||m.cancelPendingCommit!==null)&&(Kf(m,0),kc(m,en,ws,!1)),E(m,w),((Qe&2)===0||m!==Rn)&&(m===Rn&&((Qe&2)===0&&(kh|=w),ni===4&&kc(m,en,ws,!1)),Ar(m))}function v$(m,y,w){if((Qe&6)!==0)throw Error(i(327));var I=!w&&(y&124)===0&&(y&m.expiredLanes)===0||S(m,y),O=I?npt(m,y):cE(m,y,!0),z=I;do{if(O===0){xm&&!I&&kc(m,y,0,!1);break}else{if(w=m.current.alternate,z&&!tpt(w)){O=cE(m,y,!1),z=!1;continue}if(O===2){if(z=y,m.errorRecoveryDisabledLanes&z)var K=0;else K=m.pendingLanes&-536870913,K=K!==0?K:K&536870912?536870912:0;if(K!==0){y=K;t:{var ct=m;O=tg;var xt=ys&&ct.current.memoizedState.isDehydrated;if(xt&&(Kf(ct,K).flags|=256),K=cE(ct,K,!1),K!==2){if(jE&&!xt){ct.errorRecoveryDisabledLanes|=z,kh|=z,O=4;break t}z=Lr,Lr=O,z!==null&&(Lr===null?Lr=z:Lr.push.apply(Lr,z))}O=K}if(z=!1,O!==2)continue}}if(O===1){Kf(m,0),kc(m,y,0,!0);break}t:{switch(I=m,z=O,z){case 0:case 1:throw Error(i(345));case 4:if((y&4194048)!==y)break;case 6:kc(I,y,ws,!Ac);break t;case 2:Lr=null;break;case 3:case 5:break;default:throw Error(i(329))}if((y&62914560)===y&&(O=XE+300-Zs(),10<O)){if(kc(I,y,ws,!Ac),v(I,0,!0)!==0)break t;I.timeoutHandle=wpt(w$.bind(null,I,w,Lr,Lx,YE,y,ws,kh,bm,Ac,z,2,-0,0),O);break t}w$(I,w,Lr,Lx,YE,y,ws,kh,bm,Ac,z,0,-0,0)}}break}while(!0);Ar(m)}function w$(m,y,w,I,O,z,K,ct,xt,It,zt,Xt,Ht,Fe){if(m.timeoutHandle=gh,Xt=y.subtreeFlags,(Xt&8192||(Xt&16785408)===16785408)&&(Ipt(),m$(y),Xt=Npt(),Xt!==null)){m.cancelPendingCommit=Xt(N$.bind(null,m,y,z,w,I,O,K,ct,xt,zt,1,Ht,Fe)),kc(m,z,K,!It);return}N$(m,y,z,w,I,O,K,ct,xt)}function tpt(m){for(var y=m;;){var w=y.tag;if((w===0||w===11||w===15)&&y.flags&16384&&(w=y.updateQueue,w!==null&&(w=w.stores,w!==null)))for(var I=0;I<w.length;I++){var O=w[I],z=O.getSnapshot;O=O.value;try{if(!rs(z(),O))return!1}catch{return!1}}if(w=y.child,y.subtreeFlags&16384&&w!==null)w.return=y,y=w;else{if(y===m)break;for(;y.sibling===null;){if(y.return===null||y.return===m)return!0;y=y.return}y.sibling.return=y.return,y=y.sibling}}return!0}function kc(m,y,w,I){y&=~BE,y&=~kh,m.suspendedLanes|=y,m.pingedLanes&=~y,I&&(m.warmLanes|=y),I=m.expirationTimes;for(var O=y;0<O;){var z=31-ns(O),K=1<<z;I[z]=-1,O&=~K}w!==0&&M(m,w,y)}function S$(){return(Qe&6)===0?(ko(0,!1),!1):!0}function oE(){if(Ve!==null){if(bn===0)var m=Ve.return;else m=Ve,ga=wh=null,Iy(m),_m=null,Jy=0,m=Ve;for(;m!==null;)n$(m.alternate,m),m=m.return;Ve=null}}function Kf(m,y){var w=m.timeoutHandle;w!==gh&&(m.timeoutHandle=gh,Spt(w)),w=m.cancelPendingCommit,w!==null&&(m.cancelPendingCommit=null,w()),oE(),Rn=m,Ve=w=da(m.current,null),en=y,bn=0,ss=null,Ac=!1,xm=S(m,y),jE=!1,bm=ws=BE=kh=Rc=ni=0,Lr=tg=null,YE=!1,(y&8)!==0&&(y|=y&32);var I=m.entangledLanes;if(I!==0)for(m=m.entanglements,I&=y;0<I;){var O=31-ns(I),z=1<<O;y|=m[O],I&=~z}return ba=y,yc(),w}function P$(m,y){je=null,ye.H=Cx,y===Zy||y===Px?(y=Bf(),bn=3):y===OE?(y=Bf(),bn=4):bn=y===kz?8:y!==null&&typeof y=="object"&&typeof y.then=="function"?6:1,ss=y,Ve===null&&(ni=1,rx(m,nt(y,m.current)))}function k$(){var m=vs.current;return m===null?!0:(en&4194048)===en?Io===null:(en&62914560)===en||(en&536870912)!==0?m===Io:!1}function T$(){var m=ye.H;return ye.H=Cx,m===null?Cx:m}function E$(){var m=ye.A;return ye.A=Vht,m}function aE(){ni=4,Ac||(en&4194048)!==en&&vs.current!==null||(xm=!0),(Rc&134217727)===0&&(kh&134217727)===0||Rn===null||kc(Rn,en,ws,!1)}function cE(m,y,w){var I=Qe;Qe|=2;var O=T$(),z=E$();(Rn!==m||en!==y)&&(Lx=null,Kf(m,y)),y=!1;var K=ni;t:do try{if(bn!==0&&Ve!==null){var ct=Ve,xt=ss;switch(bn){case 8:oE(),K=6;break t;case 3:case 2:case 9:case 6:vs.current===null&&(y=!0);var It=bn;if(bn=0,ss=null,Jf(m,ct,xt,It),w&&xm){K=0;break t}break;default:It=bn,bn=0,ss=null,Jf(m,ct,xt,It)}}ept(),K=ni;break}catch(zt){P$(m,zt)}while(!0);return y&&m.shellSuspendCounter++,ga=wh=null,Qe=I,ye.H=O,ye.A=z,Ve===null&&(Rn=null,en=0,yc()),K}function ept(){for(;Ve!==null;)M$(Ve)}function npt(m,y){var w=Qe;Qe|=2;var I=T$(),O=E$();Rn!==m||en!==y?(Lx=null,eg=Zs()+500,Kf(m,y)):xm=S(m,y);t:do try{if(bn!==0&&Ve!==null){y=Ve;var z=ss;e:switch(bn){case 1:bn=0,ss=null,Jf(m,y,z,1);break;case 2:case 9:if(Df(z)){bn=0,ss=null,C$(y);break}y=function(){bn!==2&&bn!==9||Rn!==m||(bn=7),Ar(m)},z.then(y,y);break t;case 3:bn=7;break t;case 4:bn=5;break t;case 7:Df(z)?(bn=0,ss=null,C$(y)):(bn=0,ss=null,Jf(m,y,z,7));break;case 5:var K=null;switch(Ve.tag){case 26:K=Ve.memoizedState;case 5:case 27:var ct=Ve,xt=ct.type,It=ct.pendingProps;if(K?dz(K):K$(xt,It)){bn=0,ss=null;var zt=ct.sibling;if(zt!==null)Ve=zt;else{var Xt=ct.return;Xt!==null?(Ve=Xt,ux(Xt)):Ve=null}break e}}bn=0,ss=null,Jf(m,y,z,5);break;case 6:bn=0,ss=null,Jf(m,y,z,6);break;case 8:oE(),ni=6;break t;default:throw Error(i(462))}}ipt();break}catch(Ht){P$(m,Ht)}while(!0);return ga=wh=null,ye.H=I,ye.A=O,Qe=w,Ve!==null?0:(Rn=null,en=0,yc(),ni)}function ipt(){for(;Ve!==null&&!Rht();)M$(Ve)}function M$(m){var y=KF(m.alternate,m,ba);m.memoizedProps=m.pendingProps,y===null?ux(m):Ve=y}function C$(m){var y=m,w=y.alternate;switch(y.tag){case 15:case 0:y=VF(w,y,y.pendingProps,y.type,void 0,en);break;case 11:y=VF(w,y,y.pendingProps,y.type.render,y.ref,en);break;case 5:Iy(y);default:n$(w,y),y=Ve=D$(y,ba),y=KF(w,y,ba)}m.memoizedProps=m.pendingProps,y===null?ux(m):Ve=y}function Jf(m,y,w,I){ga=wh=null,Iy(y),_m=null,Jy=0;var O=y.return;try{if(Hut(m,O,y,w,en)){ni=1,rx(m,nt(w,m.current)),Ve=null;return}}catch(z){if(O!==null)throw Ve=O,z;ni=1,rx(m,nt(w,m.current)),Ve=null;return}y.flags&32768?(_n||I===1?m=!0:xm||(en&536870912)!==0?m=!1:(Ac=m=!0,(I===2||I===9||I===3||I===6)&&(I=vs.current,I!==null&&I.tag===13&&(I.flags|=16384))),I$(y,m)):ux(y)}function ux(m){var y=m;do{if((y.flags&32768)!==0){I$(y,Ac);return}m=y.return;var w=Zut(y.alternate,y,ba);if(w!==null){Ve=w;return}if(y=y.sibling,y!==null){Ve=y;return}Ve=y=m}while(y!==null);ni===0&&(ni=5)}function I$(m,y){do{var w=Kut(m.alternate,m);if(w!==null){w.flags&=32767,Ve=w;return}if(w=m.return,w!==null&&(w.flags|=32768,w.subtreeFlags=0,w.deletions=null),!y&&(m=m.sibling,m!==null)){Ve=m;return}Ve=m=w}while(m!==null);ni=6,Ve=null}function N$(m,y,w,I,O,z,K,ct,xt){m.cancelPendingCommit=null;do Xy();while(Ji!==0);if((Qe&6)!==0)throw Error(i(327));if(y!==null){if(y===m.current)throw Error(i(177));if(z=y.lanes|y.childLanes,z|=LE,C(m,w,z,K,ct,xt),m===Rn&&(Ve=Rn=null,en=0),vm=y,Lc=m,wm=w,UE=z,VE=O,Ez=I,(y.subtreeFlags&10256)!==0||(y.flags&10256)!==0?(m.callbackNode=null,m.callbackPriority=0,apt(EE,function(){return F$(!0),null})):(m.callbackNode=null,m.callbackPriority=0),I=(y.flags&13878)!==0,(y.subtreeFlags&13878)!==0||I){I=ye.T,ye.T=null,O=ma(),Ni(2),K=Qe,Qe|=4;try{Jut(m,y,w)}finally{Qe=K,Ni(O),ye.T=I}}Ji=1,A$(),R$(),O$()}}function A$(){if(Ji===1){Ji=0;var m=Lc,y=vm,w=(y.flags&13878)!==0;if((y.subtreeFlags&13878)!==0||w){w=ye.T,ye.T=null;var I=ma();Ni(2);var O=Qe;Qe|=4;try{h$(y,m),bpt(m.containerInfo)}finally{Qe=O,Ni(I),ye.T=w}}m.current=y,Ji=2}}function R$(){if(Ji===2){Ji=0;var m=Lc,y=vm,w=(y.flags&8772)!==0;if((y.subtreeFlags&8772)!==0||w){w=ye.T,ye.T=null;var I=ma();Ni(2);var O=Qe;Qe|=4;try{l$(m,y.alternate,y)}finally{Qe=O,Ni(I),ye.T=w}}Ji=3}}function O$(){if(Ji===4||Ji===3){Ji=0,Oht();var m=Lc,y=vm,w=wm,I=Ez;(y.subtreeFlags&10256)!==0||(y.flags&10256)!==0?Ji=5:(Ji=0,vm=Lc=null,L$(m,m.pendingLanes));var O=m.pendingLanes;if(O===0&&(Oc=null),B(w),y=y.stateNode,is&&typeof is.onCommitFiberRoot=="function")try{is.onCommitFiberRoot(Wy,y,void 0,(y.current.flags&128)===128)}catch{}if(I!==null){y=ye.T,O=ma(),Ni(2),ye.T=null;try{for(var z=m.onRecoverableError,K=0;K<I.length;K++){var ct=I[K];z(ct.value,{componentStack:ct.stack})}}finally{ye.T=y,Ni(O)}}(wm&3)!==0&&Xy(),Ar(m),O=m.pendingLanes,(w&4194090)!==0&&(O&42)!==0?m===GE?ng++:(ng=0,GE=m):ng=0,ko(0,!1)}}function L$(m,y){(m.pooledCacheLanes&=y)===0&&(y=m.pooledCache,y!=null&&(m.pooledCache=null,Gs(y)))}function Xy(m){return A$(),R$(),O$(),F$(m)}function F$(){if(Ji!==5)return!1;var m=Lc,y=UE;UE=0;var w=B(wm),I=32>w?32:w;w=ye.T;var O=ma();try{Ni(I),ye.T=null,I=VE,VE=null;var z=Lc,K=wm;if(Ji=0,vm=Lc=null,wm=0,(Qe&6)!==0)throw Error(i(331));var ct=Qe;if(Qe|=4,y$(z.current),f$(z,z.current,K,I),Qe=ct,ko(0,!1),is&&typeof is.onPostCommitFiberRoot=="function")try{is.onPostCommitFiberRoot(Wy,z)}catch{}return!0}finally{Ni(O),ye.T=w,L$(m,y)}}function $$(m,y,w){y=nt(w,y),y=zT(m.stateNode,y,2),m=_s(m,y,2),m!==null&&(E(m,2),Ar(m))}function xn(m,y,w){if(m.tag===3)$$(m,m,w);else for(;y!==null;){if(y.tag===3){$$(y,m,w);break}else if(y.tag===1){var I=y.stateNode;if(typeof y.type.getDerivedStateFromError=="function"||typeof I.componentDidCatch=="function"&&(Oc===null||!Oc.has(I))){m=nt(w,m),w=zF(2),I=_s(y,w,2),I!==null&&(DF(w,I,y,m),E(I,2),Ar(I));break}}y=y.return}}function lE(m,y,w){var I=m.pingCache;if(I===null){I=m.pingCache=new Ght;var O=new Set;I.set(y,O)}else O=I.get(y),O===void 0&&(O=new Set,I.set(y,O));O.has(w)||(jE=!0,O.add(w),m=rpt.bind(null,m,y,w),y.then(m,m))}function rpt(m,y,w){var I=m.pingCache;I!==null&&I.delete(y),m.pingedLanes|=m.suspendedLanes&w,m.warmLanes&=~w,Rn===m&&(en&w)===w&&(ni===4||ni===3&&(en&62914560)===en&&300>Zs()-XE?(Qe&2)===0&&Kf(m,0):BE|=w,bm===en&&(bm=0)),Ar(m)}function z$(m,y){y===0&&(y=k()),m=To(m,y),m!==null&&(E(m,y),Ar(m))}function spt(m){var y=m.memoizedState,w=0;y!==null&&(w=y.retryLane),z$(m,w)}function opt(m,y){var w=0;switch(m.tag){case 13:var I=m.stateNode,O=m.memoizedState;O!==null&&(w=O.retryLane);break;case 19:I=m.stateNode;break;case 22:I=m.stateNode._retryCache;break;default:throw Error(i(314))}I!==null&&I.delete(y),z$(m,w)}function apt(m,y){return yx(m,y)}function cpt(m,y,w,I){this.tag=m,this.key=w,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=y,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=I,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function uE(m){return m=m.prototype,!(!m||!m.isReactComponent)}function da(m,y){var w=m.alternate;return w===null?(w=e(m.tag,y,m.key,m.mode),w.elementType=m.elementType,w.type=m.type,w.stateNode=m.stateNode,w.alternate=m,m.alternate=w):(w.pendingProps=y,w.type=m.type,w.flags=0,w.subtreeFlags=0,w.deletions=null),w.flags=m.flags&65011712,w.childLanes=m.childLanes,w.lanes=m.lanes,w.child=m.child,w.memoizedProps=m.memoizedProps,w.memoizedState=m.memoizedState,w.updateQueue=m.updateQueue,y=m.dependencies,w.dependencies=y===null?null:{lanes:y.lanes,firstContext:y.firstContext},w.sibling=m.sibling,w.index=m.index,w.ref=m.ref,w.refCleanup=m.refCleanup,w}function D$(m,y){m.flags&=65011714;var w=m.alternate;return w===null?(m.childLanes=0,m.lanes=y,m.child=null,m.subtreeFlags=0,m.memoizedProps=null,m.memoizedState=null,m.updateQueue=null,m.dependencies=null,m.stateNode=null):(m.childLanes=w.childLanes,m.lanes=w.lanes,m.child=w.child,m.subtreeFlags=0,m.deletions=null,m.memoizedProps=w.memoizedProps,m.memoizedState=w.memoizedState,m.updateQueue=w.updateQueue,m.type=w.type,y=w.dependencies,m.dependencies=y===null?null:{lanes:y.lanes,firstContext:y.firstContext}),m}function px(m,y,w,I,O,z){var K=0;if(I=m,typeof m=="function")uE(m)&&(K=1);else if(typeof m=="string")K=qs&&wi?az(m,w,Ki.current)?26:_z(m)?27:5:qs?az(m,w,Ki.current)?26:5:wi&&_z(m)?27:5;else t:switch(m){case bE:return m=e(31,w,y,O),m.elementType=bE,m.lanes=z,m;case tm:return yh(w.children,O,z,y);case V$:K=8,O|=24;break;case mE:return m=e(12,w,y,O|2),m.elementType=mE,m.lanes=z,m;case yE:return m=e(13,w,y,O),m.elementType=yE,m.lanes=z,m;case gE:return m=e(19,w,y,O),m.elementType=gE,m.lanes=z,m;default:if(typeof m=="object"&&m!==null)switch(m.$$typeof){case hpt:case Tc:K=10;break t;case G$:K=9;break t;case _E:K=11;break t;case xE:K=14;break t;case Ec:K=16,I=null;break t}K=29,w=Error(i(130,m===null?"null":typeof m,"")),I=null}return y=e(K,w,y,O),y.elementType=m,y.type=I,y.lanes=z,y}function yh(m,y,w,I){return m=e(7,m,I,y),m.lanes=w,m}function pE(m,y,w){return m=e(6,m,null,y),m.lanes=w,m}function hE(m,y,w){return y=e(4,m.children!==null?m.children:[],m.key,y),y.lanes=w,y.stateNode={containerInfo:m.containerInfo,pendingChildren:null,implementation:m.implementation},y}function lpt(m,y,w,I,O,z,K,ct){this.tag=1,this.containerInfo=m,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=gh,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=N(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=N(0),this.hiddenUpdates=N(null),this.identifierPrefix=I,this.onUncaughtError=O,this.onCaughtError=z,this.onRecoverableError=K,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=ct,this.incompleteTransitions=new Map}function j$(m,y,w,I,O,z,K,ct,xt,It,zt,Xt){return m=new lpt(m,y,w,K,ct,xt,It,Xt),y=1,z===!0&&(y|=24),z=e(3,null,null,y),m.current=z,z.stateNode=m,y=Nr(),y.refCount++,m.pooledCache=y,y.refCount++,z.memoizedState={element:I,isDehydrated:w,cache:y},oh(z),m}function B$(m){return m?(m=rm,m):rm}function Y$(m){var y=m._reactInternals;if(y===void 0)throw typeof m.render=="function"?Error(i(188)):(m=Object.keys(m).join(","),Error(i(268,m)));return m=o(y),m=m!==null?a(m):null,m===null?null:Uy(m.stateNode)}function X$(m,y,w,I,O,z){O=B$(O),I.context===null?I.context=O:I.pendingContext=O,I=ms(y),I.payload={element:w},z=z===void 0?null:z,z!==null&&(I.callback=z),w=_s(m,I,y),w!==null&&(ts(w,m,y),ca(w,m,y))}function U$(m,y){if(m=m.memoizedState,m!==null&&m.dehydrated!==null){var w=m.retryLane;m.retryLane=w!==0&&w<y?w:y}}function dE(m,y){U$(m,y),(m=m.alternate)&&U$(m,y)}var Ue={},upt=Js(),es=uY(),fE=Object.assign,ppt=Symbol.for("react.element"),hx=Symbol.for("react.transitional.element"),Qf=Symbol.for("react.portal"),tm=Symbol.for("react.fragment"),V$=Symbol.for("react.strict_mode"),mE=Symbol.for("react.profiler"),hpt=Symbol.for("react.provider"),G$=Symbol.for("react.consumer"),Tc=Symbol.for("react.context"),_E=Symbol.for("react.forward_ref"),yE=Symbol.for("react.suspense"),gE=Symbol.for("react.suspense_list"),xE=Symbol.for("react.memo"),Ec=Symbol.for("react.lazy");Symbol.for("react.scope");var bE=Symbol.for("react.activity");Symbol.for("react.legacy_hidden"),Symbol.for("react.tracing_marker");var dpt=Symbol.for("react.memo_cache_sentinel");Symbol.for("react.view_transition");var W$=Symbol.iterator,fpt=Symbol.for("react.client.reference"),dx=Array.isArray,ye=upt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,mpt=n.rendererVersion,_pt=n.rendererPackageName,H$=n.extraDevToolsConfig,Uy=n.getPublicInstance,ypt=n.getRootHostContext,gpt=n.getChildHostContext,xpt=n.prepareForCommit,bpt=n.resetAfterCommit,vpt=n.createInstance;n.cloneMutableInstance;var vE=n.appendInitialChild,q$=n.finalizeInitialChildren,fx=n.shouldSetTextContent,Z$=n.createTextInstance;n.cloneMutableTextInstance;var wpt=n.scheduleTimeout,Spt=n.cancelTimeout,gh=n.noTimeout,fa=n.isPrimaryRenderer;n.warnsIfNotActing;var lr=n.supportsMutation,Mc=n.supportsPersistence,ys=n.supportsHydration,Ppt=n.getInstanceFromNode;n.beforeActiveInstanceBlur;var kpt=n.preparePortalMount;n.prepareScopeUpdate,n.getInstanceFromScope;var Ni=n.setCurrentUpdatePriority,ma=n.getCurrentUpdatePriority,Tpt=n.resolveUpdatePriority;n.trackSchedulerEvent,n.resolveEventType,n.resolveEventTimeStamp;var Ept=n.shouldAttemptEagerTransition,Mpt=n.detachDeletedInstance;n.requestPostPaintCallback;var Cpt=n.maySuspendCommit,K$=n.preloadInstance,Ipt=n.startSuspendingCommit,J$=n.suspendInstance;n.suspendOnActiveViewTransition;var Npt=n.waitForCommitToBeReady,em=n.NotPendingTransition,xh=n.HostTransitionContext,Apt=n.resetFormInstance;n.bindToConsole;var Rpt=n.supportsMicrotasks,Opt=n.scheduleMicrotask,Vy=n.supportsTestSelectors,Lpt=n.findFiberRoot,Fpt=n.getBoundingRect,$pt=n.getTextContent,Gy=n.isHiddenSubtree,zpt=n.matchAccessibilityRole,Dpt=n.setFocusIfFocusable,jpt=n.setupIntersectionObserver,Bpt=n.appendChild,Ypt=n.appendChildToContainer,Xpt=n.commitTextUpdate,Upt=n.commitMount,Vpt=n.commitUpdate,Gpt=n.insertBefore,Wpt=n.insertInContainerBefore,Hpt=n.removeChild,qpt=n.removeChildFromContainer,Q$=n.resetTextContent,Zpt=n.hideInstance,Kpt=n.hideTextInstance,Jpt=n.unhideInstance,Qpt=n.unhideTextInstance;n.cancelViewTransitionName,n.cancelRootViewTransitionName,n.restoreRootViewTransitionName,n.cloneRootViewTransitionContainer,n.removeRootViewTransitionClone,n.measureClonedInstance,n.hasInstanceChanged,n.hasInstanceAffectedParent,n.startViewTransition,n.startGestureTransition,n.stopGestureTransition,n.getCurrentGestureOffset,n.subscribeToGestureDirection,n.createViewTransitionInstance;var tht=n.clearContainer;n.createFragmentInstance,n.updateFragmentInstanceFiber,n.commitNewChildToFragmentInstance,n.deleteChildFromFragmentInstance;var eht=n.cloneInstance,tz=n.createContainerChildSet,ez=n.appendChildToContainerChildSet,nht=n.finalizeContainerChildren,nz=n.replaceContainerChildren,iz=n.cloneHiddenInstance,rz=n.cloneHiddenTextInstance,wE=n.isSuspenseInstancePending,SE=n.isSuspenseInstanceFallback,iht=n.getSuspenseInstanceFallbackErrorDetails,rht=n.registerSuspenseInstanceRetry,sht=n.canHydrateFormStateMarker,oht=n.isFormStateMarkerMatching,sz=n.getNextHydratableSibling,aht=n.getNextHydratableSiblingAfterSingleton,cht=n.getFirstHydratableChild,lht=n.getFirstHydratableChildWithinContainer,uht=n.getFirstHydratableChildWithinSuspenseInstance,pht=n.getFirstHydratableChildWithinSingleton,hht=n.canHydrateInstance,dht=n.canHydrateTextInstance,fht=n.canHydrateSuspenseInstance,mht=n.hydrateInstance,_ht=n.hydrateTextInstance,yht=n.hydrateSuspenseInstance,ght=n.getNextHydratableInstanceAfterSuspenseInstance,xht=n.commitHydratedContainer,bht=n.commitHydratedSuspenseInstance,vht=n.clearSuspenseBoundary,wht=n.clearSuspenseBoundaryFromContainer,oz=n.shouldDeleteUnhydratedTailInstances;n.diffHydratedPropsForDevWarnings,n.diffHydratedTextForDevWarnings,n.describeHydratableInstanceForDevWarnings;var Sht=n.validateHydratableInstance,Pht=n.validateHydratableTextInstance,qs=n.supportsResources,az=n.isHostHoistableType,PE=n.getHoistableRoot,cz=n.getResource,lz=n.acquireResource,uz=n.releaseResource,kht=n.hydrateHoistable,pz=n.mountHoistable,hz=n.unmountHoistable,Tht=n.createHoistableInstance,Eht=n.prepareToCommitHoistables,Mht=n.mayResourceSuspendCommit,dz=n.preloadResource,Cht=n.suspendResource,wi=n.supportsSingletons,fz=n.resolveSingletonInstance,Iht=n.acquireSingletonInstance,mz=n.releaseSingletonInstance,_z=n.isHostSingletonType,nm=n.isSingletonScope,kE=[],im=-1,rm={},ns=Math.clz32?Math.clz32:g,Nht=Math.log,Aht=Math.LN2,mx=256,_x=4194304,yx=es.unstable_scheduleCallback,TE=es.unstable_cancelCallback,Rht=es.unstable_shouldYield,Oht=es.unstable_requestPaint,Zs=es.unstable_now,yz=es.unstable_ImmediatePriority,Lht=es.unstable_UserBlockingPriority,EE=es.unstable_NormalPriority,Fht=es.unstable_IdlePriority,$ht=es.log,zht=es.unstable_setDisableYieldValue,Wy=null,is=null,ME,gz,CE=!1,xz=new WeakMap,sm=[],om=0,gx=null,xx=0,gs=[],xs=0,bh=null,_a=1,ya="",Ki=p(null),Hy=p(null),Cc=p(null),bx=p(null),Sr=null,Si=null,_n=!1,vh=null,Co=!1,IE=Error(i(519)),rs=typeof Object.is=="function"?Object.is:at,vx=p(null),wh=null,ga=null,Dht=typeof AbortController<"u"?AbortController:function(){var m=[],y=this.signal={aborted:!1,addEventListener:function(w,I){m.push(I)}};this.abort=function(){y.aborted=!0,m.forEach(function(w){return w()})}},jht=es.unstable_scheduleCallback,Bht=es.unstable_NormalPriority,ei={$$typeof:Tc,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0},wx=null,am=null,NE=!1,Sx=!1,AE=!1,cm=0,qy=null,RE=0,lm=0,um=null,bz=ye.S;ye.S=function(m,y){typeof y=="object"&&y!==null&&typeof y.then=="function"&&Ty(m,y),bz!==null&&bz(m,y)};var Sh=p(null),Yht=Object.prototype.hasOwnProperty,Zy=Error(i(460)),OE=Error(i(474)),Px=Error(i(542)),kx={then:function(){}},pm=null,bs=[],hm=0,LE=0,Ic=!1,FE=!1,dm=p(null),Tx=p(0),Nc=0,je=null,Pn=null,mi=null,Ex=!1,fm=!1,Ph=!1,Mx=0,Ky=0,mm=null,Xht=0,Cx={readContext:Jt,use:Wf,useCallback:Fn,useContext:Fn,useEffect:Fn,useImperativeHandle:Fn,useLayoutEffect:Fn,useInsertionEffect:Fn,useMemo:Fn,useReducer:Fn,useRef:Fn,useState:Fn,useDebugValue:Fn,useDeferredValue:Fn,useTransition:Fn,useSyncExternalStore:Fn,useId:Fn,useHostTransitionStatus:Fn,useFormState:Fn,useActionState:Fn,useOptimistic:Fn,useMemoCache:Fn,useCacheRefresh:Fn},vz={readContext:Jt,use:Wf,useCallback:function(m,y){return cr().memoizedState=[m,y===void 0?null:y],m},useContext:Jt,useEffect:_F,useImperativeHandle:function(m,y,w){w=w!=null?w.concat([m]):null,Q0(4194308,4,bF.bind(null,y,m),w)},useLayoutEffect:function(m,y){return Q0(4194308,4,m,y)},useInsertionEffect:function(m,y){Q0(4,2,m,y)},useMemo:function(m,y){var w=cr();y=y===void 0?null:y;var I=m();if(Ph){j(!0);try{m()}finally{j(!1)}}return w.memoizedState=[I,y],I},useReducer:function(m,y,w){var I=cr();if(w!==void 0){var O=w(y);if(Ph){j(!0);try{w(y)}finally{j(!1)}}}else O=y;return I.memoizedState=I.baseState=O,m={pending:null,lanes:0,dispatch:null,lastRenderedReducer:m,lastRenderedState:O},I.queue=m,m=m.dispatch=Wut.bind(null,je,m),[I.memoizedState,m]},useRef:function(m){var y=cr();return m={current:m},y.memoizedState=m},useState:function(m){m=NT(m);var y=m.queue,w=CF.bind(null,je,y);return y.dispatch=w,[m.memoizedState,w]},useDebugValue:RT,useDeferredValue:function(m,y){var w=cr();return OT(w,m,y)},useTransition:function(){var m=NT(!1);return m=kF.bind(null,je,m.queue,!0,!1),cr().memoizedState=m,[!1,m]},useSyncExternalStore:function(m,y,w){var I=je,O=cr();if(_n){if(w===void 0)throw Error(i(407));w=w()}else{if(w=y(),Rn===null)throw Error(i(349));(en&124)!==0||tF(I,y,w)}O.memoizedState=w;var z={value:w,getSnapshot:y};return O.queue=z,_F(nF.bind(null,I,z,m),[m]),I.flags|=2048,qf(9,J0(),eF.bind(null,I,z,w,y),null),w},useId:function(){var m=cr(),y=Rn.identifierPrefix;if(_n){var w=ya,I=_a;w=(I&~(1<<32-ns(I)-1)).toString(32)+w,y="\xAB"+y+"R"+w,w=Mx++,0<w&&(y+="H"+w.toString(32)),y+="\xBB"}else w=Xht++,y="\xAB"+y+"r"+w.toString(32)+"\xBB";return m.memoizedState=y},useHostTransitionStatus:LT,useFormState:pF,useActionState:pF,useOptimistic:function(m){var y=cr();y.memoizedState=y.baseState=m;var w={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return y.queue=w,y=FT.bind(null,je,!0,w),w.dispatch=y,[m,y]},useMemoCache:Ay,useCacheRefresh:function(){return cr().memoizedState=Gut.bind(null,je)}},wz={readContext:Jt,use:Wf,useCallback:wF,useContext:Jt,useEffect:yF,useImperativeHandle:vF,useInsertionEffect:gF,useLayoutEffect:xF,useMemo:SF,useReducer:Hf,useRef:mF,useState:function(){return Hf(Ws)},useDebugValue:RT,useDeferredValue:function(m,y){var w=ti();return PF(w,Pn.memoizedState,m,y)},useTransition:function(){var m=Hf(Ws)[0],y=ti().memoizedState;return[typeof m=="boolean"?m:dh(m),y]},useSyncExternalStore:Q7,useId:EF,useHostTransitionStatus:LT,useFormState:hF,useActionState:hF,useOptimistic:function(m,y){var w=ti();return sF(w,Pn,m,y)},useMemoCache:Ay,useCacheRefresh:MF},Uht={readContext:Jt,use:Wf,useCallback:wF,useContext:Jt,useEffect:yF,useImperativeHandle:vF,useInsertionEffect:gF,useLayoutEffect:xF,useMemo:SF,useReducer:Oy,useRef:mF,useState:function(){return Oy(Ws)},useDebugValue:RT,useDeferredValue:function(m,y){var w=ti();return Pn===null?OT(w,m,y):PF(w,Pn.memoizedState,m,y)},useTransition:function(){var m=Oy(Ws)[0],y=ti().memoizedState;return[typeof m=="boolean"?m:dh(m),y]},useSyncExternalStore:Q7,useId:EF,useHostTransitionStatus:LT,useFormState:fF,useActionState:fF,useOptimistic:function(m,y){var w=ti();return Pn!==null?sF(w,Pn,m,y):(w.baseState=m,[m,w.queue.dispatch])},useMemoCache:Ay,useCacheRefresh:MF},_m=null,Jy=0,ym=RF(!0),Sz=RF(!1),vs=p(null),Io=null,Pi=p(0),$E={enqueueSetState:function(m,y,w){m=m._reactInternals;var I=Qr(),O=ms(I);O.payload=y,w!=null&&(O.callback=w),y=_s(m,O,I),y!==null&&(ts(y,m,I),ca(y,m,I))},enqueueReplaceState:function(m,y,w){m=m._reactInternals;var I=Qr(),O=ms(I);O.tag=1,O.payload=y,w!=null&&(O.callback=w),y=_s(m,O,I),y!==null&&(ts(y,m,I),ca(y,m,I))},enqueueForceUpdate:function(m,y){m=m._reactInternals;var w=Qr(),I=ms(w);I.tag=2,y!=null&&(I.callback=y),y=_s(m,I,w),y!==null&&(ts(y,m,w),ca(y,m,w))}},Pz=typeof reportError=="function"?reportError:function(m){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var y=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof m=="object"&&m!==null&&typeof m.message=="string"?String(m.message):String(m),error:m});if(!window.dispatchEvent(y))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",m);return}console.error(m)},kz=Error(i(461)),Ai=!1,zE={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null},xa=!1,hi=!1,DE=!1,Tz=typeof WeakSet=="function"?WeakSet:Set,Ri=null,_i=null,Or=!1,Ks=null,gm=8192,Vht={getCacheForType:function(m){var y=Jt(ei),w=y.data.get(m);return w===void 0&&(w=m(),y.data.set(m,w)),w}},Ix=0,Nx=1,Ax=2,Rx=3,Ox=4;if(typeof Symbol=="function"&&Symbol.for){var Qy=Symbol.for;Ix=Qy("selector.component"),Nx=Qy("selector.has_pseudo_class"),Ax=Qy("selector.role"),Rx=Qy("selector.test_id"),Ox=Qy("selector.text")}var Ght=typeof WeakMap=="function"?WeakMap:Map,Qe=0,Rn=null,Ve=null,en=0,bn=0,ss=null,Ac=!1,xm=!1,jE=!1,ba=0,ni=0,Rc=0,kh=0,BE=0,ws=0,bm=0,tg=null,Lr=null,YE=!1,XE=0,eg=1/0,Lx=null,Oc=null,Ji=0,Lc=null,vm=null,wm=0,UE=0,VE=null,Ez=null,ng=0,GE=null;return Ue.attemptContinuousHydration=function(m){if(m.tag===13){var y=To(m,67108864);y!==null&&ts(y,m,67108864),dE(m,67108864)}},Ue.attemptHydrationAtCurrentPriority=function(m){if(m.tag===13){var y=Qr();y=R(y);var w=To(m,y);w!==null&&ts(w,m,y),dE(m,y)}},Ue.attemptSynchronousHydration=function(m){switch(m.tag){case 3:if(m=m.stateNode,m.current.memoizedState.isDehydrated){var y=x(m.pendingLanes);if(y!==0){for(m.pendingLanes|=2,m.entangledLanes|=2;y;){var w=1<<31-ns(y);m.entanglements[1]|=w,y&=~w}Ar(m),(Qe&6)===0&&(eg=Zs()+500,ko(0,!1))}}break;case 13:y=To(m,2),y!==null&&ts(y,m,2),S$(),dE(m,2)}},Ue.batchedUpdates=function(m,y){return m(y)},Ue.createComponentSelector=function(m){return{$$typeof:Ix,value:m}},Ue.createContainer=function(m,y,w,I,O,z,K,ct,xt,It){return j$(m,y,!1,null,w,I,z,K,ct,xt,It,null)},Ue.createHasPseudoClassSelector=function(m){return{$$typeof:Nx,value:m}},Ue.createHydrationContainer=function(m,y,w,I,O,z,K,ct,xt,It,zt,Xt,Ht){return m=j$(w,I,!0,m,O,z,ct,xt,It,zt,Xt,Ht),m.context=B$(null),w=m.current,I=Qr(),I=R(I),O=ms(I),O.callback=y??null,_s(w,O,I),y=I,m.current.lanes=y,E(m,y),Ar(m),m},Ue.createPortal=function(m,y,w){var I=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Qf,key:I==null?null:""+I,children:m,containerInfo:y,implementation:w}},Ue.createRoleSelector=function(m){return{$$typeof:Ax,value:m}},Ue.createTestNameSelector=function(m){return{$$typeof:Rx,value:m}},Ue.createTextSelector=function(m){return{$$typeof:Ox,value:m}},Ue.defaultOnCaughtError=function(m){console.error(m)},Ue.defaultOnRecoverableError=function(m){Pz(m)},Ue.defaultOnUncaughtError=function(m){Pz(m)},Ue.deferredUpdates=function(m){var y=ye.T,w=ma();try{return Ni(32),ye.T=null,m()}finally{Ni(w),ye.T=y}},Ue.discreteUpdates=function(m,y,w,I,O){var z=ye.T,K=ma();try{return Ni(2),ye.T=null,m(y,w,I,O)}finally{Ni(K),ye.T=z,Qe===0&&(eg=Zs()+500)}},Ue.findAllNodes=sE,Ue.findBoundingRects=function(m,y){if(!Vy)throw Error(i(363));y=sE(m,y),m=[];for(var w=0;w<y.length;w++)m.push(Fpt(y[w]));for(y=m.length-1;0<y;y--){w=m[y];for(var I=w.x,O=I+w.width,z=w.y,K=z+w.height,ct=y-1;0<=ct;ct--)if(y!==ct){var xt=m[ct],It=xt.x,zt=It+xt.width,Xt=xt.y,Ht=Xt+xt.height;if(I>=It&&z>=Xt&&O<=zt&&K<=Ht){m.splice(y,1);break}else if(I!==It||w.width!==xt.width||Ht<z||Xt>K){if(!(z!==Xt||w.height!==xt.height||zt<I||It>O)){It>I&&(xt.width+=It-I,xt.x=I),zt<O&&(xt.width=O-It),m.splice(y,1);break}}else{Xt>z&&(xt.height+=Xt-z,xt.y=z),Ht<K&&(xt.height=K-Xt),m.splice(y,1);break}}}return m},Ue.findHostInstance=Y$,Ue.findHostInstanceWithNoPortals=function(m){return m=o(m),m=m!==null?c(m):null,m===null?null:Uy(m.stateNode)},Ue.findHostInstanceWithWarning=function(m){return Y$(m)},Ue.flushPassiveEffects=Xy,Ue.flushSyncFromReconciler=function(m){var y=Qe;Qe|=1;var w=ye.T,I=ma();try{if(Ni(2),ye.T=null,m)return m()}finally{Ni(I),ye.T=w,Qe=y,(Qe&6)===0&&ko(0,!1)}},Ue.flushSyncWork=S$,Ue.focusWithin=function(m,y){if(!Vy)throw Error(i(363));for(m=nE(m),y=x$(m,y),y=Array.from(y),m=0;m<y.length;){var w=y[m++],I=w.tag;if(!Gy(w)){if((I===5||I===26||I===27)&&Dpt(w.stateNode))return!0;for(w=w.child;w!==null;)y.push(w),w=w.sibling}}return!1},Ue.getFindAllNodesFailureDescription=function(m,y){if(!Vy)throw Error(i(363));var w=0,I=[];m=[nE(m),0];for(var O=0;O<m.length;){var z=m[O++],K=z.tag,ct=m[O++],xt=y[ct];if((K!==5&&K!==26&&K!==27||!Gy(z))&&(iE(z,xt)&&(I.push(rE(xt)),ct++,ct>w&&(w=ct)),ct<y.length))for(z=z.child;z!==null;)m.push(z,ct),z=z.sibling}if(w<y.length){for(m=[];w<y.length;w++)m.push(rE(y[w]));return`findAllNodes was able to match part of the selector:
8
+ `+w.stack}}function nt(m,y){if(typeof m=="object"&&m!==null){var w=xz.get(m);return w!==void 0?w:(y={value:m,source:y,stack:et(y)},xz.set(m,y),y)}return{value:m,source:y,stack:et(y)}}function mt(m,y){sm[om++]=xx,sm[om++]=gx,gx=m,xx=y}function G(m,y,w){gs[xs++]=_a,gs[xs++]=ya,gs[xs++]=bh,bh=m;var I=_a;m=ya;var O=32-ns(I)-1;I&=~(1<<O),w+=1;var z=32-ns(y)+O;if(30<z){var K=O-O%5;z=(I&(1<<K)-1).toString(32),I>>=K,O-=K,_a=1<<32-ns(y)+O|w<<O|I,ya=z+m}else _a=1<<z|w<<O|I,ya=m}function tt(m){m.return!==null&&(mt(m,1),G(m,1,0))}function J(m){for(;m===gx;)gx=sm[--om],sm[om]=null,xx=sm[--om],sm[om]=null;for(;m===bh;)bh=gs[--xs],gs[xs]=null,ya=gs[--xs],gs[xs]=null,_a=gs[--xs],gs[xs]=null}function ht(m,y){_(Cc,y),_(Hy,m),_(Ki,null),m=ypt(y),d(Ki),_(Ki,m)}function pt(){d(Ki),d(Hy),d(Cc)}function St(m){m.memoizedState!==null&&_(bx,m);var y=Ki.current,w=gpt(y,m.type);y!==w&&(_(Hy,m),_(Ki,w))}function Mt(m){Hy.current===m&&(d(Ki),d(Hy)),bx.current===m&&(d(bx),fa?xh._currentValue=em:xh._currentValue2=em)}function ot(m){var y=Error(i(418,""));throw Z(nt(y,m)),IE}function Y(m,y){if(!ys)throw Error(i(175));mht(m.stateNode,m.type,m.memoizedProps,y,m)||ot(m)}function H(m){for(Sr=m.return;Sr;)switch(Sr.tag){case 5:case 13:Co=!1;return;case 27:case 3:Co=!0;return;default:Sr=Sr.return}}function it(m){if(!ys||m!==Sr)return!1;if(!_n)return H(m),_n=!0,!1;var y=m.tag;if(wi?y!==3&&y!==27&&(y!==5||oz(m.type)&&!fx(m.type,m.memoizedProps))&&Si&&ot(m):y!==3&&(y!==5||oz(m.type)&&!fx(m.type,m.memoizedProps))&&Si&&ot(m),H(m),y===13){if(!ys)throw Error(i(316));if(m=m.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(i(317));Si=ght(m)}else Si=wi&&y===27?aht(m.type,Si):Sr?sz(m.stateNode):null;return!0}function ut(){ys&&(Si=Sr=null,_n=!1)}function yt(){var m=vh;return m!==null&&(Lr===null?Lr=m:Lr.push.apply(Lr,m),vh=null),m}function Z(m){vh===null?vh=[m]:vh.push(m)}function at(m,y){return m===y&&(m!==0||1/m===1/y)||m!==m&&y!==y}function Et(m,y,w){fa?(_(vx,y._currentValue),y._currentValue=w):(_(vx,y._currentValue2),y._currentValue2=w)}function Ft(m){var y=vx.current;fa?m._currentValue=y:m._currentValue2=y,d(vx)}function Ot(m,y,w){for(;m!==null;){var I=m.alternate;if((m.childLanes&y)!==y?(m.childLanes|=y,I!==null&&(I.childLanes|=y)):I!==null&&(I.childLanes&y)!==y&&(I.childLanes|=y),m===w)break;m=m.return}}function Ie(m,y,w,I){var O=m.child;for(O!==null&&(O.return=m);O!==null;){var z=O.dependencies;if(z!==null){var K=O.child;z=z.firstContext;t:for(;z!==null;){var ct=z;z=O;for(var xt=0;xt<y.length;xt++)if(ct.context===y[xt]){z.lanes|=w,ct=z.alternate,ct!==null&&(ct.lanes|=w),Ot(z.return,w,m),I||(K=null);break t}z=ct.next}}else if(O.tag===18){if(K=O.return,K===null)throw Error(i(341));K.lanes|=w,z=K.alternate,z!==null&&(z.lanes|=w),Ot(K,w,m),K=null}else K=O.child;if(K!==null)K.return=O;else for(K=O;K!==null;){if(K===m){K=null;break}if(O=K.sibling,O!==null){O.return=K.return,K=O;break}K=K.return}O=K}}function Se(m,y,w,I){m=null;for(var O=y,z=!1;O!==null;){if(!z){if((O.flags&524288)!==0)z=!0;else if((O.flags&262144)!==0)break}if(O.tag===10){var K=O.alternate;if(K===null)throw Error(i(387));if(K=K.memoizedProps,K!==null){var ct=O.type;rs(O.pendingProps.value,K.value)||(m!==null?m.push(ct):m=[ct])}}else if(O===bx.current){if(K=O.alternate,K===null)throw Error(i(387));K.memoizedState.memoizedState!==O.memoizedState.memoizedState&&(m!==null?m.push(xh):m=[xh])}O=O.return}m!==null&&Ie(y,m,w,I),y.flags|=262144}function Kt(m){for(m=m.firstContext;m!==null;){var y=m.context;if(!rs(fa?y._currentValue:y._currentValue2,m.memoizedValue))return!0;m=m.next}return!1}function le(m){wh=m,ga=null,m=m.dependencies,m!==null&&(m.firstContext=null)}function Jt(m){return Ii(wh,m)}function qn(m,y){return wh===null&&le(m),Ii(m,y)}function Ii(m,y){var w=fa?y._currentValue:y._currentValue2;if(y={context:y,memoizedValue:w,next:null},ga===null){if(m===null)throw Error(i(308));ga=y,m.dependencies={lanes:0,firstContext:y},m.flags|=524288}else ga=ga.next=y;return w}function Nr(){return{controller:new Dht,data:new Map,refCount:0}}function Gs(m){m.refCount--,m.refCount===0&&jht(Bht,function(){m.controller.abort()})}function Ar(m){m!==am&&m.next===null&&(am===null?wx=am=m:am=am.next=m),Sx=!0,NE||(NE=!0,ky())}function ko(m,y){if(!AE&&Sx){AE=!0;do for(var w=!1,I=wx;I!==null;){if(!y)if(m!==0){var O=I.pendingLanes;if(O===0)var z=0;else{var K=I.suspendedLanes,ct=I.pingedLanes;z=(1<<31-ns(42|m)+1)-1,z&=O&~(K&~ct),z=z&201326741?z&201326741|1:z?z|2:0}z!==0&&(w=!0,Ff(I,z))}else z=en,z=v(I,I===Rn?z:0,I.cancelPendingCommit!==null||I.timeoutHandle!==gh),(z&3)===0||S(I,z)||(w=!0,Ff(I,z));I=I.next}while(w);AE=!1}}function Af(){Rf()}function Rf(){Sx=NE=!1;var m=0;cm!==0&&(Ept()&&(m=cm),cm=0);for(var y=Zs(),w=null,I=wx;I!==null;){var O=I.next,z=Of(I,y);z===0?(I.next=null,w===null?wx=O:w.next=O,O===null&&(am=w)):(w=I,(m!==0||(z&3)!==0)&&(Sx=!0)),I=O}ko(m,!1)}function Of(m,y){for(var w=m.suspendedLanes,I=m.pingedLanes,O=m.expirationTimes,z=m.pendingLanes&-62914561;0<z;){var K=31-ns(z),ct=1<<K,xt=O[K];xt===-1?((ct&w)===0||(ct&I)!==0)&&(O[K]=P(ct,y)):xt<=y&&(m.expiredLanes|=ct),z&=~ct}if(y=Rn,w=en,w=v(m,m===y?w:0,m.cancelPendingCommit!==null||m.timeoutHandle!==gh),I=m.callbackNode,w===0||m===y&&(bn===2||bn===9)||m.cancelPendingCommit!==null)return I!==null&&I!==null&&TE(I),m.callbackNode=null,m.callbackPriority=0;if((w&3)===0||S(m,w)){if(y=w&-w,y===m.callbackPriority)return y;switch(I!==null&&TE(I),B(w)){case 2:case 8:w=Lht;break;case 32:w=EE;break;case 268435456:w=Fht;break;default:w=EE}return I=Lf.bind(null,m),w=yx(w,I),m.callbackPriority=y,m.callbackNode=w,y}return I!==null&&I!==null&&TE(I),m.callbackPriority=2,m.callbackNode=null,2}function Lf(m,y){if(Ji!==0&&Ji!==5)return m.callbackNode=null,m.callbackPriority=0,null;var w=m.callbackNode;if(Xy(!0)&&m.callbackNode!==w)return null;var I=en;return I=v(m,m===Rn?I:0,m.cancelPendingCommit!==null||m.timeoutHandle!==gh),I===0?null:(v$(m,I,y),Of(m,Zs()),m.callbackNode!=null&&m.callbackNode===w?Lf.bind(null,m):null)}function Ff(m,y){if(Xy())return null;v$(m,y,!0)}function ky(){Rpt?Opt(function(){(Qe&6)!==0?yx(yz,Af):Rf()}):yx(yz,Af)}function ih(){return cm===0&&(cm=T()),cm}function Ty(m,y){if(qy===null){var w=qy=[];RE=0,lm=ih(),um={status:"pending",value:void 0,then:function(I){w.push(I)}}}return RE++,y.then($f,$f),y}function $f(){if(--RE===0&&qy!==null){um!==null&&(um.status="fulfilled");var m=qy;qy=null,lm=0,um=null;for(var y=0;y<m.length;y++)(0,m[y])()}}function Ey(m,y){var w=[],I={status:"pending",value:null,reason:null,then:function(O){w.push(O)}};return m.then(function(){I.status="fulfilled",I.value=y;for(var O=0;O<w.length;O++)(0,w[O])(y)},function(O){for(I.status="rejected",I.reason=O,O=0;O<w.length;O++)(0,w[O])(void 0)}),I}function rh(){var m=Sh.current;return m!==null?m:Rn.pooledCache}function fc(m,y){y===null?_(Sh,Sh.current):_(Sh,y.pool)}function zf(){var m=rh();return m===null?null:{parent:fa?ei._currentValue:ei._currentValue2,pool:m}}function mc(m,y){if(rs(m,y))return!0;if(typeof m!="object"||m===null||typeof y!="object"||y===null)return!1;var w=Object.keys(m),I=Object.keys(y);if(w.length!==I.length)return!1;for(I=0;I<w.length;I++){var O=w[I];if(!Yht.call(y,O)||!rs(m[O],y[O]))return!1}return!0}function Df(m){return m=m.status,m==="fulfilled"||m==="rejected"}function _c(){}function jf(m,y,w){switch(w=m[w],w===void 0?m.push(y):w!==y&&(y.then(_c,_c),y=w),y.status){case"fulfilled":return y.value;case"rejected":throw m=y.reason,Yf(m),m;default:if(typeof y.status=="string")y.then(_c,_c);else{if(m=Rn,m!==null&&100<m.shellSuspendCounter)throw Error(i(482));m=y,m.status="pending",m.then(function(I){if(y.status==="pending"){var O=y;O.status="fulfilled",O.value=I}},function(I){if(y.status==="pending"){var O=y;O.status="rejected",O.reason=I}})}switch(y.status){case"fulfilled":return y.value;case"rejected":throw m=y.reason,Yf(m),m}throw pm=y,Zy}}function Bf(){if(pm===null)throw Error(i(459));var m=pm;return pm=null,m}function Yf(m){if(m===Zy||m===Px)throw Error(i(483))}function yc(){for(var m=hm,y=LE=hm=0;y<m;){var w=bs[y];bs[y++]=null;var I=bs[y];bs[y++]=null;var O=bs[y];bs[y++]=null;var z=bs[y];if(bs[y++]=null,I!==null&&O!==null){var K=I.pending;K===null?O.next=O:(O.next=K.next,K.next=O),I.pending=O}z!==0&&Xf(w,O,z)}}function gc(m,y,w,I){bs[hm++]=m,bs[hm++]=y,bs[hm++]=w,bs[hm++]=I,LE|=I,m.lanes|=I,m=m.alternate,m!==null&&(m.lanes|=I)}function sh(m,y,w,I){return gc(m,y,w,I),xc(m)}function To(m,y){return gc(m,null,null,y),xc(m)}function Xf(m,y,w){m.lanes|=w;var I=m.alternate;I!==null&&(I.lanes|=w);for(var O=!1,z=m.return;z!==null;)z.childLanes|=w,I=z.alternate,I!==null&&(I.childLanes|=w),z.tag===22&&(m=z.stateNode,m===null||m._visibility&1||(O=!0)),m=z,z=z.return;return m.tag===3?(z=m.stateNode,O&&y!==null&&(O=31-ns(w),m=z.hiddenUpdates,I=m[O],I===null?m[O]=[y]:I.push(y),y.lane=w|536870912),z):null}function xc(m){if(50<ng)throw ng=0,GE=null,Error(i(185));for(var y=m.return;y!==null;)m=y,y=m.return;return m.tag===3?m.stateNode:null}function oh(m){m.updateQueue={baseState:m.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ah(m,y){m=m.updateQueue,y.updateQueue===m&&(y.updateQueue={baseState:m.baseState,firstBaseUpdate:m.firstBaseUpdate,lastBaseUpdate:m.lastBaseUpdate,shared:m.shared,callbacks:null})}function ms(m){return{lane:m,tag:0,payload:null,callback:null,next:null}}function _s(m,y,w){var I=m.updateQueue;if(I===null)return null;if(I=I.shared,(Qe&2)!==0){var O=I.pending;return O===null?y.next=y:(y.next=O.next,O.next=y),I.pending=y,y=xc(m),Xf(m,null,w),y}return gc(m,I,y,w),xc(m)}function ca(m,y,w){if(y=y.updateQueue,y!==null&&(y=y.shared,(w&4194048)!==0)){var I=y.lanes;I&=m.pendingLanes,w|=I,y.lanes=w,A(m,w)}}function ch(m,y){var w=m.updateQueue,I=m.alternate;if(I!==null&&(I=I.updateQueue,w===I)){var O=null,z=null;if(w=w.firstBaseUpdate,w!==null){do{var K={lane:w.lane,tag:w.tag,payload:w.payload,callback:null,next:null};z===null?O=z=K:z=z.next=K,w=w.next}while(w!==null);z===null?O=z=y:z=z.next=y}else O=z=y;w={baseState:I.baseState,firstBaseUpdate:O,lastBaseUpdate:z,shared:I.shared,callbacks:I.callbacks},m.updateQueue=w;return}m=w.lastBaseUpdate,m===null?w.firstBaseUpdate=y:m.next=y,w.lastBaseUpdate=y}function la(){if(FE){var m=um;if(m!==null)throw m}}function ua(m,y,w,I){FE=!1;var O=m.updateQueue;Ic=!1;var z=O.firstBaseUpdate,K=O.lastBaseUpdate,ct=O.shared.pending;if(ct!==null){O.shared.pending=null;var xt=ct,It=xt.next;xt.next=null,K===null?z=It:K.next=It,K=xt;var zt=m.alternate;zt!==null&&(zt=zt.updateQueue,ct=zt.lastBaseUpdate,ct!==K&&(ct===null?zt.firstBaseUpdate=It:ct.next=It,zt.lastBaseUpdate=xt))}if(z!==null){var Xt=O.baseState;K=0,zt=It=xt=null,ct=z;do{var Ht=ct.lane&-536870913,Fe=Ht!==ct.lane;if(Fe?(en&Ht)===Ht:(I&Ht)===Ht){Ht!==0&&Ht===lm&&(FE=!0),zt!==null&&(zt=zt.next={lane:0,tag:ct.tag,payload:ct.payload,callback:null,next:null});t:{var Ss=m,ig=ct;Ht=y;var Th=w;switch(ig.tag){case 1:if(Ss=ig.payload,typeof Ss=="function"){Xt=Ss.call(Th,Xt,Ht);break t}Xt=Ss;break t;case 3:Ss.flags=Ss.flags&-65537|128;case 0:if(Ss=ig.payload,Ht=typeof Ss=="function"?Ss.call(Th,Xt,Ht):Ss,Ht==null)break t;Xt=fE({},Xt,Ht);break t;case 2:Ic=!0}}Ht=ct.callback,Ht!==null&&(m.flags|=64,Fe&&(m.flags|=8192),Fe=O.callbacks,Fe===null?O.callbacks=[Ht]:Fe.push(Ht))}else Fe={lane:Ht,tag:ct.tag,payload:ct.payload,callback:ct.callback,next:null},zt===null?(It=zt=Fe,xt=Xt):zt=zt.next=Fe,K|=Ht;if(ct=ct.next,ct===null){if(ct=O.shared.pending,ct===null)break;Fe=ct,ct=Fe.next,Fe.next=null,O.lastBaseUpdate=Fe,O.shared.pending=null}}while(!0);zt===null&&(xt=Xt),O.baseState=xt,O.firstBaseUpdate=It,O.lastBaseUpdate=zt,z===null&&(O.shared.lanes=0),Rc|=K,m.lanes=K,m.memoizedState=Xt}}function Uf(m,y){if(typeof m!="function")throw Error(i(191,m));m.call(y)}function Vf(m,y){var w=m.callbacks;if(w!==null)for(m.callbacks=null,m=0;m<w.length;m++)Uf(w[m],y)}function Gf(m,y){m=ba,_(Tx,m),_(dm,y),ba=m|y.baseLanes}function lh(){_(Tx,ba),_(dm,dm.current)}function uh(){ba=Tx.current,d(dm),d(Tx)}function Fn(){throw Error(i(321))}function ph(m,y){if(y===null)return!1;for(var w=0;w<y.length&&w<m.length;w++)if(!rs(m[w],y[w]))return!1;return!0}function hh(m,y,w,I,O,z){return Nc=z,je=y,y.memoizedState=null,y.updateQueue=null,y.lanes=0,ye.H=m===null||m.memoizedState===null?vz:wz,Ph=!1,z=w(I,O),Ph=!1,fm&&(z=K0(y,w,I,O)),Z0(m),z}function Z0(m){ye.H=Cx;var y=Pn!==null&&Pn.next!==null;if(Nc=0,mi=Pn=je=null,Ex=!1,Ky=0,mm=null,y)throw Error(i(300));m===null||Ai||(m=m.dependencies,m!==null&&Kt(m)&&(Ai=!0))}function K0(m,y,w,I){je=m;var O=0;do{if(fm&&(mm=null),Ky=0,fm=!1,25<=O)throw Error(i(301));if(O+=1,mi=Pn=null,m.updateQueue!=null){var z=m.updateQueue;z.lastEffect=null,z.events=null,z.stores=null,z.memoCache!=null&&(z.memoCache.index=0)}ye.H=Uht,z=y(w,I)}while(fm);return z}function IT(){var m=ye.H,y=m.useState()[0];return y=typeof y.then=="function"?dh(y):y,m=m.useState()[0],(Pn!==null?Pn.memoizedState:null)!==m&&(je.flags|=1024),y}function My(){var m=Mx!==0;return Mx=0,m}function Cy(m,y,w){y.updateQueue=m.updateQueue,y.flags&=-2053,m.lanes&=~w}function Iy(m){if(Ex){for(m=m.memoizedState;m!==null;){var y=m.queue;y!==null&&(y.pending=null),m=m.next}Ex=!1}Nc=0,mi=Pn=je=null,fm=!1,Ky=Mx=0,mm=null}function cr(){var m={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return mi===null?je.memoizedState=mi=m:mi=mi.next=m,mi}function ti(){if(Pn===null){var m=je.alternate;m=m!==null?m.memoizedState:null}else m=Pn.next;var y=mi===null?je.memoizedState:mi.next;if(y!==null)mi=y,Pn=m;else{if(m===null)throw je.alternate===null?Error(i(467)):Error(i(310));Pn=m,m={memoizedState:Pn.memoizedState,baseState:Pn.baseState,baseQueue:Pn.baseQueue,queue:Pn.queue,next:null},mi===null?je.memoizedState=mi=m:mi=mi.next=m}return mi}function Ny(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function dh(m){var y=Ky;return Ky+=1,mm===null&&(mm=[]),m=jf(mm,m,y),y=je,(mi===null?y.memoizedState:mi.next)===null&&(y=y.alternate,ye.H=y===null||y.memoizedState===null?vz:wz),m}function Wf(m){if(m!==null&&typeof m=="object"){if(typeof m.then=="function")return dh(m);if(m.$$typeof===Tc)return Jt(m)}throw Error(i(438,String(m)))}function Ay(m){var y=null,w=je.updateQueue;if(w!==null&&(y=w.memoCache),y==null){var I=je.alternate;I!==null&&(I=I.updateQueue,I!==null&&(I=I.memoCache,I!=null&&(y={data:I.data.map(function(O){return O.slice()}),index:0})))}if(y==null&&(y={data:[],index:0}),w===null&&(w=Ny(),je.updateQueue=w),w.memoCache=y,w=y.data[y.index],w===void 0)for(w=y.data[y.index]=Array(m),I=0;I<m;I++)w[I]=dpt;return y.index++,w}function Ws(m,y){return typeof y=="function"?y(m):y}function Hf(m){var y=ti();return Ry(y,Pn,m)}function Ry(m,y,w){var I=m.queue;if(I===null)throw Error(i(311));I.lastRenderedReducer=w;var O=m.baseQueue,z=I.pending;if(z!==null){if(O!==null){var K=O.next;O.next=z.next,z.next=K}y.baseQueue=O=z,I.pending=null}if(z=m.baseState,O===null)m.memoizedState=z;else{y=O.next;var ct=K=null,xt=null,It=y,zt=!1;do{var Xt=It.lane&-536870913;if(Xt!==It.lane?(en&Xt)===Xt:(Nc&Xt)===Xt){var Ht=It.revertLane;if(Ht===0)xt!==null&&(xt=xt.next={lane:0,revertLane:0,action:It.action,hasEagerState:It.hasEagerState,eagerState:It.eagerState,next:null}),Xt===lm&&(zt=!0);else if((Nc&Ht)===Ht){It=It.next,Ht===lm&&(zt=!0);continue}else Xt={lane:0,revertLane:It.revertLane,action:It.action,hasEagerState:It.hasEagerState,eagerState:It.eagerState,next:null},xt===null?(ct=xt=Xt,K=z):xt=xt.next=Xt,je.lanes|=Ht,Rc|=Ht;Xt=It.action,Ph&&w(z,Xt),z=It.hasEagerState?It.eagerState:w(z,Xt)}else Ht={lane:Xt,revertLane:It.revertLane,action:It.action,hasEagerState:It.hasEagerState,eagerState:It.eagerState,next:null},xt===null?(ct=xt=Ht,K=z):xt=xt.next=Ht,je.lanes|=Xt,Rc|=Xt;It=It.next}while(It!==null&&It!==y);if(xt===null?K=z:xt.next=ct,!rs(z,m.memoizedState)&&(Ai=!0,zt&&(w=um,w!==null)))throw w;m.memoizedState=z,m.baseState=K,m.baseQueue=xt,I.lastRenderedState=z}return O===null&&(I.lanes=0),[m.memoizedState,I.dispatch]}function Oy(m){var y=ti(),w=y.queue;if(w===null)throw Error(i(311));w.lastRenderedReducer=m;var I=w.dispatch,O=w.pending,z=y.memoizedState;if(O!==null){w.pending=null;var K=O=O.next;do z=m(z,K.action),K=K.next;while(K!==O);rs(z,y.memoizedState)||(Ai=!0),y.memoizedState=z,y.baseQueue===null&&(y.baseState=z),w.lastRenderedState=z}return[z,I]}function Q7(m,y,w){var I=je,O=ti(),z=_n;if(z){if(w===void 0)throw Error(i(407));w=w()}else w=y();var K=!rs((Pn||O).memoizedState,w);K&&(O.memoizedState=w,Ai=!0),O=O.queue;var ct=nF.bind(null,I,O,m);if(Ly(2048,8,ct,[m]),O.getSnapshot!==y||K||mi!==null&&mi.memoizedState.tag&1){if(I.flags|=2048,qf(9,J0(),eF.bind(null,I,O,w,y),null),Rn===null)throw Error(i(349));z||(Nc&124)!==0||tF(I,y,w)}return w}function tF(m,y,w){m.flags|=16384,m={getSnapshot:y,value:w},y=je.updateQueue,y===null?(y=Ny(),je.updateQueue=y,y.stores=[m]):(w=y.stores,w===null?y.stores=[m]:w.push(m))}function eF(m,y,w,I){y.value=w,y.getSnapshot=I,iF(y)&&rF(m)}function nF(m,y,w){return w(function(){iF(y)&&rF(m)})}function iF(m){var y=m.getSnapshot;m=m.value;try{var w=y();return!rs(m,w)}catch{return!0}}function rF(m){var y=To(m,2);y!==null&&ts(y,m,2)}function NT(m){var y=cr();if(typeof m=="function"){var w=m;if(m=w(),Ph){j(!0);try{w()}finally{j(!1)}}}return y.memoizedState=y.baseState=m,y.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ws,lastRenderedState:m},y}function sF(m,y,w,I){return m.baseState=w,Ry(m,Pn,typeof I=="function"?I:Ws)}function Uut(m,y,w,I,O){if(tx(m))throw Error(i(485));if(m=y.action,m!==null){var z={payload:O,action:m,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(K){z.listeners.push(K)}};ye.T!==null?w(!0):z.isTransition=!1,I(z),w=y.pending,w===null?(z.next=y.pending=z,oF(y,z)):(z.next=w.next,y.pending=w.next=z)}}function oF(m,y){var w=y.action,I=y.payload,O=m.state;if(y.isTransition){var z=ye.T,K={};ye.T=K;try{var ct=w(O,I),xt=ye.S;xt!==null&&xt(K,ct),aF(m,y,ct)}catch(It){AT(m,y,It)}finally{ye.T=z}}else try{z=w(O,I),aF(m,y,z)}catch(It){AT(m,y,It)}}function aF(m,y,w){w!==null&&typeof w=="object"&&typeof w.then=="function"?w.then(function(I){cF(m,y,I)},function(I){return AT(m,y,I)}):cF(m,y,w)}function cF(m,y,w){y.status="fulfilled",y.value=w,lF(y),m.state=w,y=m.pending,y!==null&&(w=y.next,w===y?m.pending=null:(w=w.next,y.next=w,oF(m,w)))}function AT(m,y,w){var I=m.pending;if(m.pending=null,I!==null){I=I.next;do y.status="rejected",y.reason=w,lF(y),y=y.next;while(y!==I)}m.action=null}function lF(m){m=m.listeners;for(var y=0;y<m.length;y++)(0,m[y])()}function uF(m,y){return y}function pF(m,y){if(_n){var w=Rn.formState;if(w!==null){t:{var I=je;if(_n){if(Si){var O=sht(Si,Co);if(O){Si=sz(O),I=oht(O);break t}}ot(I)}I=!1}I&&(y=w[0])}}w=cr(),w.memoizedState=w.baseState=y,I={pending:null,lanes:0,dispatch:null,lastRenderedReducer:uF,lastRenderedState:y},w.queue=I,w=CF.bind(null,je,I),I.dispatch=w,I=NT(!1);var z=FT.bind(null,je,!1,I.queue);return I=cr(),O={state:y,dispatch:null,action:m,pending:null},I.queue=O,w=Uut.bind(null,je,O,z,w),O.dispatch=w,I.memoizedState=m,[y,w,!1]}function hF(m){var y=ti();return dF(y,Pn,m)}function dF(m,y,w){if(y=Ry(m,y,uF)[0],m=Hf(Ws)[0],typeof y=="object"&&y!==null&&typeof y.then=="function")try{var I=dh(y)}catch(K){throw K===Zy?Px:K}else I=y;y=ti();var O=y.queue,z=O.dispatch;return w!==y.memoizedState&&(je.flags|=2048,qf(9,J0(),Vut.bind(null,O,w),null)),[I,z,m]}function Vut(m,y){m.action=y}function fF(m){var y=ti(),w=Pn;if(w!==null)return dF(y,w,m);ti(),y=y.memoizedState,w=ti();var I=w.queue.dispatch;return w.memoizedState=m,[y,I,!1]}function qf(m,y,w,I){return m={tag:m,create:w,deps:I,inst:y,next:null},y=je.updateQueue,y===null&&(y=Ny(),je.updateQueue=y),w=y.lastEffect,w===null?y.lastEffect=m.next=m:(I=w.next,w.next=m,m.next=I,y.lastEffect=m),m}function J0(){return{destroy:void 0,resource:void 0}}function mF(){return ti().memoizedState}function Q0(m,y,w,I){var O=cr();I=I===void 0?null:I,je.flags|=m,O.memoizedState=qf(1|y,J0(),w,I)}function Ly(m,y,w,I){var O=ti();I=I===void 0?null:I;var z=O.memoizedState.inst;Pn!==null&&I!==null&&ph(I,Pn.memoizedState.deps)?O.memoizedState=qf(y,z,w,I):(je.flags|=m,O.memoizedState=qf(1|y,z,w,I))}function _F(m,y){Q0(8390656,8,m,y)}function yF(m,y){Ly(2048,8,m,y)}function gF(m,y){return Ly(4,2,m,y)}function xF(m,y){return Ly(4,4,m,y)}function bF(m,y){if(typeof y=="function"){m=m();var w=y(m);return function(){typeof w=="function"?w():y(null)}}if(y!=null)return m=m(),y.current=m,function(){y.current=null}}function vF(m,y,w){w=w!=null?w.concat([m]):null,Ly(4,4,bF.bind(null,y,m),w)}function RT(){}function wF(m,y){var w=ti();y=y===void 0?null:y;var I=w.memoizedState;return y!==null&&ph(y,I[1])?I[0]:(w.memoizedState=[m,y],m)}function SF(m,y){var w=ti();y=y===void 0?null:y;var I=w.memoizedState;if(y!==null&&ph(y,I[1]))return I[0];if(I=m(),Ph){j(!0);try{m()}finally{j(!1)}}return w.memoizedState=[I,y],I}function OT(m,y,w){return w===void 0||(Nc&1073741824)!==0?m.memoizedState=y:(m.memoizedState=w,m=b$(),je.lanes|=m,Rc|=m,w)}function PF(m,y,w,I){return rs(w,y)?w:dm.current!==null?(m=OT(m,w,I),rs(m,y)||(Ai=!0),m):(Nc&42)===0?(Ai=!0,m.memoizedState=w):(m=b$(),je.lanes|=m,Rc|=m,y)}function kF(m,y,w,I,O){var z=ma();Ni(z!==0&&8>z?z:8);var K=ye.T,ct={};ye.T=ct,FT(m,!1,y,w);try{var xt=O(),It=ye.S;if(It!==null&&It(ct,xt),xt!==null&&typeof xt=="object"&&typeof xt.then=="function"){var zt=Ey(xt,I);Fy(m,y,zt,Qr(m))}else Fy(m,y,I,Qr(m))}catch(Xt){Fy(m,y,{then:function(){},status:"rejected",reason:Xt},Qr())}finally{Ni(z),ye.T=K}}function TF(m){var y=m.memoizedState;if(y!==null)return y;y={memoizedState:em,baseState:em,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ws,lastRenderedState:em},next:null};var w={};return y.next={memoizedState:w,baseState:w,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ws,lastRenderedState:w},next:null},m.memoizedState=y,m=m.alternate,m!==null&&(m.memoizedState=y),y}function LT(){return Jt(xh)}function EF(){return ti().memoizedState}function MF(){return ti().memoizedState}function Gut(m){for(var y=m.return;y!==null;){switch(y.tag){case 24:case 3:var w=Qr();m=ms(w);var I=_s(y,m,w);I!==null&&(ts(I,y,w),ca(I,y,w)),y={cache:Nr()},m.payload=y;return}y=y.return}}function Wut(m,y,w){var I=Qr();w={lane:I,revertLane:0,action:w,hasEagerState:!1,eagerState:null,next:null},tx(m)?IF(y,w):(w=sh(m,y,w,I),w!==null&&(ts(w,m,I),NF(w,y,I)))}function CF(m,y,w){var I=Qr();Fy(m,y,w,I)}function Fy(m,y,w,I){var O={lane:I,revertLane:0,action:w,hasEagerState:!1,eagerState:null,next:null};if(tx(m))IF(y,O);else{var z=m.alternate;if(m.lanes===0&&(z===null||z.lanes===0)&&(z=y.lastRenderedReducer,z!==null))try{var K=y.lastRenderedState,ct=z(K,w);if(O.hasEagerState=!0,O.eagerState=ct,rs(ct,K))return gc(m,y,O,0),Rn===null&&yc(),!1}catch{}if(w=sh(m,y,O,I),w!==null)return ts(w,m,I),NF(w,y,I),!0}return!1}function FT(m,y,w,I){if(I={lane:2,revertLane:ih(),action:I,hasEagerState:!1,eagerState:null,next:null},tx(m)){if(y)throw Error(i(479))}else y=sh(m,w,I,2),y!==null&&ts(y,m,2)}function tx(m){var y=m.alternate;return m===je||y!==null&&y===je}function IF(m,y){fm=Ex=!0;var w=m.pending;w===null?y.next=y:(y.next=w.next,w.next=y),m.pending=y}function NF(m,y,w){if((w&4194048)!==0){var I=y.lanes;I&=m.pendingLanes,w|=I,y.lanes=w,A(m,w)}}function ex(m){var y=Jy;return Jy+=1,_m===null&&(_m=[]),jf(_m,m,y)}function $y(m,y){y=y.props.ref,m.ref=y!==void 0?y:null}function nx(m,y){throw y.$$typeof===ppt?Error(i(525)):(m=Object.prototype.toString.call(y),Error(i(31,m==="[object Object]"?"object with keys {"+Object.keys(y).join(", ")+"}":m)))}function AF(m){var y=m._init;return y(m._payload)}function RF(m){function y(gt,dt){if(m){var vt=gt.deletions;vt===null?(gt.deletions=[dt],gt.flags|=16):vt.push(dt)}}function w(gt,dt){if(!m)return null;for(;dt!==null;)y(gt,dt),dt=dt.sibling;return null}function I(gt){for(var dt=new Map;gt!==null;)gt.key!==null?dt.set(gt.key,gt):dt.set(gt.index,gt),gt=gt.sibling;return dt}function O(gt,dt){return gt=da(gt,dt),gt.index=0,gt.sibling=null,gt}function z(gt,dt,vt){return gt.index=vt,m?(vt=gt.alternate,vt!==null?(vt=vt.index,vt<dt?(gt.flags|=67108866,dt):vt):(gt.flags|=67108866,dt)):(gt.flags|=1048576,dt)}function K(gt){return m&&gt.alternate===null&&(gt.flags|=67108866),gt}function ct(gt,dt,vt,$t){return dt===null||dt.tag!==6?(dt=pE(vt,gt.mode,$t),dt.return=gt,dt):(dt=O(dt,vt),dt.return=gt,dt)}function xt(gt,dt,vt,$t){var ce=vt.type;return ce===tm?zt(gt,dt,vt.props.children,$t,vt.key):dt!==null&&(dt.elementType===ce||typeof ce=="object"&&ce!==null&&ce.$$typeof===Ec&&AF(ce)===dt.type)?(dt=O(dt,vt.props),$y(dt,vt),dt.return=gt,dt):(dt=px(vt.type,vt.key,vt.props,null,gt.mode,$t),$y(dt,vt),dt.return=gt,dt)}function It(gt,dt,vt,$t){return dt===null||dt.tag!==4||dt.stateNode.containerInfo!==vt.containerInfo||dt.stateNode.implementation!==vt.implementation?(dt=hE(vt,gt.mode,$t),dt.return=gt,dt):(dt=O(dt,vt.children||[]),dt.return=gt,dt)}function zt(gt,dt,vt,$t,ce){return dt===null||dt.tag!==7?(dt=yh(vt,gt.mode,$t,ce),dt.return=gt,dt):(dt=O(dt,vt),dt.return=gt,dt)}function Xt(gt,dt,vt){if(typeof dt=="string"&&dt!==""||typeof dt=="number"||typeof dt=="bigint")return dt=pE(""+dt,gt.mode,vt),dt.return=gt,dt;if(typeof dt=="object"&&dt!==null){switch(dt.$$typeof){case hx:return vt=px(dt.type,dt.key,dt.props,null,gt.mode,vt),$y(vt,dt),vt.return=gt,vt;case Qf:return dt=hE(dt,gt.mode,vt),dt.return=gt,dt;case Ec:var $t=dt._init;return dt=$t(dt._payload),Xt(gt,dt,vt)}if(dx(dt)||l(dt))return dt=yh(dt,gt.mode,vt,null),dt.return=gt,dt;if(typeof dt.then=="function")return Xt(gt,ex(dt),vt);if(dt.$$typeof===Tc)return Xt(gt,qn(gt,dt),vt);nx(gt,dt)}return null}function Ht(gt,dt,vt,$t){var ce=dt!==null?dt.key:null;if(typeof vt=="string"&&vt!==""||typeof vt=="number"||typeof vt=="bigint")return ce!==null?null:ct(gt,dt,""+vt,$t);if(typeof vt=="object"&&vt!==null){switch(vt.$$typeof){case hx:return vt.key===ce?xt(gt,dt,vt,$t):null;case Qf:return vt.key===ce?It(gt,dt,vt,$t):null;case Ec:return ce=vt._init,vt=ce(vt._payload),Ht(gt,dt,vt,$t)}if(dx(vt)||l(vt))return ce!==null?null:zt(gt,dt,vt,$t,null);if(typeof vt.then=="function")return Ht(gt,dt,ex(vt),$t);if(vt.$$typeof===Tc)return Ht(gt,dt,qn(gt,vt),$t);nx(gt,vt)}return null}function Fe(gt,dt,vt,$t,ce){if(typeof $t=="string"&&$t!==""||typeof $t=="number"||typeof $t=="bigint")return gt=gt.get(vt)||null,ct(dt,gt,""+$t,ce);if(typeof $t=="object"&&$t!==null){switch($t.$$typeof){case hx:return gt=gt.get($t.key===null?vt:$t.key)||null,xt(dt,gt,$t,ce);case Qf:return gt=gt.get($t.key===null?vt:$t.key)||null,It(dt,gt,$t,ce);case Ec:var $n=$t._init;return $t=$n($t._payload),Fe(gt,dt,vt,$t,ce)}if(dx($t)||l($t))return gt=gt.get(vt)||null,zt(dt,gt,$t,ce,null);if(typeof $t.then=="function")return Fe(gt,dt,vt,ex($t),ce);if($t.$$typeof===Tc)return Fe(gt,dt,vt,qn(dt,$t),ce);nx(dt,$t)}return null}function Ss(gt,dt,vt,$t){for(var ce=null,$n=null,Te=dt,on=dt=0,Oi=null;Te!==null&&on<vt.length;on++){Te.index>on?(Oi=Te,Te=null):Oi=Te.sibling;var an=Ht(gt,Te,vt[on],$t);if(an===null){Te===null&&(Te=Oi);break}m&&Te&&an.alternate===null&&y(gt,Te),dt=z(an,dt,on),$n===null?ce=an:$n.sibling=an,$n=an,Te=Oi}if(on===vt.length)return w(gt,Te),_n&&mt(gt,on),ce;if(Te===null){for(;on<vt.length;on++)Te=Xt(gt,vt[on],$t),Te!==null&&(dt=z(Te,dt,on),$n===null?ce=Te:$n.sibling=Te,$n=Te);return _n&&mt(gt,on),ce}for(Te=I(Te);on<vt.length;on++)Oi=Fe(Te,gt,on,vt[on],$t),Oi!==null&&(m&&Oi.alternate!==null&&Te.delete(Oi.key===null?on:Oi.key),dt=z(Oi,dt,on),$n===null?ce=Oi:$n.sibling=Oi,$n=Oi);return m&&Te.forEach(function(Fc){return y(gt,Fc)}),_n&&mt(gt,on),ce}function ig(gt,dt,vt,$t){if(vt==null)throw Error(i(151));for(var ce=null,$n=null,Te=dt,on=dt=0,Oi=null,an=vt.next();Te!==null&&!an.done;on++,an=vt.next()){Te.index>on?(Oi=Te,Te=null):Oi=Te.sibling;var Fc=Ht(gt,Te,an.value,$t);if(Fc===null){Te===null&&(Te=Oi);break}m&&Te&&Fc.alternate===null&&y(gt,Te),dt=z(Fc,dt,on),$n===null?ce=Fc:$n.sibling=Fc,$n=Fc,Te=Oi}if(an.done)return w(gt,Te),_n&&mt(gt,on),ce;if(Te===null){for(;!an.done;on++,an=vt.next())an=Xt(gt,an.value,$t),an!==null&&(dt=z(an,dt,on),$n===null?ce=an:$n.sibling=an,$n=an);return _n&&mt(gt,on),ce}for(Te=I(Te);!an.done;on++,an=vt.next())an=Fe(Te,gt,on,an.value,$t),an!==null&&(m&&an.alternate!==null&&Te.delete(an.key===null?on:an.key),dt=z(an,dt,on),$n===null?ce=an:$n.sibling=an,$n=an);return m&&Te.forEach(function(Wht){return y(gt,Wht)}),_n&&mt(gt,on),ce}function Th(gt,dt,vt,$t){if(typeof vt=="object"&&vt!==null&&vt.type===tm&&vt.key===null&&(vt=vt.props.children),typeof vt=="object"&&vt!==null){switch(vt.$$typeof){case hx:t:{for(var ce=vt.key;dt!==null;){if(dt.key===ce){if(ce=vt.type,ce===tm){if(dt.tag===7){w(gt,dt.sibling),$t=O(dt,vt.props.children),$t.return=gt,gt=$t;break t}}else if(dt.elementType===ce||typeof ce=="object"&&ce!==null&&ce.$$typeof===Ec&&AF(ce)===dt.type){w(gt,dt.sibling),$t=O(dt,vt.props),$y($t,vt),$t.return=gt,gt=$t;break t}w(gt,dt);break}else y(gt,dt);dt=dt.sibling}vt.type===tm?($t=yh(vt.props.children,gt.mode,$t,vt.key),$t.return=gt,gt=$t):($t=px(vt.type,vt.key,vt.props,null,gt.mode,$t),$y($t,vt),$t.return=gt,gt=$t)}return K(gt);case Qf:t:{for(ce=vt.key;dt!==null;){if(dt.key===ce)if(dt.tag===4&&dt.stateNode.containerInfo===vt.containerInfo&&dt.stateNode.implementation===vt.implementation){w(gt,dt.sibling),$t=O(dt,vt.children||[]),$t.return=gt,gt=$t;break t}else{w(gt,dt);break}else y(gt,dt);dt=dt.sibling}$t=hE(vt,gt.mode,$t),$t.return=gt,gt=$t}return K(gt);case Ec:return ce=vt._init,vt=ce(vt._payload),Th(gt,dt,vt,$t)}if(dx(vt))return Ss(gt,dt,vt,$t);if(l(vt)){if(ce=l(vt),typeof ce!="function")throw Error(i(150));return vt=ce.call(vt),ig(gt,dt,vt,$t)}if(typeof vt.then=="function")return Th(gt,dt,ex(vt),$t);if(vt.$$typeof===Tc)return Th(gt,dt,qn(gt,vt),$t);nx(gt,vt)}return typeof vt=="string"&&vt!==""||typeof vt=="number"||typeof vt=="bigint"?(vt=""+vt,dt!==null&&dt.tag===6?(w(gt,dt.sibling),$t=O(dt,vt),$t.return=gt,gt=$t):(w(gt,dt),$t=pE(vt,gt.mode,$t),$t.return=gt,gt=$t),K(gt)):w(gt,dt)}return function(gt,dt,vt,$t){try{Jy=0;var ce=Th(gt,dt,vt,$t);return _m=null,ce}catch(Te){if(Te===Zy||Te===Px)throw Te;var $n=e(29,Te,null,gt.mode);return $n.lanes=$t,$n.return=gt,$n}}}function bc(m){var y=m.alternate;_(Pi,Pi.current&1),_(vs,m),Io===null&&(y===null||dm.current!==null||y.memoizedState!==null)&&(Io=m)}function OF(m){if(m.tag===22){if(_(Pi,Pi.current),_(vs,m),Io===null){var y=m.alternate;y!==null&&y.memoizedState!==null&&(Io=m)}}else vc(m)}function vc(){_(Pi,Pi.current),_(vs,vs.current)}function pa(m){d(vs),Io===m&&(Io=null),d(Pi)}function ix(m){for(var y=m;y!==null;){if(y.tag===13){var w=y.memoizedState;if(w!==null&&(w=w.dehydrated,w===null||wE(w)||SE(w)))return y}else if(y.tag===19&&y.memoizedProps.revealOrder!==void 0){if((y.flags&128)!==0)return y}else if(y.child!==null){y.child.return=y,y=y.child;continue}if(y===m)break;for(;y.sibling===null;){if(y.return===null||y.return===m)return null;y=y.return}y.sibling.return=y.return,y=y.sibling}return null}function $T(m,y,w,I){y=m.memoizedState,w=w(I,y),w=w==null?y:fE({},y,w),m.memoizedState=w,m.lanes===0&&(m.updateQueue.baseState=w)}function LF(m,y,w,I,O,z,K){return m=m.stateNode,typeof m.shouldComponentUpdate=="function"?m.shouldComponentUpdate(I,z,K):y.prototype&&y.prototype.isPureReactComponent?!mc(w,I)||!mc(O,z):!0}function FF(m,y,w,I){m=y.state,typeof y.componentWillReceiveProps=="function"&&y.componentWillReceiveProps(w,I),typeof y.UNSAFE_componentWillReceiveProps=="function"&&y.UNSAFE_componentWillReceiveProps(w,I),y.state!==m&&$E.enqueueReplaceState(y,y.state,null)}function fh(m,y){var w=y;if("ref"in y){w={};for(var I in y)I!=="ref"&&(w[I]=y[I])}if(m=m.defaultProps){w===y&&(w=fE({},w));for(var O in m)w[O]===void 0&&(w[O]=m[O])}return w}function rx(m,y){try{var w=m.onUncaughtError;w(y.value,{componentStack:y.stack})}catch(I){setTimeout(function(){throw I})}}function $F(m,y,w){try{var I=m.onCaughtError;I(w.value,{componentStack:w.stack,errorBoundary:y.tag===1?y.stateNode:null})}catch(O){setTimeout(function(){throw O})}}function zT(m,y,w){return w=ms(w),w.tag=3,w.payload={element:null},w.callback=function(){rx(m,y)},w}function zF(m){return m=ms(m),m.tag=3,m}function DF(m,y,w,I){var O=w.type.getDerivedStateFromError;if(typeof O=="function"){var z=I.value;m.payload=function(){return O(z)},m.callback=function(){$F(y,w,I)}}var K=w.stateNode;K!==null&&typeof K.componentDidCatch=="function"&&(m.callback=function(){$F(y,w,I),typeof O!="function"&&(Oc===null?Oc=new Set([this]):Oc.add(this));var ct=I.stack;this.componentDidCatch(I.value,{componentStack:ct!==null?ct:""})})}function Hut(m,y,w,I,O){if(w.flags|=32768,I!==null&&typeof I=="object"&&typeof I.then=="function"){if(y=w.alternate,y!==null&&Se(y,w,O,!0),w=vs.current,w!==null){switch(w.tag){case 13:return Io===null?aE():w.alternate===null&&ni===0&&(ni=3),w.flags&=-257,w.flags|=65536,w.lanes=O,I===kx?w.flags|=16384:(y=w.updateQueue,y===null?w.updateQueue=new Set([I]):y.add(I),lE(m,I,O)),!1;case 22:return w.flags|=65536,I===kx?w.flags|=16384:(y=w.updateQueue,y===null?(y={transitions:null,markerInstances:null,retryQueue:new Set([I])},w.updateQueue=y):(w=y.retryQueue,w===null?y.retryQueue=new Set([I]):w.add(I)),lE(m,I,O)),!1}throw Error(i(435,w.tag))}return lE(m,I,O),aE(),!1}if(_n)return y=vs.current,y!==null?((y.flags&65536)===0&&(y.flags|=256),y.flags|=65536,y.lanes=O,I!==IE&&(m=Error(i(422),{cause:I}),Z(nt(m,w)))):(I!==IE&&(y=Error(i(423),{cause:I}),Z(nt(y,w))),m=m.current.alternate,m.flags|=65536,O&=-O,m.lanes|=O,I=nt(I,w),O=zT(m.stateNode,I,O),ch(m,O),ni!==4&&(ni=2)),!1;var z=Error(i(520),{cause:I});if(z=nt(z,w),tg===null?tg=[z]:tg.push(z),ni!==4&&(ni=2),y===null)return!0;I=nt(I,w),w=y;do{switch(w.tag){case 3:return w.flags|=65536,m=O&-O,w.lanes|=m,m=zT(w.stateNode,I,m),ch(w,m),!1;case 1:if(y=w.type,z=w.stateNode,(w.flags&128)===0&&(typeof y.getDerivedStateFromError=="function"||z!==null&&typeof z.componentDidCatch=="function"&&(Oc===null||!Oc.has(z))))return w.flags|=65536,O&=-O,w.lanes|=O,O=zF(O),DF(O,m,w,I),ch(w,O),!1}w=w.return}while(w!==null);return!1}function Zi(m,y,w,I){y.child=m===null?Sz(y,null,w,I):ym(y,m.child,w,I)}function jF(m,y,w,I,O){w=w.render;var z=y.ref;if("ref"in I){var K={};for(var ct in I)ct!=="ref"&&(K[ct]=I[ct])}else K=I;return le(y),I=hh(m,y,w,K,z,O),ct=My(),m!==null&&!Ai?(Cy(m,y,O),ha(m,y,O)):(_n&&ct&&tt(y),y.flags|=1,Zi(m,y,I,O),y.child)}function BF(m,y,w,I,O){if(m===null){var z=w.type;return typeof z=="function"&&!uE(z)&&z.defaultProps===void 0&&w.compare===null?(y.tag=15,y.type=z,YF(m,y,z,I,O)):(m=px(w.type,null,I,y,y.mode,O),m.ref=y.ref,m.return=y,y.child=m)}if(z=m.child,!VT(m,O)){var K=z.memoizedProps;if(w=w.compare,w=w!==null?w:mc,w(K,I)&&m.ref===y.ref)return ha(m,y,O)}return y.flags|=1,m=da(z,I),m.ref=y.ref,m.return=y,y.child=m}function YF(m,y,w,I,O){if(m!==null){var z=m.memoizedProps;if(mc(z,I)&&m.ref===y.ref)if(Ai=!1,y.pendingProps=I=z,VT(m,O))(m.flags&131072)!==0&&(Ai=!0);else return y.lanes=m.lanes,ha(m,y,O)}return DT(m,y,w,I,O)}function XF(m,y,w){var I=y.pendingProps,O=I.children,z=m!==null?m.memoizedState:null;if(I.mode==="hidden"){if((y.flags&128)!==0){if(I=z!==null?z.baseLanes|w:w,m!==null){for(O=y.child=m.child,z=0;O!==null;)z=z|O.lanes|O.childLanes,O=O.sibling;y.childLanes=z&~I}else y.childLanes=0,y.child=null;return UF(m,y,I,w)}if((w&536870912)!==0)y.memoizedState={baseLanes:0,cachePool:null},m!==null&&fc(y,z!==null?z.cachePool:null),z!==null?Gf(y,z):lh(),OF(y);else return y.lanes=y.childLanes=536870912,UF(m,y,z!==null?z.baseLanes|w:w,w)}else z!==null?(fc(y,z.cachePool),Gf(y,z),vc(y),y.memoizedState=null):(m!==null&&fc(y,null),lh(),vc(y));return Zi(m,y,O,w),y.child}function UF(m,y,w,I){var O=rh();return O=O===null?null:{parent:fa?ei._currentValue:ei._currentValue2,pool:O},y.memoizedState={baseLanes:w,cachePool:O},m!==null&&fc(y,null),lh(),OF(y),m!==null&&Se(m,y,I,!0),null}function sx(m,y){var w=y.ref;if(w===null)m!==null&&m.ref!==null&&(y.flags|=4194816);else{if(typeof w!="function"&&typeof w!="object")throw Error(i(284));(m===null||m.ref!==w)&&(y.flags|=4194816)}}function DT(m,y,w,I,O){return le(y),w=hh(m,y,w,I,void 0,O),I=My(),m!==null&&!Ai?(Cy(m,y,O),ha(m,y,O)):(_n&&I&&tt(y),y.flags|=1,Zi(m,y,w,O),y.child)}function VF(m,y,w,I,O,z){return le(y),y.updateQueue=null,w=K0(y,I,w,O),Z0(m),I=My(),m!==null&&!Ai?(Cy(m,y,z),ha(m,y,z)):(_n&&I&&tt(y),y.flags|=1,Zi(m,y,w,z),y.child)}function GF(m,y,w,I,O){if(le(y),y.stateNode===null){var z=rm,K=w.contextType;typeof K=="object"&&K!==null&&(z=Jt(K)),z=new w(I,z),y.memoizedState=z.state!==null&&z.state!==void 0?z.state:null,z.updater=$E,y.stateNode=z,z._reactInternals=y,z=y.stateNode,z.props=I,z.state=y.memoizedState,z.refs={},oh(y),K=w.contextType,z.context=typeof K=="object"&&K!==null?Jt(K):rm,z.state=y.memoizedState,K=w.getDerivedStateFromProps,typeof K=="function"&&($T(y,w,K,I),z.state=y.memoizedState),typeof w.getDerivedStateFromProps=="function"||typeof z.getSnapshotBeforeUpdate=="function"||typeof z.UNSAFE_componentWillMount!="function"&&typeof z.componentWillMount!="function"||(K=z.state,typeof z.componentWillMount=="function"&&z.componentWillMount(),typeof z.UNSAFE_componentWillMount=="function"&&z.UNSAFE_componentWillMount(),K!==z.state&&$E.enqueueReplaceState(z,z.state,null),ua(y,I,z,O),la(),z.state=y.memoizedState),typeof z.componentDidMount=="function"&&(y.flags|=4194308),I=!0}else if(m===null){z=y.stateNode;var ct=y.memoizedProps,xt=fh(w,ct);z.props=xt;var It=z.context,zt=w.contextType;K=rm,typeof zt=="object"&&zt!==null&&(K=Jt(zt));var Xt=w.getDerivedStateFromProps;zt=typeof Xt=="function"||typeof z.getSnapshotBeforeUpdate=="function",ct=y.pendingProps!==ct,zt||typeof z.UNSAFE_componentWillReceiveProps!="function"&&typeof z.componentWillReceiveProps!="function"||(ct||It!==K)&&FF(y,z,I,K),Ic=!1;var Ht=y.memoizedState;z.state=Ht,ua(y,I,z,O),la(),It=y.memoizedState,ct||Ht!==It||Ic?(typeof Xt=="function"&&($T(y,w,Xt,I),It=y.memoizedState),(xt=Ic||LF(y,w,xt,I,Ht,It,K))?(zt||typeof z.UNSAFE_componentWillMount!="function"&&typeof z.componentWillMount!="function"||(typeof z.componentWillMount=="function"&&z.componentWillMount(),typeof z.UNSAFE_componentWillMount=="function"&&z.UNSAFE_componentWillMount()),typeof z.componentDidMount=="function"&&(y.flags|=4194308)):(typeof z.componentDidMount=="function"&&(y.flags|=4194308),y.memoizedProps=I,y.memoizedState=It),z.props=I,z.state=It,z.context=K,I=xt):(typeof z.componentDidMount=="function"&&(y.flags|=4194308),I=!1)}else{z=y.stateNode,ah(m,y),K=y.memoizedProps,zt=fh(w,K),z.props=zt,Xt=y.pendingProps,Ht=z.context,It=w.contextType,xt=rm,typeof It=="object"&&It!==null&&(xt=Jt(It)),ct=w.getDerivedStateFromProps,(It=typeof ct=="function"||typeof z.getSnapshotBeforeUpdate=="function")||typeof z.UNSAFE_componentWillReceiveProps!="function"&&typeof z.componentWillReceiveProps!="function"||(K!==Xt||Ht!==xt)&&FF(y,z,I,xt),Ic=!1,Ht=y.memoizedState,z.state=Ht,ua(y,I,z,O),la();var Fe=y.memoizedState;K!==Xt||Ht!==Fe||Ic||m!==null&&m.dependencies!==null&&Kt(m.dependencies)?(typeof ct=="function"&&($T(y,w,ct,I),Fe=y.memoizedState),(zt=Ic||LF(y,w,zt,I,Ht,Fe,xt)||m!==null&&m.dependencies!==null&&Kt(m.dependencies))?(It||typeof z.UNSAFE_componentWillUpdate!="function"&&typeof z.componentWillUpdate!="function"||(typeof z.componentWillUpdate=="function"&&z.componentWillUpdate(I,Fe,xt),typeof z.UNSAFE_componentWillUpdate=="function"&&z.UNSAFE_componentWillUpdate(I,Fe,xt)),typeof z.componentDidUpdate=="function"&&(y.flags|=4),typeof z.getSnapshotBeforeUpdate=="function"&&(y.flags|=1024)):(typeof z.componentDidUpdate!="function"||K===m.memoizedProps&&Ht===m.memoizedState||(y.flags|=4),typeof z.getSnapshotBeforeUpdate!="function"||K===m.memoizedProps&&Ht===m.memoizedState||(y.flags|=1024),y.memoizedProps=I,y.memoizedState=Fe),z.props=I,z.state=Fe,z.context=xt,I=zt):(typeof z.componentDidUpdate!="function"||K===m.memoizedProps&&Ht===m.memoizedState||(y.flags|=4),typeof z.getSnapshotBeforeUpdate!="function"||K===m.memoizedProps&&Ht===m.memoizedState||(y.flags|=1024),I=!1)}return z=I,sx(m,y),I=(y.flags&128)!==0,z||I?(z=y.stateNode,w=I&&typeof w.getDerivedStateFromError!="function"?null:z.render(),y.flags|=1,m!==null&&I?(y.child=ym(y,m.child,null,O),y.child=ym(y,null,w,O)):Zi(m,y,w,O),y.memoizedState=z.state,m=y.child):m=ha(m,y,O),m}function WF(m,y,w,I){return ut(),y.flags|=256,Zi(m,y,w,I),y.child}function jT(m){return{baseLanes:m,cachePool:zf()}}function BT(m,y,w){return m=m!==null?m.childLanes&~w:0,y&&(m|=ws),m}function HF(m,y,w){var I=y.pendingProps,O=!1,z=(y.flags&128)!==0,K;if((K=z)||(K=m!==null&&m.memoizedState===null?!1:(Pi.current&2)!==0),K&&(O=!0,y.flags&=-129),K=(y.flags&32)!==0,y.flags&=-33,m===null){if(_n){if(O?bc(y):vc(y),_n){var ct=Si,xt;(xt=ct)&&(ct=fht(ct,Co),ct!==null?(y.memoizedState={dehydrated:ct,treeContext:bh!==null?{id:_a,overflow:ya}:null,retryLane:536870912,hydrationErrors:null},xt=e(18,null,null,0),xt.stateNode=ct,xt.return=y,y.child=xt,Sr=y,Si=null,xt=!0):xt=!1),xt||ot(y)}if(ct=y.memoizedState,ct!==null&&(ct=ct.dehydrated,ct!==null))return SE(ct)?y.lanes=32:y.lanes=536870912,null;pa(y)}return ct=I.children,I=I.fallback,O?(vc(y),O=y.mode,ct=ox({mode:"hidden",children:ct},O),I=yh(I,O,w,null),ct.return=y,I.return=y,ct.sibling=I,y.child=ct,O=y.child,O.memoizedState=jT(w),O.childLanes=BT(m,K,w),y.memoizedState=zE,I):(bc(y),YT(y,ct))}if(xt=m.memoizedState,xt!==null&&(ct=xt.dehydrated,ct!==null)){if(z)y.flags&256?(bc(y),y.flags&=-257,y=XT(m,y,w)):y.memoizedState!==null?(vc(y),y.child=m.child,y.flags|=128,y=null):(vc(y),O=I.fallback,ct=y.mode,I=ox({mode:"visible",children:I.children},ct),O=yh(O,ct,w,null),O.flags|=2,I.return=y,O.return=y,I.sibling=O,y.child=I,ym(y,m.child,null,w),I=y.child,I.memoizedState=jT(w),I.childLanes=BT(m,K,w),y.memoizedState=zE,y=O);else if(bc(y),SE(ct))K=iht(ct).digest,I=Error(i(419)),I.stack="",I.digest=K,Z({value:I,source:null,stack:null}),y=XT(m,y,w);else if(Ai||Se(m,y,w,!1),K=(w&m.childLanes)!==0,Ai||K){if(K=Rn,K!==null&&(I=w&-w,I=(I&42)!==0?1:R(I),I=(I&(K.suspendedLanes|w))!==0?0:I,I!==0&&I!==xt.retryLane))throw xt.retryLane=I,To(m,I),ts(K,m,I),kz;wE(ct)||aE(),y=XT(m,y,w)}else wE(ct)?(y.flags|=192,y.child=m.child,y=null):(m=xt.treeContext,ys&&(Si=uht(ct),Sr=y,_n=!0,vh=null,Co=!1,m!==null&&(gs[xs++]=_a,gs[xs++]=ya,gs[xs++]=bh,_a=m.id,ya=m.overflow,bh=y)),y=YT(y,I.children),y.flags|=4096);return y}return O?(vc(y),O=I.fallback,ct=y.mode,xt=m.child,z=xt.sibling,I=da(xt,{mode:"hidden",children:I.children}),I.subtreeFlags=xt.subtreeFlags&65011712,z!==null?O=da(z,O):(O=yh(O,ct,w,null),O.flags|=2),O.return=y,I.return=y,I.sibling=O,y.child=I,I=O,O=y.child,ct=m.child.memoizedState,ct===null?ct=jT(w):(xt=ct.cachePool,xt!==null?(z=fa?ei._currentValue:ei._currentValue2,xt=xt.parent!==z?{parent:z,pool:z}:xt):xt=zf(),ct={baseLanes:ct.baseLanes|w,cachePool:xt}),O.memoizedState=ct,O.childLanes=BT(m,K,w),y.memoizedState=zE,I):(bc(y),w=m.child,m=w.sibling,w=da(w,{mode:"visible",children:I.children}),w.return=y,w.sibling=null,m!==null&&(K=y.deletions,K===null?(y.deletions=[m],y.flags|=16):K.push(m)),y.child=w,y.memoizedState=null,w)}function YT(m,y){return y=ox({mode:"visible",children:y},m.mode),y.return=m,m.child=y}function ox(m,y){return m=e(22,m,null,y),m.lanes=0,m.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null},m}function XT(m,y,w){return ym(y,m.child,null,w),m=YT(y,y.pendingProps.children),m.flags|=2,y.memoizedState=null,m}function qF(m,y,w){m.lanes|=y;var I=m.alternate;I!==null&&(I.lanes|=y),Ot(m.return,y,w)}function UT(m,y,w,I,O){var z=m.memoizedState;z===null?m.memoizedState={isBackwards:y,rendering:null,renderingStartTime:0,last:I,tail:w,tailMode:O}:(z.isBackwards=y,z.rendering=null,z.renderingStartTime=0,z.last=I,z.tail=w,z.tailMode=O)}function ZF(m,y,w){var I=y.pendingProps,O=I.revealOrder,z=I.tail;if(Zi(m,y,I.children,w),I=Pi.current,(I&2)!==0)I=I&1|2,y.flags|=128;else{if(m!==null&&(m.flags&128)!==0)t:for(m=y.child;m!==null;){if(m.tag===13)m.memoizedState!==null&&qF(m,w,y);else if(m.tag===19)qF(m,w,y);else if(m.child!==null){m.child.return=m,m=m.child;continue}if(m===y)break t;for(;m.sibling===null;){if(m.return===null||m.return===y)break t;m=m.return}m.sibling.return=m.return,m=m.sibling}I&=1}switch(_(Pi,I),O){case"forwards":for(w=y.child,O=null;w!==null;)m=w.alternate,m!==null&&ix(m)===null&&(O=w),w=w.sibling;w=O,w===null?(O=y.child,y.child=null):(O=w.sibling,w.sibling=null),UT(y,!1,O,w,z);break;case"backwards":for(w=null,O=y.child,y.child=null;O!==null;){if(m=O.alternate,m!==null&&ix(m)===null){y.child=O;break}m=O.sibling,O.sibling=w,w=O,O=m}UT(y,!0,w,null,z);break;case"together":UT(y,!1,null,null,void 0);break;default:y.memoizedState=null}return y.child}function ha(m,y,w){if(m!==null&&(y.dependencies=m.dependencies),Rc|=y.lanes,(w&y.childLanes)===0)if(m!==null){if(Se(m,y,w,!1),(w&y.childLanes)===0)return null}else return null;if(m!==null&&y.child!==m.child)throw Error(i(153));if(y.child!==null){for(m=y.child,w=da(m,m.pendingProps),y.child=w,w.return=y;m.sibling!==null;)m=m.sibling,w=w.sibling=da(m,m.pendingProps),w.return=y;w.sibling=null}return y.child}function VT(m,y){return(m.lanes&y)!==0?!0:(m=m.dependencies,!!(m!==null&&Kt(m)))}function qut(m,y,w){switch(y.tag){case 3:ht(y,y.stateNode.containerInfo),Et(y,ei,m.memoizedState.cache),ut();break;case 27:case 5:St(y);break;case 4:ht(y,y.stateNode.containerInfo);break;case 10:Et(y,y.type,y.memoizedProps.value);break;case 13:var I=y.memoizedState;if(I!==null)return I.dehydrated!==null?(bc(y),y.flags|=128,null):(w&y.child.childLanes)!==0?HF(m,y,w):(bc(y),m=ha(m,y,w),m!==null?m.sibling:null);bc(y);break;case 19:var O=(m.flags&128)!==0;if(I=(w&y.childLanes)!==0,I||(Se(m,y,w,!1),I=(w&y.childLanes)!==0),O){if(I)return ZF(m,y,w);y.flags|=128}if(O=y.memoizedState,O!==null&&(O.rendering=null,O.tail=null,O.lastEffect=null),_(Pi,Pi.current),I)break;return null;case 22:case 23:return y.lanes=0,XF(m,y,w);case 24:Et(y,ei,m.memoizedState.cache)}return ha(m,y,w)}function KF(m,y,w){if(m!==null)if(m.memoizedProps!==y.pendingProps)Ai=!0;else{if(!VT(m,w)&&(y.flags&128)===0)return Ai=!1,qut(m,y,w);Ai=(m.flags&131072)!==0}else Ai=!1,_n&&(y.flags&1048576)!==0&&G(y,xx,y.index);switch(y.lanes=0,y.tag){case 16:t:{m=y.pendingProps;var I=y.elementType,O=I._init;if(I=O(I._payload),y.type=I,typeof I=="function")uE(I)?(m=fh(I,m),y.tag=1,y=GF(null,y,I,m,w)):(y.tag=0,y=DT(null,y,I,m,w));else{if(I!=null){if(O=I.$$typeof,O===_E){y.tag=11,y=jF(null,y,I,m,w);break t}else if(O===xE){y.tag=14,y=BF(null,y,I,m,w);break t}}throw y=u(I)||I,Error(i(306,y,""))}}return y;case 0:return DT(m,y,y.type,y.pendingProps,w);case 1:return I=y.type,O=fh(I,y.pendingProps),GF(m,y,I,O,w);case 3:t:{if(ht(y,y.stateNode.containerInfo),m===null)throw Error(i(387));var z=y.pendingProps;O=y.memoizedState,I=O.element,ah(m,y),ua(y,z,null,w);var K=y.memoizedState;if(z=K.cache,Et(y,ei,z),z!==O.cache&&Ie(y,[ei],w,!0),la(),z=K.element,ys&&O.isDehydrated)if(O={element:z,isDehydrated:!1,cache:K.cache},y.updateQueue.baseState=O,y.memoizedState=O,y.flags&256){y=WF(m,y,z,w);break t}else if(z!==I){I=nt(Error(i(424)),y),Z(I),y=WF(m,y,z,w);break t}else for(ys&&(Si=lht(y.stateNode.containerInfo),Sr=y,_n=!0,vh=null,Co=!0),w=Sz(y,null,z,w),y.child=w;w;)w.flags=w.flags&-3|4096,w=w.sibling;else{if(ut(),z===I){y=ha(m,y,w);break t}Zi(m,y,z,w)}y=y.child}return y;case 26:if(qs)return sx(m,y),m===null?(w=cz(y.type,null,y.pendingProps,null))?y.memoizedState=w:_n||(y.stateNode=Tht(y.type,y.pendingProps,Cc.current,y)):y.memoizedState=cz(y.type,m.memoizedProps,y.pendingProps,m.memoizedState),null;case 27:if(wi)return St(y),m===null&&wi&&_n&&(I=y.stateNode=fz(y.type,y.pendingProps,Cc.current,Ki.current,!1),Sr=y,Co=!0,Si=pht(y.type,I,Si)),Zi(m,y,y.pendingProps.children,w),sx(m,y),m===null&&(y.flags|=4194304),y.child;case 5:return m===null&&_n&&(Sht(y.type,y.pendingProps,Ki.current),(O=I=Si)&&(I=hht(I,y.type,y.pendingProps,Co),I!==null?(y.stateNode=I,Sr=y,Si=cht(I),Co=!1,O=!0):O=!1),O||ot(y)),St(y),O=y.type,z=y.pendingProps,K=m!==null?m.memoizedProps:null,I=z.children,fx(O,z)?I=null:K!==null&&fx(O,K)&&(y.flags|=32),y.memoizedState!==null&&(O=hh(m,y,IT,null,null,w),fa?xh._currentValue=O:xh._currentValue2=O),sx(m,y),Zi(m,y,I,w),y.child;case 6:return m===null&&_n&&(Pht(y.pendingProps,Ki.current),(m=w=Si)&&(w=dht(w,y.pendingProps,Co),w!==null?(y.stateNode=w,Sr=y,Si=null,m=!0):m=!1),m||ot(y)),null;case 13:return HF(m,y,w);case 4:return ht(y,y.stateNode.containerInfo),I=y.pendingProps,m===null?y.child=ym(y,null,I,w):Zi(m,y,I,w),y.child;case 11:return jF(m,y,y.type,y.pendingProps,w);case 7:return Zi(m,y,y.pendingProps,w),y.child;case 8:return Zi(m,y,y.pendingProps.children,w),y.child;case 12:return Zi(m,y,y.pendingProps.children,w),y.child;case 10:return I=y.pendingProps,Et(y,y.type,I.value),Zi(m,y,I.children,w),y.child;case 9:return O=y.type._context,I=y.pendingProps.children,le(y),O=Jt(O),I=I(O),y.flags|=1,Zi(m,y,I,w),y.child;case 14:return BF(m,y,y.type,y.pendingProps,w);case 15:return YF(m,y,y.type,y.pendingProps,w);case 19:return ZF(m,y,w);case 31:return I=y.pendingProps,w=y.mode,I={mode:I.mode,children:I.children},m===null?(w=ox(I,w),w.ref=y.ref,y.child=w,w.return=y,y=w):(w=da(m.child,I),w.ref=y.ref,y.child=w,w.return=y,y=w),y;case 22:return XF(m,y,w);case 24:return le(y),I=Jt(ei),m===null?(O=rh(),O===null&&(O=Rn,z=Nr(),O.pooledCache=z,z.refCount++,z!==null&&(O.pooledCacheLanes|=w),O=z),y.memoizedState={parent:I,cache:O},oh(y),Et(y,ei,O)):((m.lanes&w)!==0&&(ah(m,y),ua(y,null,null,w),la()),O=m.memoizedState,z=y.memoizedState,O.parent!==I?(O={parent:I,cache:I},y.memoizedState=O,y.lanes===0&&(y.memoizedState=y.updateQueue.baseState=O),Et(y,ei,I)):(I=z.cache,Et(y,ei,I),I!==O.cache&&Ie(y,[ei],w,!0))),Zi(m,y,y.pendingProps.children,w),y.child;case 29:throw y.pendingProps}throw Error(i(156,y.tag))}function Jr(m){m.flags|=4}function JF(m,y){if(m!==null&&m.child===y.child)return!1;if((y.flags&16)!==0)return!0;for(m=y.child;m!==null;){if((m.flags&13878)!==0||(m.subtreeFlags&13878)!==0)return!0;m=m.sibling}return!1}function GT(m,y,w,I){if(lr)for(w=y.child;w!==null;){if(w.tag===5||w.tag===6)vE(m,w.stateNode);else if(!(w.tag===4||wi&&w.tag===27)&&w.child!==null){w.child.return=w,w=w.child;continue}if(w===y)break;for(;w.sibling===null;){if(w.return===null||w.return===y)return;w=w.return}w.sibling.return=w.return,w=w.sibling}else if(Mc)for(var O=y.child;O!==null;){if(O.tag===5){var z=O.stateNode;w&&I&&(z=iz(z,O.type,O.memoizedProps)),vE(m,z)}else if(O.tag===6)z=O.stateNode,w&&I&&(z=rz(z,O.memoizedProps)),vE(m,z);else if(O.tag!==4){if(O.tag===22&&O.memoizedState!==null)z=O.child,z!==null&&(z.return=O),GT(m,O,!0,!0);else if(O.child!==null){O.child.return=O,O=O.child;continue}}if(O===y)break;for(;O.sibling===null;){if(O.return===null||O.return===y)return;O=O.return}O.sibling.return=O.return,O=O.sibling}}function QF(m,y,w,I){var O=!1;if(Mc)for(var z=y.child;z!==null;){if(z.tag===5){var K=z.stateNode;w&&I&&(K=iz(K,z.type,z.memoizedProps)),ez(m,K)}else if(z.tag===6)K=z.stateNode,w&&I&&(K=rz(K,z.memoizedProps)),ez(m,K);else if(z.tag!==4){if(z.tag===22&&z.memoizedState!==null)O=z.child,O!==null&&(O.return=z),QF(m,z,!0,!0),O=!0;else if(z.child!==null){z.child.return=z,z=z.child;continue}}if(z===y)break;for(;z.sibling===null;){if(z.return===null||z.return===y)return O;z=z.return}z.sibling.return=z.return,z=z.sibling}return O}function t$(m,y){if(Mc&&JF(m,y)){m=y.stateNode;var w=m.containerInfo,I=tz();QF(I,y,!1,!1),m.pendingChildren=I,Jr(y),nht(w,I)}}function WT(m,y,w,I){if(lr)m.memoizedProps!==I&&Jr(y);else if(Mc){var O=m.stateNode,z=m.memoizedProps;if((m=JF(m,y))||z!==I){var K=Ki.current;z=eht(O,w,z,I,!m,null),z===O?y.stateNode=O:(q$(z,w,I,K)&&Jr(y),y.stateNode=z,m?GT(z,y,!1,!1):Jr(y))}else y.stateNode=O}}function HT(m,y,w){if(Cpt(y,w)){if(m.flags|=16777216,!K$(y,w))if(k$())m.flags|=8192;else throw pm=kx,OE}else m.flags&=-16777217}function e$(m,y){if(Mht(y)){if(m.flags|=16777216,!dz(y))if(k$())m.flags|=8192;else throw pm=kx,OE}else m.flags&=-16777217}function ax(m,y){y!==null&&(m.flags|=4),m.flags&16384&&(y=m.tag!==22?k():536870912,m.lanes|=y,bm|=y)}function zy(m,y){if(!_n)switch(m.tailMode){case"hidden":y=m.tail;for(var w=null;y!==null;)y.alternate!==null&&(w=y),y=y.sibling;w===null?m.tail=null:w.sibling=null;break;case"collapsed":w=m.tail;for(var I=null;w!==null;)w.alternate!==null&&(I=w),w=w.sibling;I===null?y||m.tail===null?m.tail=null:m.tail.sibling=null:I.sibling=null}}function Zn(m){var y=m.alternate!==null&&m.alternate.child===m.child,w=0,I=0;if(y)for(var O=m.child;O!==null;)w|=O.lanes|O.childLanes,I|=O.subtreeFlags&65011712,I|=O.flags&65011712,O.return=m,O=O.sibling;else for(O=m.child;O!==null;)w|=O.lanes|O.childLanes,I|=O.subtreeFlags,I|=O.flags,O.return=m,O=O.sibling;return m.subtreeFlags|=I,m.childLanes=w,y}function Zut(m,y,w){var I=y.pendingProps;switch(J(y),y.tag){case 31:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Zn(y),null;case 1:return Zn(y),null;case 3:return w=y.stateNode,I=null,m!==null&&(I=m.memoizedState.cache),y.memoizedState.cache!==I&&(y.flags|=2048),Ft(ei),pt(),w.pendingContext&&(w.context=w.pendingContext,w.pendingContext=null),(m===null||m.child===null)&&(it(y)?Jr(y):m===null||m.memoizedState.isDehydrated&&(y.flags&256)===0||(y.flags|=1024,yt())),t$(m,y),Zn(y),null;case 26:if(qs){w=y.type;var O=y.memoizedState;return m===null?(Jr(y),O!==null?(Zn(y),e$(y,O)):(Zn(y),HT(y,w,I))):O?O!==m.memoizedState?(Jr(y),Zn(y),e$(y,O)):(Zn(y),y.flags&=-16777217):(lr?m.memoizedProps!==I&&Jr(y):WT(m,y,w,I),Zn(y),HT(y,w,I)),null}case 27:if(wi){if(Mt(y),w=Cc.current,O=y.type,m!==null&&y.stateNode!=null)lr?m.memoizedProps!==I&&Jr(y):WT(m,y,O,I);else{if(!I){if(y.stateNode===null)throw Error(i(166));return Zn(y),null}m=Ki.current,it(y)?Y(y,m):(m=fz(O,I,w,m,!0),y.stateNode=m,Jr(y))}return Zn(y),null}case 5:if(Mt(y),w=y.type,m!==null&&y.stateNode!=null)WT(m,y,w,I);else{if(!I){if(y.stateNode===null)throw Error(i(166));return Zn(y),null}m=Ki.current,it(y)?Y(y,m):(O=vpt(w,I,Cc.current,m,y),GT(O,y,!1,!1),y.stateNode=O,q$(O,w,I,m)&&Jr(y))}return Zn(y),HT(y,y.type,y.pendingProps),null;case 6:if(m&&y.stateNode!=null)w=m.memoizedProps,lr?w!==I&&Jr(y):Mc&&(w!==I?(y.stateNode=Z$(I,Cc.current,Ki.current,y),Jr(y)):y.stateNode=m.stateNode);else{if(typeof I!="string"&&y.stateNode===null)throw Error(i(166));if(m=Cc.current,w=Ki.current,it(y)){if(!ys)throw Error(i(176));if(m=y.stateNode,w=y.memoizedProps,I=null,O=Sr,O!==null)switch(O.tag){case 27:case 5:I=O.memoizedProps}_ht(m,w,y,I)||ot(y)}else y.stateNode=Z$(I,m,w,y)}return Zn(y),null;case 13:if(I=y.memoizedState,m===null||m.memoizedState!==null&&m.memoizedState.dehydrated!==null){if(O=it(y),I!==null&&I.dehydrated!==null){if(m===null){if(!O)throw Error(i(318));if(!ys)throw Error(i(344));if(O=y.memoizedState,O=O!==null?O.dehydrated:null,!O)throw Error(i(317));yht(O,y)}else ut(),(y.flags&128)===0&&(y.memoizedState=null),y.flags|=4;Zn(y),O=!1}else O=yt(),m!==null&&m.memoizedState!==null&&(m.memoizedState.hydrationErrors=O),O=!0;if(!O)return y.flags&256?(pa(y),y):(pa(y),null)}if(pa(y),(y.flags&128)!==0)return y.lanes=w,y;if(w=I!==null,m=m!==null&&m.memoizedState!==null,w){I=y.child,O=null,I.alternate!==null&&I.alternate.memoizedState!==null&&I.alternate.memoizedState.cachePool!==null&&(O=I.alternate.memoizedState.cachePool.pool);var z=null;I.memoizedState!==null&&I.memoizedState.cachePool!==null&&(z=I.memoizedState.cachePool.pool),z!==O&&(I.flags|=2048)}return w!==m&&w&&(y.child.flags|=8192),ax(y,y.updateQueue),Zn(y),null;case 4:return pt(),t$(m,y),m===null&&kpt(y.stateNode.containerInfo),Zn(y),null;case 10:return Ft(y.type),Zn(y),null;case 19:if(d(Pi),O=y.memoizedState,O===null)return Zn(y),null;if(I=(y.flags&128)!==0,z=O.rendering,z===null)if(I)zy(O,!1);else{if(ni!==0||m!==null&&(m.flags&128)!==0)for(m=y.child;m!==null;){if(z=ix(m),z!==null){for(y.flags|=128,zy(O,!1),m=z.updateQueue,y.updateQueue=m,ax(y,m),y.subtreeFlags=0,m=w,w=y.child;w!==null;)D$(w,m),w=w.sibling;return _(Pi,Pi.current&1|2),y.child}m=m.sibling}O.tail!==null&&Zs()>eg&&(y.flags|=128,I=!0,zy(O,!1),y.lanes=4194304)}else{if(!I)if(m=ix(z),m!==null){if(y.flags|=128,I=!0,m=m.updateQueue,y.updateQueue=m,ax(y,m),zy(O,!0),O.tail===null&&O.tailMode==="hidden"&&!z.alternate&&!_n)return Zn(y),null}else 2*Zs()-O.renderingStartTime>eg&&w!==536870912&&(y.flags|=128,I=!0,zy(O,!1),y.lanes=4194304);O.isBackwards?(z.sibling=y.child,y.child=z):(m=O.last,m!==null?m.sibling=z:y.child=z,O.last=z)}return O.tail!==null?(y=O.tail,O.rendering=y,O.tail=y.sibling,O.renderingStartTime=Zs(),y.sibling=null,m=Pi.current,_(Pi,I?m&1|2:m&1),y):(Zn(y),null);case 22:case 23:return pa(y),uh(),I=y.memoizedState!==null,m!==null?m.memoizedState!==null!==I&&(y.flags|=8192):I&&(y.flags|=8192),I?(w&536870912)!==0&&(y.flags&128)===0&&(Zn(y),y.subtreeFlags&6&&(y.flags|=8192)):Zn(y),w=y.updateQueue,w!==null&&ax(y,w.retryQueue),w=null,m!==null&&m.memoizedState!==null&&m.memoizedState.cachePool!==null&&(w=m.memoizedState.cachePool.pool),I=null,y.memoizedState!==null&&y.memoizedState.cachePool!==null&&(I=y.memoizedState.cachePool.pool),I!==w&&(y.flags|=2048),m!==null&&d(Sh),null;case 24:return w=null,m!==null&&(w=m.memoizedState.cache),y.memoizedState.cache!==w&&(y.flags|=2048),Ft(ei),Zn(y),null;case 25:return null;case 30:return null}throw Error(i(156,y.tag))}function Kut(m,y){switch(J(y),y.tag){case 1:return m=y.flags,m&65536?(y.flags=m&-65537|128,y):null;case 3:return Ft(ei),pt(),m=y.flags,(m&65536)!==0&&(m&128)===0?(y.flags=m&-65537|128,y):null;case 26:case 27:case 5:return Mt(y),null;case 13:if(pa(y),m=y.memoizedState,m!==null&&m.dehydrated!==null){if(y.alternate===null)throw Error(i(340));ut()}return m=y.flags,m&65536?(y.flags=m&-65537|128,y):null;case 19:return d(Pi),null;case 4:return pt(),null;case 10:return Ft(y.type),null;case 22:case 23:return pa(y),uh(),m!==null&&d(Sh),m=y.flags,m&65536?(y.flags=m&-65537|128,y):null;case 24:return Ft(ei),null;case 25:return null;default:return null}}function n$(m,y){switch(J(y),y.tag){case 3:Ft(ei),pt();break;case 26:case 27:case 5:Mt(y);break;case 4:pt();break;case 13:pa(y);break;case 19:d(Pi);break;case 10:Ft(y.type);break;case 22:case 23:pa(y),uh(),m!==null&&d(Sh);break;case 24:Ft(ei)}}function Dy(m,y){try{var w=y.updateQueue,I=w!==null?w.lastEffect:null;if(I!==null){var O=I.next;w=O;do{if((w.tag&m)===m){I=void 0;var z=w.create,K=w.inst;I=z(),K.destroy=I}w=w.next}while(w!==O)}}catch(ct){xn(y,y.return,ct)}}function wc(m,y,w){try{var I=y.updateQueue,O=I!==null?I.lastEffect:null;if(O!==null){var z=O.next;I=z;do{if((I.tag&m)===m){var K=I.inst,ct=K.destroy;if(ct!==void 0){K.destroy=void 0,O=y;var xt=w,It=ct;try{It()}catch(zt){xn(O,xt,zt)}}}I=I.next}while(I!==z)}}catch(zt){xn(y,y.return,zt)}}function i$(m){var y=m.updateQueue;if(y!==null){var w=m.stateNode;try{Vf(y,w)}catch(I){xn(m,m.return,I)}}}function r$(m,y,w){w.props=fh(m.type,m.memoizedProps),w.state=m.memoizedState;try{w.componentWillUnmount()}catch(I){xn(m,y,I)}}function jy(m,y){try{var w=m.ref;if(w!==null){switch(m.tag){case 26:case 27:case 5:var I=Uy(m.stateNode);break;case 30:I=m.stateNode;break;default:I=m.stateNode}typeof w=="function"?m.refCleanup=w(I):w.current=I}}catch(O){xn(m,y,O)}}function Eo(m,y){var w=m.ref,I=m.refCleanup;if(w!==null)if(typeof I=="function")try{I()}catch(O){xn(m,y,O)}finally{m.refCleanup=null,m=m.alternate,m!=null&&(m.refCleanup=null)}else if(typeof w=="function")try{w(null)}catch(O){xn(m,y,O)}else w.current=null}function s$(m){var y=m.type,w=m.memoizedProps,I=m.stateNode;try{Upt(I,y,w,m)}catch(O){xn(m,m.return,O)}}function qT(m,y,w){try{Vpt(m.stateNode,m.type,w,y,m)}catch(I){xn(m,m.return,I)}}function o$(m){return m.tag===5||m.tag===3||(qs?m.tag===26:!1)||(wi?m.tag===27&&nm(m.type):!1)||m.tag===4}function ZT(m){t:for(;;){for(;m.sibling===null;){if(m.return===null||o$(m.return))return null;m=m.return}for(m.sibling.return=m.return,m=m.sibling;m.tag!==5&&m.tag!==6&&m.tag!==18;){if(wi&&m.tag===27&&nm(m.type)||m.flags&2||m.child===null||m.tag===4)continue t;m.child.return=m,m=m.child}if(!(m.flags&2))return m.stateNode}}function KT(m,y,w){var I=m.tag;if(I===5||I===6)m=m.stateNode,y?Wpt(w,m,y):Ypt(w,m);else if(I!==4&&(wi&&I===27&&nm(m.type)&&(w=m.stateNode,y=null),m=m.child,m!==null))for(KT(m,y,w),m=m.sibling;m!==null;)KT(m,y,w),m=m.sibling}function cx(m,y,w){var I=m.tag;if(I===5||I===6)m=m.stateNode,y?Gpt(w,m,y):Bpt(w,m);else if(I!==4&&(wi&&I===27&&nm(m.type)&&(w=m.stateNode),m=m.child,m!==null))for(cx(m,y,w),m=m.sibling;m!==null;)cx(m,y,w),m=m.sibling}function a$(m,y,w){m=m.containerInfo;try{nz(m,w)}catch(I){xn(y,y.return,I)}}function c$(m){var y=m.stateNode,w=m.memoizedProps;try{Iht(m.type,w,y,m)}catch(I){xn(m,m.return,I)}}function Jut(m,y){for(xpt(m.containerInfo),Ri=y;Ri!==null;)if(m=Ri,y=m.child,(m.subtreeFlags&1024)!==0&&y!==null)y.return=m,Ri=y;else for(;Ri!==null;){m=Ri;var w=m.alternate;switch(y=m.flags,m.tag){case 0:break;case 11:case 15:break;case 1:if((y&1024)!==0&&w!==null){y=void 0;var I=m,O=w.memoizedProps;w=w.memoizedState;var z=I.stateNode;try{var K=fh(I.type,O,I.elementType===I.type);y=z.getSnapshotBeforeUpdate(K,w),z.__reactInternalSnapshotBeforeUpdate=y}catch(ct){xn(I,I.return,ct)}}break;case 3:(y&1024)!==0&&lr&&tht(m.stateNode.containerInfo);break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((y&1024)!==0)throw Error(i(163))}if(y=m.sibling,y!==null){y.return=m.return,Ri=y;break}Ri=m.return}}function l$(m,y,w){var I=w.flags;switch(w.tag){case 0:case 11:case 15:Sc(m,w),I&4&&Dy(5,w);break;case 1:if(Sc(m,w),I&4)if(m=w.stateNode,y===null)try{m.componentDidMount()}catch(K){xn(w,w.return,K)}else{var O=fh(w.type,y.memoizedProps);y=y.memoizedState;try{m.componentDidUpdate(O,y,m.__reactInternalSnapshotBeforeUpdate)}catch(K){xn(w,w.return,K)}}I&64&&i$(w),I&512&&jy(w,w.return);break;case 3:if(Sc(m,w),I&64&&(m=w.updateQueue,m!==null)){if(y=null,w.child!==null)switch(w.child.tag){case 27:case 5:y=Uy(w.child.stateNode);break;case 1:y=w.child.stateNode}try{Vf(m,y)}catch(K){xn(w,w.return,K)}}break;case 27:wi&&y===null&&I&4&&c$(w);case 26:case 5:Sc(m,w),y===null&&I&4&&s$(w),I&512&&jy(w,w.return);break;case 12:Sc(m,w);break;case 13:Sc(m,w),I&4&&p$(m,w),I&64&&(m=w.memoizedState,m!==null&&(m=m.dehydrated,m!==null&&(w=spt.bind(null,w),rht(m,w))));break;case 22:if(I=w.memoizedState!==null||xa,!I){y=y!==null&&y.memoizedState!==null||hi,O=xa;var z=hi;xa=I,(hi=y)&&!z?Pc(m,w,(w.subtreeFlags&8772)!==0):Sc(m,w),xa=O,hi=z}break;case 30:break;default:Sc(m,w)}}function u$(m){var y=m.alternate;y!==null&&(m.alternate=null,u$(y)),m.child=null,m.deletions=null,m.sibling=null,m.tag===5&&(y=m.stateNode,y!==null&&Mpt(y)),m.stateNode=null,m.return=null,m.dependencies=null,m.memoizedProps=null,m.memoizedState=null,m.pendingProps=null,m.stateNode=null,m.updateQueue=null}function Hs(m,y,w){for(w=w.child;w!==null;)JT(m,y,w),w=w.sibling}function JT(m,y,w){if(is&&typeof is.onCommitFiberUnmount=="function")try{is.onCommitFiberUnmount(Wy,w)}catch{}switch(w.tag){case 26:if(qs){hi||Eo(w,y),Hs(m,y,w),w.memoizedState?uz(w.memoizedState):w.stateNode&&hz(w.stateNode);break}case 27:if(wi){hi||Eo(w,y);var I=_i,O=Or;nm(w.type)&&(_i=w.stateNode,Or=!1),Hs(m,y,w),mz(w.stateNode),_i=I,Or=O;break}case 5:hi||Eo(w,y);case 6:if(lr){if(I=_i,O=Or,_i=null,Hs(m,y,w),_i=I,Or=O,_i!==null)if(Or)try{qpt(_i,w.stateNode)}catch(z){xn(w,y,z)}else try{Hpt(_i,w.stateNode)}catch(z){xn(w,y,z)}}else Hs(m,y,w);break;case 18:lr&&_i!==null&&(Or?wht(_i,w.stateNode):vht(_i,w.stateNode));break;case 4:lr?(I=_i,O=Or,_i=w.stateNode.containerInfo,Or=!0,Hs(m,y,w),_i=I,Or=O):(Mc&&a$(w.stateNode,w,tz()),Hs(m,y,w));break;case 0:case 11:case 14:case 15:hi||wc(2,w,y),hi||wc(4,w,y),Hs(m,y,w);break;case 1:hi||(Eo(w,y),I=w.stateNode,typeof I.componentWillUnmount=="function"&&r$(w,y,I)),Hs(m,y,w);break;case 21:Hs(m,y,w);break;case 22:hi=(I=hi)||w.memoizedState!==null,Hs(m,y,w),hi=I;break;default:Hs(m,y,w)}}function p$(m,y){if(ys&&y.memoizedState===null&&(m=y.alternate,m!==null&&(m=m.memoizedState,m!==null&&(m=m.dehydrated,m!==null))))try{bht(m)}catch(w){xn(y,y.return,w)}}function Qut(m){switch(m.tag){case 13:case 19:var y=m.stateNode;return y===null&&(y=m.stateNode=new Tz),y;case 22:return m=m.stateNode,y=m._retryCache,y===null&&(y=m._retryCache=new Tz),y;default:throw Error(i(435,m.tag))}}function QT(m,y){var w=Qut(m);y.forEach(function(I){var O=opt.bind(null,m,I);w.has(I)||(w.add(I),I.then(O,O))})}function wr(m,y){var w=y.deletions;if(w!==null)for(var I=0;I<w.length;I++){var O=w[I],z=m,K=y;if(lr){var ct=K;t:for(;ct!==null;){switch(ct.tag){case 27:if(wi){if(nm(ct.type)){_i=ct.stateNode,Or=!1;break t}break}case 5:_i=ct.stateNode,Or=!1;break t;case 3:case 4:_i=ct.stateNode.containerInfo,Or=!0;break t}ct=ct.return}if(_i===null)throw Error(i(160));JT(z,K,O),_i=null,Or=!1}else JT(z,K,O);z=O.alternate,z!==null&&(z.return=null),O.return=null}if(y.subtreeFlags&13878)for(y=y.child;y!==null;)h$(y,m),y=y.sibling}function h$(m,y){var w=m.alternate,I=m.flags;switch(m.tag){case 0:case 11:case 14:case 15:wr(y,m),Rr(m),I&4&&(wc(3,m,m.return),Dy(3,m),wc(5,m,m.return));break;case 1:wr(y,m),Rr(m),I&512&&(hi||w===null||Eo(w,w.return)),I&64&&xa&&(m=m.updateQueue,m!==null&&(I=m.callbacks,I!==null&&(w=m.shared.hiddenCallbacks,m.shared.hiddenCallbacks=w===null?I:w.concat(I))));break;case 26:if(qs){var O=Ks;if(wr(y,m),Rr(m),I&512&&(hi||w===null||Eo(w,w.return)),I&4){I=w!==null?w.memoizedState:null;var z=m.memoizedState;w===null?z===null?m.stateNode===null?m.stateNode=kht(O,m.type,m.memoizedProps,m):pz(O,m.type,m.stateNode):m.stateNode=lz(O,z,m.memoizedProps):I!==z?(I===null?w.stateNode!==null&&hz(w.stateNode):uz(I),z===null?pz(O,m.type,m.stateNode):lz(O,z,m.memoizedProps)):z===null&&m.stateNode!==null&&qT(m,m.memoizedProps,w.memoizedProps)}break}case 27:if(wi){wr(y,m),Rr(m),I&512&&(hi||w===null||Eo(w,w.return)),w!==null&&I&4&&qT(m,m.memoizedProps,w.memoizedProps);break}case 5:if(wr(y,m),Rr(m),I&512&&(hi||w===null||Eo(w,w.return)),lr){if(m.flags&32){O=m.stateNode;try{Q$(O)}catch(zt){xn(m,m.return,zt)}}I&4&&m.stateNode!=null&&(O=m.memoizedProps,qT(m,O,w!==null?w.memoizedProps:O)),I&1024&&(DE=!0)}break;case 6:if(wr(y,m),Rr(m),I&4&&lr){if(m.stateNode===null)throw Error(i(162));I=m.memoizedProps,w=w!==null?w.memoizedProps:I,O=m.stateNode;try{Xpt(O,w,I)}catch(zt){xn(m,m.return,zt)}}break;case 3:if(qs?(Eht(),O=Ks,Ks=PE(y.containerInfo),wr(y,m),Ks=O):wr(y,m),Rr(m),I&4){if(lr&&ys&&w!==null&&w.memoizedState.isDehydrated)try{xht(y.containerInfo)}catch(zt){xn(m,m.return,zt)}if(Mc){I=y.containerInfo,w=y.pendingChildren;try{nz(I,w)}catch(zt){xn(m,m.return,zt)}}}DE&&(DE=!1,d$(m));break;case 4:qs?(w=Ks,Ks=PE(m.stateNode.containerInfo),wr(y,m),Rr(m),Ks=w):(wr(y,m),Rr(m)),I&4&&Mc&&a$(m.stateNode,m,m.stateNode.pendingChildren);break;case 12:wr(y,m),Rr(m);break;case 13:wr(y,m),Rr(m),m.child.flags&8192&&m.memoizedState!==null!=(w!==null&&w.memoizedState!==null)&&(XE=Zs()),I&4&&(I=m.updateQueue,I!==null&&(m.updateQueue=null,QT(m,I)));break;case 22:O=m.memoizedState!==null;var K=w!==null&&w.memoizedState!==null,ct=xa,xt=hi;if(xa=ct||O,hi=xt||K,wr(y,m),hi=xt,xa=ct,Rr(m),I&8192&&(y=m.stateNode,y._visibility=O?y._visibility&-2:y._visibility|1,O&&(w===null||K||xa||hi||mh(m)),lr)){t:if(w=null,lr)for(y=m;;){if(y.tag===5||qs&&y.tag===26){if(w===null){K=w=y;try{z=K.stateNode,O?Zpt(z):Jpt(K.stateNode,K.memoizedProps)}catch(zt){xn(K,K.return,zt)}}}else if(y.tag===6){if(w===null){K=y;try{var It=K.stateNode;O?Kpt(It):Qpt(It,K.memoizedProps)}catch(zt){xn(K,K.return,zt)}}}else if((y.tag!==22&&y.tag!==23||y.memoizedState===null||y===m)&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===m)break t;for(;y.sibling===null;){if(y.return===null||y.return===m)break t;w===y&&(w=null),y=y.return}w===y&&(w=null),y.sibling.return=y.return,y=y.sibling}}I&4&&(I=m.updateQueue,I!==null&&(w=I.retryQueue,w!==null&&(I.retryQueue=null,QT(m,w))));break;case 19:wr(y,m),Rr(m),I&4&&(I=m.updateQueue,I!==null&&(m.updateQueue=null,QT(m,I)));break;case 30:break;case 21:break;default:wr(y,m),Rr(m)}}function Rr(m){var y=m.flags;if(y&2){try{if(lr){for(var w,I=m.return;I!==null;){if(o$(I)){w=I;break}I=I.return}if(w==null)throw Error(i(160));switch(w.tag){case 27:if(wi){var O=w.stateNode,z=ZT(m);cx(m,z,O);break}case 5:var K=w.stateNode;w.flags&32&&(Q$(K),w.flags&=-33);var ct=ZT(m);cx(m,ct,K);break;case 3:case 4:var xt=w.stateNode.containerInfo,It=ZT(m);KT(m,It,xt);break;default:throw Error(i(161))}}}catch(zt){xn(m,m.return,zt)}m.flags&=-3}y&4096&&(m.flags&=-4097)}function d$(m){if(m.subtreeFlags&1024)for(m=m.child;m!==null;){var y=m;d$(y),y.tag===5&&y.flags&1024&&Apt(y.stateNode),m=m.sibling}}function Sc(m,y){if(y.subtreeFlags&8772)for(y=y.child;y!==null;)l$(m,y.alternate,y),y=y.sibling}function mh(m){for(m=m.child;m!==null;){var y=m;switch(y.tag){case 0:case 11:case 14:case 15:wc(4,y,y.return),mh(y);break;case 1:Eo(y,y.return);var w=y.stateNode;typeof w.componentWillUnmount=="function"&&r$(y,y.return,w),mh(y);break;case 27:wi&&mz(y.stateNode);case 26:case 5:Eo(y,y.return),mh(y);break;case 22:y.memoizedState===null&&mh(y);break;case 30:mh(y);break;default:mh(y)}m=m.sibling}}function Pc(m,y,w){for(w=w&&(y.subtreeFlags&8772)!==0,y=y.child;y!==null;){var I=y.alternate,O=m,z=y,K=z.flags;switch(z.tag){case 0:case 11:case 15:Pc(O,z,w),Dy(4,z);break;case 1:if(Pc(O,z,w),I=z,O=I.stateNode,typeof O.componentDidMount=="function")try{O.componentDidMount()}catch(It){xn(I,I.return,It)}if(I=z,O=I.updateQueue,O!==null){var ct=I.stateNode;try{var xt=O.shared.hiddenCallbacks;if(xt!==null)for(O.shared.hiddenCallbacks=null,O=0;O<xt.length;O++)Uf(xt[O],ct)}catch(It){xn(I,I.return,It)}}w&&K&64&&i$(z),jy(z,z.return);break;case 27:wi&&c$(z);case 26:case 5:Pc(O,z,w),w&&I===null&&K&4&&s$(z),jy(z,z.return);break;case 12:Pc(O,z,w);break;case 13:Pc(O,z,w),w&&K&4&&p$(O,z);break;case 22:z.memoizedState===null&&Pc(O,z,w),jy(z,z.return);break;case 30:break;default:Pc(O,z,w)}y=y.sibling}}function tE(m,y){var w=null;m!==null&&m.memoizedState!==null&&m.memoizedState.cachePool!==null&&(w=m.memoizedState.cachePool.pool),m=null,y.memoizedState!==null&&y.memoizedState.cachePool!==null&&(m=y.memoizedState.cachePool.pool),m!==w&&(m!=null&&m.refCount++,w!=null&&Gs(w))}function eE(m,y){m=null,y.alternate!==null&&(m=y.alternate.memoizedState.cache),y=y.memoizedState.cache,y!==m&&(y.refCount++,m!=null&&Gs(m))}function Mo(m,y,w,I){if(y.subtreeFlags&10256)for(y=y.child;y!==null;)f$(m,y,w,I),y=y.sibling}function f$(m,y,w,I){var O=y.flags;switch(y.tag){case 0:case 11:case 15:Mo(m,y,w,I),O&2048&&Dy(9,y);break;case 1:Mo(m,y,w,I);break;case 3:Mo(m,y,w,I),O&2048&&(m=null,y.alternate!==null&&(m=y.alternate.memoizedState.cache),y=y.memoizedState.cache,y!==m&&(y.refCount++,m!=null&&Gs(m)));break;case 12:if(O&2048){Mo(m,y,w,I),m=y.stateNode;try{var z=y.memoizedProps,K=z.id,ct=z.onPostCommit;typeof ct=="function"&&ct(K,y.alternate===null?"mount":"update",m.passiveEffectDuration,-0)}catch(xt){xn(y,y.return,xt)}}else Mo(m,y,w,I);break;case 13:Mo(m,y,w,I);break;case 23:break;case 22:z=y.stateNode,K=y.alternate,y.memoizedState!==null?z._visibility&2?Mo(m,y,w,I):By(m,y):z._visibility&2?Mo(m,y,w,I):(z._visibility|=2,Zf(m,y,w,I,(y.subtreeFlags&10256)!==0)),O&2048&&tE(K,y);break;case 24:Mo(m,y,w,I),O&2048&&eE(y.alternate,y);break;default:Mo(m,y,w,I)}}function Zf(m,y,w,I,O){for(O=O&&(y.subtreeFlags&10256)!==0,y=y.child;y!==null;){var z=m,K=y,ct=w,xt=I,It=K.flags;switch(K.tag){case 0:case 11:case 15:Zf(z,K,ct,xt,O),Dy(8,K);break;case 23:break;case 22:var zt=K.stateNode;K.memoizedState!==null?zt._visibility&2?Zf(z,K,ct,xt,O):By(z,K):(zt._visibility|=2,Zf(z,K,ct,xt,O)),O&&It&2048&&tE(K.alternate,K);break;case 24:Zf(z,K,ct,xt,O),O&&It&2048&&eE(K.alternate,K);break;default:Zf(z,K,ct,xt,O)}y=y.sibling}}function By(m,y){if(y.subtreeFlags&10256)for(y=y.child;y!==null;){var w=m,I=y,O=I.flags;switch(I.tag){case 22:By(w,I),O&2048&&tE(I.alternate,I);break;case 24:By(w,I),O&2048&&eE(I.alternate,I);break;default:By(w,I)}y=y.sibling}}function _h(m){if(m.subtreeFlags&gm)for(m=m.child;m!==null;)m$(m),m=m.sibling}function m$(m){switch(m.tag){case 26:_h(m),m.flags&gm&&(m.memoizedState!==null?Cht(Ks,m.memoizedState,m.memoizedProps):J$(m.type,m.memoizedProps));break;case 5:_h(m),m.flags&gm&&J$(m.type,m.memoizedProps);break;case 3:case 4:if(qs){var y=Ks;Ks=PE(m.stateNode.containerInfo),_h(m),Ks=y}else _h(m);break;case 22:m.memoizedState===null&&(y=m.alternate,y!==null&&y.memoizedState!==null?(y=gm,gm=16777216,_h(m),gm=y):_h(m));break;default:_h(m)}}function _$(m){var y=m.alternate;if(y!==null&&(m=y.child,m!==null)){y.child=null;do y=m.sibling,m.sibling=null,m=y;while(m!==null)}}function Yy(m){var y=m.deletions;if((m.flags&16)!==0){if(y!==null)for(var w=0;w<y.length;w++){var I=y[w];Ri=I,g$(I,m)}_$(m)}if(m.subtreeFlags&10256)for(m=m.child;m!==null;)y$(m),m=m.sibling}function y$(m){switch(m.tag){case 0:case 11:case 15:Yy(m),m.flags&2048&&wc(9,m,m.return);break;case 3:Yy(m);break;case 12:Yy(m);break;case 22:var y=m.stateNode;m.memoizedState!==null&&y._visibility&2&&(m.return===null||m.return.tag!==13)?(y._visibility&=-3,lx(m)):Yy(m);break;default:Yy(m)}}function lx(m){var y=m.deletions;if((m.flags&16)!==0){if(y!==null)for(var w=0;w<y.length;w++){var I=y[w];Ri=I,g$(I,m)}_$(m)}for(m=m.child;m!==null;){switch(y=m,y.tag){case 0:case 11:case 15:wc(8,y,y.return),lx(y);break;case 22:w=y.stateNode,w._visibility&2&&(w._visibility&=-3,lx(y));break;default:lx(y)}m=m.sibling}}function g$(m,y){for(;Ri!==null;){var w=Ri;switch(w.tag){case 0:case 11:case 15:wc(8,w,y);break;case 23:case 22:if(w.memoizedState!==null&&w.memoizedState.cachePool!==null){var I=w.memoizedState.cachePool.pool;I!=null&&I.refCount++}break;case 24:Gs(w.memoizedState.cache)}if(I=w.child,I!==null)I.return=w,Ri=I;else t:for(w=m;Ri!==null;){I=Ri;var O=I.sibling,z=I.return;if(u$(I),I===w){Ri=null;break t}if(O!==null){O.return=z,Ri=O;break t}Ri=z}}}function nE(m){var y=Ppt(m);if(y!=null){if(typeof y.memoizedProps["data-testname"]!="string")throw Error(i(364));return y}if(m=Lpt(m),m===null)throw Error(i(362));return m.stateNode.current}function iE(m,y){var w=m.tag;switch(y.$$typeof){case Ix:if(m.type===y.value)return!0;break;case Nx:t:{for(y=y.value,m=[m,0],w=0;w<m.length;){var I=m[w++],O=I.tag,z=m[w++],K=y[z];if(O!==5&&O!==26&&O!==27||!Gy(I)){for(;K!=null&&iE(I,K);)z++,K=y[z];if(z===y.length){y=!0;break t}else for(I=I.child;I!==null;)m.push(I,z),I=I.sibling}}y=!1}return y;case Ax:if((w===5||w===26||w===27)&&zpt(m.stateNode,y.value))return!0;break;case Ox:if((w===5||w===6||w===26||w===27)&&(m=$pt(m),m!==null&&0<=m.indexOf(y.value)))return!0;break;case Rx:if((w===5||w===26||w===27)&&(m=m.memoizedProps["data-testname"],typeof m=="string"&&m.toLowerCase()===y.value.toLowerCase()))return!0;break;default:throw Error(i(365))}return!1}function rE(m){switch(m.$$typeof){case Ix:return"<"+(u(m.value)||"Unknown")+">";case Nx:return":has("+(rE(m)||"")+")";case Ax:return'[role="'+m.value+'"]';case Ox:return'"'+m.value+'"';case Rx:return'[data-testname="'+m.value+'"]';default:throw Error(i(365))}}function x$(m,y){var w=[];m=[m,0];for(var I=0;I<m.length;){var O=m[I++],z=O.tag,K=m[I++],ct=y[K];if(z!==5&&z!==26&&z!==27||!Gy(O)){for(;ct!=null&&iE(O,ct);)K++,ct=y[K];if(K===y.length)w.push(O);else for(O=O.child;O!==null;)m.push(O,K),O=O.sibling}}return w}function sE(m,y){if(!Vy)throw Error(i(363));m=nE(m),m=x$(m,y),y=[],m=Array.from(m);for(var w=0;w<m.length;){var I=m[w++],O=I.tag;if(O===5||O===26||O===27)Gy(I)||y.push(I.stateNode);else for(I=I.child;I!==null;)m.push(I),I=I.sibling}return y}function Qr(){if((Qe&2)!==0&&en!==0)return en&-en;if(ye.T!==null){var m=lm;return m!==0?m:ih()}return Tpt()}function b$(){ws===0&&(ws=(en&536870912)===0||_n?T():536870912);var m=vs.current;return m!==null&&(m.flags|=32),ws}function ts(m,y,w){(m===Rn&&(bn===2||bn===9)||m.cancelPendingCommit!==null)&&(Kf(m,0),kc(m,en,ws,!1)),E(m,w),((Qe&2)===0||m!==Rn)&&(m===Rn&&((Qe&2)===0&&(kh|=w),ni===4&&kc(m,en,ws,!1)),Ar(m))}function v$(m,y,w){if((Qe&6)!==0)throw Error(i(327));var I=!w&&(y&124)===0&&(y&m.expiredLanes)===0||S(m,y),O=I?npt(m,y):cE(m,y,!0),z=I;do{if(O===0){xm&&!I&&kc(m,y,0,!1);break}else{if(w=m.current.alternate,z&&!tpt(w)){O=cE(m,y,!1),z=!1;continue}if(O===2){if(z=y,m.errorRecoveryDisabledLanes&z)var K=0;else K=m.pendingLanes&-536870913,K=K!==0?K:K&536870912?536870912:0;if(K!==0){y=K;t:{var ct=m;O=tg;var xt=ys&&ct.current.memoizedState.isDehydrated;if(xt&&(Kf(ct,K).flags|=256),K=cE(ct,K,!1),K!==2){if(jE&&!xt){ct.errorRecoveryDisabledLanes|=z,kh|=z,O=4;break t}z=Lr,Lr=O,z!==null&&(Lr===null?Lr=z:Lr.push.apply(Lr,z))}O=K}if(z=!1,O!==2)continue}}if(O===1){Kf(m,0),kc(m,y,0,!0);break}t:{switch(I=m,z=O,z){case 0:case 1:throw Error(i(345));case 4:if((y&4194048)!==y)break;case 6:kc(I,y,ws,!Ac);break t;case 2:Lr=null;break;case 3:case 5:break;default:throw Error(i(329))}if((y&62914560)===y&&(O=XE+300-Zs(),10<O)){if(kc(I,y,ws,!Ac),v(I,0,!0)!==0)break t;I.timeoutHandle=wpt(w$.bind(null,I,w,Lr,Lx,YE,y,ws,kh,bm,Ac,z,2,-0,0),O);break t}w$(I,w,Lr,Lx,YE,y,ws,kh,bm,Ac,z,0,-0,0)}}break}while(!0);Ar(m)}function w$(m,y,w,I,O,z,K,ct,xt,It,zt,Xt,Ht,Fe){if(m.timeoutHandle=gh,Xt=y.subtreeFlags,(Xt&8192||(Xt&16785408)===16785408)&&(Ipt(),m$(y),Xt=Npt(),Xt!==null)){m.cancelPendingCommit=Xt(N$.bind(null,m,y,z,w,I,O,K,ct,xt,zt,1,Ht,Fe)),kc(m,z,K,!It);return}N$(m,y,z,w,I,O,K,ct,xt)}function tpt(m){for(var y=m;;){var w=y.tag;if((w===0||w===11||w===15)&&y.flags&16384&&(w=y.updateQueue,w!==null&&(w=w.stores,w!==null)))for(var I=0;I<w.length;I++){var O=w[I],z=O.getSnapshot;O=O.value;try{if(!rs(z(),O))return!1}catch{return!1}}if(w=y.child,y.subtreeFlags&16384&&w!==null)w.return=y,y=w;else{if(y===m)break;for(;y.sibling===null;){if(y.return===null||y.return===m)return!0;y=y.return}y.sibling.return=y.return,y=y.sibling}}return!0}function kc(m,y,w,I){y&=~BE,y&=~kh,m.suspendedLanes|=y,m.pingedLanes&=~y,I&&(m.warmLanes|=y),I=m.expirationTimes;for(var O=y;0<O;){var z=31-ns(O),K=1<<z;I[z]=-1,O&=~K}w!==0&&M(m,w,y)}function S$(){return(Qe&6)===0?(ko(0,!1),!1):!0}function oE(){if(Ve!==null){if(bn===0)var m=Ve.return;else m=Ve,ga=wh=null,Iy(m),_m=null,Jy=0,m=Ve;for(;m!==null;)n$(m.alternate,m),m=m.return;Ve=null}}function Kf(m,y){var w=m.timeoutHandle;w!==gh&&(m.timeoutHandle=gh,Spt(w)),w=m.cancelPendingCommit,w!==null&&(m.cancelPendingCommit=null,w()),oE(),Rn=m,Ve=w=da(m.current,null),en=y,bn=0,ss=null,Ac=!1,xm=S(m,y),jE=!1,bm=ws=BE=kh=Rc=ni=0,Lr=tg=null,YE=!1,(y&8)!==0&&(y|=y&32);var I=m.entangledLanes;if(I!==0)for(m=m.entanglements,I&=y;0<I;){var O=31-ns(I),z=1<<O;y|=m[O],I&=~z}return ba=y,yc(),w}function P$(m,y){je=null,ye.H=Cx,y===Zy||y===Px?(y=Bf(),bn=3):y===OE?(y=Bf(),bn=4):bn=y===kz?8:y!==null&&typeof y=="object"&&typeof y.then=="function"?6:1,ss=y,Ve===null&&(ni=1,rx(m,nt(y,m.current)))}function k$(){var m=vs.current;return m===null?!0:(en&4194048)===en?Io===null:(en&62914560)===en||(en&536870912)!==0?m===Io:!1}function T$(){var m=ye.H;return ye.H=Cx,m===null?Cx:m}function E$(){var m=ye.A;return ye.A=Vht,m}function aE(){ni=4,Ac||(en&4194048)!==en&&vs.current!==null||(xm=!0),(Rc&134217727)===0&&(kh&134217727)===0||Rn===null||kc(Rn,en,ws,!1)}function cE(m,y,w){var I=Qe;Qe|=2;var O=T$(),z=E$();(Rn!==m||en!==y)&&(Lx=null,Kf(m,y)),y=!1;var K=ni;t:do try{if(bn!==0&&Ve!==null){var ct=Ve,xt=ss;switch(bn){case 8:oE(),K=6;break t;case 3:case 2:case 9:case 6:vs.current===null&&(y=!0);var It=bn;if(bn=0,ss=null,Jf(m,ct,xt,It),w&&xm){K=0;break t}break;default:It=bn,bn=0,ss=null,Jf(m,ct,xt,It)}}ept(),K=ni;break}catch(zt){P$(m,zt)}while(!0);return y&&m.shellSuspendCounter++,ga=wh=null,Qe=I,ye.H=O,ye.A=z,Ve===null&&(Rn=null,en=0,yc()),K}function ept(){for(;Ve!==null;)M$(Ve)}function npt(m,y){var w=Qe;Qe|=2;var I=T$(),O=E$();Rn!==m||en!==y?(Lx=null,eg=Zs()+500,Kf(m,y)):xm=S(m,y);t:do try{if(bn!==0&&Ve!==null){y=Ve;var z=ss;e:switch(bn){case 1:bn=0,ss=null,Jf(m,y,z,1);break;case 2:case 9:if(Df(z)){bn=0,ss=null,C$(y);break}y=function(){bn!==2&&bn!==9||Rn!==m||(bn=7),Ar(m)},z.then(y,y);break t;case 3:bn=7;break t;case 4:bn=5;break t;case 7:Df(z)?(bn=0,ss=null,C$(y)):(bn=0,ss=null,Jf(m,y,z,7));break;case 5:var K=null;switch(Ve.tag){case 26:K=Ve.memoizedState;case 5:case 27:var ct=Ve,xt=ct.type,It=ct.pendingProps;if(K?dz(K):K$(xt,It)){bn=0,ss=null;var zt=ct.sibling;if(zt!==null)Ve=zt;else{var Xt=ct.return;Xt!==null?(Ve=Xt,ux(Xt)):Ve=null}break e}}bn=0,ss=null,Jf(m,y,z,5);break;case 6:bn=0,ss=null,Jf(m,y,z,6);break;case 8:oE(),ni=6;break t;default:throw Error(i(462))}}ipt();break}catch(Ht){P$(m,Ht)}while(!0);return ga=wh=null,ye.H=I,ye.A=O,Qe=w,Ve!==null?0:(Rn=null,en=0,yc(),ni)}function ipt(){for(;Ve!==null&&!Rht();)M$(Ve)}function M$(m){var y=KF(m.alternate,m,ba);m.memoizedProps=m.pendingProps,y===null?ux(m):Ve=y}function C$(m){var y=m,w=y.alternate;switch(y.tag){case 15:case 0:y=VF(w,y,y.pendingProps,y.type,void 0,en);break;case 11:y=VF(w,y,y.pendingProps,y.type.render,y.ref,en);break;case 5:Iy(y);default:n$(w,y),y=Ve=D$(y,ba),y=KF(w,y,ba)}m.memoizedProps=m.pendingProps,y===null?ux(m):Ve=y}function Jf(m,y,w,I){ga=wh=null,Iy(y),_m=null,Jy=0;var O=y.return;try{if(Hut(m,O,y,w,en)){ni=1,rx(m,nt(w,m.current)),Ve=null;return}}catch(z){if(O!==null)throw Ve=O,z;ni=1,rx(m,nt(w,m.current)),Ve=null;return}y.flags&32768?(_n||I===1?m=!0:xm||(en&536870912)!==0?m=!1:(Ac=m=!0,(I===2||I===9||I===3||I===6)&&(I=vs.current,I!==null&&I.tag===13&&(I.flags|=16384))),I$(y,m)):ux(y)}function ux(m){var y=m;do{if((y.flags&32768)!==0){I$(y,Ac);return}m=y.return;var w=Zut(y.alternate,y,ba);if(w!==null){Ve=w;return}if(y=y.sibling,y!==null){Ve=y;return}Ve=y=m}while(y!==null);ni===0&&(ni=5)}function I$(m,y){do{var w=Kut(m.alternate,m);if(w!==null){w.flags&=32767,Ve=w;return}if(w=m.return,w!==null&&(w.flags|=32768,w.subtreeFlags=0,w.deletions=null),!y&&(m=m.sibling,m!==null)){Ve=m;return}Ve=m=w}while(m!==null);ni=6,Ve=null}function N$(m,y,w,I,O,z,K,ct,xt){m.cancelPendingCommit=null;do Xy();while(Ji!==0);if((Qe&6)!==0)throw Error(i(327));if(y!==null){if(y===m.current)throw Error(i(177));if(z=y.lanes|y.childLanes,z|=LE,C(m,w,z,K,ct,xt),m===Rn&&(Ve=Rn=null,en=0),vm=y,Lc=m,wm=w,UE=z,VE=O,Ez=I,(y.subtreeFlags&10256)!==0||(y.flags&10256)!==0?(m.callbackNode=null,m.callbackPriority=0,apt(EE,function(){return F$(!0),null})):(m.callbackNode=null,m.callbackPriority=0),I=(y.flags&13878)!==0,(y.subtreeFlags&13878)!==0||I){I=ye.T,ye.T=null,O=ma(),Ni(2),K=Qe,Qe|=4;try{Jut(m,y,w)}finally{Qe=K,Ni(O),ye.T=I}}Ji=1,A$(),R$(),O$()}}function A$(){if(Ji===1){Ji=0;var m=Lc,y=vm,w=(y.flags&13878)!==0;if((y.subtreeFlags&13878)!==0||w){w=ye.T,ye.T=null;var I=ma();Ni(2);var O=Qe;Qe|=4;try{h$(y,m),bpt(m.containerInfo)}finally{Qe=O,Ni(I),ye.T=w}}m.current=y,Ji=2}}function R$(){if(Ji===2){Ji=0;var m=Lc,y=vm,w=(y.flags&8772)!==0;if((y.subtreeFlags&8772)!==0||w){w=ye.T,ye.T=null;var I=ma();Ni(2);var O=Qe;Qe|=4;try{l$(m,y.alternate,y)}finally{Qe=O,Ni(I),ye.T=w}}Ji=3}}function O$(){if(Ji===4||Ji===3){Ji=0,Oht();var m=Lc,y=vm,w=wm,I=Ez;(y.subtreeFlags&10256)!==0||(y.flags&10256)!==0?Ji=5:(Ji=0,vm=Lc=null,L$(m,m.pendingLanes));var O=m.pendingLanes;if(O===0&&(Oc=null),B(w),y=y.stateNode,is&&typeof is.onCommitFiberRoot=="function")try{is.onCommitFiberRoot(Wy,y,void 0,(y.current.flags&128)===128)}catch{}if(I!==null){y=ye.T,O=ma(),Ni(2),ye.T=null;try{for(var z=m.onRecoverableError,K=0;K<I.length;K++){var ct=I[K];z(ct.value,{componentStack:ct.stack})}}finally{ye.T=y,Ni(O)}}(wm&3)!==0&&Xy(),Ar(m),O=m.pendingLanes,(w&4194090)!==0&&(O&42)!==0?m===GE?ng++:(ng=0,GE=m):ng=0,ko(0,!1)}}function L$(m,y){(m.pooledCacheLanes&=y)===0&&(y=m.pooledCache,y!=null&&(m.pooledCache=null,Gs(y)))}function Xy(m){return A$(),R$(),O$(),F$(m)}function F$(){if(Ji!==5)return!1;var m=Lc,y=UE;UE=0;var w=B(wm),I=32>w?32:w;w=ye.T;var O=ma();try{Ni(I),ye.T=null,I=VE,VE=null;var z=Lc,K=wm;if(Ji=0,vm=Lc=null,wm=0,(Qe&6)!==0)throw Error(i(331));var ct=Qe;if(Qe|=4,y$(z.current),f$(z,z.current,K,I),Qe=ct,ko(0,!1),is&&typeof is.onPostCommitFiberRoot=="function")try{is.onPostCommitFiberRoot(Wy,z)}catch{}return!0}finally{Ni(O),ye.T=w,L$(m,y)}}function $$(m,y,w){y=nt(w,y),y=zT(m.stateNode,y,2),m=_s(m,y,2),m!==null&&(E(m,2),Ar(m))}function xn(m,y,w){if(m.tag===3)$$(m,m,w);else for(;y!==null;){if(y.tag===3){$$(y,m,w);break}else if(y.tag===1){var I=y.stateNode;if(typeof y.type.getDerivedStateFromError=="function"||typeof I.componentDidCatch=="function"&&(Oc===null||!Oc.has(I))){m=nt(w,m),w=zF(2),I=_s(y,w,2),I!==null&&(DF(w,I,y,m),E(I,2),Ar(I));break}}y=y.return}}function lE(m,y,w){var I=m.pingCache;if(I===null){I=m.pingCache=new Ght;var O=new Set;I.set(y,O)}else O=I.get(y),O===void 0&&(O=new Set,I.set(y,O));O.has(w)||(jE=!0,O.add(w),m=rpt.bind(null,m,y,w),y.then(m,m))}function rpt(m,y,w){var I=m.pingCache;I!==null&&I.delete(y),m.pingedLanes|=m.suspendedLanes&w,m.warmLanes&=~w,Rn===m&&(en&w)===w&&(ni===4||ni===3&&(en&62914560)===en&&300>Zs()-XE?(Qe&2)===0&&Kf(m,0):BE|=w,bm===en&&(bm=0)),Ar(m)}function z$(m,y){y===0&&(y=k()),m=To(m,y),m!==null&&(E(m,y),Ar(m))}function spt(m){var y=m.memoizedState,w=0;y!==null&&(w=y.retryLane),z$(m,w)}function opt(m,y){var w=0;switch(m.tag){case 13:var I=m.stateNode,O=m.memoizedState;O!==null&&(w=O.retryLane);break;case 19:I=m.stateNode;break;case 22:I=m.stateNode._retryCache;break;default:throw Error(i(314))}I!==null&&I.delete(y),z$(m,w)}function apt(m,y){return yx(m,y)}function cpt(m,y,w,I){this.tag=m,this.key=w,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=y,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=I,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function uE(m){return m=m.prototype,!(!m||!m.isReactComponent)}function da(m,y){var w=m.alternate;return w===null?(w=e(m.tag,y,m.key,m.mode),w.elementType=m.elementType,w.type=m.type,w.stateNode=m.stateNode,w.alternate=m,m.alternate=w):(w.pendingProps=y,w.type=m.type,w.flags=0,w.subtreeFlags=0,w.deletions=null),w.flags=m.flags&65011712,w.childLanes=m.childLanes,w.lanes=m.lanes,w.child=m.child,w.memoizedProps=m.memoizedProps,w.memoizedState=m.memoizedState,w.updateQueue=m.updateQueue,y=m.dependencies,w.dependencies=y===null?null:{lanes:y.lanes,firstContext:y.firstContext},w.sibling=m.sibling,w.index=m.index,w.ref=m.ref,w.refCleanup=m.refCleanup,w}function D$(m,y){m.flags&=65011714;var w=m.alternate;return w===null?(m.childLanes=0,m.lanes=y,m.child=null,m.subtreeFlags=0,m.memoizedProps=null,m.memoizedState=null,m.updateQueue=null,m.dependencies=null,m.stateNode=null):(m.childLanes=w.childLanes,m.lanes=w.lanes,m.child=w.child,m.subtreeFlags=0,m.deletions=null,m.memoizedProps=w.memoizedProps,m.memoizedState=w.memoizedState,m.updateQueue=w.updateQueue,m.type=w.type,y=w.dependencies,m.dependencies=y===null?null:{lanes:y.lanes,firstContext:y.firstContext}),m}function px(m,y,w,I,O,z){var K=0;if(I=m,typeof m=="function")uE(m)&&(K=1);else if(typeof m=="string")K=qs&&wi?az(m,w,Ki.current)?26:_z(m)?27:5:qs?az(m,w,Ki.current)?26:5:wi&&_z(m)?27:5;else t:switch(m){case bE:return m=e(31,w,y,O),m.elementType=bE,m.lanes=z,m;case tm:return yh(w.children,O,z,y);case V$:K=8,O|=24;break;case mE:return m=e(12,w,y,O|2),m.elementType=mE,m.lanes=z,m;case yE:return m=e(13,w,y,O),m.elementType=yE,m.lanes=z,m;case gE:return m=e(19,w,y,O),m.elementType=gE,m.lanes=z,m;default:if(typeof m=="object"&&m!==null)switch(m.$$typeof){case hpt:case Tc:K=10;break t;case G$:K=9;break t;case _E:K=11;break t;case xE:K=14;break t;case Ec:K=16,I=null;break t}K=29,w=Error(i(130,m===null?"null":typeof m,"")),I=null}return y=e(K,w,y,O),y.elementType=m,y.type=I,y.lanes=z,y}function yh(m,y,w,I){return m=e(7,m,I,y),m.lanes=w,m}function pE(m,y,w){return m=e(6,m,null,y),m.lanes=w,m}function hE(m,y,w){return y=e(4,m.children!==null?m.children:[],m.key,y),y.lanes=w,y.stateNode={containerInfo:m.containerInfo,pendingChildren:null,implementation:m.implementation},y}function lpt(m,y,w,I,O,z,K,ct){this.tag=1,this.containerInfo=m,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=gh,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=N(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=N(0),this.hiddenUpdates=N(null),this.identifierPrefix=I,this.onUncaughtError=O,this.onCaughtError=z,this.onRecoverableError=K,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=ct,this.incompleteTransitions=new Map}function j$(m,y,w,I,O,z,K,ct,xt,It,zt,Xt){return m=new lpt(m,y,w,K,ct,xt,It,Xt),y=1,z===!0&&(y|=24),z=e(3,null,null,y),m.current=z,z.stateNode=m,y=Nr(),y.refCount++,m.pooledCache=y,y.refCount++,z.memoizedState={element:I,isDehydrated:w,cache:y},oh(z),m}function B$(m){return m?(m=rm,m):rm}function Y$(m){var y=m._reactInternals;if(y===void 0)throw typeof m.render=="function"?Error(i(188)):(m=Object.keys(m).join(","),Error(i(268,m)));return m=o(y),m=m!==null?a(m):null,m===null?null:Uy(m.stateNode)}function X$(m,y,w,I,O,z){O=B$(O),I.context===null?I.context=O:I.pendingContext=O,I=ms(y),I.payload={element:w},z=z===void 0?null:z,z!==null&&(I.callback=z),w=_s(m,I,y),w!==null&&(ts(w,m,y),ca(w,m,y))}function U$(m,y){if(m=m.memoizedState,m!==null&&m.dehydrated!==null){var w=m.retryLane;m.retryLane=w!==0&&w<y?w:y}}function dE(m,y){U$(m,y),(m=m.alternate)&&U$(m,y)}var Ue={},upt=Js(),es=uY(),fE=Object.assign,ppt=Symbol.for("react.element"),hx=Symbol.for("react.transitional.element"),Qf=Symbol.for("react.portal"),tm=Symbol.for("react.fragment"),V$=Symbol.for("react.strict_mode"),mE=Symbol.for("react.profiler"),hpt=Symbol.for("react.provider"),G$=Symbol.for("react.consumer"),Tc=Symbol.for("react.context"),_E=Symbol.for("react.forward_ref"),yE=Symbol.for("react.suspense"),gE=Symbol.for("react.suspense_list"),xE=Symbol.for("react.memo"),Ec=Symbol.for("react.lazy"),bE=Symbol.for("react.activity"),dpt=Symbol.for("react.memo_cache_sentinel"),W$=Symbol.iterator,fpt=Symbol.for("react.client.reference"),dx=Array.isArray,ye=upt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,mpt=n.rendererVersion,_pt=n.rendererPackageName,H$=n.extraDevToolsConfig,Uy=n.getPublicInstance,ypt=n.getRootHostContext,gpt=n.getChildHostContext,xpt=n.prepareForCommit,bpt=n.resetAfterCommit,vpt=n.createInstance;n.cloneMutableInstance;var vE=n.appendInitialChild,q$=n.finalizeInitialChildren,fx=n.shouldSetTextContent,Z$=n.createTextInstance;n.cloneMutableTextInstance;var wpt=n.scheduleTimeout,Spt=n.cancelTimeout,gh=n.noTimeout,fa=n.isPrimaryRenderer;n.warnsIfNotActing;var lr=n.supportsMutation,Mc=n.supportsPersistence,ys=n.supportsHydration,Ppt=n.getInstanceFromNode;n.beforeActiveInstanceBlur;var kpt=n.preparePortalMount;n.prepareScopeUpdate,n.getInstanceFromScope;var Ni=n.setCurrentUpdatePriority,ma=n.getCurrentUpdatePriority,Tpt=n.resolveUpdatePriority;n.trackSchedulerEvent,n.resolveEventType,n.resolveEventTimeStamp;var Ept=n.shouldAttemptEagerTransition,Mpt=n.detachDeletedInstance;n.requestPostPaintCallback;var Cpt=n.maySuspendCommit,K$=n.preloadInstance,Ipt=n.startSuspendingCommit,J$=n.suspendInstance;n.suspendOnActiveViewTransition;var Npt=n.waitForCommitToBeReady,em=n.NotPendingTransition,xh=n.HostTransitionContext,Apt=n.resetFormInstance;n.bindToConsole;var Rpt=n.supportsMicrotasks,Opt=n.scheduleMicrotask,Vy=n.supportsTestSelectors,Lpt=n.findFiberRoot,Fpt=n.getBoundingRect,$pt=n.getTextContent,Gy=n.isHiddenSubtree,zpt=n.matchAccessibilityRole,Dpt=n.setFocusIfFocusable,jpt=n.setupIntersectionObserver,Bpt=n.appendChild,Ypt=n.appendChildToContainer,Xpt=n.commitTextUpdate,Upt=n.commitMount,Vpt=n.commitUpdate,Gpt=n.insertBefore,Wpt=n.insertInContainerBefore,Hpt=n.removeChild,qpt=n.removeChildFromContainer,Q$=n.resetTextContent,Zpt=n.hideInstance,Kpt=n.hideTextInstance,Jpt=n.unhideInstance,Qpt=n.unhideTextInstance;n.cancelViewTransitionName,n.cancelRootViewTransitionName,n.restoreRootViewTransitionName,n.cloneRootViewTransitionContainer,n.removeRootViewTransitionClone,n.measureClonedInstance,n.hasInstanceChanged,n.hasInstanceAffectedParent,n.startViewTransition,n.startGestureTransition,n.stopGestureTransition,n.getCurrentGestureOffset,n.subscribeToGestureDirection,n.createViewTransitionInstance;var tht=n.clearContainer;n.createFragmentInstance,n.updateFragmentInstanceFiber,n.commitNewChildToFragmentInstance,n.deleteChildFromFragmentInstance;var eht=n.cloneInstance,tz=n.createContainerChildSet,ez=n.appendChildToContainerChildSet,nht=n.finalizeContainerChildren,nz=n.replaceContainerChildren,iz=n.cloneHiddenInstance,rz=n.cloneHiddenTextInstance,wE=n.isSuspenseInstancePending,SE=n.isSuspenseInstanceFallback,iht=n.getSuspenseInstanceFallbackErrorDetails,rht=n.registerSuspenseInstanceRetry,sht=n.canHydrateFormStateMarker,oht=n.isFormStateMarkerMatching,sz=n.getNextHydratableSibling,aht=n.getNextHydratableSiblingAfterSingleton,cht=n.getFirstHydratableChild,lht=n.getFirstHydratableChildWithinContainer,uht=n.getFirstHydratableChildWithinSuspenseInstance,pht=n.getFirstHydratableChildWithinSingleton,hht=n.canHydrateInstance,dht=n.canHydrateTextInstance,fht=n.canHydrateSuspenseInstance,mht=n.hydrateInstance,_ht=n.hydrateTextInstance,yht=n.hydrateSuspenseInstance,ght=n.getNextHydratableInstanceAfterSuspenseInstance,xht=n.commitHydratedContainer,bht=n.commitHydratedSuspenseInstance,vht=n.clearSuspenseBoundary,wht=n.clearSuspenseBoundaryFromContainer,oz=n.shouldDeleteUnhydratedTailInstances;n.diffHydratedPropsForDevWarnings,n.diffHydratedTextForDevWarnings,n.describeHydratableInstanceForDevWarnings;var Sht=n.validateHydratableInstance,Pht=n.validateHydratableTextInstance,qs=n.supportsResources,az=n.isHostHoistableType,PE=n.getHoistableRoot,cz=n.getResource,lz=n.acquireResource,uz=n.releaseResource,kht=n.hydrateHoistable,pz=n.mountHoistable,hz=n.unmountHoistable,Tht=n.createHoistableInstance,Eht=n.prepareToCommitHoistables,Mht=n.mayResourceSuspendCommit,dz=n.preloadResource,Cht=n.suspendResource,wi=n.supportsSingletons,fz=n.resolveSingletonInstance,Iht=n.acquireSingletonInstance,mz=n.releaseSingletonInstance,_z=n.isHostSingletonType,nm=n.isSingletonScope,kE=[],im=-1,rm={},ns=Math.clz32?Math.clz32:g,Nht=Math.log,Aht=Math.LN2,mx=256,_x=4194304,yx=es.unstable_scheduleCallback,TE=es.unstable_cancelCallback,Rht=es.unstable_shouldYield,Oht=es.unstable_requestPaint,Zs=es.unstable_now,yz=es.unstable_ImmediatePriority,Lht=es.unstable_UserBlockingPriority,EE=es.unstable_NormalPriority,Fht=es.unstable_IdlePriority,$ht=es.log,zht=es.unstable_setDisableYieldValue,Wy=null,is=null,ME,gz,CE=!1,xz=new WeakMap,sm=[],om=0,gx=null,xx=0,gs=[],xs=0,bh=null,_a=1,ya="",Ki=p(null),Hy=p(null),Cc=p(null),bx=p(null),Sr=null,Si=null,_n=!1,vh=null,Co=!1,IE=Error(i(519)),rs=typeof Object.is=="function"?Object.is:at,vx=p(null),wh=null,ga=null,Dht=typeof AbortController<"u"?AbortController:function(){var m=[],y=this.signal={aborted:!1,addEventListener:function(w,I){m.push(I)}};this.abort=function(){y.aborted=!0,m.forEach(function(w){return w()})}},jht=es.unstable_scheduleCallback,Bht=es.unstable_NormalPriority,ei={$$typeof:Tc,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0},wx=null,am=null,NE=!1,Sx=!1,AE=!1,cm=0,qy=null,RE=0,lm=0,um=null,bz=ye.S;ye.S=function(m,y){typeof y=="object"&&y!==null&&typeof y.then=="function"&&Ty(m,y),bz!==null&&bz(m,y)};var Sh=p(null),Yht=Object.prototype.hasOwnProperty,Zy=Error(i(460)),OE=Error(i(474)),Px=Error(i(542)),kx={then:function(){}},pm=null,bs=[],hm=0,LE=0,Ic=!1,FE=!1,dm=p(null),Tx=p(0),Nc=0,je=null,Pn=null,mi=null,Ex=!1,fm=!1,Ph=!1,Mx=0,Ky=0,mm=null,Xht=0,Cx={readContext:Jt,use:Wf,useCallback:Fn,useContext:Fn,useEffect:Fn,useImperativeHandle:Fn,useLayoutEffect:Fn,useInsertionEffect:Fn,useMemo:Fn,useReducer:Fn,useRef:Fn,useState:Fn,useDebugValue:Fn,useDeferredValue:Fn,useTransition:Fn,useSyncExternalStore:Fn,useId:Fn,useHostTransitionStatus:Fn,useFormState:Fn,useActionState:Fn,useOptimistic:Fn,useMemoCache:Fn,useCacheRefresh:Fn},vz={readContext:Jt,use:Wf,useCallback:function(m,y){return cr().memoizedState=[m,y===void 0?null:y],m},useContext:Jt,useEffect:_F,useImperativeHandle:function(m,y,w){w=w!=null?w.concat([m]):null,Q0(4194308,4,bF.bind(null,y,m),w)},useLayoutEffect:function(m,y){return Q0(4194308,4,m,y)},useInsertionEffect:function(m,y){Q0(4,2,m,y)},useMemo:function(m,y){var w=cr();y=y===void 0?null:y;var I=m();if(Ph){j(!0);try{m()}finally{j(!1)}}return w.memoizedState=[I,y],I},useReducer:function(m,y,w){var I=cr();if(w!==void 0){var O=w(y);if(Ph){j(!0);try{w(y)}finally{j(!1)}}}else O=y;return I.memoizedState=I.baseState=O,m={pending:null,lanes:0,dispatch:null,lastRenderedReducer:m,lastRenderedState:O},I.queue=m,m=m.dispatch=Wut.bind(null,je,m),[I.memoizedState,m]},useRef:function(m){var y=cr();return m={current:m},y.memoizedState=m},useState:function(m){m=NT(m);var y=m.queue,w=CF.bind(null,je,y);return y.dispatch=w,[m.memoizedState,w]},useDebugValue:RT,useDeferredValue:function(m,y){var w=cr();return OT(w,m,y)},useTransition:function(){var m=NT(!1);return m=kF.bind(null,je,m.queue,!0,!1),cr().memoizedState=m,[!1,m]},useSyncExternalStore:function(m,y,w){var I=je,O=cr();if(_n){if(w===void 0)throw Error(i(407));w=w()}else{if(w=y(),Rn===null)throw Error(i(349));(en&124)!==0||tF(I,y,w)}O.memoizedState=w;var z={value:w,getSnapshot:y};return O.queue=z,_F(nF.bind(null,I,z,m),[m]),I.flags|=2048,qf(9,J0(),eF.bind(null,I,z,w,y),null),w},useId:function(){var m=cr(),y=Rn.identifierPrefix;if(_n){var w=ya,I=_a;w=(I&~(1<<32-ns(I)-1)).toString(32)+w,y="\xAB"+y+"R"+w,w=Mx++,0<w&&(y+="H"+w.toString(32)),y+="\xBB"}else w=Xht++,y="\xAB"+y+"r"+w.toString(32)+"\xBB";return m.memoizedState=y},useHostTransitionStatus:LT,useFormState:pF,useActionState:pF,useOptimistic:function(m){var y=cr();y.memoizedState=y.baseState=m;var w={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return y.queue=w,y=FT.bind(null,je,!0,w),w.dispatch=y,[m,y]},useMemoCache:Ay,useCacheRefresh:function(){return cr().memoizedState=Gut.bind(null,je)}},wz={readContext:Jt,use:Wf,useCallback:wF,useContext:Jt,useEffect:yF,useImperativeHandle:vF,useInsertionEffect:gF,useLayoutEffect:xF,useMemo:SF,useReducer:Hf,useRef:mF,useState:function(){return Hf(Ws)},useDebugValue:RT,useDeferredValue:function(m,y){var w=ti();return PF(w,Pn.memoizedState,m,y)},useTransition:function(){var m=Hf(Ws)[0],y=ti().memoizedState;return[typeof m=="boolean"?m:dh(m),y]},useSyncExternalStore:Q7,useId:EF,useHostTransitionStatus:LT,useFormState:hF,useActionState:hF,useOptimistic:function(m,y){var w=ti();return sF(w,Pn,m,y)},useMemoCache:Ay,useCacheRefresh:MF},Uht={readContext:Jt,use:Wf,useCallback:wF,useContext:Jt,useEffect:yF,useImperativeHandle:vF,useInsertionEffect:gF,useLayoutEffect:xF,useMemo:SF,useReducer:Oy,useRef:mF,useState:function(){return Oy(Ws)},useDebugValue:RT,useDeferredValue:function(m,y){var w=ti();return Pn===null?OT(w,m,y):PF(w,Pn.memoizedState,m,y)},useTransition:function(){var m=Oy(Ws)[0],y=ti().memoizedState;return[typeof m=="boolean"?m:dh(m),y]},useSyncExternalStore:Q7,useId:EF,useHostTransitionStatus:LT,useFormState:fF,useActionState:fF,useOptimistic:function(m,y){var w=ti();return Pn!==null?sF(w,Pn,m,y):(w.baseState=m,[m,w.queue.dispatch])},useMemoCache:Ay,useCacheRefresh:MF},_m=null,Jy=0,ym=RF(!0),Sz=RF(!1),vs=p(null),Io=null,Pi=p(0),$E={enqueueSetState:function(m,y,w){m=m._reactInternals;var I=Qr(),O=ms(I);O.payload=y,w!=null&&(O.callback=w),y=_s(m,O,I),y!==null&&(ts(y,m,I),ca(y,m,I))},enqueueReplaceState:function(m,y,w){m=m._reactInternals;var I=Qr(),O=ms(I);O.tag=1,O.payload=y,w!=null&&(O.callback=w),y=_s(m,O,I),y!==null&&(ts(y,m,I),ca(y,m,I))},enqueueForceUpdate:function(m,y){m=m._reactInternals;var w=Qr(),I=ms(w);I.tag=2,y!=null&&(I.callback=y),y=_s(m,I,w),y!==null&&(ts(y,m,w),ca(y,m,w))}},Pz=typeof reportError=="function"?reportError:function(m){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var y=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof m=="object"&&m!==null&&typeof m.message=="string"?String(m.message):String(m),error:m});if(!window.dispatchEvent(y))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",m);return}console.error(m)},kz=Error(i(461)),Ai=!1,zE={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null},xa=!1,hi=!1,DE=!1,Tz=typeof WeakSet=="function"?WeakSet:Set,Ri=null,_i=null,Or=!1,Ks=null,gm=8192,Vht={getCacheForType:function(m){var y=Jt(ei),w=y.data.get(m);return w===void 0&&(w=m(),y.data.set(m,w)),w}},Ix=0,Nx=1,Ax=2,Rx=3,Ox=4;if(typeof Symbol=="function"&&Symbol.for){var Qy=Symbol.for;Ix=Qy("selector.component"),Nx=Qy("selector.has_pseudo_class"),Ax=Qy("selector.role"),Rx=Qy("selector.test_id"),Ox=Qy("selector.text")}var Ght=typeof WeakMap=="function"?WeakMap:Map,Qe=0,Rn=null,Ve=null,en=0,bn=0,ss=null,Ac=!1,xm=!1,jE=!1,ba=0,ni=0,Rc=0,kh=0,BE=0,ws=0,bm=0,tg=null,Lr=null,YE=!1,XE=0,eg=1/0,Lx=null,Oc=null,Ji=0,Lc=null,vm=null,wm=0,UE=0,VE=null,Ez=null,ng=0,GE=null;return Ue.attemptContinuousHydration=function(m){if(m.tag===13){var y=To(m,67108864);y!==null&&ts(y,m,67108864),dE(m,67108864)}},Ue.attemptHydrationAtCurrentPriority=function(m){if(m.tag===13){var y=Qr();y=R(y);var w=To(m,y);w!==null&&ts(w,m,y),dE(m,y)}},Ue.attemptSynchronousHydration=function(m){switch(m.tag){case 3:if(m=m.stateNode,m.current.memoizedState.isDehydrated){var y=x(m.pendingLanes);if(y!==0){for(m.pendingLanes|=2,m.entangledLanes|=2;y;){var w=1<<31-ns(y);m.entanglements[1]|=w,y&=~w}Ar(m),(Qe&6)===0&&(eg=Zs()+500,ko(0,!1))}}break;case 13:y=To(m,2),y!==null&&ts(y,m,2),S$(),dE(m,2)}},Ue.batchedUpdates=function(m,y){return m(y)},Ue.createComponentSelector=function(m){return{$$typeof:Ix,value:m}},Ue.createContainer=function(m,y,w,I,O,z,K,ct,xt,It){return j$(m,y,!1,null,w,I,z,K,ct,xt,It,null)},Ue.createHasPseudoClassSelector=function(m){return{$$typeof:Nx,value:m}},Ue.createHydrationContainer=function(m,y,w,I,O,z,K,ct,xt,It,zt,Xt,Ht){return m=j$(w,I,!0,m,O,z,ct,xt,It,zt,Xt,Ht),m.context=B$(null),w=m.current,I=Qr(),I=R(I),O=ms(I),O.callback=y??null,_s(w,O,I),y=I,m.current.lanes=y,E(m,y),Ar(m),m},Ue.createPortal=function(m,y,w){var I=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Qf,key:I==null?null:""+I,children:m,containerInfo:y,implementation:w}},Ue.createRoleSelector=function(m){return{$$typeof:Ax,value:m}},Ue.createTestNameSelector=function(m){return{$$typeof:Rx,value:m}},Ue.createTextSelector=function(m){return{$$typeof:Ox,value:m}},Ue.defaultOnCaughtError=function(m){console.error(m)},Ue.defaultOnRecoverableError=function(m){Pz(m)},Ue.defaultOnUncaughtError=function(m){Pz(m)},Ue.deferredUpdates=function(m){var y=ye.T,w=ma();try{return Ni(32),ye.T=null,m()}finally{Ni(w),ye.T=y}},Ue.discreteUpdates=function(m,y,w,I,O){var z=ye.T,K=ma();try{return Ni(2),ye.T=null,m(y,w,I,O)}finally{Ni(K),ye.T=z,Qe===0&&(eg=Zs()+500)}},Ue.findAllNodes=sE,Ue.findBoundingRects=function(m,y){if(!Vy)throw Error(i(363));y=sE(m,y),m=[];for(var w=0;w<y.length;w++)m.push(Fpt(y[w]));for(y=m.length-1;0<y;y--){w=m[y];for(var I=w.x,O=I+w.width,z=w.y,K=z+w.height,ct=y-1;0<=ct;ct--)if(y!==ct){var xt=m[ct],It=xt.x,zt=It+xt.width,Xt=xt.y,Ht=Xt+xt.height;if(I>=It&&z>=Xt&&O<=zt&&K<=Ht){m.splice(y,1);break}else if(I!==It||w.width!==xt.width||Ht<z||Xt>K){if(!(z!==Xt||w.height!==xt.height||zt<I||It>O)){It>I&&(xt.width+=It-I,xt.x=I),zt<O&&(xt.width=O-It),m.splice(y,1);break}}else{Xt>z&&(xt.height+=Xt-z,xt.y=z),Ht<K&&(xt.height=K-Xt),m.splice(y,1);break}}}return m},Ue.findHostInstance=Y$,Ue.findHostInstanceWithNoPortals=function(m){return m=o(m),m=m!==null?c(m):null,m===null?null:Uy(m.stateNode)},Ue.findHostInstanceWithWarning=function(m){return Y$(m)},Ue.flushPassiveEffects=Xy,Ue.flushSyncFromReconciler=function(m){var y=Qe;Qe|=1;var w=ye.T,I=ma();try{if(Ni(2),ye.T=null,m)return m()}finally{Ni(I),ye.T=w,Qe=y,(Qe&6)===0&&ko(0,!1)}},Ue.flushSyncWork=S$,Ue.focusWithin=function(m,y){if(!Vy)throw Error(i(363));for(m=nE(m),y=x$(m,y),y=Array.from(y),m=0;m<y.length;){var w=y[m++],I=w.tag;if(!Gy(w)){if((I===5||I===26||I===27)&&Dpt(w.stateNode))return!0;for(w=w.child;w!==null;)y.push(w),w=w.sibling}}return!1},Ue.getFindAllNodesFailureDescription=function(m,y){if(!Vy)throw Error(i(363));var w=0,I=[];m=[nE(m),0];for(var O=0;O<m.length;){var z=m[O++],K=z.tag,ct=m[O++],xt=y[ct];if((K!==5&&K!==26&&K!==27||!Gy(z))&&(iE(z,xt)&&(I.push(rE(xt)),ct++,ct>w&&(w=ct)),ct<y.length))for(z=z.child;z!==null;)m.push(z,ct),z=z.sibling}if(w<y.length){for(m=[];w<y.length;w++)m.push(rE(y[w]));return`findAllNodes was able to match part of the selector:
9
9
  `+(I.join(" > ")+`
10
10
 
11
11
  No matching component was found for:
@@ -156,7 +156,7 @@ svg { font-family: 'Inter', 'Helvetica Neue', Arial, sans-serif; }
156
156
  :is(button, input, select, textarea, optgroup, option)[disabled],
157
157
  optgroup[disabled] > option,
158
158
  fieldset[disabled]:not(fieldset[disabled] legend:first-of-type *)
159
- )`,enabled:":not(:disabled)",checked:":is(:is(input[type=radio], input[type=checkbox])[checked], option:selected)",required:":is(input, select, textarea)[required]",optional:":is(input, select, textarea):not([required])",selected:"option:is([selected], select:not([multiple]):not(:has(> option[selected])) > :first-of-type)",checkbox:"[type=checkbox]",file:"[type=file]",password:"[type=password]",radio:"[type=radio]",reset:"[type=reset]",image:"[type=image]",submit:"[type=submit]",parent:":not(:empty)",header:":is(h1, h2, h3, h4, h5, h6)",button:":is(button, input[type=button])",input:":is(input, textarea, select, button)",text:"input:is(:not([type!='']), [type=text])"};var Cs=Vt(td(),1);var K5={};function J5(n,e){return n===Cs.default.falseFunc?Cs.default.falseFunc:t=>e.isTag(t)&&n(t)}function Q5(n,e){let t=e.getSiblings(n);if(t.length<=1)return[];let i=t.indexOf(n);return i<0||i===t.length-1?[]:t.slice(i+1).filter(e.isTag)}function Z5(n){return{xmlMode:!!n.xmlMode,lowerCaseAttributeNames:!!n.lowerCaseAttributeNames,lowerCaseTags:!!n.lowerCaseTags,quirksMode:!!n.quirksMode,cacheResults:!!n.cacheResults,pseudos:n.pseudos,adapter:n.adapter,equals:n.equals}}var q5=(n,e,t,i,r)=>{let s=r(e,Z5(t),i);return s===Cs.default.trueFunc?n:s===Cs.default.falseFunc?Cs.default.falseFunc:o=>s(o)&&n(o)},uw={is:q5,matches:q5,where:q5,not(n,e,t,i,r){let s=r(e,Z5(t),i);return s===Cs.default.falseFunc?n:s===Cs.default.trueFunc?Cs.default.falseFunc:o=>!s(o)&&n(o)},has(n,e,t,i,r){let{adapter:s}=t,o=Z5(t);o.relativeSelector=!0;let a=e.some(u=>u.some(Pg))?[K5]:void 0,c=r(e,o,a);if(c===Cs.default.falseFunc)return Cs.default.falseFunc;let l=J5(c,s);if(a&&c!==Cs.default.trueFunc){let{shouldTestNextSiblings:u=!1}=c;return p=>{if(!n(p))return!1;a[0]=p;let d=s.getChildren(p),_=u?[...d,...Q5(p,s)]:d;return s.existsOne(l,_)}}return u=>n(u)&&s.existsOne(l,s.getChildren(u))}};function XG(n,e,t,i,r){var s;let{name:o,data:a}=e;if(Array.isArray(a)){if(!(o in uw))throw new Error(`Unknown pseudo-class :${o}(${a})`);return uw[o](n,a,t,i,r)}let c=(s=t.pseudos)===null||s===void 0?void 0:s[o],l=typeof c=="string"?c:H5[o];if(typeof l=="string"){if(a!=null)throw new Error(`Pseudo ${o} doesn't have any arguments`);let u=Sg(l);return uw.is(n,u,t,i,r)}if(typeof c=="function")return W5(c,o,a,1),u=>c(u,a)&&n(u);if(o in Tg)return Tg[o](n,a,t,i);if(o in lw){let u=lw[o];return W5(u,o,a,2),p=>u(p,t,a)&&n(p)}throw new Error(`Unknown pseudo-class :${o}`)}function t4(n,e){let t=e.getParent(n);return t&&e.isTag(t)?t:null}function UG(n,e,t,i,r){let{adapter:s,equals:o}=t;switch(e.type){case fe.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case fe.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case fe.Attribute:{if(e.namespace!=null)throw new Error("Namespaced attributes are not yet supported by css-select");return(!t.xmlMode||t.lowerCaseAttributeNames)&&(e.name=e.name.toLowerCase()),DG[e.action](n,e,t)}case fe.Pseudo:return XG(n,e,t,i,r);case fe.Tag:{if(e.namespace!=null)throw new Error("Namespaced tag names are not yet supported by css-select");let{name:a}=e;return(!t.xmlMode||t.lowerCaseTags)&&(a=a.toLowerCase()),function(l){return s.getName(l)===a&&n(l)}}case fe.Descendant:{if(t.cacheResults===!1||typeof WeakSet>"u")return function(l){let u=l;for(;u=t4(u,s);)if(n(u))return!0;return!1};let a=new WeakSet;return function(l){let u=l;for(;u=t4(u,s);)if(!a.has(u)){if(s.isTag(u)&&n(u))return!0;a.add(u)}return!1}}case"_flexibleDescendant":return function(c){let l=c;do if(n(l))return!0;while(l=t4(l,s));return!1};case fe.Parent:return function(c){return s.getChildren(c).some(l=>s.isTag(l)&&n(l))};case fe.Child:return function(c){let l=s.getParent(c);return l!=null&&s.isTag(l)&&n(l)};case fe.Sibling:return function(c){let l=s.getSiblings(c);for(let u=0;u<l.length;u++){let p=l[u];if(o(c,p))break;if(s.isTag(p)&&n(p))return!0}return!1};case fe.Adjacent:return s.prevElementSibling?function(c){let l=s.prevElementSibling(c);return l!=null&&n(l)}:function(c){let l=s.getSiblings(c),u;for(let p=0;p<l.length;p++){let d=l[p];if(o(c,d))break;s.isTag(d)&&(u=d)}return!!u&&n(u)};case fe.Universal:{if(e.namespace!=null&&e.namespace!=="*")throw new Error("Namespaced universal selectors are not yet supported by css-select");return n}}}function VG(n,e,t){let i=pw(n,e,t);return J5(i,e.adapter)}function pw(n,e,t){let i=typeof n=="string"?Sg(n):n;return hw(i,e,t)}function GG(n){return n.type===fe.Pseudo&&(n.name==="scope"||Array.isArray(n.data)&&n.data.some(e=>e.some(GG)))}var d3t={type:fe.Descendant},f3t={type:"_flexibleDescendant"},m3t={type:fe.Pseudo,name:"scope",data:null};function _3t(n,{adapter:e},t){let i=!!t?.every(r=>{let s=e.isTag(r)&&e.getParent(r);return r===K5||s&&e.isTag(s)});for(let r of n){if(!(r.length>0&&Pg(r[0])&&r[0].type!==fe.Descendant))if(i&&!r.some(GG))r.unshift(d3t);else continue;r.unshift(m3t)}}function hw(n,e,t){var i;n.forEach(U5),t=(i=e.context)!==null&&i!==void 0?i:t;let r=Array.isArray(t),s=t&&(Array.isArray(t)?t:[t]);if(e.relativeSelector!==!1)_3t(n,e,s);else if(n.some(c=>c.length>0&&Pg(c[0])))throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");let o=!1,a=n.map(c=>{if(c.length>=2){let[l,u]=c;l.type!==fe.Pseudo||l.name!=="scope"||(r&&u.type===fe.Descendant?c[1]=f3t:(u.type===fe.Adjacent||u.type===fe.Sibling)&&(o=!0))}return y3t(c,e,s)}).reduce(g3t,Ra.default.falseFunc);return a.shouldTestNextSiblings=o,a}function y3t(n,e,t){var i;return n.reduce((r,s)=>r===Ra.default.falseFunc?Ra.default.falseFunc:UG(r,s,e,t,hw),(i=e.rootFunc)!==null&&i!==void 0?i:Ra.default.trueFunc)}function g3t(n,e){return e===Ra.default.falseFunc||n===Ra.default.trueFunc?n:n===Ra.default.falseFunc||e===Ra.default.trueFunc?e:function(i){return n(i)||e(i)}}var WG=(n,e)=>n===e,x3t={adapter:aw,equals:WG};function HG(n){var e,t,i,r;let s=n??x3t;return(e=s.adapter)!==null&&e!==void 0||(s.adapter=aw),(t=s.equals)!==null&&t!==void 0||(s.equals=(r=(i=s.adapter)===null||i===void 0?void 0:i.equals)!==null&&r!==void 0?r:WG),s}function n4(n){return function(t,i,r){let s=HG(i);return n(t,s,r)}}var wee=n4(VG),See=n4(pw),Pee=n4(hw);function qG(n){return function(t,i,r){let s=HG(r);typeof t!="function"&&(t=pw(t,s,i));let o=b3t(i,s.adapter,t.shouldTestNextSiblings);return n(t,o,s)}}function b3t(n,e,t=!1){return t&&(n=v3t(n,e)),Array.isArray(n)?e.removeSubsets(n):e.getChildren(n)}function v3t(n,e){let t=Array.isArray(n)?n.slice(0):[n],i=t.length;for(let r=0;r<i;r++){let s=Q5(t[r],e);t.push(...s)}return t}var i4=qG((n,e,t)=>n===e4.default.falseFunc||!e||e.length===0?[]:t.adapter.findAll(n,e)),dw=qG((n,e,t)=>n===e4.default.falseFunc||!e||e.length===0?null:t.adapter.findOne(n,e));Q();wt();Q();var EW=Vt(In(),1);wt();var IW=Vt(In(),1),AW=Vt(In(),1);wt();si();u4();var p4=(n,e={})=>{let t=n._internal_store;if(!t){t={counts:{}},n._internal_store=t;for(let r of n){let s=r.type,o=r[`${s}_id`];if(!o)continue;let a=Number.parseInt(o.split("_").pop());Number.isNaN(a)||(t.counts[s]=Math.max(t.counts[s]??0,a))}}return new Proxy({},{get:(r,s)=>s==="toArray"?()=>n:{get:o=>n.find(a=>a.type===s&&a[`${s}_id`]===o),getUsing:o=>{let a=Object.keys(o);if(a.length!==1)throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");let c=a[0],l=c.replace("_id",""),u=n.find(p=>p.type===l&&p[c]===o[c]);return u?n.find(p=>p.type===s&&p[`${s}_id`]===u[`${s}_id`]):null},getWhere:o=>{let a=Object.keys(o);return n.find(c=>c.type===s&&a.every(l=>c[l]===o[l]))},list:o=>{let a=o?Object.keys(o):[];return n.filter(c=>c.type===s&&a.every(l=>c[l]===o[l]))},insert:o=>{var l;(l=t.counts)[s]??(l[s]=-1),t.counts[s]++;let a=t.counts[s],c={type:s,[`${s}_id`]:`${s}_${a}`,...o};return e.validateInserts&&(Wh[s]??Gh).parse(c),n.push(c),c},delete:o=>{let a=n.find(c=>c[`${s}_id`]===o);a&&n.splice(n.indexOf(a),1)},update:(o,a)=>{let c=n.find(l=>l.type===s&&l[`${s}_id`]===o);if(c)return Object.assign(c,a),c},select:o=>{if(s==="source_component")return n.find(a=>a.type==="source_component"&&a.name===o.replace(/\./g,""));if(s==="pcb_port"||s==="source_port"||s==="schematic_port"){let[a,c]=o.replace(/\./g,"").split(/[\s\>]+/),l=n.find(p=>p.type==="source_component"&&p.name===a);if(!l)return null;let u=n.find(p=>p.type==="source_port"&&p.source_component_id===l.source_component_id&&(p.name===c||(p.port_hints??[]).includes(c)));if(!u)return null;if(s==="source_port")return u;if(s==="pcb_port")return n.find(p=>p.type==="pcb_port"&&p.source_port_id===u.source_port_id);if(s==="schematic_port")return n.find(p=>p.type==="schematic_port"&&p.source_port_id===u.source_port_id)}}}})};p4.unparsed=p4;var lW=p4;var Eie=Vt(pW(),1);ir();function so(n){let e=n.width/2,t=n.height/2;return{minX:n.center.x-e,maxX:n.center.x+e,minY:n.center.y-t,maxY:n.center.y+t}}function Ng(n,e){let t=so(n),i=so(e),r=Math.max(t.minX-i.maxX,i.minX-t.maxX,0),s=Math.max(t.minY-i.maxY,i.minY-t.maxY,0),o={x:0,y:0},a={x:0,y:0};return r===0&&s===0?{distance:0,pointA:n.center,pointB:e.center}:(o.x=Wn(n.center.x,i.minX,i.maxX),o.y=Wn(n.center.y,i.minY,i.maxY),a.x=Wn(e.center.x,t.minX,t.maxX),a.y=Wn(e.center.y,t.minY,t.maxY),{distance:Math.hypot(o.x-a.x,o.y-a.y),pointA:o,pointB:a})}function Fo(n,e){return Ng(n,e)}function _4(n,e){let t=so(n),i=so(e),r=Math.max(t.minX-i.maxX,i.minX-t.maxX,0),s=Math.max(t.minY-i.maxY,i.minY-t.maxY,0);return Math.hypot(r,s)}function Wn(n,e,t){return Math.max(e,Math.min(t,n))}function Ag(n,e){let t=Number.POSITIVE_INFINITY,i={x:0,y:0},r={x:0,y:0};for(let s of n)for(let o of e){let{distance:a,pointA:c,pointB:l}=Ng(s,o);a<t&&(t=a,i=c,r=l)}return{pointA:i,pointB:r,distance:t}}ir();ir();var gW="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var xW=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=gW[t[n]&63];return e};ir();var ad=(n,e)=>Math.abs(n.x-e.x)+Math.abs(n.y-e.y),bW=(n,e)=>{let t=e.x-n.x,i=e.y-n.y;return Math.abs(t)>Math.abs(i)?{dx:Math.sign(t),dy:0}:{dx:0,dy:Math.sign(i)}},kW=(n,e,t)=>Math.abs(n.x-e.x)*Math.abs(t.dx)+Math.abs(n.y-e.y)*Math.abs(t.dy),TW=(n,e=.1)=>`${Math.round(n.x/e)},${Math.round(n.y/e)}`,vW=(n,e)=>Math.abs(n-e)<1e-4,MW=(n,e,{viaDiameter:t=.5}={})=>{let i=[];for(let r=0;r<n.length-1;r++){let[s,o]=[n[r],n[r+1]],a=r-1>=0?n[r-1]:null,c=vW(s.y,o.y),l=vW(s.x,o.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${s.x}, ${s.y}), end: (${o.x}, ${o.y})`);let u={type:"rect",layers:[s.layer],center:{x:(s.x+o.x)/2,y:(s.y+o.y)/2},width:c?Math.abs(s.x-o.x):.1,height:l?Math.abs(s.y-o.y):.1,connectedTo:[e]};if(i.push(u),a&&a.layer===s.layer&&s.layer!==o.layer){let p={type:"rect",layers:[s.layer,o.layer],center:{x:s.x,y:s.y},connectedTo:[e],width:t,height:t};i.push(p)}}return i},CW=class{constructor(n){f(this,"obstacles");f(this,"GRID_STEP",.1);this.obstacles=n.map(e=>({...e,left:e.center.x-e.width/2,right:e.center.x+e.width/2,top:e.center.y+e.height/2,bottom:e.center.y-e.height/2}))}getObstacleAt(n,e,t){t??(t=this.GRID_STEP);for(let i of this.obstacles){let r=i.width/2+t,s=i.height/2+t;if(n>=i.center.x-r&&n<=i.center.x+r&&e>=i.center.y-s&&e<=i.center.y+s)return i}return null}isObstacleAt(n,e,t){return this.getObstacleAt(n,e,t)!==null}getDirectionDistancesToNearestObstacle(n,e){let{GRID_STEP:t}=this,i={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let r of this.obstacles)if(r.type==="rect"){let s=r.center.x-r.width/2-t,o=r.center.x+r.width/2+t,a=r.center.y+r.height/2+t,c=r.center.y-r.height/2-t;e>=c&&e<=a&&n>s&&(i.left=Math.min(i.left,n-o)),e>=c&&e<=a&&n<o&&(i.right=Math.min(i.right,s-n)),n>=s&&n<=o&&e<a&&(i.top=Math.min(i.top,c-e)),n>=s&&n<=o&&e>c&&(i.bottom=Math.min(i.bottom,e-a))}return i}getOrthoDirectionCollisionInfo(n,e,{margin:t=0}={}){let{x:i,y:r}=n,{dx:s,dy:o}=e,a=1/0,c=null;for(let l of this.obstacles){let u=l.left-t,p=l.right+t,d=l.top+t,_=l.bottom-t,g=null;s===1&&o===0?r>_&&r<d&&i<l.left&&(g=l.left-i):s===-1&&o===0?r>_&&r<d&&i>l.right&&(g=i-l.right):s===0&&o===1?i>u&&i<p&&r<l.bottom&&(g=l.bottom-r):s===0&&o===-1&&i>u&&i<p&&r>l.top&&(g=r-l.top),g!==null&&g<a&&(a=g,c=l)}return{dx:s,dy:o,wallDistance:a,obstacle:c}}getObstaclesOverlappingRegion(n){let e=[];for(let t of this.obstacles){let{left:i,right:r,top:s,bottom:o}=t;i<=n.maxX&&r>=n.minX&&s<=n.maxY&&o>=n.minY&&e.push(t)}return e}};function E3t(n){if(n.length<4)return n;let e=[{...n[0]}],t=n[0].layer;for(let i=1;i<n.length;i++){let r={start:n[i-1],end:n[i]},s=n[i].route_type==="via"||n[i-1].route_type==="via";if(n[i].layer!==t||s){e.push({...n[i]}),t=n[i].layer;continue}let o=!1,a=null,c=-1;for(let u=0;u<e.length-1;u++){let p={start:e[u],end:e[u+1]};if(p.start.layer===r.start.layer&&p.start.layer===r.start.layer){let d=M3t(p,r);if(d){o=!0,a={...d,layer:t},c=u;break}}}o&&a&&(e.splice(c+1),e.push(a));let l=e[e.length-1];(l.x!==n[i].x||l.y!==n[i].y)&&e.push(n[i])}return e}function M3t(n,e){if(n.start.x===n.end.x&&e.start.x===e.end.x||n.start.y===n.end.y&&e.start.y===e.end.y)return null;let t;if(n.start.x===n.end.x){let i=n.start.x,r=e.start.y;t={...n.start,x:i,y:r}}else{let i=e.start.x,r=n.start.y;t={...n.start,x:i,y:r}}return wW(t,n)&&wW(t,e)?t:null}function wW(n,e){return n.x>=Math.min(e.start.x,e.end.x)&&n.x<=Math.max(e.start.x,e.end.x)&&n.y>=Math.min(e.start.y,e.end.y)&&n.y<=Math.max(e.start.y,e.end.y)}function C3t(n){let e=[n[0]];for(let t=1;t<n.length-1;t++){let[i,r,s]=[n[t-1],n[t],n[t+1]];e.push(r),!(r.route_type!=="wire"||i.route_type!=="wire"||s.route_type!=="wire")&&i.layer===r.layer&&r.layer!==s.layer&&e.push({route_type:"via",from_layer:r.layer,to_layer:s.layer,x:r.x,y:r.y})}return e.push(n[n.length-1]),e}var kie=(0,IW.default)("autorouter:shortenPathWithShortcuts");function I3t(n,e){if(n.length<=2)return n;let t=[n[0]];for(let i=1;i<n.length;i++){let r={start:t[t.length-1],end:n[i]},s=-1,o=r.start.x===r.end.x,a=r.start.y===r.end.y;for(let c=i+1;c<n.length;c++){if(c<=s)continue;let l={start:n[c],end:n[c+1]};if(!l.end)continue;let u=l.start.x===l.end.x,p=l.start.y===l.end.y,d=o&&u,_=a&&p;if(_&&d||!(d||_))continue;let x=!1,v=Math.min(r.start.x,r.end.x),S=Math.max(r.start.x,r.end.x),P=Math.min(l.start.x,l.end.x),T=Math.max(l.start.x,l.end.x),k=Math.min(r.start.y,r.end.y),N=Math.max(r.start.y,r.end.y),E=Math.min(l.start.y,l.end.y),C=Math.max(l.start.y,l.end.y);if(_?x=v<=T&&S>=P:d&&(x=k<=C&&N>=E),!x)continue;let M=[],A=t[t.length-1],R=n[c+2];if(!R)continue;_&&P<S&&R.x===P&&M.push({x:P,y:r.start.y,layer:r.start.layer}),_&&T>v&&R.x===T&&M.push({x:T,y:r.start.y,layer:r.start.layer}),d&&E<N&&R.y===E&&M.push({x:r.start.x,y:E,layer:r.start.layer}),d&&C>k&&R.y===C&&M.push({x:r.start.x,y:C,layer:r.start.layer});let B=null;for(let j of M)if(!(e(A,j)||e(R,j))){B=j;break}if(B){t.push(B),i=c+1,s=c+1;break}}s===-1&&t.push(n[i])}return t[t.length-1]!==n[n.length-1]&&t.push(n[n.length-1]),t}var od=(0,EW.default)("autorouting-dataset:astar"),NW=class{constructor(n){f(this,"openSet",[]);f(this,"closedSet",new Set);f(this,"debug",!1);f(this,"debugSolutions");f(this,"debugMessage",null);f(this,"debugTraceCount",0);f(this,"input");f(this,"obstacles");f(this,"allObstacles");f(this,"startNode");f(this,"goalPoint");f(this,"GRID_STEP");f(this,"OBSTACLE_MARGIN");f(this,"MAX_ITERATIONS");f(this,"isRemovePathLoopsEnabled");f(this,"isShortenPathWithShortcutsEnabled");f(this,"GREEDY_MULTIPLIER",1.1);f(this,"iterations",-1);this.input=n.input,this.allObstacles=n.input.obstacles,this.startNode=n.startNode,this.goalPoint=n.goalPoint?{l:0,...n.goalPoint}:void 0,this.GRID_STEP=n.GRID_STEP??.1,this.OBSTACLE_MARGIN=n.OBSTACLE_MARGIN??.15,this.MAX_ITERATIONS=n.MAX_ITERATIONS??100,this.debug=n.debug??od.enabled,this.isRemovePathLoopsEnabled=n.isRemovePathLoopsEnabled??!1,this.isShortenPathWithShortcutsEnabled=n.isShortenPathWithShortcutsEnabled??!1,this.debug&&(od.enabled=!0),od.enabled&&(this.debugSolutions={},this.debugMessage="")}getNeighbors(n){return[]}isSameNode(n,e){return ad(n,e)<this.GRID_STEP}computeG(n,e){return n.g+ad(n,e)}computeH(n){return ad(n,this.goalPoint)}getNodeName(n){return TW(n,this.GRID_STEP)}solveOneStep(){this.iterations+=1;let{openSet:n,closedSet:e,GRID_STEP:t,goalPoint:i}=this;n.sort((a,c)=>a.f-c.f);let r=n.shift();if(this.computeH(r)<=t*2)return{solved:!0,current:r,newNeighbors:[]};this.closedSet.add(this.getNodeName(r));let o=[];for(let a of this.getNeighbors(r)){if(e.has(this.getNodeName(a)))continue;let c=this.computeG(r,a),l=this.openSet.find(u=>this.isSameNode(u,a));if(!l||c<l.g){let u=this.computeH(a),p=c+u*this.GREEDY_MULTIPLIER,d={...a,g:c,h:u,f:p,obstacleHit:a.obstacleHit??void 0,manDistFromParent:ad(r,a),nodesInPath:r.nodesInPath+1,parent:r,enterMarginCost:a.enterMarginCost,travelMarginCostFactor:a.travelMarginCostFactor};n.push(d),o.push(d)}}return od.enabled&&(n.sort((a,c)=>a.f-c.f),this.drawDebugSolution({current:r,newNeighbors:o})),{solved:!1,current:r,newNeighbors:o}}getStartNode(n){return{x:n.pointsToConnect[0].x,y:n.pointsToConnect[0].y,manDistFromParent:0,f:0,g:0,h:0,nodesInPath:0,parent:null}}layerToIndex(n){return 0}indexToLayer(n){return"top"}preprocessConnectionBeforeSolving(n){return n}solveConnection(n){if(n.pointsToConnect.length>2)throw new Error("GeneralizedAstarAutorouter doesn't currently support 2+ points in a connection");n=this.preprocessConnectionBeforeSolving(n);let{pointsToConnect:e}=n;for(this.iterations=0,this.closedSet=new Set,this.startNode=this.getStartNode(n),this.goalPoint={...e[e.length-1],l:this.layerToIndex(e[e.length-1].layer)},this.openSet=[this.startNode];this.iterations<this.MAX_ITERATIONS;){let{solved:t,current:i}=this.solveOneStep();if(t){let r=[],s=i;for(;s;){let o=s.l;r.unshift({x:s.x,y:s.y,layer:o!==void 0?this.indexToLayer(o):e[0].layer}),s=s.parent}return od.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations
159
+ )`,enabled:":not(:disabled)",checked:":is(:is(input[type=radio], input[type=checkbox])[checked], option:selected)",required:":is(input, select, textarea)[required]",optional:":is(input, select, textarea):not([required])",selected:"option:is([selected], select:not([multiple]):not(:has(> option[selected])) > :first-of-type)",checkbox:"[type=checkbox]",file:"[type=file]",password:"[type=password]",radio:"[type=radio]",reset:"[type=reset]",image:"[type=image]",submit:"[type=submit]",parent:":not(:empty)",header:":is(h1, h2, h3, h4, h5, h6)",button:":is(button, input[type=button])",input:":is(input, textarea, select, button)",text:"input:is(:not([type!='']), [type=text])"};var Cs=Vt(td(),1);var K5={};function J5(n,e){return n===Cs.default.falseFunc?Cs.default.falseFunc:t=>e.isTag(t)&&n(t)}function Q5(n,e){let t=e.getSiblings(n);if(t.length<=1)return[];let i=t.indexOf(n);return i<0||i===t.length-1?[]:t.slice(i+1).filter(e.isTag)}function Z5(n){return{xmlMode:!!n.xmlMode,lowerCaseAttributeNames:!!n.lowerCaseAttributeNames,lowerCaseTags:!!n.lowerCaseTags,quirksMode:!!n.quirksMode,cacheResults:!!n.cacheResults,pseudos:n.pseudos,adapter:n.adapter,equals:n.equals}}var q5=(n,e,t,i,r)=>{let s=r(e,Z5(t),i);return s===Cs.default.trueFunc?n:s===Cs.default.falseFunc?Cs.default.falseFunc:o=>s(o)&&n(o)},uw={is:q5,matches:q5,where:q5,not(n,e,t,i,r){let s=r(e,Z5(t),i);return s===Cs.default.falseFunc?n:s===Cs.default.trueFunc?Cs.default.falseFunc:o=>!s(o)&&n(o)},has(n,e,t,i,r){let{adapter:s}=t,o=Z5(t);o.relativeSelector=!0;let a=e.some(u=>u.some(Pg))?[K5]:void 0,c=r(e,o,a);if(c===Cs.default.falseFunc)return Cs.default.falseFunc;let l=J5(c,s);if(a&&c!==Cs.default.trueFunc){let{shouldTestNextSiblings:u=!1}=c;return p=>{if(!n(p))return!1;a[0]=p;let d=s.getChildren(p),_=u?[...d,...Q5(p,s)]:d;return s.existsOne(l,_)}}return u=>n(u)&&s.existsOne(l,s.getChildren(u))}};function XG(n,e,t,i,r){var s;let{name:o,data:a}=e;if(Array.isArray(a)){if(!(o in uw))throw new Error(`Unknown pseudo-class :${o}(${a})`);return uw[o](n,a,t,i,r)}let c=(s=t.pseudos)===null||s===void 0?void 0:s[o],l=typeof c=="string"?c:H5[o];if(typeof l=="string"){if(a!=null)throw new Error(`Pseudo ${o} doesn't have any arguments`);let u=Sg(l);return uw.is(n,u,t,i,r)}if(typeof c=="function")return W5(c,o,a,1),u=>c(u,a)&&n(u);if(o in Tg)return Tg[o](n,a,t,i);if(o in lw){let u=lw[o];return W5(u,o,a,2),p=>u(p,t,a)&&n(p)}throw new Error(`Unknown pseudo-class :${o}`)}function t4(n,e){let t=e.getParent(n);return t&&e.isTag(t)?t:null}function UG(n,e,t,i,r){let{adapter:s,equals:o}=t;switch(e.type){case fe.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case fe.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case fe.Attribute:{if(e.namespace!=null)throw new Error("Namespaced attributes are not yet supported by css-select");return(!t.xmlMode||t.lowerCaseAttributeNames)&&(e.name=e.name.toLowerCase()),DG[e.action](n,e,t)}case fe.Pseudo:return XG(n,e,t,i,r);case fe.Tag:{if(e.namespace!=null)throw new Error("Namespaced tag names are not yet supported by css-select");let{name:a}=e;return(!t.xmlMode||t.lowerCaseTags)&&(a=a.toLowerCase()),function(l){return s.getName(l)===a&&n(l)}}case fe.Descendant:{if(t.cacheResults===!1||typeof WeakSet>"u")return function(l){let u=l;for(;u=t4(u,s);)if(n(u))return!0;return!1};let a=new WeakSet;return function(l){let u=l;for(;u=t4(u,s);)if(!a.has(u)){if(s.isTag(u)&&n(u))return!0;a.add(u)}return!1}}case"_flexibleDescendant":return function(c){let l=c;do if(n(l))return!0;while(l=t4(l,s));return!1};case fe.Parent:return function(c){return s.getChildren(c).some(l=>s.isTag(l)&&n(l))};case fe.Child:return function(c){let l=s.getParent(c);return l!=null&&s.isTag(l)&&n(l)};case fe.Sibling:return function(c){let l=s.getSiblings(c);for(let u=0;u<l.length;u++){let p=l[u];if(o(c,p))break;if(s.isTag(p)&&n(p))return!0}return!1};case fe.Adjacent:return s.prevElementSibling?function(c){let l=s.prevElementSibling(c);return l!=null&&n(l)}:function(c){let l=s.getSiblings(c),u;for(let p=0;p<l.length;p++){let d=l[p];if(o(c,d))break;s.isTag(d)&&(u=d)}return!!u&&n(u)};case fe.Universal:{if(e.namespace!=null&&e.namespace!=="*")throw new Error("Namespaced universal selectors are not yet supported by css-select");return n}}}function VG(n,e,t){let i=pw(n,e,t);return J5(i,e.adapter)}function pw(n,e,t){let i=typeof n=="string"?Sg(n):n;return hw(i,e,t)}function GG(n){return n.type===fe.Pseudo&&(n.name==="scope"||Array.isArray(n.data)&&n.data.some(e=>e.some(GG)))}var d3t={type:fe.Descendant},f3t={type:"_flexibleDescendant"},m3t={type:fe.Pseudo,name:"scope",data:null};function _3t(n,{adapter:e},t){let i=!!t?.every(r=>{let s=e.isTag(r)&&e.getParent(r);return r===K5||s&&e.isTag(s)});for(let r of n){if(!(r.length>0&&Pg(r[0])&&r[0].type!==fe.Descendant))if(i&&!r.some(GG))r.unshift(d3t);else continue;r.unshift(m3t)}}function hw(n,e,t){var i;n.forEach(U5),t=(i=e.context)!==null&&i!==void 0?i:t;let r=Array.isArray(t),s=t&&(Array.isArray(t)?t:[t]);if(e.relativeSelector!==!1)_3t(n,e,s);else if(n.some(c=>c.length>0&&Pg(c[0])))throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");let o=!1,a=n.map(c=>{if(c.length>=2){let[l,u]=c;l.type!==fe.Pseudo||l.name!=="scope"||(r&&u.type===fe.Descendant?c[1]=f3t:(u.type===fe.Adjacent||u.type===fe.Sibling)&&(o=!0))}return y3t(c,e,s)}).reduce(g3t,Ra.default.falseFunc);return a.shouldTestNextSiblings=o,a}function y3t(n,e,t){var i;return n.reduce((r,s)=>r===Ra.default.falseFunc?Ra.default.falseFunc:UG(r,s,e,t,hw),(i=e.rootFunc)!==null&&i!==void 0?i:Ra.default.trueFunc)}function g3t(n,e){return e===Ra.default.falseFunc||n===Ra.default.trueFunc?n:n===Ra.default.falseFunc||e===Ra.default.trueFunc?e:function(i){return n(i)||e(i)}}var WG=(n,e)=>n===e,x3t={adapter:aw,equals:WG};function HG(n){var e,t,i,r;let s=n??x3t;return(e=s.adapter)!==null&&e!==void 0||(s.adapter=aw),(t=s.equals)!==null&&t!==void 0||(s.equals=(r=(i=s.adapter)===null||i===void 0?void 0:i.equals)!==null&&r!==void 0?r:WG),s}function n4(n){return function(t,i,r){let s=HG(i);return n(t,s,r)}}var wee=n4(VG),See=n4(pw),Pee=n4(hw);function qG(n){return function(t,i,r){let s=HG(r);typeof t!="function"&&(t=pw(t,s,i));let o=b3t(i,s.adapter,t.shouldTestNextSiblings);return n(t,o,s)}}function b3t(n,e,t=!1){return t&&(n=v3t(n,e)),Array.isArray(n)?e.removeSubsets(n):e.getChildren(n)}function v3t(n,e){let t=Array.isArray(n)?n.slice(0):[n],i=t.length;for(let r=0;r<i;r++){let s=Q5(t[r],e);t.push(...s)}return t}var i4=qG((n,e,t)=>n===e4.default.falseFunc||!e||e.length===0?[]:t.adapter.findAll(n,e)),dw=qG((n,e,t)=>n===e4.default.falseFunc||!e||e.length===0?null:t.adapter.findOne(n,e));Q();wt();Q();var EW=Vt(In(),1);wt();var IW=Vt(In(),1),AW=Vt(In(),1);wt();si();u4();var p4=(n,e={})=>{let t=n._internal_store;if(!t){t={counts:{}},n._internal_store=t;for(let r of n){let s=r.type,o=r[`${s}_id`];if(!o)continue;let a=Number.parseInt(o.split("_").pop());Number.isNaN(a)||(t.counts[s]=Math.max(t.counts[s]??0,a))}}return new Proxy({},{get:(r,s)=>s==="toArray"?()=>n:{get:o=>n.find(a=>a.type===s&&a[`${s}_id`]===o),getUsing:o=>{let a=Object.keys(o);if(a.length!==1)throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");let c=a[0],l=c.replace("_id",""),u=n.find(p=>p.type===l&&p[c]===o[c]);return u?n.find(p=>p.type===s&&p[`${s}_id`]===u[`${s}_id`]):null},getWhere:o=>{let a=Object.keys(o);return n.find(c=>c.type===s&&a.every(l=>c[l]===o[l]))},list:o=>{let a=o?Object.keys(o):[];return n.filter(c=>c.type===s&&a.every(l=>c[l]===o[l]))},insert:o=>{var l;(l=t.counts)[s]??(l[s]=-1),t.counts[s]++;let a=t.counts[s],c={type:s,[`${s}_id`]:`${s}_${a}`,...o};return e.validateInserts&&(Wh[s]??Gh).parse(c),n.push(c),c},delete:o=>{let a=n.find(c=>c[`${s}_id`]===o);a&&n.splice(n.indexOf(a),1)},update:(o,a)=>{let c=n.find(l=>l[`${s}_id`]===o);if(c)return Object.assign(c,a),c},select:o=>{if(s==="source_component")return n.find(a=>a.type==="source_component"&&a.name===o.replace(/\./g,""));if(s==="pcb_port"||s==="source_port"||s==="schematic_port"){let[a,c]=o.replace(/\./g,"").split(/[\s\>]+/),l=n.find(p=>p.type==="source_component"&&p.name===a);if(!l)return null;let u=n.find(p=>p.type==="source_port"&&p.source_component_id===l.source_component_id&&(p.name===c||(p.port_hints??[]).includes(c)));if(!u)return null;if(s==="source_port")return u;if(s==="pcb_port")return n.find(p=>p.type==="pcb_port"&&p.source_port_id===u.source_port_id);if(s==="schematic_port")return n.find(p=>p.type==="schematic_port"&&p.source_port_id===u.source_port_id)}}}})};p4.unparsed=p4;var lW=p4;var Eie=Vt(pW(),1);ir();function so(n){let e=n.width/2,t=n.height/2;return{minX:n.center.x-e,maxX:n.center.x+e,minY:n.center.y-t,maxY:n.center.y+t}}function Ng(n,e){let t=so(n),i=so(e),r=Math.max(t.minX-i.maxX,i.minX-t.maxX,0),s=Math.max(t.minY-i.maxY,i.minY-t.maxY,0),o={x:0,y:0},a={x:0,y:0};return r===0&&s===0?{distance:0,pointA:n.center,pointB:e.center}:(o.x=Wn(n.center.x,i.minX,i.maxX),o.y=Wn(n.center.y,i.minY,i.maxY),a.x=Wn(e.center.x,t.minX,t.maxX),a.y=Wn(e.center.y,t.minY,t.maxY),{distance:Math.hypot(o.x-a.x,o.y-a.y),pointA:o,pointB:a})}function Fo(n,e){return Ng(n,e)}function _4(n,e){let t=so(n),i=so(e),r=Math.max(t.minX-i.maxX,i.minX-t.maxX,0),s=Math.max(t.minY-i.maxY,i.minY-t.maxY,0);return Math.hypot(r,s)}function Wn(n,e,t){return Math.max(e,Math.min(t,n))}function Ag(n,e){let t=Number.POSITIVE_INFINITY,i={x:0,y:0},r={x:0,y:0};for(let s of n)for(let o of e){let{distance:a,pointA:c,pointB:l}=Ng(s,o);a<t&&(t=a,i=c,r=l)}return{pointA:i,pointB:r,distance:t}}ir();ir();var gW="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var xW=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=gW[t[n]&63];return e};ir();var ad=(n,e)=>Math.abs(n.x-e.x)+Math.abs(n.y-e.y),bW=(n,e)=>{let t=e.x-n.x,i=e.y-n.y;return Math.abs(t)>Math.abs(i)?{dx:Math.sign(t),dy:0}:{dx:0,dy:Math.sign(i)}},kW=(n,e,t)=>Math.abs(n.x-e.x)*Math.abs(t.dx)+Math.abs(n.y-e.y)*Math.abs(t.dy),TW=(n,e=.1)=>`${Math.round(n.x/e)},${Math.round(n.y/e)}`,vW=(n,e)=>Math.abs(n-e)<1e-4,MW=(n,e,{viaDiameter:t=.5}={})=>{let i=[];for(let r=0;r<n.length-1;r++){let[s,o]=[n[r],n[r+1]],a=r-1>=0?n[r-1]:null,c=vW(s.y,o.y),l=vW(s.x,o.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${s.x}, ${s.y}), end: (${o.x}, ${o.y})`);let u={type:"rect",layers:[s.layer],center:{x:(s.x+o.x)/2,y:(s.y+o.y)/2},width:c?Math.abs(s.x-o.x):.1,height:l?Math.abs(s.y-o.y):.1,connectedTo:[e]};if(i.push(u),a&&a.layer===s.layer&&s.layer!==o.layer){let p={type:"rect",layers:[s.layer,o.layer],center:{x:s.x,y:s.y},connectedTo:[e],width:t,height:t};i.push(p)}}return i},CW=class{constructor(n){f(this,"obstacles");f(this,"GRID_STEP",.1);this.obstacles=n.map(e=>({...e,left:e.center.x-e.width/2,right:e.center.x+e.width/2,top:e.center.y+e.height/2,bottom:e.center.y-e.height/2}))}getObstacleAt(n,e,t){t??(t=this.GRID_STEP);for(let i of this.obstacles){let r=i.width/2+t,s=i.height/2+t;if(n>=i.center.x-r&&n<=i.center.x+r&&e>=i.center.y-s&&e<=i.center.y+s)return i}return null}isObstacleAt(n,e,t){return this.getObstacleAt(n,e,t)!==null}getDirectionDistancesToNearestObstacle(n,e){let{GRID_STEP:t}=this,i={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let r of this.obstacles)if(r.type==="rect"){let s=r.center.x-r.width/2-t,o=r.center.x+r.width/2+t,a=r.center.y+r.height/2+t,c=r.center.y-r.height/2-t;e>=c&&e<=a&&n>s&&(i.left=Math.min(i.left,n-o)),e>=c&&e<=a&&n<o&&(i.right=Math.min(i.right,s-n)),n>=s&&n<=o&&e<a&&(i.top=Math.min(i.top,c-e)),n>=s&&n<=o&&e>c&&(i.bottom=Math.min(i.bottom,e-a))}return i}getOrthoDirectionCollisionInfo(n,e,{margin:t=0}={}){let{x:i,y:r}=n,{dx:s,dy:o}=e,a=1/0,c=null;for(let l of this.obstacles){let u=l.left-t,p=l.right+t,d=l.top+t,_=l.bottom-t,g=null;s===1&&o===0?r>_&&r<d&&i<l.left&&(g=l.left-i):s===-1&&o===0?r>_&&r<d&&i>l.right&&(g=i-l.right):s===0&&o===1?i>u&&i<p&&r<l.bottom&&(g=l.bottom-r):s===0&&o===-1&&i>u&&i<p&&r>l.top&&(g=r-l.top),g!==null&&g<a&&(a=g,c=l)}return{dx:s,dy:o,wallDistance:a,obstacle:c}}getObstaclesOverlappingRegion(n){let e=[];for(let t of this.obstacles){let{left:i,right:r,top:s,bottom:o}=t;i<=n.maxX&&r>=n.minX&&s<=n.maxY&&o>=n.minY&&e.push(t)}return e}};function E3t(n){if(n.length<4)return n;let e=[{...n[0]}],t=n[0].layer;for(let i=1;i<n.length;i++){let r={start:n[i-1],end:n[i]},s=n[i].route_type==="via"||n[i-1].route_type==="via";if(n[i].layer!==t||s){e.push({...n[i]}),t=n[i].layer;continue}let o=!1,a=null,c=-1;for(let u=0;u<e.length-1;u++){let p={start:e[u],end:e[u+1]};if(p.start.layer===r.start.layer&&p.start.layer===r.start.layer){let d=M3t(p,r);if(d){o=!0,a={...d,layer:t},c=u;break}}}o&&a&&(e.splice(c+1),e.push(a));let l=e[e.length-1];(l.x!==n[i].x||l.y!==n[i].y)&&e.push(n[i])}return e}function M3t(n,e){if(n.start.x===n.end.x&&e.start.x===e.end.x||n.start.y===n.end.y&&e.start.y===e.end.y)return null;let t;if(n.start.x===n.end.x){let i=n.start.x,r=e.start.y;t={...n.start,x:i,y:r}}else{let i=e.start.x,r=n.start.y;t={...n.start,x:i,y:r}}return wW(t,n)&&wW(t,e)?t:null}function wW(n,e){return n.x>=Math.min(e.start.x,e.end.x)&&n.x<=Math.max(e.start.x,e.end.x)&&n.y>=Math.min(e.start.y,e.end.y)&&n.y<=Math.max(e.start.y,e.end.y)}function C3t(n){let e=[n[0]];for(let t=1;t<n.length-1;t++){let[i,r,s]=[n[t-1],n[t],n[t+1]];e.push(r),!(r.route_type!=="wire"||i.route_type!=="wire"||s.route_type!=="wire")&&i.layer===r.layer&&r.layer!==s.layer&&e.push({route_type:"via",from_layer:r.layer,to_layer:s.layer,x:r.x,y:r.y})}return e.push(n[n.length-1]),e}var kie=(0,IW.default)("autorouter:shortenPathWithShortcuts");function I3t(n,e){if(n.length<=2)return n;let t=[n[0]];for(let i=1;i<n.length;i++){let r={start:t[t.length-1],end:n[i]},s=-1,o=r.start.x===r.end.x,a=r.start.y===r.end.y;for(let c=i+1;c<n.length;c++){if(c<=s)continue;let l={start:n[c],end:n[c+1]};if(!l.end)continue;let u=l.start.x===l.end.x,p=l.start.y===l.end.y,d=o&&u,_=a&&p;if(_&&d||!(d||_))continue;let x=!1,v=Math.min(r.start.x,r.end.x),S=Math.max(r.start.x,r.end.x),P=Math.min(l.start.x,l.end.x),T=Math.max(l.start.x,l.end.x),k=Math.min(r.start.y,r.end.y),N=Math.max(r.start.y,r.end.y),E=Math.min(l.start.y,l.end.y),C=Math.max(l.start.y,l.end.y);if(_?x=v<=T&&S>=P:d&&(x=k<=C&&N>=E),!x)continue;let M=[],A=t[t.length-1],R=n[c+2];if(!R)continue;_&&P<S&&R.x===P&&M.push({x:P,y:r.start.y,layer:r.start.layer}),_&&T>v&&R.x===T&&M.push({x:T,y:r.start.y,layer:r.start.layer}),d&&E<N&&R.y===E&&M.push({x:r.start.x,y:E,layer:r.start.layer}),d&&C>k&&R.y===C&&M.push({x:r.start.x,y:C,layer:r.start.layer});let B=null;for(let j of M)if(!(e(A,j)||e(R,j))){B=j;break}if(B){t.push(B),i=c+1,s=c+1;break}}s===-1&&t.push(n[i])}return t[t.length-1]!==n[n.length-1]&&t.push(n[n.length-1]),t}var od=(0,EW.default)("autorouting-dataset:astar"),NW=class{constructor(n){f(this,"openSet",[]);f(this,"closedSet",new Set);f(this,"debug",!1);f(this,"debugSolutions");f(this,"debugMessage",null);f(this,"debugTraceCount",0);f(this,"input");f(this,"obstacles");f(this,"allObstacles");f(this,"startNode");f(this,"goalPoint");f(this,"GRID_STEP");f(this,"OBSTACLE_MARGIN");f(this,"MAX_ITERATIONS");f(this,"isRemovePathLoopsEnabled");f(this,"isShortenPathWithShortcutsEnabled");f(this,"GREEDY_MULTIPLIER",1.1);f(this,"iterations",-1);this.input=n.input,this.allObstacles=n.input.obstacles,this.startNode=n.startNode,this.goalPoint=n.goalPoint?{l:0,...n.goalPoint}:void 0,this.GRID_STEP=n.GRID_STEP??.1,this.OBSTACLE_MARGIN=n.OBSTACLE_MARGIN??.15,this.MAX_ITERATIONS=n.MAX_ITERATIONS??100,this.debug=n.debug??od.enabled,this.isRemovePathLoopsEnabled=n.isRemovePathLoopsEnabled??!1,this.isShortenPathWithShortcutsEnabled=n.isShortenPathWithShortcutsEnabled??!1,this.debug&&(od.enabled=!0),od.enabled&&(this.debugSolutions={},this.debugMessage="")}getNeighbors(n){return[]}isSameNode(n,e){return ad(n,e)<this.GRID_STEP}computeG(n,e){return n.g+ad(n,e)}computeH(n){return ad(n,this.goalPoint)}getNodeName(n){return TW(n,this.GRID_STEP)}solveOneStep(){this.iterations+=1;let{openSet:n,closedSet:e,GRID_STEP:t,goalPoint:i}=this;n.sort((a,c)=>a.f-c.f);let r=n.shift();if(this.computeH(r)<=t*2)return{solved:!0,current:r,newNeighbors:[]};this.closedSet.add(this.getNodeName(r));let o=[];for(let a of this.getNeighbors(r)){if(e.has(this.getNodeName(a)))continue;let c=this.computeG(r,a),l=this.openSet.find(u=>this.isSameNode(u,a));if(!l||c<l.g){let u=this.computeH(a),p=c+u*this.GREEDY_MULTIPLIER,d={...a,g:c,h:u,f:p,obstacleHit:a.obstacleHit??void 0,manDistFromParent:ad(r,a),nodesInPath:r.nodesInPath+1,parent:r,enterMarginCost:a.enterMarginCost,travelMarginCostFactor:a.travelMarginCostFactor};n.push(d),o.push(d)}}return od.enabled&&(n.sort((a,c)=>a.f-c.f),this.drawDebugSolution({current:r,newNeighbors:o})),{solved:!1,current:r,newNeighbors:o}}getStartNode(n){return{x:n.pointsToConnect[0].x,y:n.pointsToConnect[0].y,manDistFromParent:0,f:0,g:0,h:0,nodesInPath:0,parent:null}}layerToIndex(n){return 0}indexToLayer(n){return"top"}preprocessConnectionBeforeSolving(n){return n}solveConnection(n){if(n.pointsToConnect.length>2)throw new Error("GeneralizedAstarAutorouter doesn't currently support 2+ points in a connection");n=this.preprocessConnectionBeforeSolving(n);let{pointsToConnect:e}=n;for(this.iterations=0,this.closedSet=new Set,this.startNode=this.getStartNode(n),this.goalPoint={...e[e.length-1],l:this.layerToIndex(e[e.length-1].layer)},this.openSet=[this.startNode];this.iterations<this.MAX_ITERATIONS;){let{solved:t,current:i}=this.solveOneStep();if(t){let r=[],s=i;for(;s;){let o=s.l;r.unshift({x:s.x,y:s.y,layer:o!==void 0?this.indexToLayer(o):e[0].layer}),s=s.parent}return od.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations
160
160
  `),this.isRemovePathLoopsEnabled&&(r=E3t(r)),this.isShortenPathWithShortcutsEnabled&&(r=I3t(r,(o,a)=>{if(o.x===a.x&&o.y===a.y)return!1;let c=this.obstacles.getOrthoDirectionCollisionInfo({x:o.x,y:o.y,l:this.layerToIndex(o.layer)??0},{dx:Math.sign(a.x-o.x),dy:Math.sign(a.y-o.y),dl:0},{margin:.05}),l=Math.sqrt((o.x-a.x)**2+(o.y-a.y)**2);return c.wallDistance<l})),{solved:!0,route:r,connectionName:n.name}}if(this.openSet.length===0)break}return od.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations (failed)
161
161
  `),{solved:!1,connectionName:n.name}}createObstacleList({dominantLayer:n,connection:e,obstaclesFromTraces:t}){return new CW(this.allObstacles.filter(i=>!i.connectedTo.includes(e.name)).filter(i=>i.layers.includes(n)).concat(t??[]))}postprocessConnectionSolveResult(n,e){return e}solve(){let n=[],e=[];this.debugTraceCount=0;for(let t of this.input.connections){let i=t.pointsToConnect[0].layer??"top";this.debugTraceCount+=1,this.obstacles=this.createObstacleList({dominantLayer:i,connection:t,obstaclesFromTraces:e});let r=this.solveConnection(t);r=this.postprocessConnectionSolveResult(t,r),n.push(r),od.enabled&&this.drawDebugTraceObstacles(e),r.solved&&e.push(...MW(r.route.map(s=>({x:s.x,y:s.y,layer:s.layer??i})),t.name))}return n}solveAndMapToTraces(){return this.solve().flatMap(e=>e.solved?[{type:"pcb_trace",pcb_trace_id:`pcb_trace_for_${e.connectionName}`,route:C3t(e.route.map(t=>({route_type:"wire",x:t.x,y:t.y,width:this.input.minTraceWidth,layer:t.layer})))}]:[])}getDebugGroup(){let n=`t${this.debugTraceCount}_iter[${this.iterations-1}]`;return this.iterations<30||this.iterations<100&&this.iterations%10===0||this.iterations<1e3&&this.iterations%100===0||!this.debugSolutions?n:null}drawDebugTraceObstacles(n){let{debugTraceCount:e,debugSolutions:t}=this;for(let i in t)i.startsWith(`t${e}_`)&&t[i].push(...n.map((r,s)=>({type:"pcb_smtpad",pcb_component_id:"",layer:r.layers[0],width:r.width,shape:"rect",x:r.center.x,y:r.center.y,pcb_smtpad_id:`trace_obstacle_${s}`,height:r.height})))}drawDebugSolution({current:n,newNeighbors:e}){let t=this.getDebugGroup();if(!t)return;let{openSet:i,debugTraceCount:r,debugSolutions:s}=this;s[t]??(s[t]=[]);let o=s[t];o.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${n.x}_${n.y}`,font:"tscircuit2024",font_size:.25,text:"X"+(n.l!==void 0?n.l:""),pcb_component_id:"",layer:"top",anchor_position:{x:n.x,y:n.y},anchor_alignment:"center"});for(let a=0;a<i.length;a++){let c=i[a];o.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${c.x}_${c.y}`,layer:"top",route:[[0,.05],[.05,0],[0,-.05],[-.05,0],[0,.05]].map(([l,u])=>({x:c.x+l,y:c.y+u})),stroke_width:.01}),o.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${c.x}_${c.y}`,font:"tscircuit2024",font_size:.03,text:a.toString(),pcb_component_id:"",layer:"top",anchor_position:{x:c.x,y:c.y},anchor_alignment:"center"})}if(n.parent){let a=[],c=n;for(;c;)a.unshift(c),c=c.parent;o.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${n.x}_${n.y}`,layer:"top",route:a,stroke_width:.01})}}},N3t=(0,AW.default)("autorouting-dataset:infinite-grid-ijump-astar:get-distance-to-overcome-obstacle");function y4({node:n,travelDir:e,wallDir:t,obstacle:i,obstacles:r,obstaclesInRow:s=0,OBSTACLE_MARGIN:o=.15,SHOULD_DETECT_CONJOINED_OBSTACLES:a=!1,MAX_CONJOINED_OBSTACLES:c=20}){let l;if(e.dx===0?e.dy>0?l=i.center.y+i.height/2-n.y:l=n.y-(i.center.y-i.height/2):e.dx>0?l=i.center.x+i.width/2-n.x:l=n.x-(i.center.x-i.width/2),l+=o,a&&s<c){let u=r.getObstacleAt(n.x+e.dx*l+t.dx*(t.wallDistance+.001),n.y+e.dy*l+t.dy*(t.wallDistance+.001));if(u===i)return l;if(u&&u.type==="rect"){let p=e.dy===0,d=p?i.height:i.width;if((p?u.height:u.width)>d)return N3t("next obstacle on path is bigger, not trying to overcome it"),l;let g=y4({node:{x:n.x+e.dx*l,y:n.y+e.dy*l},travelDir:e,wallDir:t,obstacle:u,obstacles:r,obstaclesInRow:s+1,SHOULD_DETECT_CONJOINED_OBSTACLES:a,MAX_CONJOINED_OBSTACLES:c,OBSTACLE_MARGIN:o});l+=g}}return l}var A3t=class extends NW{constructor(){super(...arguments);f(this,"MAX_ITERATIONS",200)}getNeighbors(e){let t=this.obstacles,i=this.goalPoint,r;e.parent?r=bW(e.parent,e):r=bW(e,i);let s=[{dx:0,dy:1},{dx:1,dy:0},{dx:0,dy:-1},{dx:-1,dy:0}].filter(a=>a.dx===r.dx*-1&&a.dy===r.dy*-1?!1:!(a.dx===r.dx&&a.dy===r.dy&&e.parent?.obstacleHit)).map(a=>t.getOrthoDirectionCollisionInfo(e,a,{margin:this.OBSTACLE_MARGIN})).filter(a=>a.wallDistance>=this.OBSTACLE_MARGIN),o=[];for(let a of s){let c=null;e?.obstacleHit&&(c=y4({node:e,travelDir:a,wallDir:{...r,wallDistance:this.OBSTACLE_MARGIN},obstacle:e.obstacleHit,obstacles:t,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let l=kW(e,i,a),u=(a.dx===0||Math.sign(i.x-e.x)===a.dx)&&(a.dy===0||Math.sign(i.y-e.y)===a.dy);l<a.wallDistance&&l>0&&u?o.push({...a,travelDistance:l}):c!==null&&c<a.wallDistance?o.push({...a,travelDistance:c}):a.wallDistance!==1/0&&o.push({...a,travelDistance:a.wallDistance-this.OBSTACLE_MARGIN})}return o.filter(a=>!t.isObstacleAt(e.x+a.dx*a.travelDistance,e.y+a.dy*a.travelDistance)).map(a=>({x:e.x+a.dx*a.travelDistance,y:e.y+a.dy*a.travelDistance,obstacleHit:a.obstacle}))}};function R3t(n,e=4){let{center:t,width:i,height:r,rotation:s}=n,o=[],a=s*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(s%360+360)%360;if(r<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/e;for(let _=0;_<e;_++){let g=(_-e/2+.5)*d,x=-g*c,v=-g*l,S=d*1.1,P=Math.abs(r*c)+Math.abs(d*l);o.push({center:{x:t.x+x,y:t.y+v},width:S,height:P})}}else{let d=r/e;for(let _=0;_<e;_++){let g=(_-e/2+.5)*d,x=-g*l,v=g*c,S=Math.abs(i*c)+Math.abs(d*l),P=d*1.1;o.push({center:{x:t.x+x,y:t.y+v},width:S,height:P})}}return o}var xw=["top","inner1","inner2","bottom"],RW=(n,e)=>{let t=r=>e?r.concat(r.map(s=>e?.getNetConnectedToId(s)).filter(Boolean)):r,i=[];for(let r of n)if(r.type==="pcb_smtpad"){if(r.shape==="circle")i.push({type:"oval",layers:[r.layer],center:{x:r.x,y:r.y},width:r.radius*2,height:r.radius*2,connectedTo:t([r.pcb_smtpad_id])});else if(r.shape==="rect")i.push({type:"rect",layers:[r.layer],center:{x:r.x,y:r.y},width:r.width,height:r.height,connectedTo:t([r.pcb_smtpad_id])});else if(r.shape==="rotated_rect"){let s={center:{x:r.x,y:r.y},width:r.width,height:r.height,rotation:r.ccw_rotation},o=R3t(s);for(let a of o)i.push({type:"rect",layers:[r.layer],center:a.center,width:a.width,height:a.height,connectedTo:t([r.pcb_smtpad_id])})}}else if(r.type==="pcb_keepout")r.shape==="circle"?i.push({type:"oval",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.radius*2,height:r.radius*2,connectedTo:[]}):r.shape==="rect"&&i.push({type:"rect",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.type==="pcb_hole")r.hole_shape==="oval"?i.push({type:"oval",center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="square"?i.push({type:"rect",layers:xw,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]}):(r.hole_shape==="round"||r.hole_shape==="circle")&&i.push({type:"rect",layers:xw,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]});else if(r.type==="pcb_plated_hole")r.shape==="circle"?i.push({type:"oval",layers:xw,center:{x:r.x,y:r.y},width:r.outer_diameter,height:r.outer_diameter,connectedTo:t([r.pcb_plated_hole_id])}):(r.shape==="oval"||r.shape==="pill")&&i.push({type:"oval",layers:xw,center:{x:r.x,y:r.y},width:r.outer_width,height:r.outer_height,connectedTo:t([r.pcb_plated_hole_id])});else if(r.type==="pcb_trace"){let s=MW(r.route.map(o=>({x:o.x,y:o.y,layer:"layer"in o?o.layer:o.from_layer})),r.source_trace_id);i.push(...s)}else r.type==="pcb_via"&&i.push({type:"rect",layers:r.layers,center:{x:r.x,y:r.y},connectedTo:[],width:r.outer_diameter,height:r.outer_diameter});return i};function SW(n){let{pcbConnMap:e,goalElementId:t}=n;if(!t.startsWith("pcb_port_"))throw new Error(`Currently alternative goal boxes must have a goal id with prefix "pcb_port_" (got ${t})`);let i=e.getAllTracesConnectedToPort(t);return RW(i).map(r=>({...r,connectedTo:[t]}))}var OW=n=>{let{connection:e,pcbConnMap:t}=n;if(e.pointsToConnect.length!==2)throw new Error(`Connection must have exactly 2 points for alternative goal boxes (got ${e.pointsToConnect.length})`);let[i,r]=e.pointsToConnect;if(!i.pcb_port_id||!r.pcb_port_id)throw new Error(`Connection points must have pcb_port_id for alternative goal box calculation (got ${i.pcb_port_id} and ${r.pcb_port_id})`);let s=SW({goalElementId:i.pcb_port_id,pcbConnMap:t}).concat([{center:i,width:.01,height:.01,connectedTo:[i.pcb_port_id],layers:[i.layer],type:"rect"}]),o=SW({goalElementId:r.pcb_port_id,pcbConnMap:t}).concat([{center:r,width:.01,height:.01,connectedTo:[r.pcb_port_id],layers:[r.layer],type:"rect"}]);if(s.length<=1&&o.length<=1)return{...e,startPoint:i,endPoint:r,goalBoxes:[]};let a=Ag(s,o),c,l,u;return s.length>=o.length?(c={...r,...a.pointB},l={...i,...a.pointA},u=s):(c={...i,...a.pointA},l={...r,...a.pointB},u=o),{startPoint:c,endPoint:l,goalBoxes:u,name:e.name,pointsToConnect:[c,l]}},O3t=(n,e={})=>{let t={minTraceWidth:.1};t.layerCount=e.layerCount??1,t.obstacles=RW(n,e.connMap),t.connections=[];for(let r of n)if(r.type==="source_trace"){let s={name:r.source_trace_id,pointsToConnect:r.connected_source_port_ids.map(o=>{let a=lW(n).pcb_port.getWhere({source_port_id:o});if(!a)throw new Error(`Could not find pcb_port for source_port_id "${o}"`);return{x:a.x,y:a.y,layer:a.layers?.[0]??"top",pcb_port_id:a.pcb_port_id}})};if(e.optimizeWithGoalBoxes){let o=new gw(n);s=OW({connection:s,pcbConnMap:o})}t.connections.push(s),L3t(t.obstacles,s.pointsToConnect,s.name)}let i={minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0};for(let r of t.obstacles)i.minX=Math.min(i.minX,r.center.x-r.width/2),i.maxX=Math.max(i.maxX,r.center.x+r.width/2),i.minY=Math.min(i.minY,r.center.y-r.height/2),i.maxY=Math.max(i.maxY,r.center.y+r.height/2);for(let r of t.connections)for(let s of r.pointsToConnect)i.minX=Math.min(i.minX,s.x),i.maxX=Math.max(i.maxX,s.x),i.minY=Math.min(i.minY,s.y),i.maxY=Math.max(i.maxY,s.y);return t.bounds=i,t},L3t=(n,e,t)=>{for(let i of e)for(let r of n)F3t(i,r)&&r.connectedTo.push(t)};function F3t(n,e){let t=e.width/2,i=e.height/2;if(e.type==="rect")return n.x>=e.center.x-t&&n.x<=e.center.x+t&&n.y>=e.center.y-i&&n.y<=e.center.y+i;if(e.type==="oval"){let r=(n.x-e.center.x)/t,s=(n.y-e.center.y)/i;return r*r+s*s<=1}return!1}function PW(n,e){let t=e.x>n.x?1:e.x<n.x?-1:0,i=e.y>n.y?1:e.y<n.y?-1:0,r=e.l>n.l?1:e.l<n.l?-1:0;return{dx:t,dy:i,dl:r}}var g4={1:["top"],2:["top","bottom"],4:["top","inner1","inner2","bottom"]},$3t=n=>g4[n];function LW(n,e){let i=g4[n].indexOf(e);if(i===-1)throw new Error(`Invalid layer for getLayerIndex (for layerCount === ${n}): "${e}"`);return i}function z3t(n,e){let i=g4[n][e];if(!i)throw new Error(`Invalid index for indexToLayer (for layerCount === ${n}): "${e}"`);return i}var D3t=class extends CW{constructor(e,t){super([]);f(this,"obstacles");f(this,"GRID_STEP",.1);f(this,"layerCount");this.layerCount=e;let i=$3t(e);this.obstacles=t.flatMap(r=>r.layers.filter(s=>i.includes(s)).map(s=>({...r,left:r.center.x-r.width/2,right:r.center.x+r.width/2,top:r.center.y+r.height/2,bottom:r.center.y-r.height/2,l:LW(e,s)})))}getObstacleAt(e,t,i,r){r??(r=this.GRID_STEP);for(let s of this.obstacles){if(s.l!==i)continue;let o=s.width/2+r,a=s.height/2+r;if(e>=s.center.x-o&&e<=s.center.x+o&&t>=s.center.y-a&&t<=s.center.y+a)return s}return null}isObstacleAt(e,t,i,r){return this.getObstacleAt(e,t,i,r)!==null}getDirectionDistancesToNearestObstacle3d(e,t,i){let{GRID_STEP:r}=this,s={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let o of this.obstacles)if(o.l===i&&o.type==="rect"){let a=o.center.x-o.width/2-r,c=o.center.x+o.width/2+r,l=o.center.y+o.height/2+r,u=o.center.y-o.height/2-r;t>=u&&t<=l&&e>a&&(s.left=Math.min(s.left,e-c)),t>=u&&t<=l&&e<c&&(s.right=Math.min(s.right,a-e)),e>=a&&e<=c&&t<l&&(s.top=Math.min(s.top,u-t)),e>=a&&e<=c&&t>u&&(s.bottom=Math.min(s.bottom,t-l))}return s}getOrthoDirectionCollisionInfo(e,t,{margin:i=0}={}){let{x:r,y:s,l:o}=e,{dx:a,dy:c,dl:l}=t,u=1/0,p=null;if(l!==0){let d=o+l;return this.isObstacleAt(r,s,d,i)?(u=1,p=this.getObstacleAt(r,s,d,i)):u=1,{dx:a,dy:c,dl:l,wallDistance:u,obstacle:p}}else{for(let d of this.obstacles){if(d.l!==o)continue;let _=d.left-i,g=d.right+i,x=d.top+i,v=d.bottom-i,S=null;a===1&&c===0?s>v&&s<x&&r<d.left&&(S=d.left-r):a===-1&&c===0?s>v&&s<x&&r>d.right&&(S=r-d.right):a===0&&c===1?r>_&&r<g&&s<d.bottom&&(S=d.bottom-s):a===0&&c===-1&&r>_&&r<g&&s>d.top&&(S=s-d.top),S!==null&&S<u&&(u=S,p=d)}return{dx:a,dy:c,dl:0,wallDistance:u,obstacle:p}}}getObstaclesOverlappingRegion(e){let t=[];for(let i of this.obstacles){if(i.l!==e.l)continue;let{left:r,right:s,top:o,bottom:a}=i;r<=e.maxX&&s>=e.minX&&o>=e.minY&&a<=e.maxY&&t.push(i)}return t}},bw=class extends NW{constructor(e){super(e);f(this,"MAX_ITERATIONS",500);f(this,"VIA_COST",4);f(this,"VIA_DIAMETER",.5);f(this,"allowLayerChange",!0);f(this,"layerCount");f(this,"obstacles");f(this,"optimizeWithGoalBoxes");f(this,"connMap");f(this,"pcbConnMap");f(this,"GOAL_RUSH_FACTOR",1.1);f(this,"defaultGoalViaMargin",.5);f(this,"marginsWithCosts");this.layerCount=e.input.layerCount??2,this.MAX_ITERATIONS=e.MAX_ITERATIONS??this.MAX_ITERATIONS,this.VIA_COST=e.VIA_COST??this.VIA_COST,this.connMap=e.connMap,this.pcbConnMap=e.pcbConnMap??new gw,this.optimizeWithGoalBoxes=e.optimizeWithGoalBoxes??!1,this.obstacles=null,this.marginsWithCosts=e.marginsWithCosts??[{margin:1,enterCost:0,travelCostFactor:1},{margin:this.OBSTACLE_MARGIN,enterCost:10,travelCostFactor:2}]}get largestMargin(){return this.marginsWithCosts[0].margin}preprocessConnectionBeforeSolving(e){return this.optimizeWithGoalBoxes?OW({connection:e,pcbConnMap:this.pcbConnMap}):e}postprocessConnectionSolveResult(e,t){if(!t.solved)return t;if(this.optimizeWithGoalBoxes){let i=t.route.map(r=>({x:r.x,y:r.y,route_type:"wire",layer:r.layer,width:this.input.minTraceWidth}));i[0].start_pcb_port_id=e.pointsToConnect[0].pcb_port_id,i[i.length-1].end_pcb_port_id=e.pointsToConnect[1].pcb_port_id,this.pcbConnMap.addTrace({type:"pcb_trace",pcb_trace_id:`postprocess_trace_${xW(8)}`,route:i})}return t}createObstacleList({dominantLayer:e,connection:t,obstaclesFromTraces:i}){let r=this.connMap?this.connMap.getNetConnectedToId(t.name):t.name;if(!r)throw new Error(`The connection.name "${t.name}" wasn't present in the full connectivity map`);return new D3t(this.layerCount,this.allObstacles.filter(s=>!s.connectedTo.includes(r)).concat(i??[]))}computeG(e,t){let i=e.g+ad(e,t)*(e.travelMarginCostFactor??1)+(t.enterMarginCost??0);return(t.l??e.l!==-1??-1)&&(i+=this.VIA_COST),i}computeH(e){let t=Math.abs(e.x-this.goalPoint.x),i=Math.abs(e.y-this.goalPoint.y),r=Math.abs(e.l-this.goalPoint.l);return(t+i)**this.GOAL_RUSH_FACTOR+r*this.VIA_COST}getStartNode(e){return{...super.getStartNode(e),l:this.layerToIndex(e.pointsToConnect[0].layer)}}layerToIndex(e){return LW(this.layerCount,e)}indexToLayer(e){return z3t(this.layerCount,e)}getNodeName(e){return`${TW(e,this.GRID_STEP)}-${e.l??0}`}hasSpaceForVia(e,t){return e.every(i=>this.obstacles.getObstaclesOverlappingRegion({minX:t.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:t.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:t.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:t.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:i}).length===0)}getNeighborsSurroundingGoal(e){let t=this.obstacles,i=this.goalPoint,r=[],s=[{dx:1,dy:0,dl:0},{dx:-1,dy:0,dl:0},{dx:0,dy:1,dl:0},{dx:0,dy:-1,dl:0}],o=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin;for(let a of s){let c={x:e.x+a.dx*o,y:e.y+a.dy*o,l:e.l+a.dl,obstacleHit:null};this.hasSpaceForVia([e.l,i.l],c)&&r.push(c)}return r}getNeighbors(e){let t=this.obstacles,i=this.goalPoint,r=ad(e,i);if(r<=this.OBSTACLE_MARGIN)return this.getNeighborsSurroundingGoal(e);let s;e.parent?s=PW(e.parent,e):s=PW(e,i);let o=[{dx:0,dy:1,dl:0},{dx:1,dy:0,dl:0},{dx:0,dy:-1,dl:0},{dx:-1,dy:0,dl:0}],a=r>this.VIA_DIAMETER+this.OBSTACLE_MARGIN,c=ad(e,this.startNode)>this.VIA_DIAMETER+this.OBSTACLE_MARGIN;this.allowLayerChange&&a&&c&&(e.l<this.layerCount-1&&o.push({dx:0,dy:0,dl:1}),e.l>0&&o.push({dx:0,dy:0,dl:-1}));let l=o.filter(p=>p.dx===s.dx*-1&&p.dy===s.dy*-1&&p.dl===s.dl*-1?!1:!(p.dx===s.dx&&p.dy===s.dy&&p.dl===s.dl&&e.parent?.obstacleHit)).map(p=>t.getOrthoDirectionCollisionInfo(e,p,{margin:this.OBSTACLE_MARGIN})).filter(p=>!(p.wallDistance<this.OBSTACLE_MARGIN)),u=[];for(let p of l){let d=p.dx===0&&p.dy===0&&p.dl===1,_=p.dx===0&&p.dy===0&&p.dl===-1;if((d||_)&&![e.l,e.l+p.dl].every(P=>t.getObstaclesOverlappingRegion({minX:e.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:e.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:e.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:e.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:P}).length===0))continue;if(d){e.l<this.layerCount-1&&u.push({...p,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}if(_){e.l>0&&u.push({...p,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}let g=null;e?.obstacleHit&&(g=y4({node:e,travelDir:p,wallDir:{...s,wallDistance:this.OBSTACLE_MARGIN},obstacle:e.obstacleHit,obstacles:t,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let x=kW(e,i,p),v=(p.dx===0||Math.sign(i.x-e.x)===p.dx)&&(p.dy===0||Math.sign(i.y-e.y)===p.dy);if(x<p.wallDistance&&x>0&&v){let S=e.l===i.l,P=0;!S&&Math.abs(x-r)<this.GRID_STEP&&(P=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin),u.push({...p,travelDistance:x-P,enterMarginCost:0,travelMarginCostFactor:1})}else if(g!==null&&g<p.wallDistance){for(let{margin:S,enterCost:P,travelCostFactor:T}of this.marginsWithCosts)g-this.OBSTACLE_MARGIN+S*2<p.wallDistance&&u.push({...p,travelDistance:g-this.OBSTACLE_MARGIN+S,enterMarginCost:P,travelMarginCostFactor:T});if(p.wallDistance===1/0)u.push({...p,travelDistance:x,enterMarginCost:0,travelMarginCostFactor:1});else if(p.wallDistance>this.largestMargin)for(let{margin:S,enterCost:P,travelCostFactor:T}of this.marginsWithCosts)p.wallDistance>this.largestMargin+S&&u.push({...p,travelDistance:p.wallDistance-S,enterMarginCost:P,travelMarginCostFactor:T})}else if(p.wallDistance!==1/0)for(let{margin:S,enterCost:P,travelCostFactor:T}of this.marginsWithCosts)p.wallDistance>S&&u.push({...p,travelDistance:p.wallDistance-S,enterMarginCost:P,travelMarginCostFactor:T})}return u.map(p=>({x:e.x+p.dx*p.travelDistance,y:e.y+p.dy*p.travelDistance,l:e.l+p.dl,obstacleHit:p.obstacle,travelMarginCostFactor:p.travelMarginCostFactor,enterMarginCost:p.enterMarginCost}))}};function FW(n){let e=O3t(n),t=new A3t({input:e});return{solution:t.solveAndMapToTraces(),debugSolutions:t.debugSolutions,debugMessage:t.debugMessage}}Q();Q();wt();wt();Q();Q();Q();wt();Q();Q();wt();Q();wt();Q();Q();Q();Q();wt();Q();Q();wt();Q();Q();wt();Q();Q();wt();Q();Q();Q();Q();Q();Q();Q();Q();Q();Q();wt();Q();wt();Q();wt();Q();Q();wt();wt();Q();wt();Q();Q();wt();Q();Q();Q();wt();Q();wt();Q();wt();Q();wt();Q();wt();Q();wt();Q();wt();Q();Q();Q();Q();Q();Q();Q();Q();wt();Q();wt();Q();Q();wt();Q();wt();Q();Q();Q();wt();Q();wt();wt();Q();Q();Q();wt();Q();Q();Q();wt();Q();wt();Q();wt();Q();wt();Q();wt();Q();wt();Q();wt();Q();wt();Q();Q();wt();Q();wt();Q();wt();Q();Q();wt();wt();Q();Q();wt();wt();Q();Q();wt();Q();wt();Q();wt();Q();wt();Q();wt();Q();wt();Q();Q();wt();Q();wt();Q();wt();Q();wt();Q();wt();Q();wt();Q();wt();Q();wt();wt();Q();wt();Q();wt();Q();Q();wt();Q();wt();Q();wt();Q();wt();Q();wt();Q();Q();var Ct=n=>{};Ct("extra props b");Ct("missing props b");Ct(!0);Ct("property a has mismatched types");var j3t=h.enum(["up","down","left","right"]),Xie=h.enum(["top-to-bottom","left-to-right","bottom-to-top","right-to-left"]);Ct(!0);Ct(!0);var oo=h.array(h.string().or(h.number()));Ct(!0);var B3t=h.string().regex(/^calc\(.*\)$/),pe=V,$i=B3t.or(V),Sw=h.object({x:V,y:V,z:V}),Y3t=h.object({x:h.union([h.number(),h.string()]),y:h.union([h.number(),h.string()]),z:h.union([h.number(),h.string()])}),Hc=h.object({rotationOffset:h.number().or(Y3t).optional(),positionOffset:Sw.optional(),size:Sw.optional(),modelUnitToMmScale:pe.optional(),zOffsetFromSurface:pe.optional()});Ct(!0);var X3t=Hc.extend({stlUrl:h.string()}),U3t=Hc.extend({objUrl:h.string(),mtlUrl:h.string().optional()}),V3t=Hc.extend({gltfUrl:h.string()}),G3t=Hc.extend({glbUrl:h.string()}),W3t=Hc.extend({stepUrl:h.string()}),H3t=Hc.extend({wrlUrl:h.string()}),q3t=Hc.extend({jscad:h.record(h.any())}),UW=h.union([h.null(),h.string(),h.custom(n=>n&&typeof n=="object"&&"type"in n&&"props"in n),X3t,U3t,V3t,G3t,W3t,H3t,q3t]);Ct(!0);var Z3t=h.custom(n=>!0),v4=h.object({silkscreenFontSize:V.optional(),viaPadDiameter:V.optional(),viaHoleDiameter:V.optional(),silkscreenTextPosition:h.union([h.enum(["centered","outside","none"]),h.object({offsetX:h.number(),offsetY:h.number()})]).optional(),silkscreenTextVisibility:h.enum(["hidden","visible","inherit"]).optional()});Ct(!0);var K3t=h.object({defaultPassiveSize:h.union([h.enum(["xs","sm","md"]),V]).optional(),defaultCapacitorOrientation:h.enum(["vertical","none"]).optional()});Ct(!0);var J3t=h.custom(n=>!0),Be=h.object({pcbX:$i.optional(),pcbY:$i.optional(),pcbLeftEdgeX:$i.optional(),pcbRightEdgeX:$i.optional(),pcbTopEdgeY:$i.optional(),pcbBottomEdgeY:$i.optional(),pcbOffsetX:V.optional(),pcbOffsetY:V.optional(),pcbRotation:tn.optional(),pcbPositionAnchor:h.string().optional(),pcbPositionMode:h.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),layer:he.optional(),pcbMarginTop:V.optional(),pcbMarginRight:V.optional(),pcbMarginBottom:V.optional(),pcbMarginLeft:V.optional(),pcbMarginX:V.optional(),pcbMarginY:V.optional(),pcbStyle:v4.optional(),pcbRelative:h.boolean().optional(),relative:h.boolean().optional()});Ct(!0);var Pw=h.object({pcbX:$i.optional(),pcbY:$i.optional(),pcbLeftEdgeX:$i.optional(),pcbRightEdgeX:$i.optional(),pcbTopEdgeY:$i.optional(),pcbBottomEdgeY:$i.optional(),pcbOffsetX:V.optional(),pcbOffsetY:V.optional(),pcbRotation:tn.optional(),pcbPositionAnchor:h.string().optional(),pcbPositionMode:h.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),pcbMarginTop:V.optional(),pcbMarginRight:V.optional(),pcbMarginBottom:V.optional(),pcbMarginLeft:V.optional(),pcbMarginX:V.optional(),pcbMarginY:V.optional(),pcbStyle:v4.optional(),schMarginTop:V.optional(),schMarginRight:V.optional(),schMarginBottom:V.optional(),schMarginLeft:V.optional(),schMarginX:V.optional(),schMarginY:V.optional(),schX:V.optional(),schY:V.optional(),schRotation:tn.optional(),layer:he.optional(),footprint:Z3t.optional(),symbol:J3t.optional(),schStyle:K3t.optional(),relative:h.boolean().optional(),schRelative:h.boolean().optional(),pcbRelative:h.boolean().optional()});Ct(!0);var Q3t=h.object({supplierPartNumbers:h.record(Lm,h.array(h.string())).optional()});Ct(!0);var tMt=h.object({providesPower:h.boolean().optional(),requiresPower:h.boolean().optional(),providesGround:h.boolean().optional(),requiresGround:h.boolean().optional(),providesVoltage:h.union([h.string(),h.number()]).optional(),requiresVoltage:h.union([h.string(),h.number()]).optional(),doNotConnect:h.boolean().optional(),includeInBoardPinout:h.boolean().optional(),highlightColor:h.string().optional(),mustBeConnected:h.boolean().optional()});Ct(!0);var oi=Pw.merge(Q3t).extend({key:h.any().optional(),name:h.string(),cadModel:UW.optional(),children:h.any().optional(),symbolName:h.string().optional(),doNotPlace:h.boolean().optional(),obstructsWithinBounds:h.boolean().optional().describe("Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath"),showAsTranslucentModel:h.boolean().optional().describe("Whether to show this component's CAD model as translucent in the 3D viewer."),pinAttributes:h.record(h.string(),tMt).optional()});Ct(!0);var w4=["pin1","left","pin2","right"],kw=["pin1","left","anode","pos","pin2","right","cathode","neg"],sre=V.or(h.enum(["2x","3x","4x"]));var qc=h.enum(["vertical","horizontal","pos_top","pos_bottom","pos_left","pos_right","neg_top","neg_bottom","neg_left","neg_right"]).describe("horizontal means pins go 1->2 rightward and vertical means pins go 1->2 downward (generally, positive on top)");Ct(!0);var vw=h.object({pins:h.array(h.union([h.number(),h.string()])),direction:h.union([h.literal("top-to-bottom"),h.literal("left-to-right"),h.literal("bottom-to-top"),h.literal("right-to-left")])}),Og=h.object({leftSize:h.number().optional().describe("@deprecated, use leftPinCount"),topSize:h.number().optional().describe("@deprecated, use topPinCount"),rightSize:h.number().optional().describe("@deprecated, use rightPinCount"),bottomSize:h.number().optional().describe("@deprecated, use bottomPinCount"),leftPinCount:h.number().optional(),rightPinCount:h.number().optional(),topPinCount:h.number().optional(),bottomPinCount:h.number().optional(),leftSide:vw.optional(),rightSide:vw.optional(),topSide:vw.optional(),bottomSide:vw.optional()}),S4=Og;Ct(!0);var Lg=h.record(h.object({marginLeft:V.optional(),marginRight:V.optional(),marginTop:V.optional(),marginBottom:V.optional(),leftMargin:V.optional(),rightMargin:V.optional(),topMargin:V.optional(),bottomMargin:V.optional()}));Ct(!0);var Ns=h.string().regex(/^[A-Za-z0-9_]+$/),VW=V.or(h.enum(["xs","sm","default","md"])).describe("distance between pin1 and pin2 of the schematic symbol"),r_=h.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),$o=h.object({x:V,y:V}),Fg=h.object({edit_event_id:h.string(),in_progress:h.boolean().optional(),created_at:h.number()});Ct(!0);var eMt=Fg.extend({pcb_edit_event_type:h.literal("edit_component_location").describe("deprecated"),edit_event_type:h.literal("edit_pcb_component_location"),pcb_component_id:h.string(),original_center:h.object({x:h.number(),y:h.number()}),new_center:h.object({x:h.number(),y:h.number()})});Ct(!0);var nMt=Fg.extend({pcb_edit_event_type:h.literal("edit_trace_hint").describe("deprecated"),edit_event_type:h.literal("edit_pcb_trace_hint").optional(),pcb_port_id:h.string(),pcb_trace_hint_id:h.string().optional(),route:h.array(h.object({x:h.number(),y:h.number(),via:h.boolean().optional()}))});Ct(!0);var iMt=Fg.extend({edit_event_type:h.literal("edit_schematic_component_location"),schematic_component_id:h.string(),original_center:h.object({x:h.number(),y:h.number()}),new_center:h.object({x:h.number(),y:h.number()})});Ct(!0);var Pre=Fg.extend({edit_event_type:h.literal("edit_pcb_group_location"),pcb_group_id:h.string(),original_center:h.object({x:h.number(),y:h.number()}),new_center:h.object({x:h.number(),y:h.number()})});Ct(!0);var Tre=Fg.extend({edit_event_type:h.literal("edit_schematic_group_location"),schematic_group_id:h.string(),original_center:h.object({x:h.number(),y:h.number()}),new_center:h.object({x:h.number(),y:h.number()})});Ct(!0);var Mre=h.union([eMt,nMt,iMt]);Ct(!0);var rMt=h.object({selector:h.string(),relative_to:h.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Zt});Ct(!0);var sMt=h.object({pcb_port_selector:h.string(),offsets:h.array(tr)});Ct(!0);var oMt=h.object({selector:h.string(),relative_to:h.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Zt});Ct(!0);var aMt=h.object({pcb_placements:h.array(rMt).optional(),manual_trace_hints:h.array(sMt).optional(),schematic_placements:h.array(oMt).optional()});Ct(!0);var s_=h.string().or(h.array(h.string()).readonly()).or(h.array(h.string())),cd=n=>h.record(h.enum(n),s_),Rg=h.object({layoutMode:h.enum(["grid","flex","match-adapt","relative","none"]).optional(),position:h.enum(["absolute","relative"]).optional(),grid:h.boolean().optional(),gridCols:h.number().or(h.string()).optional(),gridRows:h.number().or(h.string()).optional(),gridTemplateRows:h.string().optional(),gridTemplateColumns:h.string().optional(),gridTemplate:h.string().optional(),gridGap:h.number().or(h.string()).optional(),gridRowGap:h.number().or(h.string()).optional(),gridColumnGap:h.number().or(h.string()).optional(),flex:h.boolean().or(h.string()).optional(),flexDirection:h.enum(["row","column"]).optional(),alignItems:h.enum(["start","center","end","stretch"]).optional(),justifyContent:h.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),flexRow:h.boolean().optional(),flexColumn:h.boolean().optional(),gap:h.number().or(h.string()).optional(),pack:h.boolean().optional().describe("Pack the contents of this group using a packing strategy"),packOrderStrategy:h.enum(["largest_to_smallest","first_to_last","highest_to_lowest_pin_count"]).optional(),packPlacementStrategy:h.enum(["shortest_connection_along_outline"]).optional(),padding:D.optional(),paddingLeft:D.optional(),paddingRight:D.optional(),paddingTop:D.optional(),paddingBottom:D.optional(),paddingX:D.optional(),paddingY:D.optional(),width:D.optional(),height:D.optional(),matchAdapt:h.boolean().optional(),matchAdaptTemplate:h.any().optional()});Ct(!0);var $W=h.object({strokeWidth:D.optional(),dashed:h.boolean().optional(),solid:h.boolean().optional()}),cMt=h.custom(n=>typeof n=="string"),lMt=h.object({serverUrl:h.string().optional(),inputFormat:h.enum(["simplified","circuit-json"]).optional(),serverMode:h.enum(["job","solve-endpoint"]).optional(),serverCacheEnabled:h.boolean().optional(),cache:h.custom(n=>!0).optional(),traceClearance:D.optional(),groupMode:h.enum(["sequential_trace","subcircuit","sequential-trace"]).optional(),algorithmFn:h.custom(n=>typeof n=="function"||n===void 0).optional(),preset:h.enum(["sequential_trace","subcircuit","auto","auto_local","auto_cloud","freerouting","laser_prefab","sequential-trace","auto-local","auto-cloud"]).optional(),local:h.boolean().optional()}),uMt=h.union([h.literal("sequential_trace"),h.literal("subcircuit"),h.literal("auto"),h.literal("auto_local"),h.literal("auto_cloud"),h.literal("freerouting"),h.literal("laser_prefab"),h.literal("sequential-trace"),h.literal("auto-local"),h.literal("auto-cloud")]),pMt=h.string(),GW=h.union([lMt,uMt,pMt]),P4=Pw.extend({name:h.string().optional(),children:h.any().optional(),schTitle:h.string().optional(),key:h.any().optional(),showAsSchematicBox:h.boolean().optional(),connections:h.record(h.string(),s_.optional()).optional(),schPinArrangement:S4.optional(),schPinSpacing:D.optional(),schPinStyle:Lg.optional(),...Rg.shape,grid:Rg.shape.grid.describe("@deprecated use pcbGrid"),flex:Rg.shape.flex.describe("@deprecated use pcbFlex"),pcbGrid:h.boolean().optional(),pcbGridCols:h.number().or(h.string()).optional(),pcbGridRows:h.number().or(h.string()).optional(),pcbGridTemplateRows:h.string().optional(),pcbGridTemplateColumns:h.string().optional(),pcbGridTemplate:h.string().optional(),pcbGridGap:h.number().or(h.string()).optional(),pcbGridRowGap:h.number().or(h.string()).optional(),pcbGridColumnGap:h.number().or(h.string()).optional(),pcbFlex:h.boolean().or(h.string()).optional(),pcbFlexGap:h.number().or(h.string()).optional(),pcbFlexDirection:h.enum(["row","column"]).optional(),pcbAlignItems:h.enum(["start","center","end","stretch"]).optional(),pcbJustifyContent:h.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),pcbFlexRow:h.boolean().optional(),pcbFlexColumn:h.boolean().optional(),pcbGap:h.number().or(h.string()).optional(),pcbPack:h.boolean().optional(),pcbPackGap:h.number().or(h.string()).optional(),schGrid:h.boolean().optional(),schGridCols:h.number().or(h.string()).optional(),schGridRows:h.number().or(h.string()).optional(),schGridTemplateRows:h.string().optional(),schGridTemplateColumns:h.string().optional(),schGridTemplate:h.string().optional(),schGridGap:h.number().or(h.string()).optional(),schGridRowGap:h.number().or(h.string()).optional(),schGridColumnGap:h.number().or(h.string()).optional(),schFlex:h.boolean().or(h.string()).optional(),schFlexGap:h.number().or(h.string()).optional(),schFlexDirection:h.enum(["row","column"]).optional(),schAlignItems:h.enum(["start","center","end","stretch"]).optional(),schJustifyContent:h.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),schFlexRow:h.boolean().optional(),schFlexColumn:h.boolean().optional(),schGap:h.number().or(h.string()).optional(),schPack:h.boolean().optional(),schMatchAdapt:h.boolean().optional(),pcbWidth:D.optional(),pcbHeight:D.optional(),minTraceWidth:D.optional(),schWidth:D.optional(),schHeight:D.optional(),pcbLayout:Rg.optional(),schLayout:Rg.optional(),cellBorder:$W.nullable().optional(),border:$W.nullable().optional(),schPadding:D.optional(),schPaddingLeft:D.optional(),schPaddingRight:D.optional(),schPaddingTop:D.optional(),schPaddingBottom:D.optional(),pcbPadding:D.optional(),pcbPaddingLeft:D.optional(),pcbPaddingRight:D.optional(),pcbPaddingTop:D.optional(),pcbPaddingBottom:D.optional(),pcbPositionAnchor:cMt.optional()}),WW=h.custom(n=>"findPart"in n),k4=P4.extend({manualEdits:aMt.optional(),schAutoLayoutEnabled:h.boolean().optional(),schTraceAutoLabelEnabled:h.boolean().optional(),schMaxTraceDistance:V.optional(),routingDisabled:h.boolean().optional(),defaultTraceWidth:D.optional(),minTraceWidth:D.optional(),partsEngine:WW.optional(),pcbRouteCache:h.custom(n=>!0).optional(),autorouter:GW.optional(),square:h.boolean().optional(),emptyArea:h.string().optional(),filledArea:h.string().optional(),width:V.optional(),height:V.optional(),outline:h.array($o).optional(),outlineOffsetX:V.optional(),outlineOffsetY:V.optional(),circuitJson:h.array(h.any()).optional()}),hMt=k4.extend({subcircuit:h.literal(!0)}),HW=h.discriminatedUnion("subcircuit",[P4.extend({subcircuit:h.literal(!1).optional()}),hMt]);Ct(!0);Ct(!0);Ct(!0);Ct(!0);var i_=h.custom(n=>typeof n=="string"),T4=k4.omit({connections:!0}).extend({material:h.enum(["fr4","fr1"]).default("fr4"),layers:h.union([h.literal(1),h.literal(2),h.literal(4),h.literal(6),h.literal(8)]).default(2),borderRadius:pe.optional(),thickness:pe.optional(),boardAnchorPosition:$o.optional(),boardAnchorAlignment:r_.optional(),title:h.string().optional(),solderMaskColor:i_.optional(),topSolderMaskColor:i_.optional(),bottomSolderMaskColor:i_.optional(),silkscreenColor:i_.optional(),topSilkscreenColor:i_.optional(),bottomSilkscreenColor:i_.optional(),doubleSidedAssembly:h.boolean().optional().default(!1),schematicDisabled:h.boolean().optional()});Ct(!0);var qW=P4.omit({width:!0,height:!0,children:!0}).extend({width:pe,height:pe,children:h.any().optional(),noSolderMask:h.boolean().optional(),panelizationMethod:h.enum(["tab-routing","none"]).optional(),boardGap:pe.optional(),tabWidth:pe.optional(),tabLength:pe.optional(),mouseBites:h.boolean().optional()});Ct(!0);var Dre=k4.extend({padding:V.optional(),paddingLeft:V.optional(),paddingRight:V.optional(),paddingTop:V.optional(),paddingBottom:V.optional()});Ct(!0);var dMt=h.string().or(h.array(h.string()).readonly()).or(h.array(h.string())),fMt=h.custom().pipe(h.record(h.string(),dMt)),mMt=h.record(Ns,Ns.or(h.array(Ns).readonly()).or(h.array(Ns)));Ct(!0);var _Mt=h.object({manufacturerPartNumber:h.string().optional(),supplierPartNumber:h.record(Lm,h.array(h.string())).optional()}),o_=oi.extend({manufacturerPartNumber:h.string().optional(),pinLabels:mMt.optional(),showPinAliases:h.boolean().optional(),pcbPinLabels:h.record(h.string(),h.string()).optional(),internallyConnectedPins:h.array(h.array(h.union([h.string(),h.number()]))).optional(),externallyConnectedPins:h.array(h.array(h.string())).optional(),schPinArrangement:Og.optional(),schPortArrangement:Og.optional(),pinCompatibleVariants:h.array(_Mt).optional(),schPinStyle:Lg.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional(),noSchematicRepresentation:h.boolean().optional(),connections:fMt.optional()});Ct(!0);var ZW=o_;Ct(!0);var E4=oi.extend({manufacturerPartNumber:h.string().optional(),pinLabels:h.record(h.number().or(Ns),Ns.or(h.array(Ns))).optional(),schPinStyle:Lg.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional(),schDirection:h.enum(["left","right"]).optional(),schPinArrangement:S4.optional(),schPortArrangement:Og.optional(),pcbPinLabels:h.record(h.string(),h.string()).optional(),pinCount:h.union([h.literal(2),h.literal(3)]).optional(),internallyConnectedPins:h.array(h.array(h.union([h.string(),h.number()]))).optional(),connections:h.custom().pipe(h.record(h.string(),s_)).optional()});Ct(!0);var KW=E4.extend({bridgedPins:h.array(h.array(h.string())).optional(),bridged:h.boolean().optional()});Ct(!0);var Wre=oi.extend({manufacturerPartNumber:h.string().optional(),pinLabels:h.record(h.number().or(Ns),Ns.or(h.array(Ns))).optional(),schPinStyle:Lg.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional(),schDirection:h.enum(["left","right"]).optional(),schPortArrangement:Og.optional(),internallyConnectedPins:h.array(h.array(h.union([h.string(),h.number()]))).optional(),standard:h.enum(["usb_c","m2"]).optional()});Ct(!0);var JW=oi.extend({standard:h.enum(["TSC0001_36P_XALT_2025_11","0805","0603","1206"]).optional()});Ct(!0);var QW=oi.extend({currentRating:h.union([h.number(),h.string()]),voltageRating:h.union([h.number(),h.string()]).optional(),schShowRatings:h.boolean().optional(),schOrientation:qc.optional(),connections:h.record(h.string(),h.union([h.string(),h.array(h.string()).readonly(),h.array(h.string())])).optional()}),ww=h.custom().transform(n=>{if(n!==void 0)return V.parse(n)}),tH=h.discriminatedUnion("shape",[Be.omit({pcbRotation:!0,layer:!0}).extend({name:h.string().optional(),connectsTo:h.string().or(h.array(h.string())).optional(),shape:h.literal("circle"),holeDiameter:V,outerDiameter:V,padDiameter:V.optional().describe("Diameter of the copper pad"),portHints:oo.optional(),solderMaskMargin:V.optional(),coveredWithSolderMask:h.boolean().optional()}),Be.omit({layer:!0}).extend({name:h.string().optional(),connectsTo:h.string().or(h.array(h.string())).optional(),shape:h.literal("oval"),outerWidth:V,outerHeight:V,holeWidth:ww,holeHeight:ww,innerWidth:V.optional().describe("DEPRECATED use holeWidth"),innerHeight:V.optional().describe("DEPRECATED use holeHeight"),portHints:oo.optional(),solderMaskMargin:V.optional(),coveredWithSolderMask:h.boolean().optional()}),Be.omit({layer:!0}).extend({name:h.string().optional(),connectsTo:h.string().or(h.array(h.string())).optional(),shape:h.literal("pill"),rectPad:h.boolean().optional(),outerWidth:V,outerHeight:V,holeWidth:ww,holeHeight:ww,innerWidth:V.optional().describe("DEPRECATED use holeWidth"),innerHeight:V.optional().describe("DEPRECATED use holeHeight"),portHints:oo.optional(),holeOffsetX:V.optional(),holeOffsetY:V.optional(),solderMaskMargin:V.optional(),coveredWithSolderMask:h.boolean().optional()}),Be.omit({pcbRotation:!0,layer:!0}).extend({name:h.string().optional(),connectsTo:h.string().or(h.array(h.string())).optional(),shape:h.literal("circular_hole_with_rect_pad"),holeDiameter:V,rectPadWidth:V,rectPadHeight:V,rectBorderRadius:V.optional(),holeShape:h.literal("circle").optional(),padShape:h.literal("rect").optional(),portHints:oo.optional(),holeOffsetX:V.optional(),holeOffsetY:V.optional(),solderMaskMargin:V.optional(),coveredWithSolderMask:h.boolean().optional()}),Be.omit({pcbRotation:!0,layer:!0}).extend({name:h.string().optional(),connectsTo:h.string().or(h.array(h.string())).optional(),shape:h.literal("pill_hole_with_rect_pad"),holeShape:h.literal("pill"),padShape:h.literal("rect"),holeWidth:V,holeHeight:V,rectPadWidth:V,rectPadHeight:V,portHints:oo.optional(),holeOffsetX:V.optional(),holeOffsetY:V.optional(),solderMaskMargin:V.optional(),coveredWithSolderMask:h.boolean().optional()}),Be.omit({pcbRotation:!0,layer:!0}).extend({name:h.string().optional(),connectsTo:h.string().or(h.array(h.string())).optional(),shape:h.literal("hole_with_polygon_pad"),holeShape:h.enum(["circle","oval","pill","rotated_pill"]),holeDiameter:V.optional(),holeWidth:V.optional(),holeHeight:V.optional(),padOutline:h.array($o),holeOffsetX:V,holeOffsetY:V,portHints:oo.optional(),solderMaskMargin:V.optional(),coveredWithSolderMask:h.boolean().optional()})]).refine(n=>("innerWidth"in n&&n.innerWidth!==void 0&&(n.holeWidth??(n.holeWidth=n.innerWidth)),"innerHeight"in n&&n.innerHeight!==void 0&&(n.holeHeight??(n.holeHeight=n.innerHeight)),n));Ct(!0);var yMt=["pin1","pin2","pos","neg"],eH=oi.extend({resistance:Yc,pullupFor:h.string().optional(),pullupTo:h.string().optional(),pulldownFor:h.string().optional(),pulldownTo:h.string().optional(),schOrientation:qc.optional(),schSize:VW.optional(),connections:cd(yMt).optional()}),nH=w4;Ct(!0);var iH=oi.extend({maxResistance:Yc,pinVariant:h.enum(["two_pin","three_pin"]).optional()});Ct(!0);var gMt=w4,rH=oi.extend({frequency:zr,loadCapacitance:ka,manufacturerPartNumber:h.string().optional(),mpn:h.string().optional(),pinVariant:h.enum(["two_pin","four_pin"]).optional(),schOrientation:qc.optional(),connections:cd(gMt).optional()});Ct(!0);var sH=oi.extend({frequency:zr,loadCapacitance:ka,pinVariant:h.enum(["no_ground","ground_pin","two_ground_pins"]).optional()});Ct(!0);var cse=T4.extend({leftPinCount:h.number().optional(),rightPinCount:h.number().optional(),topPinCount:h.number().optional(),bottomPinCount:h.number().optional(),leftPins:h.array(h.string()).optional(),rightPins:h.array(h.string()).optional(),topPins:h.array(h.string()).optional(),bottomPins:h.array(h.string()).optional(),pinPitch:V.optional(),innerHoles:h.boolean().optional()});Ct(!0);var xMt=["pin1","pin2","pos","neg","anode","cathode"],oH=oi.extend({capacitance:ka,maxVoltageRating:pr.optional(),schShowRatings:h.boolean().optional().default(!1),polarized:h.boolean().optional().default(!1),decouplingFor:h.string().optional(),decouplingTo:h.string().optional(),bypassFor:h.string().optional(),bypassTo:h.string().optional(),maxDecouplingTraceLength:h.number().optional(),schOrientation:qc.optional(),schSize:VW.optional(),connections:cd(xMt).optional()}),aH=kw;Ct(!0);var hse=h.object({name:h.string(),connectsTo:h.string().or(h.array(h.string())).optional(),highlightColor:h.string().optional(),isPowerNet:h.boolean().optional(),isGroundNet:h.boolean().optional()});Ct(!0);var fse=h.object({name:h.string().optional(),pcbOnly:h.boolean().optional(),schOnly:h.boolean().optional()});Ct(!0);var bMt=h.object({pcb:h.literal(!0).optional(),xDist:pe,left:h.string(),right:h.string(),edgeToEdge:h.literal(!0).optional(),centerToCenter:h.literal(!0).optional()});Ct(!0);var vMt=h.object({pcb:h.literal(!0).optional(),yDist:pe,top:h.string(),bottom:h.string(),edgeToEdge:h.literal(!0).optional(),centerToCenter:h.literal(!0).optional()});Ct(!0);var wMt=h.object({pcb:h.literal(!0).optional(),sameY:h.literal(!0).optional(),for:h.array(h.string())});Ct(!0);var SMt=h.object({pcb:h.literal(!0).optional(),sameX:h.literal(!0).optional(),for:h.array(h.string())});Ct(!0);var cH=h.union([bMt,vMt,wMt,SMt]);Ct(!0);var PMt=Be.omit({layer:!0,pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("rect"),width:pe,height:pe});Ct(!0);var kMt=Be.omit({layer:!0,pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("circle"),radius:pe});Ct(!0);var TMt=Be.omit({layer:!0,pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("polygon"),points:h.array($o)});Ct(!0);var lH=h.discriminatedUnion("shape",[PMt,kMt,TMt]),EMt=Be.omit({pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("rect"),width:pe,height:pe,rectBorderRadius:pe.optional(),cornerRadius:pe.optional(),portHints:oo.optional(),coveredWithSolderMask:h.boolean().optional(),solderMaskMargin:pe.optional()});Ct(!0);var MMt=Be.omit({pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("rotated_rect"),width:pe,height:pe,ccwRotation:h.number(),cornerRadius:pe.optional(),portHints:oo.optional(),coveredWithSolderMask:h.boolean().optional(),solderMaskMargin:pe.optional()});Ct(!0);var CMt=Be.omit({pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("circle"),radius:pe,portHints:oo.optional(),coveredWithSolderMask:h.boolean().optional(),solderMaskMargin:pe.optional()});Ct(!0);var IMt=Be.omit({pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("pill"),width:pe,height:pe,radius:pe,portHints:oo.optional(),coveredWithSolderMask:h.boolean().optional(),solderMaskMargin:pe.optional()});Ct(!0);var NMt=Be.omit({pcbRotation:!0}).extend({name:h.string().optional(),shape:h.literal("polygon"),points:h.array($o),portHints:oo.optional(),coveredWithSolderMask:h.boolean().optional(),solderMaskMargin:pe.optional()});Ct(!0);var uH=h.discriminatedUnion("shape",[CMt,EMt,MMt,IMt,NMt]);Ct(!0);var AMt=Be.omit({pcbRotation:!0}).extend({shape:h.literal("rect"),width:pe,height:pe});Ct(!0);var RMt=Be.omit({pcbRotation:!0}).extend({shape:h.literal("circle"),radius:pe});Ct(!0);var xse=h.union([RMt,AMt]);Ct(!0);var OMt=Be.extend({name:h.string().optional(),shape:h.literal("circle").optional(),diameter:pe.optional(),radius:pe.optional(),solderMaskMargin:pe.optional(),coveredWithSolderMask:h.boolean().optional()}).transform(n=>({...n,diameter:n.diameter??2*n.radius,radius:n.radius??n.diameter/2})),LMt=Be.extend({name:h.string().optional(),shape:h.literal("pill"),width:pe,height:pe,solderMaskMargin:pe.optional(),coveredWithSolderMask:h.boolean().optional()}),FMt=Be.extend({name:h.string().optional(),shape:h.literal("rect"),width:pe,height:pe,solderMaskMargin:pe.optional(),coveredWithSolderMask:h.boolean().optional()}),pH=h.union([OMt,LMt,FMt]);Ct(!0);var x4=h.union([h.string(),h.custom(n=>!!n.getPortSelector)]),zW=h.object({key:h.string().optional(),thickness:V.optional(),width:V.optional().describe("Alias for trace thickness"),schematicRouteHints:h.array($o).optional(),pcbRouteHints:h.array(tr).optional(),pcbPathRelativeTo:h.string().optional(),pcbPath:h.array(h.union([$o,h.string()])).optional(),pcbStraightLine:h.boolean().optional().describe("Draw a straight pcb trace between the connected points"),schDisplayLabel:h.string().optional(),schStroke:h.string().optional(),highlightColor:h.string().optional(),maxLength:V.optional()}),hH=h.union([zW.extend({path:h.array(x4)}),zW.extend({from:x4,to:x4})]),dH=h.object({children:h.any().optional(),originalLayer:he.default("top").optional(),circuitJson:h.array(h.any()).optional()});Ct(!0);var fH=h.object({originalFacingDirection:h.enum(["up","down","left","right"]).default("right").optional()});Ct(!0);var $Mt=h.number().or(h.string().endsWith("mAh")).transform(n=>{if(typeof n=="string"){let e=n.replace("mAh",""),t=Number.parseFloat(e);if(Number.isNaN(t))throw new Error("Invalid capacity");return t}return n}).describe("Battery capacity in mAh"),mH=oi.extend({capacity:$Mt.optional(),voltage:pr.optional(),standard:h.enum(["AA","AAA","9V","CR2032","18650","C"]).optional(),schOrientation:qc.optional()});Ct(!0);var zMt=h.enum(["vertical","horizontal"]).describe("vertical means pins go 1->2 downward and horizontal means pins go 1->2 rightward");Ct(!0);var _H=oi.extend({pinCount:h.number(),pitch:V.optional(),schFacingDirection:h.enum(["up","down","left","right"]).optional(),gender:h.enum(["male","female","unpopulated"]).optional().default("male"),showSilkscreenPinLabels:h.boolean().optional(),pcbPinLabels:h.record(h.string(),h.string()).optional(),doubleRow:h.boolean().optional(),rightAngle:h.boolean().optional(),pcbOrientation:zMt.optional(),holeDiameter:V.optional(),platedDiameter:V.optional(),pinLabels:h.record(h.string(),Ns).or(h.array(Ns)).optional(),connections:h.custom().pipe(h.record(h.string(),s_)).optional(),facingDirection:h.enum(["left","right"]).optional(),schPinArrangement:S4.optional(),schPinStyle:Lg.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional()});Ct(!0);var Rse=h.object({net:h.string().optional(),connection:h.string().optional(),schX:pe.optional(),schY:pe.optional(),schRotation:tn.optional(),anchorSide:h.enum(["left","top","right","bottom"]).optional()});Ct(!0);var yH=h.object({net:h.string().optional(),connection:h.string().optional(),connectsTo:h.string().or(h.array(h.string())).optional(),schX:pe.optional(),schY:pe.optional(),schRotation:tn.optional(),anchorSide:h.enum(["left","top","right","bottom"]).optional()});Ct(!0);var gH=o_.extend({});Ct(!0);Ct(!0);var DMt=h.custom(n=>typeof n=="string"),xH=h.object({simulationType:h.literal("spice_transient_analysis").default("spice_transient_analysis"),duration:hr.optional(),timePerStep:hr.optional(),spiceEngine:DMt.optional()});Ct(!0);var jMt=["pin1","pin2","pin3","emitter","collector","base","gate","source","drain"],bH=oi.extend({type:h.enum(["npn","pnp","bjt","jfet","mosfet","igbt"]),connections:cd(jMt).optional()});Ct(!0);var vH=oi.extend({channelType:h.enum(["n","p"]),mosfetMode:h.enum(["enhancement","depletion"])});Ct(!0);var BMt=w4,wH=oi.extend({inductance:Kx,maxCurrentRating:h.union([h.string(),h.number()]).optional(),schOrientation:qc.optional(),connections:cd(BMt).optional()});Ct(!0);var YMt=h.enum(["anode","cathode","pin1","pin2","pos","neg"]),XMt=h.string().or(h.array(h.string()).readonly()).or(h.array(h.string())),UMt=h.record(YMt,XMt),VMt=h.enum(["standard","schottky","zener","avalanche","photo","tvs"]),SH=oi.extend({connections:UMt.optional(),variant:VMt.optional().default("standard"),standard:h.boolean().optional(),schottky:h.boolean().optional(),zener:h.boolean().optional(),avalanche:h.boolean().optional(),photo:h.boolean().optional(),tvs:h.boolean().optional(),schOrientation:qc.optional()}).superRefine((n,e)=>{if([n.standard,n.schottky,n.zener,n.avalanche,n.photo,n.tvs].filter(Boolean).length>1)return e.addIssue({code:h.ZodIssueCode.custom,message:"Exactly one diode variant must be enabled",path:[]}),h.INVALID}).transform(n=>{let e={...n,standard:!1,schottky:!1,zener:!1,avalanche:!1,photo:!1,tvs:!1};if(n.standard)e.standard=!0;else if(n.schottky)e.schottky=!0;else if(n.zener)e.zener=!0;else if(n.photo)e.photo=!0;else if(n.tvs)e.tvs=!0;else switch(n.variant){case"standard":e.standard=!0;break;case"schottky":e.schottky=!0;break;case"zener":e.zener=!0;break;case"avalanche":e.avalanche=!0;break;case"photo":e.photo=!0;break;case"tvs":e.tvs=!0;break;default:e.standard=!0}return e}),PH=kw;Ct(!0);var kH=oi.extend({color:h.string().optional(),wavelength:h.string().optional(),schDisplayValue:h.string().optional(),schOrientation:qc.optional(),connections:cd(kw).optional(),laser:h.boolean().optional()}),TH=kw,EH=oi.extend({type:h.enum(["spst","spdt","dpst","dpdt"]).optional(),isNormallyClosed:h.boolean().optional().default(!1),spst:h.boolean().optional(),spdt:h.boolean().optional(),dpst:h.boolean().optional(),dpdt:h.boolean().optional(),simSwitchFrequency:zr.optional(),simCloseAt:hr.optional(),simOpenAt:hr.optional(),simStartClosed:h.boolean().optional(),simStartOpen:h.boolean().optional(),connections:h.custom().pipe(h.record(h.string(),s_)).optional()}).transform(n=>{let e={...n};switch(e.dpdt?e.type="dpdt":e.spst?e.type="spst":e.spdt?e.type="spdt":e.dpst&&(e.type="dpst"),e.type){case"spdt":e.spdt=!0;break;case"spst":e.spst=!0;break;case"dpst":e.dpst=!0;break;case"dpdt":e.dpdt=!0;break}return e});Ct(!0);var MH=Be.extend({text:h.string(),anchorAlignment:h.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:h.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:h.string().optional()});Ct(!0);var CH=Be.omit({pcbRotation:!0}).extend({width:V,height:V,strokeWidth:V.optional(),isFilled:h.boolean().optional(),hasStroke:h.boolean().optional(),isStrokeDashed:h.boolean().optional(),color:h.string().optional(),cornerRadius:V.optional()}),IH=Be.omit({pcbLeftEdgeX:!0,pcbRightEdgeX:!0,pcbTopEdgeY:!0,pcbBottomEdgeY:!0,pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:h.array(tr),strokeWidth:D.optional(),color:h.string().optional()}),DW=h.union([h.string(),$o]),NH=Be.omit({pcbLeftEdgeX:!0,pcbRightEdgeX:!0,pcbTopEdgeY:!0,pcbBottomEdgeY:!0,pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:DW,to:DW,text:h.string().optional(),offset:V.optional(),font:h.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:h.string().optional(),arrowSize:V.optional(),units:h.enum(["in","mm"]).optional(),outerEdgeToEdge:h.literal(!0).optional(),centerToCenter:h.literal(!0).optional(),innerEdgeToEdge:h.literal(!0).optional()});Ct(!0);var noe=h.object({layer:h.string().optional(),thickness:V.optional(),route:h.array(tr)}),AH=Pw.extend({name:h.string().optional(),fromLayer:he,toLayer:he,holeDiameter:V.optional(),outerDiameter:V.optional(),connectsTo:h.string().or(h.array(h.string())).optional(),netIsAssignable:h.boolean().optional()});Ct(!0);var GMt=h.object({pin1:s_}).strict(),RH=oi.extend({connections:GMt.optional(),footprintVariant:h.enum(["pad","through_hole"]).optional(),padShape:h.enum(["rect","circle"]).optional().default("circle"),padDiameter:V.optional(),holeDiameter:V.optional(),width:V.optional(),height:V.optional()}).refine(n=>n.footprintVariant!=="through_hole"||n.holeDiameter!==void 0,{message:"holeDiameter is required for through_hole testpoints"});Ct(!0);var OH=Be.omit({pcbRotation:!0,layer:!0}).extend({connection:h.string()});Ct(!0);var LH=h.union([Be.omit({pcbRotation:!0}).extend({shape:h.literal("circle"),radius:V}),Be.extend({shape:h.literal("rect"),width:V,height:V})]),hoe=Be.omit({pcbRotation:!0}).extend({width:V,height:V,strokeWidth:V.optional(),isFilled:h.boolean().optional(),hasStroke:h.boolean().optional(),isStrokeDashed:h.boolean().optional(),color:h.string().optional()}),moe=Be.omit({pcbLeftEdgeX:!0,pcbRightEdgeX:!0,pcbTopEdgeY:!0,pcbBottomEdgeY:!0,pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({outline:h.array($o),strokeWidth:D.optional(),isClosed:h.boolean().optional(),isStrokeDashed:h.boolean().optional(),color:h.string().optional()}),FH=h.object({name:h.string().optional(),layer:he,connectsTo:h.string(),padMargin:pe.optional(),traceMargin:pe.optional(),clearance:pe.optional(),boardEdgeMargin:pe.optional(),cutoutMargin:pe.optional(),coveredWithSolderMask:h.boolean().optional().default(!0)});Ct(!0);var $H=h.object({originalLayer:he.default("top").optional(),children:h.any().optional()});Ct(!0);var WMt=h.object({pcbX:$i.optional(),pcbY:$i.optional(),pcbLeftEdgeX:$i.optional(),pcbRightEdgeX:$i.optional(),pcbTopEdgeY:$i.optional(),pcbBottomEdgeY:$i.optional(),pcbOffsetX:pe.optional(),pcbOffsetY:pe.optional(),pcbZ:pe.optional()}),HMt=Hc.extend({modelUrl:h.string(),stepUrl:h.string().optional()}),qMt=HMt.merge(WMt);Ct(!0);var zH=h.union([h.null(),h.string(),qMt]),DH=oi.extend({voltage:pr}),ZMt=["pin1","pin2","pos","neg"],KMt=h.union([h.string(),h.number()]).transform(n=>typeof n=="string"?n.endsWith("%")?parseFloat(n.slice(0,-1))/100:parseFloat(n):n).pipe(h.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),jH=oi.extend({voltage:pr.optional(),frequency:zr.optional(),peakToPeakVoltage:pr.optional(),waveShape:h.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:tn.optional(),dutyCycle:KMt.optional(),connections:cd(ZMt).optional()});Ct(!0);var BH=oi.omit({name:!0}).extend({name:h.string().optional(),connectsTo:h.string(),referenceTo:h.string().optional(),color:h.string().optional()});Ct(!0);var YH=h.object({center:Zt,radius:V,startAngleDegrees:tn,endAngleDegrees:tn,direction:h.enum(["clockwise","counterclockwise"]).default("counterclockwise"),strokeWidth:V.optional(),color:h.string().optional(),isDashed:h.boolean().optional().default(!1)}),XH=h.object({schX:V.optional(),schY:V.optional(),width:V.optional(),height:V.optional(),overlay:h.array(h.string()).optional(),padding:V.optional(),paddingLeft:V.optional(),paddingRight:V.optional(),paddingTop:V.optional(),paddingBottom:V.optional(),title:h.string().optional(),titleAlignment:r_.default("top_left"),titleColor:h.string().optional(),titleFontSize:V.optional(),titleInside:h.boolean().default(!1),strokeStyle:h.enum(["solid","dashed"]).default("solid")}).refine(n=>n.width!==void 0&&n.height!==void 0||Array.isArray(n.overlay)&&n.overlay.length>0,{message:"Must provide either both `width` and `height`, or a non-empty `overlay` array."}).refine(n=>!(n.width!==void 0&&n.height!==void 0&&Array.isArray(n.overlay)&&n.overlay.length>0),{message:"Cannot provide both `width`/`height` and `overlay` at the same time."}),UH=h.object({center:Zt,radius:V,strokeWidth:V.optional(),color:h.string().optional(),isFilled:h.boolean().optional().default(!1),fillColor:h.string().optional(),isDashed:h.boolean().optional().default(!1)}),VH=h.object({schX:V.optional(),schY:V.optional(),width:V,height:V,rotation:tn.default(0),strokeWidth:V.optional(),color:h.string().optional(),isFilled:h.boolean().optional().default(!1),fillColor:h.string().optional(),isDashed:h.boolean().optional().default(!1),cornerRadius:V.optional()}),GH=h.object({x1:V,y1:V,x2:V,y2:V,strokeWidth:V.optional(),color:h.string().optional(),isDashed:h.boolean().optional().default(!1)}),JMt=h.enum(["center","left","right","top","bottom"]),WH=h.object({schX:V.optional(),schY:V.optional(),text:h.string(),fontSize:h.number().default(1),anchor:h.union([JMt.describe("legacy"),r_]).default("center"),color:h.string().default("#000000"),schRotation:tn.default(0)}),joe=h.object({points:h.array(Zt),isFilled:h.boolean().optional().default(!1),fillColor:h.enum(["red","blue"]).optional()}),HH=h.object({schX:V.optional(),schY:V.optional(),children:h.any().optional(),cellPadding:V.optional(),borderWidth:V.optional(),anchor:r_.optional(),fontSize:V.optional()});Ct(!0);var qH=h.object({children:h.any().optional(),height:V.optional()});Ct(!0);var ZH=h.object({children:h.string().optional(),horizontalAlign:h.enum(["left","center","right"]).optional(),verticalAlign:h.enum(["top","middle","bottom"]).optional(),fontSize:V.optional(),rowSpan:h.number().optional(),colSpan:h.number().optional(),width:V.optional(),text:h.string().optional()});Ct(!0);var qoe=Be.extend({text:h.string(),anchorAlignment:r_.default("center"),font:h.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),layers:h.array(he).optional()}),KH=Be.extend({text:h.string(),anchorAlignment:r_.default("center"),font:h.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),isKnockout:h.boolean().optional(),knockoutPadding:D.optional(),knockoutPaddingLeft:D.optional(),knockoutPaddingRight:D.optional(),knockoutPaddingTop:D.optional(),knockoutPaddingBottom:D.optional(),layers:h.array(he).optional()}),JH=Be.omit({pcbLeftEdgeX:!0,pcbRightEdgeX:!0,pcbTopEdgeY:!0,pcbBottomEdgeY:!0,pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:h.array(tr),strokeWidth:D.optional()}),QH=Be.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({strokeWidth:V,x1:V,y1:V,x2:V,y2:V}),tq=Be.omit({pcbRotation:!0}).extend({filled:h.boolean().default(!0).optional(),stroke:h.enum(["dashed","solid","none"]).optional(),strokeWidth:V.optional(),width:V,height:V,cornerRadius:V.optional()}),eq=Be.omit({pcbRotation:!0}).extend({isFilled:h.boolean().optional(),isOutline:h.boolean().optional(),strokeWidth:V.optional(),radius:V}),jW=h.object({x:V,y:V,via:h.boolean().optional(),toLayer:he.optional()}),nq=h.object({for:h.string().optional().describe("Selector for the port you're targeting, not required if you're inside a trace"),order:h.number().optional(),offset:tr.or(jW).optional(),offsets:h.array(tr).or(h.array(jW)).optional(),traceWidth:h.number().optional()}),cae=Pw.extend({name:h.string(),pinNumber:h.number().optional(),aliases:h.array(h.string()).optional(),direction:j3t,connectsTo:h.string().or(h.array(h.string())).optional()}),iq=Be.extend({text:h.string(),anchorAlignment:h.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:h.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:h.string().optional()});Ct(!0);var rq=Be.omit({pcbRotation:!0}).extend({width:V,height:V,strokeWidth:V.optional(),isFilled:h.boolean().optional(),hasStroke:h.boolean().optional(),isStrokeDashed:h.boolean().optional(),color:h.string().optional(),cornerRadius:V.optional()});Ct(!0);var sq=Be.omit({pcbLeftEdgeX:!0,pcbRightEdgeX:!0,pcbTopEdgeY:!0,pcbBottomEdgeY:!0,pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:h.array(tr),strokeWidth:D.optional(),color:h.string().optional()});Ct(!0);var oq=Be.omit({pcbLeftEdgeX:!0,pcbRightEdgeX:!0,pcbTopEdgeY:!0,pcbBottomEdgeY:!0,pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({x1:V,y1:V,x2:V,y2:V,strokeWidth:V.optional(),color:h.string().optional(),isDashed:h.boolean().optional()});Ct(!0);var BW=h.union([h.string(),$o]),aq=Be.omit({pcbLeftEdgeX:!0,pcbRightEdgeX:!0,pcbTopEdgeY:!0,pcbBottomEdgeY:!0,pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:BW,to:BW,text:h.string().optional(),offset:V.optional(),font:h.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:h.string().optional(),arrowSize:V.optional(),units:h.enum(["in","mm"]).optional(),outerEdgeToEdge:h.literal(!0).optional(),centerToCenter:h.literal(!0).optional(),innerEdgeToEdge:h.literal(!0).optional()});Ct(!0);var cq=h.array(h.any()).describe("Circuit JSON"),b4=h.object({footprintCircuitJson:h.array(h.any()),cadModel:UW.optional()}),YW=h.function().args(h.string()).returns(h.promise(b4)).or(h.function().args(h.string(),h.object({resolvedPcbStyle:v4.optional()}).optional()).returns(h.promise(b4))).describe("A function that takes a path and returns Circuit JSON"),QMt=h.object({loadFromUrl:h.function().args(h.string()).returns(h.promise(b4)).describe("A function that takes a footprint file URL and returns Circuit JSON")}),tCt=h.object({engineVersionString:h.string().optional(),simulationResultCircuitJson:cq}),eCt=h.object({simulate:h.function().args(h.string()).returns(h.promise(tCt)).describe("A function that takes a SPICE string and returns a simulation result")}),nCt=h.custom(n=>typeof n=="string"),XW=h.object({run:h.function().args().returns(h.promise(h.unknown())).describe("Run the autorouter"),getOutputSimpleRouteJson:h.function().args().returns(h.promise(h.any())).describe("Get the resulting SimpleRouteJson")}),iCt=h.object({createAutorouter:h.function().args(h.any(),h.any().optional()).returns(h.union([XW,h.promise(XW)])).describe("Create an autorouter instance")}),rCt=h.object({partsEngine:WW.optional(),autorouter:GW.optional(),autorouterMap:h.record(h.string(),iCt).optional(),registryApiUrl:h.string().optional(),cloudAutorouterUrl:h.string().optional(),projectName:h.string().optional(),projectBaseUrl:h.string().optional(),version:h.string().optional(),url:h.string().optional(),printBoardInformationToSilkscreen:h.boolean().optional(),includeBoardFiles:h.array(h.string()).describe('The board files to automatically build with "tsci build", defaults to ["**/*.circuit.tsx"]. Can be an array of files or globs').optional(),snapshotsDir:h.string().describe('The directory where snapshots are stored for "tsci snapshot", defaults to "tests/__snapshots__"').optional(),defaultSpiceEngine:nCt.optional(),localCacheEngine:h.any().optional(),pcbDisabled:h.boolean().optional(),schematicDisabled:h.boolean().optional(),partsEngineDisabled:h.boolean().optional(),spiceEngineMap:h.record(h.string(),eCt).optional(),footprintLibraryMap:h.record(h.string(),h.union([YW,h.record(h.string(),h.union([cq,YW]))])).optional(),footprintFileParserMap:h.record(h.string(),QMt).optional(),resolveProjectStaticFileImportUrl:h.function().args(h.string()).returns(h.promise(h.string())).describe("A function that returns a string URL for static files for the project").optional()});Ct(!0);var sCt=rCt,bae=sCt.pick({projectName:!0,projectBaseUrl:!0,version:!0,url:!0,printBoardInformationToSilkscreen:!0,includeBoardFiles:!0,snapshotsDir:!0,defaultSpiceEngine:!0});Ct(!0);wt();Q();wt();wt();wt();Ia();Q();var Wa=Vt(Js(),1);Ia();Q();function Zc(){return new M4}var M4=class n{constructor(){f(this,"index",{});f(this,"array",[])}size(){return this.array.length}empty(){return this.array.length===0}itemAt(e){return this.array[e]}contains(e){return this.index[e.id()]!==void 0}find(e){let t=this.index[e.id()];return t===void 0?void 0:this.array[t]}setDefault(e,t){let i=this.index[e.id()];if(i===void 0){let r=new Tw(e,t());return this.index[e.id()]=this.array.length,this.array.push(r),r}else return this.array[i]}insert(e,t){let i=new Tw(e,t),r=this.index[e.id()];return r===void 0?(this.index[e.id()]=this.array.length,this.array.push(i)):this.array[r]=i,i}erase(e){let t=this.index[e.id()];if(t===void 0)return;this.index[e.id()]=void 0;let i=this.array[t],r=this.array.pop();return i!==r&&(this.array[t]=r,this.index[r.first.id()]=t),i}copy(){let e=new n;for(let t=0;t<this.array.length;t++){let i=this.array[t].copy();e.array[t]=i,e.index[i.first.id()]=t}return e}},Tw=class n{constructor(e,t){f(this,"first");f(this,"second");this.first=e,this.second=t}copy(){return new n(this.first,this.second)}};var Oa=class{constructor(e=""){f(this,"_name");f(this,"_value",0);f(this,"_context",null);f(this,"_id",oCt++);this._name=e}id(){return this._id}name(){return this._name}setName(e){this._name=e}context(){return this._context}setContext(e){this._context=e}value(){return this._value}setValue(e){this._value=e}plus(e){return new Dn(this,e)}minus(e){return new Dn(this,typeof e=="number"?-e:[-1,e])}multiply(e){return new Dn([e,this])}divide(e){return new Dn([1/e,this])}toJSON(){return{name:this._name,value:this._value}}toString(){return this._context+"["+this._name+":"+this._value+"]"}},oCt=0;var Dn=class n{constructor(){f(this,"_terms");f(this,"_constant");let e=aCt(arguments);this._terms=e.terms,this._constant=e.constant}terms(){return this._terms}constant(){return this._constant}value(){let e=this._constant;for(let t=0,i=this._terms.size();t<i;t++){let r=this._terms.itemAt(t);e+=r.first.value()*r.second}return e}plus(e){return new n(this,e)}minus(e){return new n(this,typeof e=="number"?-e:[-1,e])}multiply(e){return new n([e,this])}divide(e){return new n([1/e,this])}isConstant(){return this._terms.size()==0}toString(){let e=this._terms.array.map(function(t){return t.second+"*"+t.first.toString()}).join(" + ");return!this.isConstant()&&this._constant!==0&&(e+=" + "),e+=this._constant,e}};function aCt(n){let e=0,t=()=>0,i=Zc();for(let r=0,s=n.length;r<s;++r){let o=n[r];if(typeof o=="number")e+=o;else if(o instanceof Oa)i.setDefault(o,t).second+=1;else if(o instanceof Dn){e+=o.constant();let a=o.terms();for(let c=0,l=a.size();c<l;c++){let u=a.itemAt(c);i.setDefault(u.first,t).second+=u.second}}else if(o instanceof Array){if(o.length!==2)throw new Error("array must have length 2");let a=o[0],c=o[1];if(typeof a!="number")throw new Error("array item 0 must be a number");if(c instanceof Oa)i.setDefault(c,t).second+=a;else if(c instanceof Dn){e+=c.constant()*a;let l=c.terms();for(let u=0,p=l.size();u<p;u++){let d=l.itemAt(u);i.setDefault(d.first,t).second+=d.second*a}}else throw new Error("array item 1 must be a variable or expression")}else throw new Error("invalid Expression argument: "+o)}return{terms:i,constant:e}}var ao=class ao{static create(e,t,i,r=1){let s=0;return s+=Math.max(0,Math.min(1e3,e*r))*1e6,s+=Math.max(0,Math.min(1e3,t*r))*1e3,s+=Math.max(0,Math.min(1e3,i*r)),s}static clip(e){return Math.max(0,Math.min(ao.required,e))}};f(ao,"required",ao.create(1e3,1e3,1e3)),f(ao,"strong",ao.create(1,0,0)),f(ao,"medium",ao.create(0,1,0)),f(ao,"weak",ao.create(0,0,1));var On=ao;var ai;(function(n){n[n.Le=0]="Le",n[n.Ge=1]="Ge",n[n.Eq=2]="Eq"})(ai||(ai={}));var ki=class{constructor(e,t,i,r=On.required){f(this,"_expression");f(this,"_operator");f(this,"_strength");f(this,"_id",cCt++);this._operator=t,this._strength=On.clip(r),i===void 0&&e instanceof Dn?this._expression=e:this._expression=e.minus(i)}id(){return this._id}expression(){return this._expression}op(){return this._operator}strength(){return this._strength}toString(){return this._expression.toString()+" "+["<=",">=","="][this._operator]+" 0 ("+this._strength.toString()+")"}},cCt=0;var a_=class{constructor(){f(this,"maxIterations",1e3);f(this,"_cnMap",lCt());f(this,"_rowMap",uCt());f(this,"_varMap",pCt());f(this,"_editMap",hCt());f(this,"_infeasibleRows",[]);f(this,"_objective",new Cw);f(this,"_artificial",null);f(this,"_idTick",0)}createConstraint(e,t,i,r=On.required){let s=new ki(e,t,i,r);return this.addConstraint(s),s}addConstraint(e){if(this._cnMap.find(e)!==void 0)throw new Error("duplicate constraint");let i=this._createRow(e),r=i.row,s=i.tag,o=this._chooseSubject(r,s);if(o.type()===rn.Invalid&&r.allDummies())if(Ew(r.constant()))o=s.marker;else throw new Error("unsatisfiable constraint");if(o.type()===rn.Invalid){if(!this._addWithArtificialVariable(r))throw new Error("unsatisfiable constraint")}else r.solveFor(o),this._substitute(o,r),this._rowMap.insert(o,r);this._cnMap.insert(e,s),this._optimize(this._objective)}removeConstraint(e){let t=this._cnMap.erase(e);if(t===void 0)throw new Error("unknown constraint");this._removeConstraintEffects(e,t.second);let i=t.second.marker,r=this._rowMap.erase(i);if(r===void 0){let s=this._getMarkerLeavingSymbol(i);if(s.type()===rn.Invalid)throw new Error("failed to find leaving row");r=this._rowMap.erase(s),r.second.solveForEx(s,i),this._substitute(i,r.second)}this._optimize(this._objective)}hasConstraint(e){return this._cnMap.contains(e)}getConstraints(){return this._cnMap.array.map(({first:e})=>e)}addEditVariable(e,t){if(this._editMap.find(e)!==void 0)throw new Error("duplicate edit variable");if(t=On.clip(t),t===On.required)throw new Error("bad required strength");let r=new Dn(e),s=new ki(r,ai.Eq,void 0,t);this.addConstraint(s);let a={tag:this._cnMap.find(s).second,constraint:s,constant:0};this._editMap.insert(e,a)}removeEditVariable(e){let t=this._editMap.erase(e);if(t===void 0)throw new Error("unknown edit variable");this.removeConstraint(t.second.constraint)}hasEditVariable(e){return this._editMap.contains(e)}suggestValue(e,t){let i=this._editMap.find(e);if(i===void 0)throw new Error("unknown edit variable");let r=this._rowMap,s=i.second,o=t-s.constant;s.constant=t;let a=s.tag.marker,c=r.find(a);if(c!==void 0){c.second.add(-o)<0&&this._infeasibleRows.push(a),this._dualOptimize();return}let l=s.tag.other;if(c=r.find(l),c!==void 0){c.second.add(o)<0&&this._infeasibleRows.push(l),this._dualOptimize();return}for(let u=0,p=r.size();u<p;++u){let d=r.itemAt(u),_=d.second,g=_.coefficientFor(a);g!==0&&_.add(o*g)<0&&d.first.type()!==rn.External&&this._infeasibleRows.push(d.first)}this._dualOptimize()}updateVariables(){let e=this._varMap,t=this._rowMap;for(let i=0,r=e.size();i<r;++i){let s=e.itemAt(i),o=t.find(s.second);o!==void 0?s.first.setValue(o.second.constant()):s.first.setValue(0)}}_getVarSymbol(e){let t=()=>this._makeSymbol(rn.External);return this._varMap.setDefault(e,t).second}_createRow(e){let t=e.expression(),i=new Cw(t.constant()),r=t.terms();for(let c=0,l=r.size();c<l;++c){let u=r.itemAt(c);if(!Ew(u.second)){let p=this._getVarSymbol(u.first),d=this._rowMap.find(p);d!==void 0?i.insertRow(d.second,u.second):i.insertSymbol(p,u.second)}}let s=this._objective,o=e.strength(),a={marker:Kc,other:Kc};switch(e.op()){case ai.Le:case ai.Ge:{let c=e.op()===ai.Le?1:-1,l=this._makeSymbol(rn.Slack);if(a.marker=l,i.insertSymbol(l,c),o<On.required){let u=this._makeSymbol(rn.Error);a.other=u,i.insertSymbol(u,-c),s.insertSymbol(u,o)}break}case ai.Eq:{if(o<On.required){let c=this._makeSymbol(rn.Error),l=this._makeSymbol(rn.Error);a.marker=c,a.other=l,i.insertSymbol(c,-1),i.insertSymbol(l,1),s.insertSymbol(c,o),s.insertSymbol(l,o)}else{let c=this._makeSymbol(rn.Dummy);a.marker=c,i.insertSymbol(c)}break}}return i.constant()<0&&i.reverseSign(),{row:i,tag:a}}_chooseSubject(e,t){let i=e.cells();for(let s=0,o=i.size();s<o;++s){let a=i.itemAt(s);if(a.first.type()===rn.External)return a.first}let r=t.marker.type();return(r===rn.Slack||r===rn.Error)&&e.coefficientFor(t.marker)<0?t.marker:(r=t.other.type(),(r===rn.Slack||r===rn.Error)&&e.coefficientFor(t.other)<0?t.other:Kc)}_addWithArtificialVariable(e){let t=this._makeSymbol(rn.Slack);this._rowMap.insert(t,e.copy()),this._artificial=e.copy(),this._optimize(this._artificial);let i=Ew(this._artificial.constant());this._artificial=null;let r=this._rowMap.erase(t);if(r!==void 0){let o=r.second;if(o.isConstant())return i;let a=this._anyPivotableSymbol(o);if(a.type()===rn.Invalid)return!1;o.solveForEx(t,a),this._substitute(a,o),this._rowMap.insert(a,o)}let s=this._rowMap;for(let o=0,a=s.size();o<a;++o)s.itemAt(o).second.removeSymbol(t);return this._objective.removeSymbol(t),i}_substitute(e,t){let i=this._rowMap;for(let r=0,s=i.size();r<s;++r){let o=i.itemAt(r);o.second.substitute(e,t),o.second.constant()<0&&o.first.type()!==rn.External&&this._infeasibleRows.push(o.first)}this._objective.substitute(e,t),this._artificial&&this._artificial.substitute(e,t)}_optimize(e){let t=0;for(;t<this.maxIterations;){let i=this._getEnteringSymbol(e);if(i.type()===rn.Invalid)return;let r=this._getLeavingSymbol(i);if(r.type()===rn.Invalid)throw new Error("the objective is unbounded");let s=this._rowMap.erase(r).second;s.solveForEx(r,i),this._substitute(i,s),this._rowMap.insert(i,s),t++}throw new Error("solver iterations exceeded")}_dualOptimize(){let e=this._rowMap,t=this._infeasibleRows;for(;t.length!==0;){let i=t.pop(),r=e.find(i);if(r!==void 0&&r.second.constant()<0){let s=this._getDualEnteringSymbol(r.second);if(s.type()===rn.Invalid)throw new Error("dual optimize failed");let o=r.second;e.erase(i),o.solveForEx(i,s),this._substitute(s,o),e.insert(s,o)}}}_getEnteringSymbol(e){let t=e.cells();for(let i=0,r=t.size();i<r;++i){let s=t.itemAt(i),o=s.first;if(s.second<0&&o.type()!==rn.Dummy)return o}return Kc}_getDualEnteringSymbol(e){let t=Number.MAX_VALUE,i=Kc,r=e.cells();for(let s=0,o=r.size();s<o;++s){let a=r.itemAt(s),c=a.first,l=a.second;if(l>0&&c.type()!==rn.Dummy){let p=this._objective.coefficientFor(c)/l;p<t&&(t=p,i=c)}}return i}_getLeavingSymbol(e){let t=Number.MAX_VALUE,i=Kc,r=this._rowMap;for(let s=0,o=r.size();s<o;++s){let a=r.itemAt(s),c=a.first;if(c.type()!==rn.External){let l=a.second,u=l.coefficientFor(e);if(u<0){let p=-l.constant()/u;p<t&&(t=p,i=c)}}}return i}_getMarkerLeavingSymbol(e){let t=Number.MAX_VALUE,i=t,r=t,s=Kc,o=s,a=s,c=s,l=this._rowMap;for(let u=0,p=l.size();u<p;++u){let d=l.itemAt(u),_=d.second,g=_.coefficientFor(e);if(g===0)continue;let x=d.first;if(x.type()===rn.External)c=x;else if(g<0){let v=-_.constant()/g;v<i&&(i=v,o=x)}else{let v=_.constant()/g;v<r&&(r=v,a=x)}}return o!==s?o:a!==s?a:c}_removeConstraintEffects(e,t){t.marker.type()===rn.Error&&this._removeMarkerEffects(t.marker,e.strength()),t.other.type()===rn.Error&&this._removeMarkerEffects(t.other,e.strength())}_removeMarkerEffects(e,t){let i=this._rowMap.find(e);i!==void 0?this._objective.insertRow(i.second,-t):this._objective.insertSymbol(e,-t)}_anyPivotableSymbol(e){let t=e.cells();for(let i=0,r=t.size();i<r;++i){let s=t.itemAt(i),o=s.first.type();if(o===rn.Slack||o===rn.Error)return s.first}return Kc}_makeSymbol(e){return new Mw(e,this._idTick++)}};function Ew(n){let e=1e-8;return n<0?-n<e:n<e}function lCt(){return Zc()}function uCt(){return Zc()}function pCt(){return Zc()}function hCt(){return Zc()}var rn;(function(n){n[n.Invalid=0]="Invalid",n[n.External=1]="External",n[n.Slack=2]="Slack",n[n.Error=3]="Error",n[n.Dummy=4]="Dummy"})(rn||(rn={}));var Mw=class{constructor(e,t){f(this,"_id");f(this,"_type");this._id=t,this._type=e}id(){return this._id}type(){return this._type}},Kc=new Mw(rn.Invalid,-1),Cw=class n{constructor(e=0){f(this,"_cellMap",Zc());f(this,"_constant");this._constant=e}cells(){return this._cellMap}constant(){return this._constant}isConstant(){return this._cellMap.empty()}allDummies(){let e=this._cellMap;for(let t=0,i=e.size();t<i;++t)if(e.itemAt(t).first.type()!==rn.Dummy)return!1;return!0}copy(){let e=new n(this._constant);return e._cellMap=this._cellMap.copy(),e}add(e){return this._constant+=e}insertSymbol(e,t=1){let i=this._cellMap.setDefault(e,()=>0);Ew(i.second+=t)&&this._cellMap.erase(e)}insertRow(e,t=1){this._constant+=e._constant*t;let i=e._cellMap;for(let r=0,s=i.size();r<s;++r){let o=i.itemAt(r);this.insertSymbol(o.first,o.second*t)}}removeSymbol(e){this._cellMap.erase(e)}reverseSign(){this._constant=-this._constant;let e=this._cellMap;for(let t=0,i=e.size();t<i;++t){let r=e.itemAt(t);r.second=-r.second}}solveFor(e){let t=this._cellMap,r=-1/t.erase(e).second;this._constant*=r;for(let s=0,o=t.size();s<o;++s)t.itemAt(s).second*=r}solveForEx(e,t){this.insertSymbol(e,-1),this.solveFor(t)}coefficientFor(e){let t=this._cellMap.find(e);return t!==void 0?t.second:0}substitute(e,t){let i=this._cellMap.erase(e);i!==void 0&&this.insertRow(t,i.second)}};var Mnt=Vt(In(),1);Q();wt();wt();ir();var R4={};$c(R4,{areBoundsCompletelyInsidePolygon:()=>A4,areBoundsOverlappingPolygon:()=>N4,boundsAreaOverlap:()=>vq,boundsDistance:()=>wq,boundsIntersection:()=>Sq,clamp:()=>Wn,computeDistanceBetweenBoxes:()=>Fo,computeGapBetweenBoxes:()=>_4,computeManhattanDistanceBetweenBoxes:()=>Ng,distSq:()=>fq,distance:()=>zi,doBoundsOverlap:()=>Jc,doSegmentsIntersect:()=>Ti,doesLineIntersectLine:()=>La,doesSegmentIntersectRect:()=>C4,findNearestPointsBetweenBoxSets:()=>Ag,getBoundingBox:()=>so,getBoundsFromPoints:()=>co,getSegmentIntersection:()=>pd,getUnitVectorFromDirection:()=>Ow,getUnitVectorFromPointAToB:()=>Rw,grid:()=>Pq,isPointInsidePolygon:()=>Aw,isRectCompletelyInsidePolygon:()=>xq,isRectOverlappingPolygon:()=>gq,midpoint:()=>dq,normalizeDegrees:()=>hd,onSegment:()=>ud,orientation:()=>ld,pointToBoundsDistance:()=>hq,pointToBoxDistance:()=>pq,pointToSegmentClosestPoint:()=>uq,pointToSegmentDistance:()=>gi,range:()=>bq,segmentToBoundsMinDistance:()=>$g,segmentToBoxMinDistance:()=>Iw,segmentToCircleMinDistance:()=>Nw,segmentToSegmentMinDistance:()=>c_});function La([n,e],[t,i],{lineThickness:r=0}={}){return r===0?Ti(n,e,t,i):dCt(n,e,t,i)<=r}function Ti(n,e,t,i){let r=ld(n,e,t),s=ld(n,e,i),o=ld(t,i,n),a=ld(t,i,e);return!!(r!==s&&o!==a||r===0&&ud(n,t,e)||s===0&&ud(n,i,e)||o===0&&ud(t,n,i)||a===0&&ud(t,e,i))}function ld(n,e,t){let i=(e.y-n.y)*(t.x-e.x)-(e.x-n.x)*(t.y-e.y);return i===0?0:i>0?1:2}function ud(n,e,t){return e.x<=Math.max(n.x,t.x)&&e.x>=Math.min(n.x,t.x)&&e.y<=Math.max(n.y,t.y)&&e.y>=Math.min(n.y,t.y)}function dCt(n,e,t,i){if(n.x===e.x&&n.y===e.y)return gi(n,t,i);if(t.x===i.x&&t.y===i.y)return gi(t,n,e);if(Ti(n,e,t,i))return 0;let r=[gi(n,t,i),gi(e,t,i),gi(t,n,e),gi(i,n,e)];return Math.min(...r)}function gi(n,e,t){let i=(t.x-e.x)**2+(t.y-e.y)**2;if(i===0)return zi(n,e);let r=((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/i;r=Math.max(0,Math.min(1,r));let s={x:e.x+r*(t.x-e.x),y:e.y+r*(t.y-e.y)};return zi(n,s)}function zi(n,e){let t=n.x-e.x,i=n.y-e.y;return Math.sqrt(t*t+i*i)}function pd(n,e,t,i){let r=e.x-n.x,s=e.y-n.y,o=i.x-t.x,a=i.y-t.y,c=n.x-t.x,l=n.y-t.y,u=r*a-s*o;if(Math.abs(u)<1e-10)return null;let p=(l*o-c*a)/u,d=(r*l-s*c)/u,_=1e-9;if(p>=-_&&p<=1+_&&d>=-_&&d<=1+_){let g=n.x+p*r,x=n.y+p*s;return{x:g,y:x}}return null}function C4(n,e,t){let i=c=>c.x>=t.minX&&c.x<=t.maxX&&c.y>=t.minY&&c.y<=t.maxY;if(i(n)||i(e))return!0;let r={x:t.minX,y:t.minY},s={x:t.maxX,y:t.minY},o={x:t.minX,y:t.maxY},a={x:t.maxX,y:t.maxY};return Ti(n,e,r,s)||Ti(n,e,s,a)||Ti(n,e,a,o)||Ti(n,e,o,r)}function c_(n,e,t,i){if(n.x===e.x&&n.y===e.y)return gi(n,t,i);if(t.x===i.x&&t.y===i.y)return gi(t,n,e);if(Ti(n,e,t,i))return 0;let r=[gi(n,t,i),gi(e,t,i),gi(t,n,e),gi(i,n,e)];return Math.min(...r)}function $g(n,e,t){let i={x:t.minX,y:t.minY},r={x:t.maxX,y:t.minY},s={x:t.minX,y:t.maxY},o={x:t.maxX,y:t.maxY};if(Ti(n,e,i,r)||Ti(n,e,r,o)||Ti(n,e,o,s)||Ti(n,e,s,i)||n.x>=t.minX&&n.x<=t.maxX&&n.y>=t.minY&&n.y<=t.maxY&&e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)return 0;let a=[gi(i,n,e),gi(r,n,e),gi(s,n,e),gi(o,n,e)];if(n.x>=t.minX&&n.x<=t.maxX&&n.y>=t.minY&&n.y<=t.maxY||e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)return 0;if(n.x<t.minX||n.x>t.maxX||n.y<t.minY||n.y>t.maxY){let c=Wn(n.x,t.minX,t.maxX),l=Wn(n.y,t.minY,t.maxY);a.push(zi(n,{x:c,y:l}))}if(e.x<t.minX||e.x>t.maxX||e.y<t.minY||e.y>t.maxY){let c=Wn(e.x,t.minX,t.maxX),l=Wn(e.y,t.minY,t.maxY);a.push(zi(e,{x:c,y:l}))}return Math.min(...a)}function Iw(n,e,t){let i=t.width/2,r=t.height/2,s={minX:t.center.x-i,maxX:t.center.x+i,minY:t.center.y-r,maxY:t.center.y+r};return $g(n,e,s)}function Nw(n,e,t){let i={x:t.x,y:t.y};if(n.x===e.x&&n.y===e.y)return Math.max(0,zi(n,i)-t.radius);let r={x:e.x-n.x,y:e.y-n.y},s={x:i.x-n.x,y:i.y-n.y},o=r.x*r.x+r.y*r.y,a=Math.max(0,Math.min(1,(r.x*s.x+r.y*s.y)/o)),c={x:n.x+a*r.x,y:n.y+a*r.y},l=zi(c,i);return Math.max(0,l-t.radius)}function uq(n,e,t){let i=t.x-e.x,r=t.y-e.y,s=i*i+r*r;if(s===0)return{x:e.x,y:e.y};let o=((n.x-e.x)*i+(n.y-e.y)*r)/s;return o=Math.max(0,Math.min(1,o)),{x:e.x+o*i,y:e.y+o*r}}function hd(n){return(n%360+360)%360}function pq(n,e){let t=e.width/2,i=e.height/2,r=e.center.x-t,s=e.center.x+t,o=e.center.y-i,a=e.center.y+i;if(n.x>=r&&n.x<=s&&n.y>=o&&n.y<=a)return 0;let c=Wn(n.x,r,s),l=Wn(n.y,o,a);return zi(n,{x:c,y:l})}function hq(n,e){if(n.x>=e.minX&&n.x<=e.maxX&&n.y>=e.minY&&n.y<=e.maxY)return 0;let t=Wn(n.x,e.minX,e.maxX),i=Wn(n.y,e.minY,e.maxY);return zi(n,{x:t,y:i})}function dq(n,e){return{x:(n.x+e.x)/2,y:(n.y+e.y)/2}}function fq(n,e){let t=n.x-e.x,i=n.y-e.y;return t*t+i*i}var mq=n=>{if("minX"in n)return n;let e=n.width/2,t=n.height/2;return{minX:n.center.x-e,minY:n.center.y-t,maxX:n.center.x+e,maxY:n.center.y+t}},I4=n=>[{x:n.minX,y:n.minY},{x:n.maxX,y:n.minY},{x:n.maxX,y:n.maxY},{x:n.minX,y:n.maxY}],_q=n=>{let e=[];for(let t=0;t<n.length;t++){let i=n[t],r=n[(t+1)%n.length];e.push([i,r])}return e},fCt=(n,e,t)=>{let i=(n.y-e.y)*(t.x-e.x)-(n.x-e.x)*(t.y-e.y);if(Math.abs(i)>1e-9)return!1;let r=(n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y);if(r<0)return!1;let s=(t.x-e.x)**2+(t.y-e.y)**2;return!(r>s)},mCt=(n,e)=>n.x>=e.minX&&n.x<=e.maxX&&n.y>=e.minY&&n.y<=e.maxY,Aw=(n,e)=>{if(e.length<3)return!1;let t=_q(e);for(let[r,s]of t)if(fCt(n,r,s))return!0;let i=!1;for(let r=0,s=e.length-1;r<e.length;s=r++){let o=e[r].x,a=e[r].y,c=e[s].x,l=e[s].y;a>n.y!=l>n.y&&n.x<(c-o)*(n.y-a)/(l-a)+o&&(i=!i)}return i},yq=(n,e)=>{let t=I4(n),i=[[t[0],t[1]],[t[1],t[2]],[t[2],t[3]],[t[3],t[0]]],r=_q(e);for(let[s,o]of r)for(let[a,c]of i)if(Ti(s,o,a,c))return!0;return!1},N4=(n,e)=>e.length<3?!1:e.some(i=>mCt(i,n))||I4(n).some(i=>Aw(i,e))?!0:yq(n,e),A4=(n,e)=>e.length<3||!I4(n).every(i=>Aw(i,e))?!1:!yq(n,e),gq=(n,e)=>N4(mq(n),e),xq=(n,e)=>A4(mq(n),e);function bq(n,e,t=1){if(t===0)throw new Error("step cannot be 0");let i,r;e===void 0?(i=0,r=n):(i=n,r=e);let s=[];if(t>0)for(let o=i;o<r;o+=t)s.push(o);else for(let o=i;o>r;o+=t)s.push(o);return s}var vq=(n,e)=>{let t=Math.max(0,Math.min(n.maxX,e.maxX)-Math.max(n.minX,e.minX)),i=Math.max(0,Math.min(n.maxY,e.maxY)-Math.max(n.minY,e.minY));return t*i};var wq=(n,e)=>{let t=n.maxX<e.minX?e.minX-n.maxX:e.maxX<n.minX?n.minX-e.maxX:0,i=n.maxY<e.minY?e.minY-n.maxY:e.maxY<n.minY?n.minY-e.maxY:0;return Math.sqrt(t*t+i*i)};var Sq=(n,e)=>{let t=Math.max(n.minX,e.minX),i=Math.max(n.minY,e.minY),r=Math.min(n.maxX,e.maxX),s=Math.min(n.maxY,e.maxY);return t>r||i>s?null:{minX:t,minY:i,maxX:r,maxY:s}};var Jc=(n,e)=>!(n.maxX<e.minX||e.maxX<n.minX||n.maxY<e.minY||e.maxY<n.minY);var co=n=>{if(n.length===0)return null;let e=n[0].x,t=n[0].y,i=n[0].x,r=n[0].y;for(let s=1;s<n.length;s++){let o=n[s];o.x<e&&(e=o.x),o.y<t&&(t=o.y),o.x>i&&(i=o.x),o.y>r&&(r=o.y)}return{minX:e,minY:t,maxX:i,maxY:r}};var Rw=(n,e)=>{let t={x:e.x-n.x,y:e.y-n.y},i=Math.sqrt(t.x**2+t.y**2);return{x:t.x/i,y:t.y/i}},Ow=n=>{switch(n){case"up":return{x:0,y:1};case"down":return{x:0,y:-1};case"left":return{x:-1,y:0};case"right":return{x:1,y:0}}};function Pq({rows:n,cols:e,xSpacing:t,ySpacing:i,width:r,height:s,offsetX:o=0,offsetY:a=0,yDirection:c="cartesian",centered:l=!0}){let u=t??1,p=i??1,d=r??e*u,_=s??n*p,g=l?-d/2:0,x=l?-_/2:0,v=r?r/e:u,S=s?s/n:p,P=[];for(let T=0;T<n;T++)for(let k=0;k<e;k++){let N=T*e+k,E=o+g+k*v+v/2,C=a+T*S+S/2,M=c==="cartesian"?a+x+(n-1-T)*S+S/2:a+x+T*S+S/2;P.push({index:N,center:{x:E,y:M},topLeft:{x:E-v/2,y:M+S/2},bottomRight:{x:E+v/2,y:M-S/2},row:T,col:k})}return P}wt();zg();var kq={name:"@tscircuit/capacity-autorouter",main:"./dist/index.js",version:"0.0.140",type:"module",files:["dist"],scripts:{start:"cosmos",build:"tsup ./lib/index.ts --minify terser --external @tscircuit/core --external circuit-to-svg --format esm --dts --sourcemap",bench:"bun test tests/spatial-index-bench.test.ts",format:"biome format --write .","format:check":"biome format .","vercel-build":"cosmos-export","repomix:lib":"repomix --ignore 'testing/**,**/TwoRouteHighDensitySolver/**,**/RouteStitchingSolver/**,solvers/CapacitySegmentPointOptimizer/CapacitySegmentPointOptimizer.ts' lib","bug-report":"bun run scripts/download-bug-report.ts","bug-report-with-test":"bun run scripts/create-bug-report-test.ts"},devDependencies:{"@biomejs/biome":"^1.9.4","@radix-ui/react-icons":"^1.3.2","@radix-ui/react-menubar":"^1.1.14","@react-hook/resize-observer":"^2.0.2","@resvg/resvg-js":"^2.6.2","@tscircuit/checks":"^0.0.75","@tscircuit/circuit-json-util":"^0.0.46","@tscircuit/core":"^0.0.337","@tscircuit/math-utils":"^0.0.27","@types/bun":"^1.2.23","@types/fast-json-stable-stringify":"^2.1.2","@types/object-hash":"^3.0.6","@types/rbush":"^4.0.0","@types/react":"^19.0.8","@types/react-dom":"^19.0.3","@vercel/node":"^5.1.7","@vitejs/plugin-react":"^4.3.4","circuit-json-to-connectivity-map":"^0.0.19","circuit-to-svg":"^0.0.220",clsx:"^2.1.1",flatbush:"^4.4.0","graphics-debug":"^0.0.44","looks-same":"9",rbush:"^4.0.1",react:"18","react-cosmos":"^6.2.3","react-cosmos-plugin-vite":"^6.2.0","react-dom":"18","react-konva":"18",recharts:"^2.15.1","tailwind-merge":"^3.2.0",terser:"^5.43.1",tsup:"^8.3.6",typescript:"^5.9.3","use-mouse-matrix-transform":"^1.3.0",vite:"^6.0.11","vite-tsconfig-paths":"^5.1.4"},dependencies:{"fast-json-stable-stringify":"^2.1.0","object-hash":"^3.0.0"}};wt();ir();Ae();var v9=Vt(Js(),1);wt();var Lnt=Vt(In(),1);var uN={};$c(uN,{AssignableViaAutoroutingPipelineSolver:()=>o5t,AutoroutingPipelineSolver:()=>HZ,CapacityMeshSolver:()=>t5t,InMemoryCache:()=>IZ,LocalStorageCache:()=>NZ,calculateOptimalCapacityDepth:()=>oN,convertSrjToGraphicsObject:()=>Kg,getGlobalInMemoryCache:()=>x_,getGlobalLocalStorageCache:()=>AZ,getTunedTotalCapacity1:()=>uo,setupGlobalCaches:()=>Zg});var CZ=Vt(zw(),1),YZ=Vt(zw(),1),VZ=Vt(zw(),1);var yd=(...n)=>{let e={points:[],lines:[],circles:[],rects:[]};return n.forEach((t,i)=>{t&&(t.lines&&(e.lines=[...e.lines||[],...t.lines.map(r=>({...r,step:i}))]),t.points&&(e.points=[...e.points||[],...t.points.map(r=>({...r,step:i}))]),t.circles&&(e.circles=[...e.circles||[],...t.circles.map(r=>({...r,step:i}))]),t.rects&&(e.rects=[...e.rects||[],...t.rects.map(r=>({...r,step:i}))]))}),e},cn=class{constructor(){f(this,"MAX_ITERATIONS",1e3);f(this,"solved",!1);f(this,"failed",!1);f(this,"iterations",0);f(this,"progress",0);f(this,"error",null);f(this,"activeSubSolver");f(this,"failedSubSolvers");f(this,"timeToSolve");f(this,"stats",{});f(this,"cacheHit");f(this,"cacheKey");f(this,"cacheToSolveSpaceTransform")}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(n){throw this.error=`${this.constructor.name} error: ${n}`,console.error(this.error),this.failed=!0,n}!this.solved&&this.iterations>this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,console.error(this.error),this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}solve(){let n=Date.now();for(;!this.solved&&!this.failed;)this.step();let e=Date.now();this.timeToSolve=e-n}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function Dq(n){let e=n.width/2,t=n.height/2;return{minX:n.center.x-e,maxX:n.center.x+e,minY:n.center.y-t,maxY:n.center.y+t}}function nl(n,e,t){return Math.max(e,Math.min(t,n))}function Di(n,e,t,i){let r=Dw(n,e,t),s=Dw(n,e,i),o=Dw(t,i,n),a=Dw(t,i,e);return r!==s&&o!==a||!(r!==0||!jw(n,t,e))||!(s!==0||!jw(n,i,e))||!(o!==0||!jw(t,n,i))||!(a!==0||!jw(t,e,i))}function Dw(n,e,t){let i=(e.y-n.y)*(t.x-e.x)-(e.x-n.x)*(t.y-e.y);return i===0?0:i>0?1:2}function jw(n,e,t){return e.x<=Math.max(n.x,t.x)&&e.x>=Math.min(n.x,t.x)&&e.y<=Math.max(n.y,t.y)&&e.y>=Math.min(n.y,t.y)}function _r(n,e,t){let i=(t.x-e.x)**2+(t.y-e.y)**2;if(i===0)return Qt(n,e);let r=((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/i;return r=Math.max(0,Math.min(1,r)),Qt(n,{x:e.x+r*(t.x-e.x),y:e.y+r*(t.y-e.y)})}function Qt(n,e){let t=n.x-e.x,i=n.y-e.y;return Math.sqrt(t*t+i*i)}function hZ(n,e,t,i){let r=e.x-n.x,s=e.y-n.y,o=i.x-t.x,a=i.y-t.y,c=n.x-t.x,l=n.y-t.y,u=r*a-s*o;if(Math.abs(u)<1e-10)return null;let p=(l*o-c*a)/u,d=(r*l-s*c)/u,_=1e-9;return p>=-1e-9&&p<=1+_&&d>=-1e-9&&d<=1+_?{x:n.x+p*r,y:n.y+p*s}:null}function jq(n,e){return{x:(n.x+e.x)/2,y:(n.y+e.y)/2}}var dZ=n=>{if("minX"in n)return n;let e=n.width/2,t=n.height/2;return{minX:n.center.x-e,minY:n.center.y-t,maxX:n.center.x+e,maxY:n.center.y+t}},sN=n=>[{x:n.minX,y:n.minY},{x:n.maxX,y:n.minY},{x:n.maxX,y:n.maxY},{x:n.minX,y:n.maxY}],fZ=n=>{let e=[];for(let t=0;t<n.length;t++){let i=n[t],r=n[(t+1)%n.length];e.push([i,r])}return e},MCt=(n,e,t)=>{let i=(n.y-e.y)*(t.x-e.x)-(n.x-e.x)*(t.y-e.y);if(Math.abs(i)>1e-9)return!1;let r=(n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y);return r<0?!1:!(r>(t.x-e.x)**2+(t.y-e.y)**2)},mZ=(n,e)=>{if(e.length<3)return!1;let t=fZ(e);for(let[r,s]of t)if(MCt(n,r,s))return!0;let i=!1;for(let r=0,s=e.length-1;r<e.length;s=r++){let o=e[r].x,a=e[r].y,c=e[s].x,l=e[s].y;a>n.y!=l>n.y&&n.x<(c-o)*(n.y-a)/(l-a)+o&&(i=!i)}return i},_Z=(n,e)=>{let t=sN(n),i=[[t[0],t[1]],[t[1],t[2]],[t[2],t[3]],[t[3],t[0]]],r=fZ(e);for(let[s,o]of r)for(let[a,c]of i)if(Di(s,o,a,c))return!0;return!1},H4=(n,e)=>((t,i)=>!(i.length<3)&&(!!i.some(r=>((s,o)=>s.x>=o.minX&&s.x<=o.maxX&&s.y>=o.minY&&s.y<=o.maxY)(r,t))||!!sN(t).some(r=>mZ(r,i))||_Z(t,i)))(dZ(n),e),yZ=(n,e)=>((t,i)=>!(i.length<3)&&!!sN(t).every(r=>mZ(r,i))&&!_Z(t,i))(dZ(n),e);function q4(n,e,t,i){if(n.x===e.x&&n.y===e.y)return _r(n,t,i);if(t.x===i.x&&t.y===i.y)return _r(t,n,e);if(Di(n,e,t,i))return 0;let r=[_r(n,t,i),_r(e,t,i),_r(t,n,e),_r(i,n,e)];return Math.min(...r)}function gZ(n,e,t){let i=t.width/2,r=t.height/2;return(function(s,o,a){let c={x:a.minX,y:a.minY},l={x:a.maxX,y:a.minY},u={x:a.minX,y:a.maxY},p={x:a.maxX,y:a.maxY};if(Di(s,o,c,l)||Di(s,o,l,p)||Di(s,o,p,u)||Di(s,o,u,c)||s.x>=a.minX&&s.x<=a.maxX&&s.y>=a.minY&&s.y<=a.maxY&&o.x>=a.minX&&o.x<=a.maxX&&o.y>=a.minY&&o.y<=a.maxY)return 0;let d=[_r(c,s,o),_r(l,s,o),_r(u,s,o),_r(p,s,o)];if(s.x>=a.minX&&s.x<=a.maxX&&s.y>=a.minY&&s.y<=a.maxY||o.x>=a.minX&&o.x<=a.maxX&&o.y>=a.minY&&o.y<=a.maxY)return 0;if(s.x<a.minX||s.x>a.maxX||s.y<a.minY||s.y>a.maxY){let _=nl(s.x,a.minX,a.maxX),g=nl(s.y,a.minY,a.maxY);d.push(Qt(s,{x:_,y:g}))}if(o.x<a.minX||o.x>a.maxX||o.y<a.minY||o.y>a.maxY){let _=nl(o.x,a.minX,a.maxX),g=nl(o.y,a.minY,a.maxY);d.push(Qt(o,{x:_,y:g}))}return Math.min(...d)})(n,e,{minX:t.center.x-i,maxX:t.center.x+i,minY:t.center.y-r,maxY:t.center.y+r})}function f_(n,e,t){let i=t.x-e.x,r=t.y-e.y,s=i*i+r*r;if(s===0)return{x:e.x,y:e.y};let o=((n.x-e.x)*i+(n.y-e.y)*r)/s;return o=Math.max(0,Math.min(1,o)),{x:e.x+o*i,y:e.y+o*r}}function Xr(){return Xr=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)({}).hasOwnProperty.call(t,i)&&(n[i]=t[i])}return n},Xr.apply(null,arguments)}function eS(n,e){return(eS=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,i){return t.__proto__=i,t})(n,e)}function xZ(n){return(xZ=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(n)}function bZ(){try{var n=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(bZ=function(){return!!n})()}function Z4(n){var e=typeof Map=="function"?new Map:void 0;return Z4=function(t){if(t===null||!(function(r){try{return Function.toString.call(r).indexOf("[native code]")!==-1}catch{return typeof r=="function"}})(t))return t;if(typeof t!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return(function(r,s,o){if(bZ())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,s);var c=new(r.bind.apply(r,a));return o&&eS(c,o.prototype),c})(t,arguments,xZ(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),eS(i,t)},Z4(n)}var Yr=(function(n){var e,t;function i(r){var s;if(1)s=n.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+r+" for more information.")||this;else for(var o,a,c;c<o;c++);return(function(l){if(l===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return l})(s)}return t=n,(e=i).prototype=Object.create(t.prototype),e.prototype.constructor=e,eS(e,t),i})(Z4(Error));function Bq(n,e){return n.substr(-e.length)===e}var CCt=/^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;function Yq(n){return typeof n!="string"?n:n.match(CCt)?parseFloat(n):n}var Xq=function(n){return function(e,t){t===void 0&&(t="16px");var i=e,r=t;if(typeof e=="string"){if(!Bq(e,"px"))throw new Yr(69,n,e);i=Yq(e)}if(typeof t=="string"){if(!Bq(t,"px"))throw new Yr(70,n,t);r=Yq(t)}if(typeof i=="string")throw new Yr(71,e,n);if(typeof r=="string")throw new Yr(72,t,n);return""+i/r+n}};Xq("em"),Xq("rem");function $4(n){return Math.round(255*n)}function ICt(n,e,t){return $4(n)+","+$4(e)+","+$4(t)}function Wg(n,e,t,i){if(i===void 0&&(i=ICt),e===0)return i(t,t,t);var r=(n%360+360)%360/60,s=(1-Math.abs(2*t-1))*e,o=s*(1-Math.abs(r%2-1)),a=0,c=0,l=0;r>=0&&r<1?(a=s,c=o):r>=1&&r<2?(a=o,c=s):r>=2&&r<3?(c=s,l=o):r>=3&&r<4?(c=o,l=s):r>=4&&r<5?(a=o,l=s):r>=5&&r<6&&(a=s,l=o);var u=t-s/2;return i(a+u,c+u,l+u)}var Uq={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},NCt=/^#[a-fA-F0-9]{6}$/,ACt=/^#[a-fA-F0-9]{8}$/,RCt=/^#[a-fA-F0-9]{3}$/,OCt=/^#[a-fA-F0-9]{4}$/,z4=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,LCt=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,FCt=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,$Ct=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function m_(n){if(typeof n!="string")throw new Yr(3);var e=(function(d){if(typeof d!="string")return d;var _=d.toLowerCase();return Uq[_]?"#"+Uq[_]:d})(n);if(e.match(NCt))return{red:parseInt(""+e[1]+e[2],16),green:parseInt(""+e[3]+e[4],16),blue:parseInt(""+e[5]+e[6],16)};if(e.match(ACt)){var t=parseFloat((parseInt(""+e[7]+e[8],16)/255).toFixed(2));return{red:parseInt(""+e[1]+e[2],16),green:parseInt(""+e[3]+e[4],16),blue:parseInt(""+e[5]+e[6],16),alpha:t}}if(e.match(RCt))return{red:parseInt(""+e[1]+e[1],16),green:parseInt(""+e[2]+e[2],16),blue:parseInt(""+e[3]+e[3],16)};if(e.match(OCt)){var i=parseFloat((parseInt(""+e[4]+e[4],16)/255).toFixed(2));return{red:parseInt(""+e[1]+e[1],16),green:parseInt(""+e[2]+e[2],16),blue:parseInt(""+e[3]+e[3],16),alpha:i}}var r=z4.exec(e);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var s=LCt.exec(e.substring(0,50));if(s)return{red:parseInt(""+s[1],10),green:parseInt(""+s[2],10),blue:parseInt(""+s[3],10),alpha:parseFloat(""+s[4])>1?parseFloat(""+s[4])/100:parseFloat(""+s[4])};var o=FCt.exec(e);if(o){var a="rgb("+Wg(parseInt(""+o[1],10),parseInt(""+o[2],10)/100,parseInt(""+o[3],10)/100)+")",c=z4.exec(a);if(!c)throw new Yr(4,e,a);return{red:parseInt(""+c[1],10),green:parseInt(""+c[2],10),blue:parseInt(""+c[3],10)}}var l=$Ct.exec(e.substring(0,50));if(l){var u="rgb("+Wg(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",p=z4.exec(u);if(!p)throw new Yr(4,e,u);return{red:parseInt(""+p[1],10),green:parseInt(""+p[2],10),blue:parseInt(""+p[3],10),alpha:parseFloat(""+l[4])>1?parseFloat(""+l[4])/100:parseFloat(""+l[4])}}throw new Yr(5)}function il(n){return(function(e){var t,i=e.red/255,r=e.green/255,s=e.blue/255,o=Math.max(i,r,s),a=Math.min(i,r,s),c=(o+a)/2;if(o===a)return e.alpha!==void 0?{hue:0,saturation:0,lightness:c,alpha:e.alpha}:{hue:0,saturation:0,lightness:c};var l=o-a,u=c>.5?l/(2-o-a):l/(o+a);switch(o){case i:t=(r-s)/l+(r<s?6:0);break;case r:t=(s-i)/l+2;break;default:t=(i-r)/l+4}return t*=60,e.alpha!==void 0?{hue:t,saturation:u,lightness:c,alpha:e.alpha}:{hue:t,saturation:u,lightness:c}})(m_(n))}var K4=function(n){return n.length===7&&n[1]===n[2]&&n[3]===n[4]&&n[5]===n[6]?"#"+n[1]+n[3]+n[5]:n};function md(n){var e=n.toString(16);return e.length===1?"0"+e:e}function D4(n){return md(Math.round(255*n))}function zCt(n,e,t){return K4("#"+D4(n)+D4(e)+D4(t))}function Bw(n,e,t){return Wg(n,e,t,zCt)}function J4(n,e,t){if(typeof n=="number"&&typeof e=="number"&&typeof t=="number")return K4("#"+md(n)+md(e)+md(t));if(typeof n=="object"&&e===void 0&&t===void 0)return K4("#"+md(n.red)+md(n.green)+md(n.blue));throw new Yr(6)}function lS(n,e,t,i){if(typeof n=="string"&&typeof e=="number"){var r=m_(n);return"rgba("+r.red+","+r.green+","+r.blue+","+e+")"}if(typeof n=="number"&&typeof e=="number"&&typeof t=="number"&&typeof i=="number")return i>=1?J4(n,e,t):"rgba("+n+","+e+","+t+","+i+")";if(typeof n=="object"&&e===void 0&&t===void 0&&i===void 0)return n.alpha>=1?J4(n.red,n.green,n.blue):"rgba("+n.red+","+n.green+","+n.blue+","+n.alpha+")";throw new Yr(7)}function rl(n){if(typeof n!="object")throw new Yr(8);if((function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&typeof e.alpha=="number"})(n))return lS(n);if((function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&(typeof e.alpha!="number"||e.alpha===void 0)})(n))return J4(n);if((function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&typeof e.alpha=="number"})(n))return(function(e,t,i,r){if(typeof e=="number"&&typeof t=="number"&&typeof i=="number"&&typeof r=="number")return r>=1?Bw(e,t,i):"rgba("+Wg(e,t,i)+","+r+")";if(typeof e=="object"&&t===void 0&&i===void 0&&r===void 0)return e.alpha>=1?Bw(e.hue,e.saturation,e.lightness):"rgba("+Wg(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new Yr(2)})(n);if((function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&(typeof e.alpha!="number"||e.alpha===void 0)})(n))return(function(e,t,i){if(typeof e=="number"&&typeof t=="number"&&typeof i=="number")return Bw(e,t,i);if(typeof e=="object"&&t===void 0&&i===void 0)return Bw(e.hue,e.saturation,e.lightness);throw new Yr(1)})(n);throw new Yr(8)}function vZ(n,e,t){return function(){var i=t.concat(Array.prototype.slice.call(arguments));return i.length>=e?n.apply(this,i):vZ(n,e,i)}}function as(n){return vZ(n,n.length,[])}as(function(n,e){if(e==="transparent")return e;var t=il(e);return rl(Xr({},t,{hue:t.hue+parseFloat(n)}))});function g_(n,e,t){return Math.max(n,Math.min(e,t))}as(function(n,e){if(e==="transparent")return e;var t=il(e);return rl(Xr({},t,{lightness:g_(0,1,t.lightness-parseFloat(n))}))});as(function(n,e){if(e==="transparent")return e;var t=il(e);return rl(Xr({},t,{saturation:g_(0,1,t.saturation-parseFloat(n))}))});as(function(n,e){if(e==="transparent")return e;var t=il(e);return rl(Xr({},t,{lightness:g_(0,1,t.lightness+parseFloat(n))}))});var wZ=as(function(n,e,t){if(e==="transparent")return t;if(t==="transparent")return e;if(n===0)return t;var i=m_(e),r=Xr({},i,{alpha:typeof i.alpha=="number"?i.alpha:1}),s=m_(t),o=Xr({},s,{alpha:typeof s.alpha=="number"?s.alpha:1}),a=r.alpha-o.alpha,c=2*parseFloat(n)-1,l=((c*a===-1?c:c+a)/(1+c*a)+1)/2,u=1-l;return lS({red:Math.floor(r.red*l+o.red*u),green:Math.floor(r.green*l+o.green*u),blue:Math.floor(r.blue*l+o.blue*u),alpha:r.alpha*parseFloat(n)+o.alpha*(1-parseFloat(n))})});as(function(n,e){if(e==="transparent")return e;var t=m_(e);return lS(Xr({},t,{alpha:g_(0,1,(100*(typeof t.alpha=="number"?t.alpha:1)+100*parseFloat(n))/100)}))});as(function(n,e){if(e==="transparent")return e;var t=il(e);return rl(Xr({},t,{saturation:g_(0,1,t.saturation+parseFloat(n))}))});as(function(n,e){return e==="transparent"?e:rl(Xr({},il(e),{hue:parseFloat(n)}))});as(function(n,e){return e==="transparent"?e:rl(Xr({},il(e),{lightness:parseFloat(n)}))});as(function(n,e){return e==="transparent"?e:rl(Xr({},il(e),{saturation:parseFloat(n)}))});as(function(n,e){return e==="transparent"?e:wZ(parseFloat(n),"rgb(0, 0, 0)",e)});as(function(n,e){return e==="transparent"?e:wZ(parseFloat(n),"rgb(255, 255, 255)",e)});var DCt=as(function(n,e){if(e==="transparent")return e;var t=m_(e);return lS(Xr({},t,{alpha:g_(0,1,+(100*(typeof t.alpha=="number"?t.alpha:1)-100*parseFloat(n)).toFixed(2)/100)}))}),Vq=["blue","orange","purple","cyan","magenta","yellowgreen","darkgoldenrod","deeppink"],Hg=(n,e)=>{let t={};for(let i=0;i<n.connections.length;i++){let r=n.connections[i],s=e?.getNetConnectedToId(r.name);s&&!t[s]&&(t[s]=`hsl(${300*i/n.connections.length}, 100%, 50%)`),t[r.name]=(s?t[s]:null)??`hsl(${340*i/n.connections.length}, 100%, 50%)`}return t},Jn=(n,e)=>{try{return DCt(e,n)}catch(t){return console.error(t),n}},gd=(n,e)=>n==="top"?0:n==="bottom"?e-1:parseInt(n.slice(5)),uo=(n,e=1)=>{let t=(("width"in n?n.width:n)/.5/2)**1.1*e;return n.availableZ?.length===1&&t>1?1:t},oN=(n,e=.5,t=16)=>{let i=0,r=n;for(;i<t&&!(uo({width:r})<=e);)r/=2,i++;return Math.max(1,i)};function SZ(n,e,t=0,i=n.length-1,r=jCt){for(;i>t;){if(i-t>600){let c=i-t+1,l=e-t+1,u=Math.log(c),p=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*p*(c-p)/c)*(l-c/2<0?-1:1);SZ(n,e,Math.max(t,Math.floor(e-l*p/c+d)),Math.min(i,Math.floor(e+(c-l)*p/c+d)),r)}let s=n[e],o=t,a=i;for(jg(n,t,e),r(n[i],s)>0&&jg(n,t,i);o<a;){for(jg(n,o,a),o++,a--;r(n[o],s)<0;)o++;for(;r(n[a],s)>0;)a--}r(n[t],s)===0?jg(n,t,a):(a++,jg(n,a,i)),a<=e&&(t=a+1),e<=a&&(i=a-1)}}function jg(n,e,t){let i=n[e];n[e]=n[t],n[t]=i}function jCt(n,e){return n<e?-1:n>e?1:0}var BCt=class{constructor(n=9){this._maxEntries=Math.max(4,n),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(n){let e=this.data,t=[];if(!Xw(n,e))return t;let i=this.toBBox,r=[];for(;e;){for(let s=0;s<e.children.length;s++){let o=e.children[s],a=e.leaf?i(o):o;Xw(n,a)&&(e.leaf?t.push(o):B4(n,a)?this._all(o,t):r.push(o))}e=r.pop()}return t}collides(n){let e=this.data;if(!Xw(n,e))return!1;let t=[];for(;e;){for(let i=0;i<e.children.length;i++){let r=e.children[i],s=e.leaf?this.toBBox(r):r;if(Xw(n,s)){if(e.leaf||B4(n,s))return!0;t.push(r)}}e=t.pop()}return!1}load(n){if(!n||!n.length)return this;if(n.length<this._minEntries){for(let t=0;t<n.length;t++)this.insert(n[t]);return this}let e=this._build(n.slice(),0,n.length-1,0);if(this.data.children.length)if(this.data.height===e.height)this._splitRoot(this.data,e);else{if(this.data.height<e.height){let t=this.data;this.data=e,e=t}this._insert(e,this.data.height-e.height-1,!0)}else this.data=e;return this}insert(n){return n&&this._insert(n,this.data.height-1),this}clear(){return this.data=h_([]),this}remove(n,e){if(!n)return this;let t=this.data,i=this.toBBox(n),r=[],s=[],o,a,c;for(;t||r.length;){if(t||(t=r.pop(),a=r[r.length-1],o=s.pop(),c=!0),t.leaf){let l=YCt(n,t.children,e);if(l!==-1)return t.children.splice(l,1),r.push(t),this._condense(r),this}c||t.leaf||!B4(t,i)?a?(o++,t=a.children[o],c=!1):t=null:(r.push(t),s.push(o),o=0,a=t,t=t.children[0])}return this}toBBox(n){return n}compareMinX(n,e){return n.minX-e.minX}compareMinY(n,e){return n.minY-e.minY}toJSON(){return this.data}fromJSON(n){return this.data=n,this}_all(n,e){let t=[];for(;n;)n.leaf?e.push(...n.children):t.push(...n.children),n=t.pop();return e}_build(n,e,t,i){let r=t-e+1,s,o=this._maxEntries;if(r<=o)return s=h_(n.slice(e,t+1)),p_(s,this.toBBox),s;i||(i=Math.ceil(Math.log(r)/Math.log(o)),o=Math.ceil(r/Math.pow(o,i-1))),s=h_([]),s.leaf=!1,s.height=i;let a=Math.ceil(r/o),c=a*Math.ceil(Math.sqrt(o));Gq(n,e,t,c,this.compareMinX);for(let l=e;l<=t;l+=c){let u=Math.min(l+c-1,t);Gq(n,l,u,a,this.compareMinY);for(let p=l;p<=u;p+=a){let d=Math.min(p+a-1,u);s.children.push(this._build(n,p,d,i-1))}}return p_(s,this.toBBox),s}_chooseSubtree(n,e,t,i){for(;i.push(e),!e.leaf&&i.length-1!==t;){let r,s=1/0,o=1/0;for(let a=0;a<e.children.length;a++){let c=e.children[a],l=j4(c),u=VCt(n,c)-l;u<o?(o=u,s=l<s?l:s,r=c):u===o&&l<s&&(s=l,r=c)}e=r||e.children[0]}return e}_insert(n,e,t){let i=t?n:this.toBBox(n),r=[],s=this._chooseSubtree(i,this.data,e,r);for(s.children.push(n),Yg(s,i);e>=0&&r[e].children.length>this._maxEntries;)this._split(r,e),e--;this._adjustParentBBoxes(i,r,e)}_split(n,e){let t=n[e],i=t.children.length,r=this._minEntries;this._chooseSplitAxis(t,r,i);let s=this._chooseSplitIndex(t,r,i),o=h_(t.children.splice(s,t.children.length-s));o.height=t.height,o.leaf=t.leaf,p_(t,this.toBBox),p_(o,this.toBBox),e?n[e-1].children.push(o):this._splitRoot(t,o)}_splitRoot(n,e){this.data=h_([n,e]),this.data.height=n.height+1,this.data.leaf=!1,p_(this.data,this.toBBox)}_chooseSplitIndex(n,e,t){let i,r=1/0,s=1/0;for(let o=e;o<=t-e;o++){let a=Bg(n,0,o,this.toBBox),c=Bg(n,o,t,this.toBBox),l=GCt(a,c),u=j4(a)+j4(c);l<r?(r=l,i=o,s=u<s?u:s):l===r&&u<s&&(s=u,i=o)}return i||t-e}_chooseSplitAxis(n,e,t){let i=n.leaf?this.compareMinX:XCt,r=n.leaf?this.compareMinY:UCt;this._allDistMargin(n,e,t,i)<this._allDistMargin(n,e,t,r)&&n.children.sort(i)}_allDistMargin(n,e,t,i){n.children.sort(i);let r=this.toBBox,s=Bg(n,0,e,r),o=Bg(n,t-e,t,r),a=Yw(s)+Yw(o);for(let c=e;c<t-e;c++){let l=n.children[c];Yg(s,n.leaf?r(l):l),a+=Yw(s)}for(let c=t-e-1;c>=e;c--){let l=n.children[c];Yg(o,n.leaf?r(l):l),a+=Yw(o)}return a}_adjustParentBBoxes(n,e,t){for(let i=t;i>=0;i--)Yg(e[i],n)}_condense(n){for(let e,t=n.length-1;t>=0;t--)n[t].children.length===0?t>0?(e=n[t-1].children,e.splice(e.indexOf(n[t]),1)):this.clear():p_(n[t],this.toBBox)}};function YCt(n,e,t){if(!t)return e.indexOf(n);for(let i=0;i<e.length;i++)if(t(n,e[i]))return i;return-1}function p_(n,e){Bg(n,0,n.children.length,e,n)}function Bg(n,e,t,i,r){r||(r=h_(null)),r.minX=1/0,r.minY=1/0,r.maxX=-1/0,r.maxY=-1/0;for(let s=e;s<t;s++){let o=n.children[s];Yg(r,n.leaf?i(o):o)}return r}function Yg(n,e){return n.minX=Math.min(n.minX,e.minX),n.minY=Math.min(n.minY,e.minY),n.maxX=Math.max(n.maxX,e.maxX),n.maxY=Math.max(n.maxY,e.maxY),n}function XCt(n,e){return n.minX-e.minX}function UCt(n,e){return n.minY-e.minY}function j4(n){return(n.maxX-n.minX)*(n.maxY-n.minY)}function Yw(n){return n.maxX-n.minX+(n.maxY-n.minY)}function VCt(n,e){return(Math.max(e.maxX,n.maxX)-Math.min(e.minX,n.minX))*(Math.max(e.maxY,n.maxY)-Math.min(e.minY,n.minY))}function GCt(n,e){let t=Math.max(n.minX,e.minX),i=Math.max(n.minY,e.minY),r=Math.min(n.maxX,e.maxX),s=Math.min(n.maxY,e.maxY);return Math.max(0,r-t)*Math.max(0,s-i)}function B4(n,e){return n.minX<=e.minX&&n.minY<=e.minY&&e.maxX<=n.maxX&&e.maxY<=n.maxY}function Xw(n,e){return e.minX<=n.maxX&&e.minY<=n.maxY&&e.maxX>=n.minX&&e.maxY>=n.minY}function h_(n){return{children:n,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Gq(n,e,t,i,r){let s=[e,t];for(;s.length;){if((t=s.pop())-(e=s.pop())<=i)continue;let o=e+Math.ceil((t-e)/i/2)*i;SZ(n,o,e,t,r),s.push(e,o,o,t)}}var Wq=class{constructor(n=9){f(this,"tree");this.tree=new BCt(n)}insert(n,e,t,i,r){this.tree.insert({minX:e,minY:t,maxX:i,maxY:r,data:n})}bulkLoad(n){let e=n.map(({item:t,minX:i,minY:r,maxX:s,maxY:o})=>({minX:i,minY:r,maxX:s,maxY:o,data:t}));this.tree.load(e)}search(n,e,t,i){return this.tree.search({minX:n,minY:e,maxX:t,maxY:i}).map(r=>r.data)}clear(){this.tree.clear()}},WCt=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(n,e){let t=this.length++;for(;t>0;){let i=t-1>>1,r=this.values[i];if(e>=r)break;this.ids[t]=this.ids[i],this.values[t]=r,t=i}this.ids[t]=n,this.values[t]=e}pop(){if(this.length===0)return;let n=this.ids,e=this.values,t=n[0],i=--this.length;if(i>0){let r=n[i],s=e[i],o=0,a=i>>1;for(;o<a;){let c=1+(o<<1),l=c+1,u=c+(+(l<i)&+(e[l]<e[c]));if(e[u]>=s)break;n[o]=n[u],e[o]=e[u],o=u}n[o]=r,e[o]=s}return t}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){this.ids.length=this.values.length=this.length}},Hq=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],qq=class PZ{static from(e,t=0){if(t%8!=0)throw new Error("byteOffset must be 8-byte aligned.");if(!e||e.byteLength===void 0||e.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[i,r]=new Uint8Array(e,t+0,2);if(i!==251)throw new Error("Data does not appear to be in a Flatbush format.");let s=r>>4;if(s!==3)throw new Error(`Got v${s} data when expected v3.`);let o=Hq[15&r];if(!o)throw new Error("Unrecognized array type.");let[a]=new Uint16Array(e,t+2,1),[c]=new Uint32Array(e,t+4,1);return new PZ(c,a,o,void 0,e,t)}constructor(e,t=16,i=Float64Array,r=ArrayBuffer,s,o=0){if(e===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(e)||e<=0)throw new Error(`Unexpected numItems value: ${e}.`);this.numItems=+e,this.nodeSize=Math.min(Math.max(+t,2),65535),this.byteOffset=o;let a=e,c=a;this._levelBounds=[4*a];do a=Math.ceil(a/this.nodeSize),c+=a,this._levelBounds.push(4*c);while(a!==1);this.ArrayType=i,this.IndexArrayType=c<16384?Uint16Array:Uint32Array;let l=Hq.indexOf(i),u=4*c*i.BYTES_PER_ELEMENT;if(l<0)throw new Error(`Unexpected typed array class: ${i}.`);if(s)this.data=s,this._boxes=new i(s,o+8,4*c),this._indices=new this.IndexArrayType(s,o+8+u,c),this._pos=4*c,this.minX=this._boxes[this._pos-4],this.minY=this._boxes[this._pos-3],this.maxX=this._boxes[this._pos-2],this.maxY=this._boxes[this._pos-1];else{let p=this.data=new r(8+u+c*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new i(p,8,4*c),this._indices=new this.IndexArrayType(p,8+u,c),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(p,0,2).set([251,48+l]),new Uint16Array(p,2,1)[0]=t,new Uint32Array(p,4,1)[0]=e}this._queue=new WCt}add(e,t,i=e,r=t){let s=this._pos>>2,o=this._boxes;return this._indices[s]=s,o[this._pos++]=e,o[this._pos++]=t,o[this._pos++]=i,o[this._pos++]=r,e<this.minX&&(this.minX=e),t<this.minY&&(this.minY=t),i>this.maxX&&(this.maxX=i),r>this.maxY&&(this.maxY=r),s}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let e=this._boxes;if(this.numItems<=this.nodeSize)return e[this._pos++]=this.minX,e[this._pos++]=this.minY,e[this._pos++]=this.maxX,void(e[this._pos++]=this.maxY);let t=this.maxX-this.minX||1,i=this.maxY-this.minY||1,r=new Uint32Array(this.numItems);for(let s=0,o=0;s<this.numItems;s++){let a=e[o++],c=e[o++],l=e[o++],u=e[o++],p=Math.floor(65535*((a+l)/2-this.minX)/t),d=Math.floor(65535*((c+u)/2-this.minY)/i);r[s]=qCt(p,d)}Q4(r,e,this._indices,0,this.numItems-1,this.nodeSize);for(let s=0,o=0;s<this._levelBounds.length-1;s++){let a=this._levelBounds[s];for(;o<a;){let c=o,l=e[o++],u=e[o++],p=e[o++],d=e[o++];for(let _=1;_<this.nodeSize&&o<a;_++)l=Math.min(l,e[o++]),u=Math.min(u,e[o++]),p=Math.max(p,e[o++]),d=Math.max(d,e[o++]);this._indices[this._pos>>2]=c,e[this._pos++]=l,e[this._pos++]=u,e[this._pos++]=p,e[this._pos++]=d}}}search(e,t,i,r,s){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let o=this._boxes.length-4,a=[],c=[];for(;o!==void 0;){let l=Math.min(o+4*this.nodeSize,Zq(o,this._levelBounds));for(let u=o;u<l;u+=4){let p=this._boxes[u];if(i<p)continue;let d=this._boxes[u+1];if(r<d)continue;let _=this._boxes[u+2];if(e>_)continue;let g=this._boxes[u+3];if(t>g)continue;let x=0|this._indices[u>>2];o>=4*this.numItems?a.push(x):(s===void 0||s(x,p,d,_,g))&&c.push(x)}o=a.pop()}return c}neighbors(e,t,i=1/0,r=1/0,s){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let o=this._boxes.length-4,a=this._queue,c=[],l=r*r;t:for(;o!==void 0;){let u=Math.min(o+4*this.nodeSize,Zq(o,this._levelBounds));for(let p=o;p<u;p+=4){let d=0|this._indices[p>>2],_=this._boxes[p],g=this._boxes[p+1],x=this._boxes[p+2],v=this._boxes[p+3],S=e<_?_-e:e>x?e-x:0,P=t<g?g-t:t>v?t-v:0,T=S*S+P*P;T>l||(o>=4*this.numItems?a.push(d<<1,T):(s===void 0||s(d))&&a.push(1+(d<<1),T))}for(;a.length&&1&a.peek();)if(a.peekValue()>l||(c.push(a.pop()>>1),c.length===i))break t;o=a.length?a.pop()>>1:void 0}return a.clear(),c}};function Zq(n,e){let t=0,i=e.length-1;for(;t<i;){let r=t+i>>1;e[r]>n?i=r:t=r+1}return e[t]}function Q4(n,e,t,i,r,s){if(Math.floor(i/s)>=Math.floor(r/s))return;let o=n[i],a=n[i+r>>1],c=n[r],l=c,u=Math.max(o,a);c>u?l=u:u===o?l=Math.max(a,c):u===a&&(l=Math.max(o,c));let p=i-1,d=r+1;for(;;){do p++;while(n[p]<l);do d--;while(n[d]>l);if(p>=d)break;HCt(n,e,t,p,d)}Q4(n,e,t,i,d,s),Q4(n,e,t,d+1,r,s)}function HCt(n,e,t,i,r){let s=n[i];n[i]=n[r],n[r]=s;let o=4*i,a=4*r,c=e[o],l=e[o+1],u=e[o+2],p=e[o+3];e[o]=e[a],e[o+1]=e[a+1],e[o+2]=e[a+2],e[o+3]=e[a+3],e[a]=c,e[a+1]=l,e[a+2]=u,e[a+3]=p;let d=t[i];t[i]=t[r],t[r]=d}function qCt(n,e){let t=n^e,i=65535^t,r=65535^(n|e),s=n&(65535^e),o=t|i>>1,a=t>>1^t,c=r>>1^i&s>>1^r,l=t&r>>1^s>>1^s;t=o,i=a,r=c,s=l,o=t&t>>2^i&i>>2,a=t&i>>2^i&(t^i)>>2,c^=t&r>>2^i&s>>2,l^=i&r>>2^(t^i)&s>>2,t=o,i=a,r=c,s=l,o=t&t>>4^i&i>>4,a=t&i>>4^i&(t^i)>>4,c^=t&r>>4^i&s>>4,l^=i&r>>4^(t^i)&s>>4,t=o,i=a,r=c,s=l,c^=t&r>>8^i&s>>8,l^=i&r>>8^(t^i)&s>>8,t=c^c>>1,i=l^l>>1;let u=n^e,p=i|65535^(u|t);return u=16711935&(u|u<<8),u=252645135&(u|u<<4),u=858993459&(u|u<<2),u=1431655765&(u|u<<1),p=16711935&(p|p<<8),p=252645135&(p|p<<4),p=858993459&(p|p<<2),p=1431655765&(p|p<<1),(p<<1|u)>>>0}var ZCt=class{constructor(n){f(this,"index");f(this,"items",[]);f(this,"currentIndex",0);f(this,"capacity");this.capacity=Math.max(1,n),this.index=new qq(this.capacity)}insert(n,e,t,i,r){if(this.currentIndex>=this.index.numItems)throw new Error("Exceeded initial capacity");this.items[this.currentIndex]=n,this.index.add(e,t,i,r),this.currentIndex++}finish(){this.index.finish()}search(n,e,t,i){return this.index.search(n,e,t,i).map(r=>this.items[r]||null).filter(Boolean)}clear(){this.items=[],this.currentIndex=0,this.index=new qq(this.capacity)}},kZ=class{constructor(n="native",e=[]){f(this,"idx");f(this,"storage",[]);n==="flatbush"?e.length===0?(this.idx=new Wq,n="rbush"):this.idx=new ZCt(e.length):this.idx=n==="rbush"?new Wq:new class{constructor(){f(this,"shi",new KCt(e))}insert(t){}search(t,i,r,s){let o=(t+r)/2,a=(i+s)/2,c=r-t,l=s-i;return this.shi.getNodesInArea(o,a,c,l)}clear(){}},e.forEach(t=>this.insert(t)),n==="flatbush"&&e.length>0&&this.idx.finish?.()}insert(n){this.storage.push(n),this.idx.insert(n,n.center.x-n.width/2,n.center.y-n.height/2,n.center.x+n.width/2,n.center.y+n.height/2)}search(n){return this.idx.search(n.minX,n.minY,n.maxX,n.maxY)}searchArea(n,e,t,i){return this.search({minX:n-t/2,minY:e-i/2,maxX:n+t/2,maxY:e+i/2})}},KCt=class{constructor(n){f(this,"buckets");f(this,"CELL_SIZE",.4);this.obstacles=n,this.buckets=new Map;for(let e=0;e<n.length;e++){let t=n[e],i=t.center.x-t.width/2,r=t.center.y-t.height/2,s=t.center.x+t.width/2,o=t.center.y+t.height/2;for(let a=i;a<=s;a+=this.CELL_SIZE)for(let c=r;c<=o;c+=this.CELL_SIZE){let l=this.getBucketKey(a,c),u=this.buckets.get(l);u?u.push([t,e]):this.buckets.set(l,[[t,e]])}}}getBucketKey(n,e){return`${Math.floor(n/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getNodesInArea(n,e,t,i){let r=[],s=new Set,o=e-i/2,a=n+t/2,c=e+i/2;for(let l=n-t/2;l<=a;l+=this.CELL_SIZE)for(let u=o;u<=c;u+=this.CELL_SIZE){let p=this.getBucketKey(l,u),d=this.buckets.get(p)||[];for(let _ of d)s.has(_[1])||(s.add(_[1]),r.push(_[0]))}return r}},JCt=class{constructor(n){f(this,"buckets");f(this,"CELL_SIZE",5);this.targets=n,this.buckets=new Map;for(let e=0;e<n.length;e++){let t=n[e],i=Math.floor(t.bounds.minX/this.CELL_SIZE)*this.CELL_SIZE,r=Math.floor(t.bounds.minY/this.CELL_SIZE)*this.CELL_SIZE,s=t.bounds.maxX,o=t.bounds.maxY;for(let a=i;a<=s;a+=this.CELL_SIZE)for(let c=r;c<=o;c+=this.CELL_SIZE){let l=this.getBucketKey(a,c),u=this.buckets.get(l);u?u.push([t,e]):this.buckets.set(l,[[t,e]])}}}getBucketKey(n,e){return`${Math.floor(n/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getTargetsInArea(n,e,t,i){let r=[],s=new Set,o=Math.floor((n-t/2)/this.CELL_SIZE)*this.CELL_SIZE,a=Math.floor((e-i/2)/this.CELL_SIZE)*this.CELL_SIZE,c=n+t/2,l=e+i/2;for(let u=o;u<=c;u+=this.CELL_SIZE)for(let p=a;p<=l;p+=this.CELL_SIZE){let d=this.getBucketKey(u,p),_=this.buckets.get(d)||[];for(let g of _)s.has(g[1])||(s.add(g[1]),r.push(g[0]))}return r}},QCt=class extends cn{constructor(e,t={}){super();f(this,"unfinishedNodes");f(this,"finishedNodes");f(this,"nodeToXYOverlappingObstaclesMap");f(this,"layerCount");f(this,"outlinePolygon");f(this,"MAX_DEPTH",4);f(this,"targets");f(this,"targetTree");f(this,"obstacleTree");f(this,"_nextNodeCounter",0);this.srj=e,this.opts=t,this.MAX_DEPTH=t?.capacityDepth??this.MAX_DEPTH,this.MAX_ITERATIONS=1e5,this.layerCount=e.layerCount??2,this.outlinePolygon=e.outline&&e.outline.length>=3?e.outline:void 0;for(let o of e.obstacles)if(!o.zLayers){let a=[];for(let c of o.layers)a.push(gd(c,e.layerCount));o.zLayers=a}let i={x:(e.bounds.minX+e.bounds.maxX)/2,y:(e.bounds.minY+e.bounds.maxY)/2},r={width:e.bounds.maxX-e.bounds.minX,height:e.bounds.maxY-e.bounds.minY},s=Math.max(r.width,r.height);this.unfinishedNodes=[{capacityMeshNodeId:this.getNextNodeId(),center:i,width:s,height:s,layer:"top",availableZ:Array.from({length:this.layerCount},(o,a)=>a),_depth:0,_containsTarget:!0,_containsObstacle:!0,_completelyInsideObstacle:!1}],this.finishedNodes=[],this.nodeToXYOverlappingObstaclesMap=new Map,this.obstacleTree=new kZ("flatbush",this.srj.obstacles),this.targets=this.computeTargets(),this.targetTree=new JCt(this.targets)}computeTargets(){let e=[];for(let t of this.srj.connections)for(let i of t.pointsToConnect){let r=this.obstacleTree.searchArea(i.x,i.y,.01,.01).filter(a=>a.zLayers.some(c=>c===gd(i.layer,this.layerCount))),s={minX:i.x-.005,minY:i.y-.005,maxX:i.x+.005,maxY:i.y+.005};r.length>0&&(s={minX:Math.min(...r.map(a=>a.center.x-a.width/2)),minY:Math.min(...r.map(a=>a.center.y-a.height/2)),maxX:Math.max(...r.map(a=>a.center.x+a.width/2)),maxY:Math.max(...r.map(a=>a.center.y+a.height/2))});let o={...i,connectionName:t.name,availableZ:[gd(i.layer,this.layerCount)],bounds:s};e.push(o)}return e}getNodeBounds(e){let t=e.width/2,i=e.height/2;return{minX:e.center.x-t,maxX:e.center.x+t,minY:e.center.y-i,maxY:e.center.y+i}}getNodeRect(e){return{center:{x:e.center.x,y:e.center.y},width:e.width,height:e.height}}getNextNodeId(){return"cn"+this._nextNodeCounter++}getCapacityFromDepth(e){return(this.MAX_DEPTH-e+1)**2}getTargetIfNodeContainsTarget(e){let t=e.width>4*this.targetTree.CELL_SIZE?this.targets:this.targetTree.getTargetsInArea(e.center.x,e.center.y,e.width,e.height);for(let i of t)if(i.bounds.minX<=e.center.x+e.width/2&&i.bounds.maxX>=e.center.x-e.width/2&&i.bounds.minY<=e.center.y+e.height/2&&i.bounds.maxY>=e.center.y-e.height/2&&i.availableZ.some(r=>e.availableZ.includes(r)))return i;return null}getXYOverlappingObstacles(e){let t=this.nodeToXYOverlappingObstaclesMap.get(e.capacityMeshNodeId);if(t)return t;let i=[],r=this.getNodeBounds(e),s=r.minX,o=r.maxX,a=r.minY,c=r.maxY,l=e._parent?this.getXYOverlappingObstacles(e._parent):this.srj.obstacles;for(let u of l){let p=u.center.x-u.width/2,d=u.center.x+u.width/2,_=u.center.y-u.height/2,g=u.center.y+u.height/2;(o>=p&&s<=d&&c>=_&&a<=g||s>=p&&o<=d&&a>=_&&c<=g||p>=s&&d<=o&&_>=a&&g<=c)&&i.push(u)}return this.nodeToXYOverlappingObstaclesMap.set(e.capacityMeshNodeId,i),i}getXYZOverlappingObstacles(e){let t=this.getXYOverlappingObstacles(e),i=[];for(let r of t)e.availableZ.some(s=>r.zLayers.includes(s))&&i.push(r);return i}doesNodeOverlapObstacle(e){if(this.getXYZOverlappingObstacles(e).length>0)return!0;let t=this.getNodeBounds(e);if(this.outlinePolygon){let i=this.getNodeRect(e);if(!yZ(i,this.outlinePolygon))return!0}return t.minX<this.srj.bounds.minX||t.maxX>this.srj.bounds.maxX||t.minY<this.srj.bounds.minY||t.maxY>this.srj.bounds.maxY}isNodeCompletelyInsideObstacle(e){let t=this.getXYZOverlappingObstacles(e),i=this.getNodeBounds(e);if(this.outlinePolygon){let r=this.getNodeRect(e);if(!H4(r,this.outlinePolygon))return!0}for(let r of t){let s=r.center.x-r.width/2,o=r.center.x+r.width/2,a=r.center.y-r.height/2,c=r.center.y+r.height/2;if(i.minX>=s&&i.maxX<=o&&i.minY>=a&&i.maxY<=c)return!0}return!1}getChildNodes(e){if(e._depth===this.MAX_DEPTH)return[];let t=[],i={width:e.width/2,height:e.height/2},r=[{x:e.center.x-i.width/2,y:e.center.y-i.height/2},{x:e.center.x+i.width/2,y:e.center.y-i.height/2},{x:e.center.x-i.width/2,y:e.center.y+i.height/2},{x:e.center.x+i.width/2,y:e.center.y+i.height/2}];for(let s of r){let o={capacityMeshNodeId:this.getNextNodeId(),center:s,width:i.width,height:i.height,layer:e.layer,availableZ:e.availableZ,_depth:(e._depth??0)+1,_parent:e};o._containsObstacle=this.doesNodeOverlapObstacle(o);let a=this.getTargetIfNodeContainsTarget(o);a&&(o._targetConnectionName=a.connectionName,o.availableZ=a.availableZ,o._containsTarget=!0),o._containsObstacle&&(o._completelyInsideObstacle=this.isNodeCompletelyInsideObstacle(o)),o._completelyInsideObstacle&&!o._containsTarget||t.push(o)}return t}shouldNodeBeXYSubdivided(e){return!(e._depth>=this.MAX_DEPTH)&&(!!e._containsTarget||!(!e._containsObstacle||e._completelyInsideObstacle))}_step(){let e=this.unfinishedNodes.pop();if(!e)return void(this.solved=!0);let t=this.getChildNodes(e),i=[],r=[];for(let s of t){let o=this.shouldNodeBeXYSubdivided(s);o?r.push(s):o||s._containsObstacle?!o&&s._containsTarget&&i.push(s):i.push(s)}this.unfinishedNodes.push(...r),this.finishedNodes.push(...i)}visualize(){let e={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Capacity Mesh Visualization"};if(this.outlinePolygon&&this.outlinePolygon.length>=2){let i=this.outlinePolygon.map(r=>({x:r.x,y:r.y}));i.push({...i[0]}),e.lines.push({points:i,strokeColor:"rgba(0, 136, 255, 0.95)",label:"outline"});for(let r of this.outlinePolygon)e.points.push({x:r.x,y:r.y,color:"rgba(0, 136, 255, 0.95)"})}for(let i of this.srj.obstacles)e.rects.push({center:i.center,width:i.width,height:i.height,fill:i.zLayers?.length===1&&i.zLayers?.includes(1)?"rgba(0,0,255,0.3)":"rgba(255,0,0,0.3)",stroke:"red",label:["obstacle",`z: ${i.zLayers.join(",")}`].join(`
162
162
  `)});let t=[...this.finishedNodes,...this.unfinishedNodes];for(let i of t){let r=Math.min(...i.availableZ),s=this.unfinishedNodes.length>0&&i===this.unfinishedNodes[this.unfinishedNodes.length-1];e.rects.push({center:{x:i.center.x+r*i.width*.05,y:i.center.y-r*i.width*.05},width:Math.max(i.width-2,.8*i.width),height:Math.max(i.height-2,.8*i.height),fill:i._containsObstacle?"rgba(255,0,0,0.1)":{"0,1":"rgba(0,0,0,0.1)",0:"rgba(0,200,200, 0.1)",1:"rgba(0,0,200, 0.1)"}[i.availableZ.join(",")]??"rgba(0,200,200,0.1)",stroke:s?"rgba(255,165,0,0.5)":void 0,label:[i.capacityMeshNodeId,`availableZ: ${i.availableZ.join(",")}`,`target? ${i._containsTarget??!1}`,`obs? ${i._containsObstacle??!1}`,`${i.width.toFixed(2)}x${i.height.toFixed(2)}`,`capacity: ${uo(i).toFixed(2)}`].join(`
@@ -242,15 +242,15 @@ gap_distance=${i.gapDistance}`,color:"rgba(255,0,0,0.8)"})}if(this.outputPackedC
242
242
  ${o.decouplingCapGroupId}`,r.fill=WAt(o.decouplingCapGroupId,.8))}return t}getConstructorParams(){return[this.inputProblem]}computeProgress(){let e=Object.keys(this.inputProblem.chipMap).length||1,t=e-this.queuedChips.length;return Math.min(1,Math.max(0,t/e))}};function qAt(n){let{inputProblem:e,pinIdToStronglyConnectedPins:t}=n,i=new Map,r=new Set,s=!1,o=new Map;for(let[a,c]of Object.entries(e.pinStrongConnMap)){if(!c)continue;s=!0;let l=a.split("-");if(l.length===2&&l[0]&&l[1]){let u=e.chipPinMap[l[0]],p=e.chipPinMap[l[1]];if(u&&p){let d=l[0].split(".")[0],_=l[1].split(".")[0];if(d&&_&&d!==_){let g=`${d}-${_}`,x=`${_}-${d}`;o.has(g)||o.set(g,new Set),o.has(x)||o.set(x,new Set),o.get(g).add(u.side),o.get(x).add(p.side)}}}}if(s)for(let[a,c]of Object.entries(e.netConnMap)){if(!c)continue;let[l,u]=a.split("-");l&&u&&r.add(l)}else for(let[a,c]of Object.entries(e.netConnMap)){if(!c)continue;let[l,u]=a.split("-");if(l&&u){if(!e.chipPinMap[l])continue;let d=l.split(".")[0],_=!0;for(let[g,x]of o.entries()){let[v,S]=g.split("-");if(v===d)for(let[P,T]of Object.entries(e.netConnMap)){if(!T)continue;let[k,N]=P.split("-");if(N===u&&k&&k!==l){let E=e.chipPinMap[k];if(!E)continue;if(k.split(".")[0]===S&&!x.has(E.side)){_=!1;break}}}}if(_)i.set(l,u);else{let g=`${l}_opposite-strong-side-disconnected`;i.set(l,g),r.add(l)}}}for(let[a,c]of Object.entries(e.pinStrongConnMap)){if(!c)continue;let l=a.split("-");if(l.length===2&&l[0]&&l[1]){let u=i.get(l[0])||i.get(l[1]);u?(i.set(l[0],u),i.set(l[1],u)):(i.set(l[0],a),i.set(l[1],a))}}return{pinToNetworkMap:i,filteredPins:r}}var ZAt=n=>{let e=n.flatMap(a=>[a.offset.x-a.size.x/2,a.offset.x+a.size.x/2]),t=n.flatMap(a=>[a.offset.y-a.size.y/2,a.offset.y+a.size.y/2]),i=e.length?Math.min(...e):0,r=e.length?Math.max(...e):0,s=t.length?Math.min(...t):0,o=t.length?Math.max(...t):0;return{minX:i,maxX:r,minY:s,maxY:o}},IQ=.1,KAt=class extends O_{constructor(e){super();f(this,"partitionInputProblem");f(this,"layout",null);f(this,"pinIdToStronglyConnectedPins");this.partitionInputProblem=e.partitionInputProblem,this.pinIdToStronglyConnectedPins=e.pinIdToStronglyConnectedPins}_step(){if(!this.activeSubSolver){let e=this.createPackInput();this.activeSubSolver=new P1(e),this.activeSubSolver=this.activeSubSolver}if(this.activeSubSolver.step(),this.activeSubSolver.failed){this.failed=!0,this.error=`PackSolver2 failed: ${this.activeSubSolver.error}`;return}this.activeSubSolver.solved&&(this.layout=this.createLayoutFromPackingResult(this.activeSubSolver.packedComponents),this.solved=!0,this.activeSubSolver=null)}createPackInput(){let e=qAt({inputProblem:this.partitionInputProblem,pinIdToStronglyConnectedPins:this.pinIdToStronglyConnectedPins}).pinToNetworkMap,t=Object.entries(this.partitionInputProblem.chipMap).map(([r,s])=>{let o=[];for(let l of s.pins){let u=this.partitionInputProblem.chipPinMap[l];if(!u)continue;let p=e.get(l)||`${l}_isolated`;o.push({padId:l,networkId:p,type:"rect",offset:{x:u.offset.x,y:u.offset.y},size:{x:IQ,y:IQ}})}let a=ZAt(o),c={x:a.maxX-a.minX,y:a.maxY-a.minY};return o.push({padId:`${r}_body`,networkId:`${r}_body_disconnected`,type:"rect",offset:{x:0,y:0},size:{x:Math.max(c.x,s.size.x),y:Math.max(c.y,s.size.y)}}),{componentId:r,pads:o,availableRotationDegrees:s.availableRotations||[0,90,180,270]}}),i=this.partitionInputProblem.chipGap;return this.partitionInputProblem.partitionType==="decoupling_caps"&&(i=this.partitionInputProblem.decouplingCapsGap??i),{components:t,minGap:i,packOrderStrategy:"largest_to_smallest",packPlacementStrategy:"minimum_closest_sum_squared_distance"}}createLayoutFromPackingResult(e){let t={};for(let i of e){let r=i.componentId;t[r]={x:i.center.x,y:i.center.y,ccwRotationDegrees:i.ccwRotationOffset||i.ccwRotationDegrees||0}}return{chipPlacements:t,groupPlacements:{}}}visualize(){if(this.activeSubSolver&&!this.solved)return this.activeSubSolver.visualize();if(!this.layout){let e=DS(this.partitionInputProblem);return R_(this.partitionInputProblem,e)}return R_(this.partitionInputProblem,this.layout)}getConstructorParams(){return[this.partitionInputProblem]}},JAt=class extends O_{constructor(e){super();f(this,"partitions");f(this,"packedPartitions",[]);f(this,"completedSolvers",[]);f(this,"activeSolver",null);f(this,"currentPartitionIndex",0);f(this,"pinIdToStronglyConnectedPins");this.partitions=e.partitions,this.pinIdToStronglyConnectedPins=e.pinIdToStronglyConnectedPins}_step(){if(this.currentPartitionIndex>=this.partitions.length){this.solved=!0;return}if(!this.activeSolver){let e=this.partitions[this.currentPartitionIndex];this.activeSolver=new KAt({partitionInputProblem:e,pinIdToStronglyConnectedPins:this.pinIdToStronglyConnectedPins}),this.activeSubSolver=this.activeSolver}if(this.activeSolver.step(),this.activeSolver.failed){this.failed=!0,this.error=`Partition ${this.currentPartitionIndex} failed: ${this.activeSolver.error}`;return}if(this.activeSolver.solved){if(this.completedSolvers.push(this.activeSolver),this.activeSolver.layout)this.packedPartitions.push({inputProblem:this.partitions[this.currentPartitionIndex],layout:this.activeSolver.layout});else{this.failed=!0,this.error=`Partition ${this.currentPartitionIndex} completed but has no layout`;return}this.activeSolver=null,this.activeSubSolver=null,this.currentPartitionIndex++}}visualize(){if(this.activeSolver)return this.activeSolver.visualize();if(this.completedSolvers.length===0)return super.visualize();let e=this.completedSolvers.map(i=>i.visualize()),t=this.completedSolvers.map((i,r)=>`packed_partition_${r}`);return wd(e,{titles:t})}getConstructorParams(){return[this.partitions]}},QAt=class extends O_{constructor(e){super();f(this,"packedPartitions");f(this,"inputProblem");f(this,"finalLayout",null);f(this,"packSolver2",null);this.packedPartitions=e.packedPartitions,this.inputProblem=e.inputProblem}_step(){try{if(this.packedPartitions.length===0){this.finalLayout={chipPlacements:{},groupPlacements:{}},this.solved=!0;return}if(this.packedPartitions.length===1){this.finalLayout=this.packedPartitions[0].layout,this.solved=!0;return}let e=this.organizePackedPartitions();if(!this.packSolver2){let t=this.createPackInput(e);this.packSolver2=new P1(t),this.activeSubSolver=this.packSolver2}if(this.packSolver2.step(),this.packSolver2.failed){this.failed=!0,this.error=`PackSolver2 failed: ${this.packSolver2.error}`;return}if(this.packSolver2.solved){let t=this.applyPackingResult(this.packSolver2.packedComponents,e);this.finalLayout=t,this.solved=!0,this.activeSubSolver=null}}catch(e){this.failed=!0,this.error=`Failed to pack partitions: ${e}`}}organizePackedPartitions(){let e=[];for(let t=0;t<this.packedPartitions.length;t++){let i=this.packedPartitions[t],r=Object.keys(i.layout.chipPlacements);if(r.length>0){let s=1/0,o=-1/0,a=1/0,c=-1/0;for(let u of r){let p=i.layout.chipPlacements[u],d=i.inputProblem.chipMap[u],_=d.size.x,g=d.size.y;(p.ccwRotationDegrees===90||p.ccwRotationDegrees===270)&&([_,g]=[g,_]);let x=p.x-_/2,v=p.x+_/2,S=p.y-g/2,P=p.y+g/2;s=Math.min(s,x),o=Math.max(o,v),a=Math.min(a,S),c=Math.max(c,P)}let l={minX:s,maxX:o,minY:a,maxY:c};e.push({partitionIndex:t,chipIds:r,bounds:l})}}return e}createPackInput(e){let t=new Map;for(let r of this.packedPartitions){for(let[s,o]of Object.entries(r.inputProblem.netConnMap)){if(!o)continue;let[a,c]=s.split("-");a&&c&&t.set(a,c)}for(let[s,o]of Object.entries(r.inputProblem.pinStrongConnMap)){if(!o)continue;let a=s.split("-");if(a.length===2&&a[0]&&a[1]){let c=t.get(a[0])||t.get(a[1]);c?(t.set(a[0],c),t.set(a[1],c)):(t.set(a[0],s),t.set(a[1],s))}}}return{components:e.map(r=>{let s=this.packedPartitions[r.partitionIndex],o=r.bounds.maxX-r.bounds.minX,a=r.bounds.maxY-r.bounds.minY,c=(r.bounds.minX+r.bounds.maxX)/2,l=(r.bounds.minY+r.bounds.maxY)/2,u=[{padId:`partition_${r.partitionIndex}_body`,networkId:`partition_${r.partitionIndex}_disconnected`,type:"rect",offset:{x:0,y:0},size:{x:Math.max(o,.1),y:Math.max(a,.1)}}],p=new Set,d=new Map;for(let _ of r.chipIds){let g=s.layout.chipPlacements[_],x=s.inputProblem.chipMap[_];for(let v of x.pins){let S=s.inputProblem.chipPinMap[v];if(!S)continue;let P={x:S.offset.x,y:S.offset.y},T=g.ccwRotationDegrees||0;T===90?P={x:-S.offset.y,y:S.offset.x}:T===180?P={x:-S.offset.x,y:-S.offset.y}:T===270&&(P={x:S.offset.y,y:-S.offset.x});let k=g.x+P.x,N=g.y+P.y;d.set(v,{x:k,y:N});let E=t.get(v)||`${v}_disconnected`;if(!p.has(E)){p.add(E);let C=k-c,M=N-l;u.push({padId:`${r.partitionIndex}_pin_${v}`,networkId:E,type:"rect",offset:{x:C,y:M},size:{x:.01,y:.01}})}}}return{componentId:`partition_${r.partitionIndex}`,pads:u,availableRotationDegrees:[0]}}),minGap:this.inputProblem.partitionGap,packOrderStrategy:"largest_to_smallest",packPlacementStrategy:"minimum_sum_squared_distance_to_network"}}applyPackingResult(e,t){let i={};for(let r of e){let s=parseInt(r.componentId.replace("partition_","")),o=t.find(c=>c.partitionIndex===s),a=this.packedPartitions[s];if(o&&a){let c=(o.bounds.minX+o.bounds.maxX)/2,l=(o.bounds.minY+o.bounds.maxY)/2,u=r.center.x,p=r.center.y,d=u-c,_=p-l;for(let g of o.chipIds){let x=a.layout.chipPlacements[g];i[g]={x:x.x+d,y:x.y+_,ccwRotationDegrees:x.ccwRotationDegrees}}}}return{chipPlacements:i,groupPlacements:{}}}visualize(){if(this.packSolver2&&!this.solved)return this.packSolver2.visualize();if(!this.finalLayout)return super.visualize();let e={chipMap:{},chipPinMap:{},pinStrongConnMap:{},netMap:{},netConnMap:{},chipGap:this.inputProblem.chipGap,partitionGap:this.inputProblem.partitionGap};for(let t of this.packedPartitions)Object.assign(e.chipMap,t.inputProblem.chipMap),Object.assign(e.chipPinMap,t.inputProblem.chipPinMap),Object.assign(e.pinStrongConnMap,t.inputProblem.pinStrongConnMap),Object.assign(e.netMap,t.inputProblem.netMap),Object.assign(e.netConnMap,t.inputProblem.netConnMap);return R_(e,this.finalLayout)}getConstructorParams(){return{packedPartitions:this.packedPartitions,inputProblem:this.inputProblem}}},t9t=n=>{let e={},t=Object.keys(n.chipPinMap);for(let i=0;i<t.length;i++)for(let r=i+1;r<t.length;r++){let s=t[i],o=t[r];(n.pinStrongConnMap[`${s}-${o}`]||n.pinStrongConnMap[`${o}-${s}`])&&(e[s]??(e[s]=[]),e[o]??(e[o]=[]),e[s].push(n.chipPinMap[o]),e[o].push(n.chipPinMap[s]))}return e};function zS(n,e,t,i={}){return{solverName:n,solverClass:e,getConstructorParams:t,onSolved:i.onSolved}}var NQ=class extends O_{constructor(e){super();f(this,"identifyDecouplingCapsSolver");f(this,"chipPartitionsSolver");f(this,"packInnerPartitionsSolver");f(this,"partitionPackingSolver");f(this,"startTimeOfPhase");f(this,"endTimeOfPhase");f(this,"timeSpentOnPhase");f(this,"firstIterationOfPhase");f(this,"pinIdToStronglyConnectedPins");f(this,"inputProblem");f(this,"chipPartitions");f(this,"packedPartitions");f(this,"pipelineDef",[zS("identifyDecouplingCapsSolver",HAt,()=>[this.inputProblem],{onSolved:e=>{}}),zS("chipPartitionsSolver",GAt,()=>[{inputProblem:this.inputProblem,decouplingCapGroups:this.identifyDecouplingCapsSolver?.outputDecouplingCapGroups}],{onSolved:e=>{this.chipPartitions=this.chipPartitionsSolver.partitions}}),zS("packInnerPartitionsSolver",JAt,()=>[{partitions:this.chipPartitions,pinIdToStronglyConnectedPins:this.pinIdToStronglyConnectedPins}],{onSolved:e=>{this.packedPartitions=this.packInnerPartitionsSolver.packedPartitions}}),zS("partitionPackingSolver",QAt,()=>[{packedPartitions:this.packedPartitions||[],inputProblem:this.inputProblem}],{onSolved:e=>{}})]);f(this,"currentPipelineStepIndex",0);this.inputProblem=e,this.MAX_ITERATIONS=1e6,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={},this.firstIterationOfPhase={},this.pinIdToStronglyConnectedPins=t9t(e)}_step(){let e=this.pipelineDef[this.currentPipelineStepIndex];if(!e){this.solved=!0;return}if(this.activeSubSolver){this.activeSubSolver.step(),this.activeSubSolver.solved?(this.endTimeOfPhase[e.solverName]=performance.now(),this.timeSpentOnPhase[e.solverName]=this.endTimeOfPhase[e.solverName]-this.startTimeOfPhase[e.solverName],e.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++):this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let t=e.getConstructorParams(this);this.activeSubSolver=new e.solverClass(...t),this[e.solverName]=this.activeSubSolver,this.timeSpentOnPhase[e.solverName]=0,this.startTimeOfPhase[e.solverName]=performance.now(),this.firstIterationOfPhase[e.solverName]=this.iterations}solveUntilPhase(e){for(;this.getCurrentPhase()!==e;)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();if(this.solved&&this.partitionPackingSolver?.solved)return this.partitionPackingSolver.visualize();let e=this.identifyDecouplingCapsSolver?.visualize(),t=this.chipPartitionsSolver?.visualize(),i=this.packInnerPartitionsSolver?.visualize(),r=this.partitionPackingSolver?.visualize(),s=DS(this.inputProblem),a=[R_(this.inputProblem,s),e,t,i,r].filter(Boolean).map((c,l)=>{for(let u of c.rects??[])u.step=l;for(let u of c.points??[])u.step=l;for(let u of c.circles??[])u.step=l;for(let u of c.texts??[])u.step=l;for(let u of c.lines??[])u.step=l;return c});return a.length===1?a[0]:{points:a.flatMap(c=>c.points||[]),rects:a.flatMap(c=>c.rects||[]),lines:a.flatMap(c=>c.lines||[]),circles:a.flatMap(c=>c.circles||[]),texts:a.flatMap(c=>c.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():this.partitionPackingSolver?.solved?this.partitionPackingSolver.visualize():this.packInnerPartitionsSolver?.solved?this.packInnerPartitionsSolver.visualize():this.chipPartitionsSolver?.solved?this.chipPartitionsSolver.visualize():this.identifyDecouplingCapsSolver?.solved?this.identifyDecouplingCapsSolver.visualize():super.preview()}checkForOverlaps(e){let t=[],i=Object.keys(e.chipPlacements);for(let r=0;r<i.length;r++)for(let s=r+1;s<i.length;s++){let o=i[r],a=i[s],c=e.chipPlacements[o],l=e.chipPlacements[a],u=this.inputProblem.chipMap[o],p=this.inputProblem.chipMap[a];if(!u||!p)continue;let d=this.getRotatedBounds(c,u.size),_=this.getRotatedBounds(l,p.size),g=this.calculateOverlapArea(d,_);g>0&&t.push({chip1:o,chip2:a,overlapArea:g})}return t}getRotatedBounds(e,t){let i=t.x/2,r=t.y/2,s=e.ccwRotationDegrees*Math.PI/180,o=Math.abs(Math.cos(s)),a=Math.abs(Math.sin(s)),c=i*o+r*a,l=i*a+r*o;return{minX:e.x-c,maxX:e.x+c,minY:e.y-l,maxY:e.y+l}}calculateOverlapArea(e,t){if(e.maxX<=t.minX||e.minX>=t.maxX||e.maxY<=t.minY||e.minY>=t.maxY)return 0;let i=Math.min(e.maxX,t.maxX)-Math.max(e.minX,t.minX),r=Math.min(e.maxY,t.maxY)-Math.max(e.minY,t.minY);return i*r}getOutputLayout(){if(!this.solved)throw new Error("Pipeline not solved yet. Call solve() or step() until solved.");let e;if(this.partitionPackingSolver?.solved&&this.partitionPackingSolver.finalLayout)e=this.partitionPackingSolver.finalLayout;else throw new Error("No layout available. Pipeline may have failed or not progressed far enough.");let t=this.checkForOverlaps(e);if(t.length>0){let i=t.map(r=>`${r.chip1} overlaps ${r.chip2} (area: ${r.overlapArea.toFixed(4)})`).join(", ");console.warn(`Warning: ${t.length} chip overlaps detected in final layout: ${i}`)}return e}};var Bnt=Vt(In(),1);ir();wt();Ae();var RQ={flexGrow:0,flexShrink:1,flexBasis:0,alignSelf:"auto",width:void 0,height:void 0},OQ=class{constructor(n={}){f(this,"id");f(this,"metadata");f(this,"size",{width:0,height:0});f(this,"position",{x:0,y:0});f(this,"style");this.style={...RQ,...n},this.id=n.id,this.metadata=n.metadata}},e9t=class extends OQ{build(){}},AQ=class PA extends OQ{constructor(t,i,r={}){super({});f(this,"children",[]);f(this,"direction","row");f(this,"columnGap",0);f(this,"rowGap",0);f(this,"justifyContent","flex-start");f(this,"alignItems","stretch");this.size.width=t,this.size.height=i,this.id=r.id,Object.assign(this,r)}addChild(t,i){if(t instanceof PA){let s=t;return i&&(s.style={...RQ,...i}),this.children.push(s),s}let r=new e9t(t);return this.children.push(r),r}build(){let t=this.direction.startsWith("row"),i=t?"width":"height",r=t?"height":"width",s=t?this.columnGap:this.rowGap,o=t?this.rowGap:this.columnGap,a=s*Math.max(0,this.children.length-1),c=this.size[i],l=this.size[r],u=0,p=0,d=0;for(let E of this.children)u+=E.style.flexBasis,p+=E.style.flexGrow,d+=E.style.flexShrink;let _=c-u-a;for(let E of this.children){let C=E.style.flexBasis;_>0&&p>0?C+=_*E.style.flexGrow/p:_<0&&d>0&&(C+=_*E.style.flexShrink/d,C<0&&(C=0)),E.size[i]=C;let M=E.style.alignSelf!=="auto"?E.style.alignSelf:this.alignItems,A=t?E.style.height:E.style.width;A!==void 0?E.size[r]=A:M==="stretch"&&(E.size[r]=l)}let g=this.children.reduce((E,C)=>E+C.size[i],0)+a,x=c-g,v=0,S=s,P=this.children.length;switch(this.justifyContent){case"flex-start":break;case"flex-end":v=x;break;case"center":v=x/2;break;case"space-between":S=P>1?s+x/(P-1):0;break;case"space-around":S=s+x/P,v=S/2;break;case"space-evenly":S=s+x/(P+1),v=S;break}let T=this.direction.endsWith("reverse")?[...this.children].reverse():this.children,k=v;for(let E of T)t?(E.position.x=this.direction==="row"?k:c-k-E.size.width,E.position.y=N(E,r,l,this.alignItems)):(E.position.y=this.direction==="column"?k:c-k-E.size.height,E.position.x=N(E,r,l,this.alignItems)),k+=E.size[i]+S;for(let E of this.children)E instanceof PA&&E.build();function N(E,C,M,A){switch(E.style.alignSelf!=="auto"?E.style.alignSelf:A){case"flex-start":return 0;case"flex-end":return M-E.size[C];case"center":return(M-E.size[C])/2;case"stretch":default:return 0}}}},jS=class extends AQ{constructor(n,e,t={}){super(n,e,t)}getLayout(){this.build();let n={};return this._collectLayout(this,n),n}_collectLayout(n,e,t={counter:0}){for(let i of n.children){let r=i.id??`_$$${t.counter++}`;e[r]={position:i.position,size:i.size},i instanceof AQ&&this._collectLayout(i,e,t)}}};wt();Ae();wt();var LQ=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20].map(n=>`hsl(${n*360/21}deg, 100%, 50%)`),n9t=n=>{let e=0;for(let t=0;t<n.length;t++)e=(e<<5)-e+n.charCodeAt(t);return e},DQ=n=>LQ[Math.abs(n9t(n))%LQ.length],i9t=n=>{let e=g=>g?typeof g=="string"?g:g.join(" "):void 0,t=["display:grid","background-color:gray"],{gridTemplateRows:i,gridTemplateColumns:r,gap:s,justifyItems:o,alignItems:a,containerWidth:c,containerHeight:l}=n.opts,u=e(i);u&&t.push(`grid-template-rows:${u}`);let p=e(r);if(p&&t.push(`grid-template-columns:${p}`),s!==void 0)if(typeof s=="number")t.push(`gap:${s}px`);else{let[g,x]=s;t.push(`row-gap:${g}px`,`column-gap:${x}px`)}o&&t.push(`justify-items:${o}`),a&&t.push(`align-items:${a}`),c!=null&&t.push(`width:${c}px`),l!=null&&t.push(`height:${l}px`);let d=t.join(";"),_=n.opts.children.map(g=>{let x=["display:flex",`background-color:${DQ(g.key)}`];if(g.area)x.push(`grid-area:${g.area}`);else{if(typeof g.row=="string"&&g.row.includes("/"))x.push(`grid-row:${g.row}`);else{let T=g.rowStart??g.row,k=g.rowEnd,N=g.rowSpan;T!==void 0||k!==void 0?T!==void 0&&k!==void 0?x.push(`grid-row:${T} / ${k}`):T!==void 0?N!==void 0?x.push(`grid-row:${T} / span ${N}`):x.push(`grid-row-start:${T}`):x.push(`grid-row-end:${k}`):N!==void 0&&x.push(`grid-row:auto / span ${N}`)}if(typeof g.column=="string"&&g.column.includes("/"))x.push(`grid-column:${g.column}`);else{let T=g.columnStart??g.column,k=g.columnEnd,N=g.columnSpan;T!==void 0||k!==void 0?T!==void 0&&k!==void 0?x.push(`grid-column:${T} / ${k}`):T!==void 0?N!==void 0?x.push(`grid-column:${T} / span ${N}`):x.push(`grid-column-start:${T}`):x.push(`grid-column-end:${k}`):N!==void 0&&x.push(`grid-column:auto / span ${N}`)}}let v=x.join(";"),S=["font-size: 7px"];if(g.contentWidth!==void 0){let T=typeof g.contentWidth=="string"?g.contentWidth:`${g.contentWidth}px`;S.push(`width:${T}`)}else S.push(`width:${g.key.length*5}px`);if(g.contentHeight!==void 0){let T=typeof g.contentHeight=="string"?g.contentHeight:`${g.contentHeight}px`;S.push(`height:${T}`)}let P=S.join(";");return` <div id="${g.key}" style="${v}"><div style="${P}">${g.key}</div></div>`});return`<div style="${d}">
243
243
  ${_.join(`
244
244
  `)}
245
- </div>`},r9t=n=>{let e=n.layout(),t={title:"CssGrid",coordinateSystem:"screen",lines:[],circles:[],points:[],rects:[],texts:[]},{cells:i}=e;for(let r of i){let{x:s,y:o,width:a,height:c,key:l}=r;t.rects.push({center:{x:s+a/2,y:o+c/2},width:a,height:c,fill:DQ(l),label:l})}return t};function BS(n){return n.replace(/repeat\((\d+),\s*([^)]+)\)/g,(e,t,i)=>Array(Number(t)).fill(i.trim()).join(" "))}function YS(n){return n.trim().split(/\s+/).filter(Boolean)}function FQ(n){return n?YS(BS(n)).length:0}function $Q(n,e){if(n==="auto")return{fr:1};if(n.endsWith("%")){let i=parseFloat(n);return e!=null?e*i/100:0}if(n.endsWith("px"))return parseFloat(n);if(n.endsWith("em"))return parseFloat(n)*16;if(n.endsWith("fr"))return{fr:parseFloat(n)};let t=parseFloat(n);return Number.isNaN(t)?0:t}function zQ(n,e){return n>0?n:e+2+n}var s9t=n=>{let e=n.opts,t=e.children,i,r;if("gridTemplate"in e&&typeof e.gridTemplate=="string"){let[E,C]=e.gridTemplate.split("/");i=E?.trim(),r=C?.trim()}else i=typeof e.gridTemplateRows=="string"?e.gridTemplateRows:void 0,r=typeof e.gridTemplateColumns=="string"?e.gridTemplateColumns:void 0;let s=FQ(r),o=FQ(i);function a(E,C,M,A){if(!E)return 0;let R=BS(E),B=YS(R),j=B.length,U=0,X=!1;for(let et=0;et<B.length;et++){let nt=B[et];if(nt.endsWith("px"))U+=parseFloat(nt);else if(nt.endsWith("em"))U+=parseFloat(nt)*16;else if(nt.endsWith("fr")||nt==="auto"){X=!0;let mt=0;for(let G of C){let tt=M?G.columnStart||G.column:G.rowStart||G.row,J=M?G.columnSpan||1:G.rowSpan||1,ht=M?G.contentWidth:G.contentHeight,pt=(typeof tt=="number"?tt:parseInt(tt||"1"))-1,St=typeof J=="number"?J:parseInt(J.toString());if(pt<=et&&et<pt+St&&ht){let Mt=typeof ht=="string"&&ht.endsWith("px")?parseFloat(ht):typeof ht=="number"?ht:0;mt=Math.max(mt,Mt/St)}}U+=mt}}let W=A*(j-1);return U+W}function c(E,C,M,A=!0,R=1){if(!E)return[];if(C==null){let J=BS(E),ht=YS(J),pt=ht.length,St=Y=>Y===void 0?0:typeof Y=="number"?Y:(Y.endsWith("px"),parseFloat(Y)),Mt=new Array(pt).fill(0),ot=0;for(let Y of t){let H=A?typeof Y.columnSpan=="number"?Y.columnSpan:Y.columnSpan?parseInt(Y.columnSpan.toString()):1:typeof Y.rowSpan=="number"?Y.rowSpan:Y.rowSpan?parseInt(Y.rowSpan.toString()):1,it=A?Y.contentWidth:Y.contentHeight,ut=St(it)/H,yt;A?(Y.columnStart!==void 0||Y.column!==void 0)&&(yt=parseInt(Y.columnStart??Y.column)-1):(Y.rowStart!==void 0||Y.row!==void 0)&&(yt=parseInt(Y.rowStart??Y.row)-1),(yt===void 0||Number.isNaN(yt))&&(A?yt=ot%pt:yt=Math.floor(ot/R),ot+=H);for(let Z=0;Z<H&&yt+Z<pt;Z++)Mt[yt+Z]=Math.max(Mt[yt+Z],ut)}return ht.forEach((Y,H)=>{let it=$Q(Y,void 0);typeof it=="number"&&(Mt[H]=it)}),Mt}let B=BS(E),j=YS(B),U=j.length,X=C;X==null&&(X=a(E,t,A,M));let W=X-M*(U-1),et=0,nt=0,mt=[],G=[];j.forEach((J,ht)=>{let pt=$Q(J,W);typeof pt=="number"?(G.push(pt),et+=pt):pt&&typeof pt=="object"&&"fr"in pt?(G.push(pt),nt+=pt.fr,mt.push({idx:ht,fr:pt.fr})):(G.push(0),et+=0)});let tt=Math.max(W-et,0);return G.map(J=>typeof J=="number"?J:nt>0?tt/nt*J.fr:0)}let l=typeof e.gap=="number"?e.gap:Array.isArray(e.gap)?e.gap[0]:0,u=typeof e.gap=="number"?e.gap:Array.isArray(e.gap)?e.gap[1]:0,p=c(i,e.containerHeight,l,!1,s||1),d=c(r,e.containerWidth,u,!0,o||1),_=p.length,g=d.length;g===0&&t.length>0&&(g=1);let x=[],v=0;for(let E of t){let C=E.rowStart!==void 0?E.rowStart:E.row,M=E.columnStart!==void 0?E.columnStart:E.column,A=E.rowSpan!==void 0?typeof E.rowSpan=="string"?parseInt(E.rowSpan):E.rowSpan:1,R=E.columnSpan!==void 0?typeof E.columnSpan=="string"?parseInt(E.columnSpan):E.columnSpan:1;if(E.rowEnd!==void 0){let U=typeof E.rowEnd=="string"?parseInt(E.rowEnd):E.rowEnd;C!==void 0?A=U-(typeof C=="string"?parseInt(C):C):C=U-A}if(E.columnEnd!==void 0){let U=typeof E.columnEnd=="string"?parseInt(E.columnEnd):E.columnEnd;M!==void 0?R=U-(typeof M=="string"?parseInt(M):M):M=U-R}if(typeof C=="string"&&(C=parseInt(C)),typeof M=="string"&&(M=parseInt(M)),typeof C=="number"&&C<0&&(C=zQ(C,_)),typeof M=="number"&&M<0&&(M=zQ(M,g)),C===void 0&&M!==void 0)C=1;else if(M===void 0&&C!==void 0)M=1;else if(C===void 0&&M===void 0){let U=v;C=Math.floor(U/g)+1,M=U%g+1}let B=C-1,j=M-1;A=Math.max(1,A),R=Math.max(1,R),x.push({key:E.key,row:B,column:j,rowSpan:A,columnSpan:R,x:0,y:0,width:0,height:0}),v+=R}let S=p.length,P=d.length;for(let E of x)E.row+E.rowSpan>S&&(S=E.row+E.rowSpan),E.column+E.columnSpan>P&&(P=E.column+E.columnSpan);if(p.length===0&&S>0&&e.containerHeight){let E=S,M=(e.containerHeight-l*(E-1))/E;for(let A=0;A<E;A++)p.push(M)}else for(;p.length<S;)p.push(0);if(d.length===0&&P>0&&e.containerWidth){let E=P,M=(e.containerWidth-u*(E-1))/E;for(let A=0;A<E;A++)d.push(M)}else if(d.length===0&&t.length>0&&e.containerWidth)d.push(e.containerWidth);else for(;d.length<P;)d.push(0);let T=(E,C,M)=>{let A=0;for(let R=0;R<E;R++)A+=C[R]||0,A+=M;return A},k=(E,C,M,A)=>{let R=0;for(let B=E;B<E+C;B++)R+=M[B]||0,B>E&&(R+=A);return R},N={};for(let E of x){let C=t.find(G=>G.key===E.key),M=T(E.column,d,u),A=T(E.row,p,l),R=k(E.column,E.columnSpan,d,u),B=k(E.row,E.rowSpan,p,l),j=G=>G===void 0?0:typeof G=="string"?G.endsWith("px")?parseFloat(G):G.endsWith("%")?0:parseFloat(G):G,U=j(C?.contentWidth),X=j(C?.contentHeight),W=R,et=B,nt=M,mt=A;if(U>0)switch(W=U,e.justifyItems||"stretch"){case"start":nt=M;break;case"end":nt=M+R-W;break;case"center":nt=M+(R-W)/2;break;case"stretch":W=R,nt=M;break}if(X>0)switch(et=X,e.alignItems||"stretch"){case"start":mt=A;break;case"end":mt=A+B-et;break;case"center":mt=A+(B-et)/2;break;case"stretch":et=B,mt=A;break}E.x=nt,E.y=mt,E.width=W,E.height=et,N[E.key]={x:nt,y:mt,width:W,height:et}}return{cells:x,rowSizes:p,columnSizes:d,rowGap:l,columnGap:u,itemCoordinates:N}},jQ=class{constructor(n){f(this,"opts");this.opts=n}layout(){return s9t(this)}convertToHtml(){return i9t(this)}visualize(){return r9t(this)}};wt();var Ynt=Vt(In(),1);Ae();Ae();wt();var kA=class{constructor(n){f(this,"netMap");f(this,"idToNetMap");this.netMap=n,this.idToNetMap={};for(let[e,t]of Object.entries(n))for(let i of t)this.idToNetMap[i]=e}addConnections(n){for(let e of n){let t=new Set;for(let r of e){let s=this.idToNetMap[r];s&&t.add(s)}let i;if(t.size===0)i=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[i]=[];else if(t.size===1)i=t.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{i=t.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(let r of t)if(r!==i){let s=this.netMap[i],o=this.netMap[r];if(s&&o){s.push(...o),this.netMap[r]=s;for(let a of s)this.idToNetMap[a]=i}}}for(let r of e){let s=this.netMap[i];s&&!s.includes(r)&&s.push(r),this.idToNetMap[r]=i}}}getIdsConnectedToNet(n){return this.netMap[n]||[]}getNetConnectedToId(n){return this.idToNetMap[n]}areIdsConnected(n,e){if(n===e)return!0;let t=this.getNetConnectedToId(n);if(!t)return!1;let i=this.getNetConnectedToId(e);return i?t===i||i===n||i===n:!1}areAllIdsConnected(n){if(n.length===0)return!0;let e=this.getNetConnectedToId(n[0]);if(!e)return!1;for(let t of n){let i=this.getNetConnectedToId(t);if(i===void 0||i!==e)return!1}return!0}};zg();var k1=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(e,t){let i=this.length++;for(;i>0;){let r=i-1>>1,s=this.values[r];if(t>=s)break;this.ids[i]=this.ids[r],this.values[i]=s,i=r}this.ids[i]=e,this.values[i]=t}pop(){if(this.length===0)return;let e=this.ids,t=this.values,i=e[0],r=--this.length;if(r>0){let s=e[r],o=t[r],a=0,c=r>>1;for(;a<c;){let l=(a<<1)+1,u=l+1,p=l+(+(u<r)&+(t[u]<t[l]));if(t[p]>=o)break;e[a]=e[p],t[a]=t[p],a=p}e[a]=s,t[a]=o}return i}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){this.ids.length=this.values.length=this.length}};var BQ=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],TA=3,T1=class n{static from(e,t=0){if(t%8!==0)throw new Error("byteOffset must be 8-byte aligned.");if(!e||e.byteLength===void 0||e.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[i,r]=new Uint8Array(e,t+0,2);if(i!==251)throw new Error("Data does not appear to be in a Flatbush format.");let s=r>>4;if(s!==TA)throw new Error(`Got v${s} data when expected v${TA}.`);let o=BQ[r&15];if(!o)throw new Error("Unrecognized array type.");let[a]=new Uint16Array(e,t+2,1),[c]=new Uint32Array(e,t+4,1);return new n(c,a,o,void 0,e,t)}constructor(e,t=16,i=Float64Array,r=ArrayBuffer,s,o=0){if(e===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(e)||e<=0)throw new Error(`Unexpected numItems value: ${e}.`);this.numItems=+e,this.nodeSize=Math.min(Math.max(+t,2),65535),this.byteOffset=o;let a=e,c=a;this._levelBounds=[a*4];do a=Math.ceil(a/this.nodeSize),c+=a,this._levelBounds.push(c*4);while(a!==1);this.ArrayType=i,this.IndexArrayType=c<16384?Uint16Array:Uint32Array;let l=BQ.indexOf(i),u=c*4*i.BYTES_PER_ELEMENT;if(l<0)throw new Error(`Unexpected typed array class: ${i}.`);if(s)this.data=s,this._boxes=new i(s,o+8,c*4),this._indices=new this.IndexArrayType(s,o+8+u,c),this._pos=c*4,this.minX=this._boxes[this._pos-4],this.minY=this._boxes[this._pos-3],this.maxX=this._boxes[this._pos-2],this.maxY=this._boxes[this._pos-1];else{let p=this.data=new r(8+u+c*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new i(p,8,c*4),this._indices=new this.IndexArrayType(p,8+u,c),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(p,0,2).set([251,(TA<<4)+l]),new Uint16Array(p,2,1)[0]=t,new Uint32Array(p,4,1)[0]=e}this._queue=new k1}add(e,t,i=e,r=t){let s=this._pos>>2,o=this._boxes;return this._indices[s]=s,o[this._pos++]=e,o[this._pos++]=t,o[this._pos++]=i,o[this._pos++]=r,e<this.minX&&(this.minX=e),t<this.minY&&(this.minY=t),i>this.maxX&&(this.maxX=i),r>this.maxY&&(this.maxY=r),s}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let e=this._boxes;if(this.numItems<=this.nodeSize){e[this._pos++]=this.minX,e[this._pos++]=this.minY,e[this._pos++]=this.maxX,e[this._pos++]=this.maxY;return}let t=this.maxX-this.minX||1,i=this.maxY-this.minY||1,r=new Uint32Array(this.numItems),s=65535;for(let o=0,a=0;o<this.numItems;o++){let c=e[a++],l=e[a++],u=e[a++],p=e[a++],d=Math.floor(s*((c+u)/2-this.minX)/t),_=Math.floor(s*((l+p)/2-this.minY)/i);r[o]=a9t(d,_)}EA(r,e,this._indices,0,this.numItems-1,this.nodeSize);for(let o=0,a=0;o<this._levelBounds.length-1;o++){let c=this._levelBounds[o];for(;a<c;){let l=a,u=e[a++],p=e[a++],d=e[a++],_=e[a++];for(let g=1;g<this.nodeSize&&a<c;g++)u=Math.min(u,e[a++]),p=Math.min(p,e[a++]),d=Math.max(d,e[a++]),_=Math.max(_,e[a++]);this._indices[this._pos>>2]=l,e[this._pos++]=u,e[this._pos++]=p,e[this._pos++]=d,e[this._pos++]=_}}}search(e,t,i,r,s){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let o=this._boxes.length-4,a=[],c=[];for(;o!==void 0;){let l=Math.min(o+this.nodeSize*4,YQ(o,this._levelBounds));for(let u=o;u<l;u+=4){let p=this._boxes[u];if(i<p)continue;let d=this._boxes[u+1];if(r<d)continue;let _=this._boxes[u+2];if(e>_)continue;let g=this._boxes[u+3];if(t>g)continue;let x=this._indices[u>>2]|0;o>=this.numItems*4?a.push(x):(s===void 0||s(x,p,d,_,g))&&c.push(x)}o=a.pop()}return c}neighbors(e,t,i=1/0,r=1/0,s){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let o=this._boxes.length-4,a=this._queue,c=[],l=r*r;t:for(;o!==void 0;){let u=Math.min(o+this.nodeSize*4,YQ(o,this._levelBounds));for(let p=o;p<u;p+=4){let d=this._indices[p>>2]|0,_=this._boxes[p],g=this._boxes[p+1],x=this._boxes[p+2],v=this._boxes[p+3],S=e<_?_-e:e>x?e-x:0,P=t<g?g-t:t>v?t-v:0,T=S*S+P*P;T>l||(o>=this.numItems*4?a.push(d<<1,T):(s===void 0||s(d))&&a.push((d<<1)+1,T))}for(;a.length&&a.peek()&1;)if(a.peekValue()>l||(c.push(a.pop()>>1),c.length===i))break t;o=a.length?a.pop()>>1:void 0}return a.clear(),c}};function YQ(n,e){let t=0,i=e.length-1;for(;t<i;){let r=t+i>>1;e[r]>n?i=r:t=r+1}return e[t]}function EA(n,e,t,i,r,s){if(Math.floor(i/s)>=Math.floor(r/s))return;let o=n[i],a=n[i+r>>1],c=n[r],l=c,u=Math.max(o,a);c>u?l=u:u===o?l=Math.max(a,c):u===a&&(l=Math.max(o,c));let p=i-1,d=r+1;for(;;){do p++;while(n[p]<l);do d--;while(n[d]>l);if(p>=d)break;o9t(n,e,t,p,d)}EA(n,e,t,i,d,s),EA(n,e,t,d+1,r,s)}function o9t(n,e,t,i,r){let s=n[i];n[i]=n[r],n[r]=s;let o=4*i,a=4*r,c=e[o],l=e[o+1],u=e[o+2],p=e[o+3];e[o]=e[a],e[o+1]=e[a+1],e[o+2]=e[a+2],e[o+3]=e[a+3],e[a]=c,e[a+1]=l,e[a+2]=u,e[a+3]=p;let d=t[i];t[i]=t[r],t[r]=d}function a9t(n,e){let t=n^e,i=65535^t,r=65535^(n|e),s=n&(e^65535),o=t|i>>1,a=t>>1^t,c=r>>1^i&s>>1^r,l=t&r>>1^s>>1^s;t=o,i=a,r=c,s=l,o=t&t>>2^i&i>>2,a=t&i>>2^i&(t^i)>>2,c^=t&r>>2^i&s>>2,l^=i&r>>2^(t^i)&s>>2,t=o,i=a,r=c,s=l,o=t&t>>4^i&i>>4,a=t&i>>4^i&(t^i)>>4,c^=t&r>>4^i&s>>4,l^=i&r>>4^(t^i)&s>>4,t=o,i=a,r=c,s=l,c^=t&r>>8^i&s>>8,l^=i&r>>8^(t^i)&s>>8,t=c^c>>1,i=l^l>>1;let u=n^e,p=i|65535^(u|t);return u=(u|u<<8)&16711935,u=(u|u<<4)&252645135,u=(u|u<<2)&858993459,u=(u|u<<1)&1431655765,p=(p|p<<8)&16711935,p=(p|p<<4)&252645135,p=(p|p<<2)&858993459,p=(p|p<<1)&1431655765,(p<<1|u)>>>0}var Tr=class{constructor(){f(this,"MAX_ITERATIONS",1e5);f(this,"solved",!1);f(this,"failed",!1);f(this,"iterations",0);f(this,"progress",0);f(this,"error",null);f(this,"activeSubSolver");f(this,"failedSubSolvers");f(this,"timeToSolve");f(this,"stats",{})}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(n){throw this.error=`${this.constructor.name} error: ${n}`,this.failed=!0,n}!this.solved&&this.iterations>this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}solve(){let n=Date.now();for(;!this.solved&&!this.failed;)this.step();let e=Date.now();this.timeToSolve=e-n}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}},LA=n=>{let e=new kA({});for(let i of n.directConnections)e.addConnections([i.netId?[i.netId,...i.pinIds]:i.pinIds]);let t=new kA(e.netMap);for(let i of n.netConnections)t.addConnections([[i.netId,...i.pinIds]]);return{directConnMap:e,netConnMap:t}};function c9t(n,e={}){let t=n.length,i=e?.maxDistance??Number.POSITIVE_INFINITY;if(t<=1)return[];{let u=new Set;for(let p of n){if(u.has(p.pinId))throw new Error(`Duplicate pinId detected: "${p.pinId}"`);u.add(p.pinId)}}let r=(u,p)=>Math.abs(u.x-p.x)+Math.abs(u.y-p.y),s=new Array(t).fill(!1),o=new Array(t).fill(Number.POSITIVE_INFINITY),a=new Array(t).fill(-1),c=0;for(let u=1;u<t;u++)n[u].pinId<n[c].pinId&&(c=u);o[c]=0;let l=[];for(let u=0;u<t;u++){let p=-1,d=Number.POSITIVE_INFINITY,_="";for(let g=0;g<t;g++)if(!s[g]){let x=o[g];(x<d||x===d&&(_===""||n[g].pinId<_))&&(d=x,_=n[g].pinId,p=g)}s[p]=!0,a[p]!==-1&&l.push([n[p].pinId,n[a[p]].pinId]);for(let g=0;g<t;g++)if(!s[g]){let x=r(n[p],n[g]),v=e?.forbidEdge?.(n[p],n[g])??!1,S=x>i||v?Number.POSITIVE_INFINITY:x;(S<o[g]||S===o[g]&&n[p].pinId<n[a[g]]?.pinId)&&(o[g]=S,a[g]=p)}}return l}var E1=(n,e)=>{let{x:t,y:i}=n,{center:r,width:s,height:o}=e,a=r.y+o/2,c=r.y-o/2,l=r.x+s/2,u=r.x-s/2,p=a-i,d=i-c,_=l-t,g=t-u,x=Math.min(p,d,_,g);return x===p?"y+":x===d?"y-":x===_?"x+":"x-"},l9t=n=>{let{pins:e,inputProblem:t,pinIdMap:i,chipMap:r}=n,s=d=>{let _=new Set,g=[d];_.add(d);let x=t.directConnections||[];for(;g.length;){let v=g.shift();for(let S of x)if(S.pinIds.includes(v))for(let P of S.pinIds)_.has(P)||(_.add(P),g.push(P))}return _},o=e[0].pinId,a=e[1].pinId,c=new Set([...s(o),...s(a)]),l=new Map,u=new Map,p=new Set(e.map(d=>d.chipId));for(let d of c){let _=i.get(d);if(!_)continue;let g=r[_.chipId];if(!g)continue;let x=_._facingDirection??E1(_,g),v=u.get(g.chipId);if(!v){v={center:g.center};let S={xPos:0,xNeg:0,yPos:0,yNeg:0};for(let P of g.pins){let T=P._facingDirection??E1(P,g);T==="x+"&&S.xPos++,T==="x-"&&S.xNeg++,T==="y+"&&S.yPos++,T==="y-"&&S.yNeg++}v.counts=S,u.set(g.chipId,v)}x==="x+"&&(v.hasXPos=!0),x==="x-"&&(v.hasXNeg=!0),x==="y+"&&(v.hasYPos=!0),x==="y-"&&(v.hasYNeg=!0)}for(let[d,_]of u){let g=new Set,x={axes:g},v=_.counts;!!!(v&&(v.xPos>1||v.xNeg>1||v.yPos>1||v.yNeg>1))&&p.has(d)||(_.hasXPos&&_.hasXNeg&&(x.x=_.center.x,g.add("x")),_.hasYPos&&_.hasYNeg&&(x.y=_.center.y,g.add("y"))),g.size>0&&l.set(d,x)}return l},MA=n=>{let{inputProblem:e,chipMap:t,pinIdMap:i,p1:r,p2:s}=n,o=l9t({pins:[r,s],inputProblem:e,pinIdMap:i,chipMap:t});if(o.size===0)return!1;let a=1e-9,c=(_,g)=>{for(let[,x]of o)if(x.axes.has("x")&&typeof x.x=="number"&&(_.x-x.x)*(g.x-x.x)<-a||x.axes.has("y")&&typeof x.y=="number"&&(_.y-x.y)*(g.y-x.y)<-a)return!0;return!1};if(Math.abs(r.x-s.x)<a||Math.abs(r.y-s.y)<a)return c({x:r.x,y:r.y},{x:s.x,y:s.y});let l={x:s.x,y:r.y},u={x:r.x,y:s.y},p=c({x:r.x,y:r.y},l)||c(l,{x:s.x,y:s.y}),d=c({x:r.x,y:r.y},u)||c(u,{x:s.x,y:s.y});return p&&d},Ls=(n,e=1)=>`hsl(${n.split("").reduce((i,r)=>i*31+r.charCodeAt(0),0)%360}, 100%, 50%, ${e})`,us=(n,e={})=>{let{connectionAlpha:t=.8,chipAlpha:i=.8}=e,r={lines:[],points:[],rects:[]},s=new Map;for(let o of n.chips)for(let a of o.pins)s.set(a.pinId,a);for(let o of n.chips){r.rects.push({label:o.chipId,center:o.center,width:o.width,height:o.height,fill:Ls(o.chipId,i)});for(let a of o.pins)r.points.push({label:`${a.pinId}
245
+ </div>`},r9t=n=>{let e=n.layout(),t={title:"CssGrid",coordinateSystem:"screen",lines:[],circles:[],points:[],rects:[],texts:[]},{cells:i}=e;for(let r of i){let{x:s,y:o,width:a,height:c,key:l}=r;t.rects.push({center:{x:s+a/2,y:o+c/2},width:a,height:c,fill:DQ(l),label:l})}return t};function BS(n){return n.replace(/repeat\((\d+),\s*([^)]+)\)/g,(e,t,i)=>Array(Number(t)).fill(i.trim()).join(" "))}function YS(n){return n.trim().split(/\s+/).filter(Boolean)}function FQ(n){return n?YS(BS(n)).length:0}function $Q(n,e){if(n==="auto")return{fr:1};if(n.endsWith("%")){let i=parseFloat(n);return e!=null?e*i/100:0}if(n.endsWith("px"))return parseFloat(n);if(n.endsWith("em"))return parseFloat(n)*16;if(n.endsWith("fr"))return{fr:parseFloat(n)};let t=parseFloat(n);return Number.isNaN(t)?0:t}function zQ(n,e){return n>0?n:e+2+n}var s9t=n=>{let e=n.opts,t=e.children,i,r;if("gridTemplate"in e&&typeof e.gridTemplate=="string"){let[E,C]=e.gridTemplate.split("/");i=E?.trim(),r=C?.trim()}else i=typeof e.gridTemplateRows=="string"?e.gridTemplateRows:void 0,r=typeof e.gridTemplateColumns=="string"?e.gridTemplateColumns:void 0;let s=FQ(r),o=FQ(i);function a(E,C,M,A){if(!E)return 0;let R=BS(E),B=YS(R),j=B.length,U=0,X=!1;for(let et=0;et<B.length;et++){let nt=B[et];if(nt.endsWith("px"))U+=parseFloat(nt);else if(nt.endsWith("em"))U+=parseFloat(nt)*16;else if(nt.endsWith("fr")||nt==="auto"){X=!0;let mt=0;for(let G of C){let tt=M?G.columnStart||G.column:G.rowStart||G.row,J=M?G.columnSpan||1:G.rowSpan||1,ht=M?G.contentWidth:G.contentHeight,pt=(typeof tt=="number"?tt:parseInt(tt||"1"))-1,St=typeof J=="number"?J:parseInt(J.toString());if(pt<=et&&et<pt+St&&ht){let Mt=typeof ht=="string"&&ht.endsWith("px")?parseFloat(ht):typeof ht=="number"?ht:0;mt=Math.max(mt,Mt/St)}}U+=mt}}let W=A*(j-1);return U+W}function c(E,C,M,A=!0,R=1){if(!E)return[];if(C==null){let J=BS(E),ht=YS(J),pt=ht.length,St=Y=>Y===void 0?0:typeof Y=="number"?Y:(Y.endsWith("px"),parseFloat(Y)),Mt=new Array(pt).fill(0),ot=0;for(let Y of t){let H=A?typeof Y.columnSpan=="number"?Y.columnSpan:Y.columnSpan?parseInt(Y.columnSpan.toString()):1:typeof Y.rowSpan=="number"?Y.rowSpan:Y.rowSpan?parseInt(Y.rowSpan.toString()):1,it=A?Y.contentWidth:Y.contentHeight,ut=St(it)/H,yt;A?(Y.columnStart!==void 0||Y.column!==void 0)&&(yt=parseInt(Y.columnStart??Y.column)-1):(Y.rowStart!==void 0||Y.row!==void 0)&&(yt=parseInt(Y.rowStart??Y.row)-1),(yt===void 0||Number.isNaN(yt))&&(A?yt=ot%pt:yt=Math.floor(ot/R),ot+=H);for(let Z=0;Z<H&&yt+Z<pt;Z++)Mt[yt+Z]=Math.max(Mt[yt+Z],ut)}return ht.forEach((Y,H)=>{let it=$Q(Y,void 0);typeof it=="number"&&(Mt[H]=it)}),Mt}let B=BS(E),j=YS(B),U=j.length,X=C;X==null&&(X=a(E,t,A,M));let W=X-M*(U-1),et=0,nt=0,mt=[],G=[];j.forEach((J,ht)=>{let pt=$Q(J,W);typeof pt=="number"?(G.push(pt),et+=pt):pt&&typeof pt=="object"&&"fr"in pt?(G.push(pt),nt+=pt.fr,mt.push({idx:ht,fr:pt.fr})):(G.push(0),et+=0)});let tt=Math.max(W-et,0);return G.map(J=>typeof J=="number"?J:nt>0?tt/nt*J.fr:0)}let l=typeof e.gap=="number"?e.gap:Array.isArray(e.gap)?e.gap[0]:0,u=typeof e.gap=="number"?e.gap:Array.isArray(e.gap)?e.gap[1]:0,p=c(i,e.containerHeight,l,!1,s||1),d=c(r,e.containerWidth,u,!0,o||1),_=p.length,g=d.length;g===0&&t.length>0&&(g=1);let x=[],v=0;for(let E of t){let C=E.rowStart!==void 0?E.rowStart:E.row,M=E.columnStart!==void 0?E.columnStart:E.column,A=E.rowSpan!==void 0?typeof E.rowSpan=="string"?parseInt(E.rowSpan):E.rowSpan:1,R=E.columnSpan!==void 0?typeof E.columnSpan=="string"?parseInt(E.columnSpan):E.columnSpan:1;if(E.rowEnd!==void 0){let U=typeof E.rowEnd=="string"?parseInt(E.rowEnd):E.rowEnd;C!==void 0?A=U-(typeof C=="string"?parseInt(C):C):C=U-A}if(E.columnEnd!==void 0){let U=typeof E.columnEnd=="string"?parseInt(E.columnEnd):E.columnEnd;M!==void 0?R=U-(typeof M=="string"?parseInt(M):M):M=U-R}if(typeof C=="string"&&(C=parseInt(C)),typeof M=="string"&&(M=parseInt(M)),typeof C=="number"&&C<0&&(C=zQ(C,_)),typeof M=="number"&&M<0&&(M=zQ(M,g)),C===void 0&&M!==void 0)C=1;else if(M===void 0&&C!==void 0)M=1;else if(C===void 0&&M===void 0){let U=v;C=Math.floor(U/g)+1,M=U%g+1}let B=C-1,j=M-1;A=Math.max(1,A),R=Math.max(1,R),x.push({key:E.key,row:B,column:j,rowSpan:A,columnSpan:R,x:0,y:0,width:0,height:0}),v+=R}let S=p.length,P=d.length;for(let E of x)E.row+E.rowSpan>S&&(S=E.row+E.rowSpan),E.column+E.columnSpan>P&&(P=E.column+E.columnSpan);if(p.length===0&&S>0&&e.containerHeight){let E=S,M=(e.containerHeight-l*(E-1))/E;for(let A=0;A<E;A++)p.push(M)}else for(;p.length<S;)p.push(0);if(d.length===0&&P>0&&e.containerWidth){let E=P,M=(e.containerWidth-u*(E-1))/E;for(let A=0;A<E;A++)d.push(M)}else if(d.length===0&&t.length>0&&e.containerWidth)d.push(e.containerWidth);else for(;d.length<P;)d.push(0);let T=(E,C,M)=>{let A=0;for(let R=0;R<E;R++)A+=C[R]||0,A+=M;return A},k=(E,C,M,A)=>{let R=0;for(let B=E;B<E+C;B++)R+=M[B]||0,B>E&&(R+=A);return R},N={};for(let E of x){let C=t.find(G=>G.key===E.key),M=T(E.column,d,u),A=T(E.row,p,l),R=k(E.column,E.columnSpan,d,u),B=k(E.row,E.rowSpan,p,l),j=G=>G===void 0?0:typeof G=="string"?G.endsWith("px")?parseFloat(G):G.endsWith("%")?0:parseFloat(G):G,U=j(C?.contentWidth),X=j(C?.contentHeight),W=R,et=B,nt=M,mt=A;if(U>0)switch(W=U,e.justifyItems||"stretch"){case"start":nt=M;break;case"end":nt=M+R-W;break;case"center":nt=M+(R-W)/2;break;case"stretch":W=R,nt=M;break}if(X>0)switch(et=X,e.alignItems||"stretch"){case"start":mt=A;break;case"end":mt=A+B-et;break;case"center":mt=A+(B-et)/2;break;case"stretch":et=B,mt=A;break}E.x=nt,E.y=mt,E.width=W,E.height=et,N[E.key]={x:nt,y:mt,width:W,height:et}}return{cells:x,rowSizes:p,columnSizes:d,rowGap:l,columnGap:u,itemCoordinates:N}},jQ=class{constructor(n){f(this,"opts");this.opts=n}layout(){return s9t(this)}convertToHtml(){return i9t(this)}visualize(){return r9t(this)}};wt();var Ynt=Vt(In(),1);Ae();Ae();wt();var kA=class{constructor(n){f(this,"netMap");f(this,"idToNetMap");this.netMap=n,this.idToNetMap={};for(let[e,t]of Object.entries(n))for(let i of t)this.idToNetMap[i]=e}addConnections(n){for(let e of n){let t=new Set;for(let r of e){let s=this.idToNetMap[r];s&&t.add(s)}let i;if(t.size===0)i=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[i]=[];else if(t.size===1)i=t.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{i=t.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(let r of t)if(r!==i){let s=this.netMap[i],o=this.netMap[r];if(s&&o){s.push(...o),this.netMap[r]=s;for(let a of s)this.idToNetMap[a]=i}}}for(let r of e){let s=this.netMap[i];s&&!s.includes(r)&&s.push(r),this.idToNetMap[r]=i}}}getIdsConnectedToNet(n){return this.netMap[n]||[]}getNetConnectedToId(n){return this.idToNetMap[n]}areIdsConnected(n,e){if(n===e)return!0;let t=this.getNetConnectedToId(n);if(!t)return!1;let i=this.getNetConnectedToId(e);return i?t===i||i===n||i===n:!1}areAllIdsConnected(n){if(n.length===0)return!0;let e=this.getNetConnectedToId(n[0]);if(!e)return!1;for(let t of n){let i=this.getNetConnectedToId(t);if(i===void 0||i!==e)return!1}return!0}};zg();var k1=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(e,t){let i=this.length++;for(;i>0;){let r=i-1>>1,s=this.values[r];if(t>=s)break;this.ids[i]=this.ids[r],this.values[i]=s,i=r}this.ids[i]=e,this.values[i]=t}pop(){if(this.length===0)return;let e=this.ids,t=this.values,i=e[0],r=--this.length;if(r>0){let s=e[r],o=t[r],a=0,c=r>>1;for(;a<c;){let l=(a<<1)+1,u=l+1,p=l+(+(u<r)&+(t[u]<t[l]));if(t[p]>=o)break;e[a]=e[p],t[a]=t[p],a=p}e[a]=s,t[a]=o}return i}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){this.ids.length=this.values.length=this.length}};var BQ=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],TA=3,T1=class n{static from(e,t=0){if(t%8!==0)throw new Error("byteOffset must be 8-byte aligned.");if(!e||e.byteLength===void 0||e.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[i,r]=new Uint8Array(e,t+0,2);if(i!==251)throw new Error("Data does not appear to be in a Flatbush format.");let s=r>>4;if(s!==TA)throw new Error(`Got v${s} data when expected v${TA}.`);let o=BQ[r&15];if(!o)throw new Error("Unrecognized array type.");let[a]=new Uint16Array(e,t+2,1),[c]=new Uint32Array(e,t+4,1);return new n(c,a,o,void 0,e,t)}constructor(e,t=16,i=Float64Array,r=ArrayBuffer,s,o=0){if(e===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(e)||e<=0)throw new Error(`Unexpected numItems value: ${e}.`);this.numItems=+e,this.nodeSize=Math.min(Math.max(+t,2),65535),this.byteOffset=o;let a=e,c=a;this._levelBounds=[a*4];do a=Math.ceil(a/this.nodeSize),c+=a,this._levelBounds.push(c*4);while(a!==1);this.ArrayType=i,this.IndexArrayType=c<16384?Uint16Array:Uint32Array;let l=BQ.indexOf(i),u=c*4*i.BYTES_PER_ELEMENT;if(l<0)throw new Error(`Unexpected typed array class: ${i}.`);if(s)this.data=s,this._boxes=new i(s,o+8,c*4),this._indices=new this.IndexArrayType(s,o+8+u,c),this._pos=c*4,this.minX=this._boxes[this._pos-4],this.minY=this._boxes[this._pos-3],this.maxX=this._boxes[this._pos-2],this.maxY=this._boxes[this._pos-1];else{let p=this.data=new r(8+u+c*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new i(p,8,c*4),this._indices=new this.IndexArrayType(p,8+u,c),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(p,0,2).set([251,(TA<<4)+l]),new Uint16Array(p,2,1)[0]=t,new Uint32Array(p,4,1)[0]=e}this._queue=new k1}add(e,t,i=e,r=t){let s=this._pos>>2,o=this._boxes;return this._indices[s]=s,o[this._pos++]=e,o[this._pos++]=t,o[this._pos++]=i,o[this._pos++]=r,e<this.minX&&(this.minX=e),t<this.minY&&(this.minY=t),i>this.maxX&&(this.maxX=i),r>this.maxY&&(this.maxY=r),s}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let e=this._boxes;if(this.numItems<=this.nodeSize){e[this._pos++]=this.minX,e[this._pos++]=this.minY,e[this._pos++]=this.maxX,e[this._pos++]=this.maxY;return}let t=this.maxX-this.minX||1,i=this.maxY-this.minY||1,r=new Uint32Array(this.numItems),s=65535;for(let o=0,a=0;o<this.numItems;o++){let c=e[a++],l=e[a++],u=e[a++],p=e[a++],d=Math.floor(s*((c+u)/2-this.minX)/t),_=Math.floor(s*((l+p)/2-this.minY)/i);r[o]=a9t(d,_)}EA(r,e,this._indices,0,this.numItems-1,this.nodeSize);for(let o=0,a=0;o<this._levelBounds.length-1;o++){let c=this._levelBounds[o];for(;a<c;){let l=a,u=e[a++],p=e[a++],d=e[a++],_=e[a++];for(let g=1;g<this.nodeSize&&a<c;g++)u=Math.min(u,e[a++]),p=Math.min(p,e[a++]),d=Math.max(d,e[a++]),_=Math.max(_,e[a++]);this._indices[this._pos>>2]=l,e[this._pos++]=u,e[this._pos++]=p,e[this._pos++]=d,e[this._pos++]=_}}}search(e,t,i,r,s){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let o=this._boxes.length-4,a=[],c=[];for(;o!==void 0;){let l=Math.min(o+this.nodeSize*4,YQ(o,this._levelBounds));for(let u=o;u<l;u+=4){let p=this._boxes[u];if(i<p)continue;let d=this._boxes[u+1];if(r<d)continue;let _=this._boxes[u+2];if(e>_)continue;let g=this._boxes[u+3];if(t>g)continue;let x=this._indices[u>>2]|0;o>=this.numItems*4?a.push(x):(s===void 0||s(x,p,d,_,g))&&c.push(x)}o=a.pop()}return c}neighbors(e,t,i=1/0,r=1/0,s){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let o=this._boxes.length-4,a=this._queue,c=[],l=r*r;t:for(;o!==void 0;){let u=Math.min(o+this.nodeSize*4,YQ(o,this._levelBounds));for(let p=o;p<u;p+=4){let d=this._indices[p>>2]|0,_=this._boxes[p],g=this._boxes[p+1],x=this._boxes[p+2],v=this._boxes[p+3],S=e<_?_-e:e>x?e-x:0,P=t<g?g-t:t>v?t-v:0,T=S*S+P*P;T>l||(o>=this.numItems*4?a.push(d<<1,T):(s===void 0||s(d))&&a.push((d<<1)+1,T))}for(;a.length&&a.peek()&1;)if(a.peekValue()>l||(c.push(a.pop()>>1),c.length===i))break t;o=a.length?a.pop()>>1:void 0}return a.clear(),c}};function YQ(n,e){let t=0,i=e.length-1;for(;t<i;){let r=t+i>>1;e[r]>n?i=r:t=r+1}return e[t]}function EA(n,e,t,i,r,s){if(Math.floor(i/s)>=Math.floor(r/s))return;let o=n[i],a=n[i+r>>1],c=n[r],l=c,u=Math.max(o,a);c>u?l=u:u===o?l=Math.max(a,c):u===a&&(l=Math.max(o,c));let p=i-1,d=r+1;for(;;){do p++;while(n[p]<l);do d--;while(n[d]>l);if(p>=d)break;o9t(n,e,t,p,d)}EA(n,e,t,i,d,s),EA(n,e,t,d+1,r,s)}function o9t(n,e,t,i,r){let s=n[i];n[i]=n[r],n[r]=s;let o=4*i,a=4*r,c=e[o],l=e[o+1],u=e[o+2],p=e[o+3];e[o]=e[a],e[o+1]=e[a+1],e[o+2]=e[a+2],e[o+3]=e[a+3],e[a]=c,e[a+1]=l,e[a+2]=u,e[a+3]=p;let d=t[i];t[i]=t[r],t[r]=d}function a9t(n,e){let t=n^e,i=65535^t,r=65535^(n|e),s=n&(e^65535),o=t|i>>1,a=t>>1^t,c=r>>1^i&s>>1^r,l=t&r>>1^s>>1^s;t=o,i=a,r=c,s=l,o=t&t>>2^i&i>>2,a=t&i>>2^i&(t^i)>>2,c^=t&r>>2^i&s>>2,l^=i&r>>2^(t^i)&s>>2,t=o,i=a,r=c,s=l,o=t&t>>4^i&i>>4,a=t&i>>4^i&(t^i)>>4,c^=t&r>>4^i&s>>4,l^=i&r>>4^(t^i)&s>>4,t=o,i=a,r=c,s=l,c^=t&r>>8^i&s>>8,l^=i&r>>8^(t^i)&s>>8,t=c^c>>1,i=l^l>>1;let u=n^e,p=i|65535^(u|t);return u=(u|u<<8)&16711935,u=(u|u<<4)&252645135,u=(u|u<<2)&858993459,u=(u|u<<1)&1431655765,p=(p|p<<8)&16711935,p=(p|p<<4)&252645135,p=(p|p<<2)&858993459,p=(p|p<<1)&1431655765,(p<<1|u)>>>0}var Tr=class{constructor(){f(this,"MAX_ITERATIONS",1e5);f(this,"solved",!1);f(this,"failed",!1);f(this,"iterations",0);f(this,"progress",0);f(this,"error",null);f(this,"activeSubSolver");f(this,"failedSubSolvers");f(this,"timeToSolve");f(this,"stats",{})}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(n){throw this.error=`${this.constructor.name} error: ${n}`,this.failed=!0,n}!this.solved&&this.iterations>this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}solve(){let n=Date.now();for(;!this.solved&&!this.failed;)this.step();let e=Date.now();this.timeToSolve=e-n}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}},LA=n=>{let e=new kA({});for(let i of n.directConnections)e.addConnections([i.netId?[i.netId,...i.pinIds]:i.pinIds]);let t=new kA(e.netMap);for(let i of n.netConnections)t.addConnections([[i.netId,...i.pinIds]]);return{directConnMap:e,netConnMap:t}};function c9t(n,e={}){let t=n.length,i=e?.maxDistance??Number.POSITIVE_INFINITY;if(t<=1)return[];{let u=new Set;for(let p of n){if(u.has(p.pinId))throw new Error(`Duplicate pinId detected: "${p.pinId}"`);u.add(p.pinId)}}let r=(u,p)=>Math.abs(u.x-p.x)+Math.abs(u.y-p.y),s=new Array(t).fill(!1),o=new Array(t).fill(Number.POSITIVE_INFINITY),a=new Array(t).fill(-1),c=0;for(let u=1;u<t;u++)n[u].pinId<n[c].pinId&&(c=u);o[c]=0;let l=[];for(let u=0;u<t;u++){let p=-1,d=Number.POSITIVE_INFINITY,_="";for(let g=0;g<t;g++)if(!s[g]){let x=o[g];(x<d||x===d&&(_===""||n[g].pinId<_))&&(d=x,_=n[g].pinId,p=g)}s[p]=!0,a[p]!==-1&&l.push([n[p].pinId,n[a[p]].pinId]);for(let g=0;g<t;g++)if(!s[g]){let x=r(n[p],n[g]),v=e?.forbidEdge?.(n[p],n[g])??!1,S=x>i||v?Number.POSITIVE_INFINITY:x;(S<o[g]||S===o[g]&&n[p].pinId<n[a[g]]?.pinId)&&(o[g]=S,a[g]=p)}}return l}var E1=(n,e)=>{let{x:t,y:i}=n,{center:r,width:s,height:o}=e,a=r.y+o/2,c=r.y-o/2,l=r.x+s/2,u=r.x-s/2,p=a-i,d=i-c,_=l-t,g=t-u,x=Math.min(p,d,_,g);return x===p?"y+":x===d?"y-":x===_?"x+":"x-"},l9t=n=>{let{pins:e,inputProblem:t,pinIdMap:i,chipMap:r}=n,s=d=>{let _=new Set,g=[d];_.add(d);let x=t.directConnections||[];for(;g.length;){let v=g.shift();for(let S of x)if(S.pinIds.includes(v))for(let P of S.pinIds)_.has(P)||(_.add(P),g.push(P))}return _},o=e[0].pinId,a=e[1].pinId,c=new Set([...s(o),...s(a)]),l=new Map,u=new Map,p=new Set(e.map(d=>d.chipId));for(let d of c){let _=i.get(d);if(!_)continue;let g=r[_.chipId];if(!g)continue;let x=_._facingDirection??E1(_,g),v=u.get(g.chipId);if(!v){v={center:g.center};let S={xPos:0,xNeg:0,yPos:0,yNeg:0};for(let P of g.pins){let T=P._facingDirection??E1(P,g);T==="x+"&&S.xPos++,T==="x-"&&S.xNeg++,T==="y+"&&S.yPos++,T==="y-"&&S.yNeg++}v.counts=S,u.set(g.chipId,v)}x==="x+"&&(v.hasXPos=!0),x==="x-"&&(v.hasXNeg=!0),x==="y+"&&(v.hasYPos=!0),x==="y-"&&(v.hasYNeg=!0)}for(let[d,_]of u){let g=new Set,x={axes:g},v=_.counts;!(v&&(v.xPos>1||v.xNeg>1||v.yPos>1||v.yNeg>1))&&p.has(d)||(_.hasXPos&&_.hasXNeg&&(x.x=_.center.x,g.add("x")),_.hasYPos&&_.hasYNeg&&(x.y=_.center.y,g.add("y"))),g.size>0&&l.set(d,x)}return l},MA=n=>{let{inputProblem:e,chipMap:t,pinIdMap:i,p1:r,p2:s}=n,o=l9t({pins:[r,s],inputProblem:e,pinIdMap:i,chipMap:t});if(o.size===0)return!1;let a=1e-9,c=(_,g)=>{for(let[,x]of o)if(x.axes.has("x")&&typeof x.x=="number"&&(_.x-x.x)*(g.x-x.x)<-a||x.axes.has("y")&&typeof x.y=="number"&&(_.y-x.y)*(g.y-x.y)<-a)return!0;return!1};if(Math.abs(r.x-s.x)<a||Math.abs(r.y-s.y)<a)return c({x:r.x,y:r.y},{x:s.x,y:s.y});let l={x:s.x,y:r.y},u={x:r.x,y:s.y},p=c({x:r.x,y:r.y},l)||c(l,{x:s.x,y:s.y}),d=c({x:r.x,y:r.y},u)||c(u,{x:s.x,y:s.y});return p&&d},Ls=(n,e=1)=>`hsl(${n.split("").reduce((i,r)=>i*31+r.charCodeAt(0),0)%360}, 100%, 50%, ${e})`,us=(n,e={})=>{let{connectionAlpha:t=.8,chipAlpha:i=.8}=e,r={lines:[],points:[],rects:[]},s=new Map;for(let o of n.chips)for(let a of o.pins)s.set(a.pinId,a);for(let o of n.chips){r.rects.push({label:o.chipId,center:o.center,width:o.width,height:o.height,fill:Ls(o.chipId,i)});for(let a of o.pins)r.points.push({label:`${a.pinId}
246
246
  ${a._facingDirection??E1(a,o)}`,x:a.x,y:a.y,color:Ls(a.pinId,.8)})}for(let o of n.directConnections){let[a,c]=o.pinIds,l=s.get(a),u=s.get(c);r.lines.push({points:[{x:l.x,y:l.y},{x:u.x,y:u.y}],strokeColor:Ls(o.netId??`${a}-${c}`,t)})}for(let o of n.netConnections){let a=o.pinIds.map(c=>s.get(c));for(let c=0;c<a.length-1;c++)for(let l=c+1;l<a.length;l++){let u=a[c],p=a[l];r.lines.push({points:[{x:u.x,y:u.y},{x:p.x,y:p.y}],strokeColor:Ls(o.netId,t),strokeDash:"4 2"})}}return r},u9t=class extends Tr{constructor({inputProblem:e}){super();f(this,"inputProblem");f(this,"mspConnectionPairs",[]);f(this,"dcConnMap");f(this,"globalConnMap");f(this,"queuedDcNetIds");f(this,"chipMap");f(this,"maxMspPairDistance");f(this,"pinMap");f(this,"userNetIdByPinId");this.inputProblem=e,this.maxMspPairDistance=e.maxMspPairDistance??1;let{directConnMap:t,netConnMap:i}=LA(e);this.dcConnMap=t,this.globalConnMap=i,this.pinMap={};for(let r of e.chips)for(let s of r.pins)this.pinMap[s.pinId]={...s,chipId:r.chipId};this.chipMap={};for(let r of e.chips)this.chipMap[r.chipId]=r;this.userNetIdByPinId={};for(let r of e.directConnections)if(r.netId){let[s,o]=r.pinIds;this.userNetIdByPinId[s]=r.netId,this.userNetIdByPinId[o]=r.netId}for(let r of e.netConnections)for(let s of r.pinIds)this.userNetIdByPinId[s]=r.netId;this.queuedDcNetIds=Object.keys(i.netMap)}getConstructorParams(){return{inputProblem:this.inputProblem}}_step(){if(this.queuedDcNetIds.length===0){this.solved=!0;return}let e=this.queuedDcNetIds.shift(),i=this.globalConnMap.getIdsConnectedToNet(e).filter(o=>!!this.pinMap[o]);if(i.length<=1)return;if(i.length===2){let[o,a]=i,c=this.pinMap[o],l=this.pinMap[a];if(Math.abs(c.x-l.x)+Math.abs(c.y-l.y)>this.maxMspPairDistance)return;let p=new Map(Object.entries(this.pinMap));if(MA({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:p,p1:c,p2:l}))return;let d=this.globalConnMap.getNetConnectedToId(o),_=this.userNetIdByPinId[o]??this.userNetIdByPinId[a];this.mspConnectionPairs.push({mspPairId:`${o}-${a}`,dcConnNetId:e,globalConnNetId:d,userNetId:_,pins:[c,l]});return}let r=new Map(Object.entries(this.pinMap)),s=c9t(i.map(o=>this.pinMap[o]).filter(Boolean),{maxDistance:this.maxMspPairDistance,forbidEdge:(o,a)=>MA({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:r,p1:o,p2:a})});for(let[o,a]of s){let c=this.pinMap[o],l=this.pinMap[a];if(MA({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:r,p1:c,p2:l}))continue;let u=this.globalConnMap.getNetConnectedToId(o),p=this.userNetIdByPinId[o]??this.userNetIdByPinId[a];this.mspConnectionPairs.push({mspPairId:`${o}-${a}`,dcConnNetId:e,globalConnNetId:u,userNetId:p,pins:[c,l]})}}visualize(){let e=us(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let t of this.mspConnectionPairs)e.lines.push({points:[{x:t.pins[0].x,y:t.pins[0].y},{x:t.pins[1].x,y:t.pins[1].y}],strokeColor:Ls(t.mspPairId,.75)});return e}};function FA(n){let e=n.width/2,t=n.height/2;return{minX:n.center.x-e,maxX:n.center.x+e,minY:n.center.y-t,maxY:n.center.y+t}}var p9t=n=>{let e=FA(n);return{chipId:n.chipId,...e}},US=n=>n.chips.map(p9t),$A=1e-9,Ba=(n,e,t=$A)=>Math.abs(n.x-e.x)<t,ml=(n,e,t=$A)=>Math.abs(n.y-e.y)<t,C1=(n,e,t,i=$A)=>{let r=Ba(n,e,i),s=ml(n,e,i);if(!r&&!s)return!1;if(r){let o=n.x;if(o<t.minX-i||o>t.maxX+i)return!1;let a=Math.min(n.y,e.y),c=Math.max(n.y,e.y);return Math.min(c,t.maxY)-Math.max(a,t.minY)>i}else{let o=n.y;if(o<t.minY-i||o>t.maxY+i)return!1;let a=Math.min(n.x,e.x),c=Math.max(n.x,e.x);return Math.min(c,t.maxX)-Math.max(a,t.minX)>i}},h9t=(n,e,t={})=>{for(let i=0;i<n.length-1;i++){let r=n[i],s=n[i+1],o=t.excludeRectIdsForSegment?.(i)??new Set;for(let a of e)if(!o.has(a.chipId)&&C1(r,s,a))return{segIndex:i,rect:a}}return null},d9t=(n,e)=>{for(let t=0;t<n.length-1;t++)for(let i of e)if(C1(n[t],n[t+1],i))return!0;return!1},QQ=1e-9,f9t=(n,e)=>({minX:Math.min(n.x,e.x),maxX:Math.max(n.x,e.x),minY:Math.min(n.y,e.y),maxY:Math.max(n.y,e.y)}),XQ=(n,e,t,i=QQ)=>n==="x"?e.x<t.minX-i?[(e.x+t.minX)/2]:e.x>t.maxX+i?[(e.x+t.maxX)/2]:[t.minX-.2,t.maxX+.2]:e.y<t.minY-i?[(e.y+t.minY)/2]:e.y>t.maxY+i?[(e.y+t.maxY)/2]:[t.minY-.2,t.maxY+.2],m9t=(n,e,t,i,r,s=QQ)=>{let o=[...i].map(a=>t.get(a)).filter(a=>!!a);if(n==="x"){let a=[r.minX,...o.map(d=>d.maxX)].filter(d=>d<e.minX-s),c=[r.maxX,...o.map(d=>d.minX)].filter(d=>d>e.maxX+s),l=a.length>0?Math.max(...a):void 0,u=c.length>0?Math.min(...c):void 0,p=[];return l!==void 0&&p.push((l+e.minX)/2),u!==void 0&&p.push((e.maxX+u)/2),p}else{let a=[r.minY,...o.map(d=>d.maxY)].filter(d=>d<e.minY-s),c=[r.maxY,...o.map(d=>d.minY)].filter(d=>d>e.maxY+s),l=a.length>0?Math.max(...a):void 0,u=c.length>0?Math.min(...c):void 0,p=[];return l!==void 0&&p.push((l+e.minY)/2),u!==void 0&&p.push((e.maxY+u)/2),p}},_9t=1e-9,y9t=(n,e,t,i,r=_9t)=>{if(e<0||e>=n.length-1)return null;let s=n[e],o=n[e+1],a=Ba(s,o,r),c=ml(s,o,r);if(!a&&!c||a&&t!=="x"||c&&t!=="y")return null;let l=n.map(u=>({...u}));if(t==="x"){if(Math.abs(s.x-i)<r&&Math.abs(o.x-i)<r)return null;l[e]={...l[e],x:i},l[e+1]={...l[e+1],x:i}}else{if(Math.abs(s.y-i)<r&&Math.abs(o.y-i)<r)return null;l[e]={...l[e],y:i},l[e+1]={...l[e+1],y:i}}if(e-1>=0){let u=l[e-1],p=l[e];if(Math.abs(u.x-p.x)+Math.abs(u.y-p.y)<r)return null}if(e+2<=l.length-1){let u=l[e+1],p=l[e+2];if(Math.abs(u.x-p.x)+Math.abs(u.y-p.y)<r)return null}for(let u=0;u<l.length-1;u++){let p=l[u],d=l[u+1];if(!ml(p,d,r)&&!Ba(p,d,r))return null}return l},UQ=(n,e=6)=>n.map(i=>`${i.x.toFixed(e)},${i.y.toFixed(e)}`).join("|"),ttt=class extends Tr{constructor(e){super();f(this,"pins");f(this,"inputProblem");f(this,"chipMap");f(this,"obstacles");f(this,"rectById");f(this,"aabb");f(this,"baseElbow");f(this,"solvedTracePath",null);f(this,"queue",[]);f(this,"visited",new Set);this.pins=e.pins,this.inputProblem=e.inputProblem,this.chipMap=e.chipMap;for(let r of this.pins)if(!r._facingDirection){let s=this.chipMap[r.chipId];r._facingDirection=E1(r,s)}this.obstacles=US(this.inputProblem),this.rectById=new Map(this.obstacles.map(r=>[r.chipId,r]));let[t,i]=this.pins;this.baseElbow=Qc({x:t.x,y:t.y,facingDirection:t._facingDirection},{x:i.x,y:i.y,facingDirection:i._facingDirection},{overshoot:.2}),this.aabb=f9t({x:t.x,y:t.y},{x:i.x,y:i.y}),this.queue.push({path:this.baseElbow,collisionChipIds:new Set}),this.visited.add(UQ(this.baseElbow))}getConstructorParams(){return{chipMap:this.chipMap,pins:this.pins,inputProblem:this.inputProblem}}axisOfSegment(e,t){return Ba(e,t)?"x":ml(e,t)?"y":null}pathLength(e){let t=0;for(let i=0;i<e.length-1;i++)t+=Math.abs(e[i+1].x-e[i].x)+Math.abs(e[i+1].y-e[i].y);return t}_step(){if(this.solvedTracePath){this.solved=!0;return}let e=this.queue.shift();if(!e){this.failed=!0,this.error="No collision-free path found";return}let{path:t,collisionChipIds:i}=e,[r,s]=this.pins,o=h9t(t,this.obstacles);if(!o){let v=t[0],S=t[t.length-1],P=1e-9,T=(k,N)=>Math.abs(k.x-N.x)<P&&Math.abs(k.y-N.y)<P;T(v,{x:r.x,y:r.y})&&T(S,{x:s.x,y:s.y})&&(this.solvedTracePath=t,this.solved=!0);return}let{segIndex:a,rect:c}=o,l=a===0,u=a===t.length-2;if(l){if(t.length<3)return;a=1}else if(u){if(t.length<3)return;a=t.length-3}let p=t[a],d=t[a+1],_=this.axisOfSegment(p,d);if(!_)return;let g=[];if(i.size===0){let v=XQ(_,{x:r.x,y:r.y},c),S=XQ(_,{x:s.x,y:s.y},c),P=[...v,...S],T=[...new Set(P)];g.push(...T)}else{let v=m9t(_,c,this.rectById,i,this.aabb);g.push(...v)}let x=[];for(let v of g){let S=y9t(t,a,_,v);if(!S)continue;let P=UQ(S);if(this.visited.has(P))continue;this.visited.add(P);let T=new Set(i);T.add(c.chipId);let k=this.pathLength(S);x.push({path:S,collisionRectIds:T,len:k})}x.sort((v,S)=>v.len-S.len);for(let v of x)this.queue.push({path:v.path,collisionChipIds:v.collisionRectIds})}visualize(){let e=us(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});e.lines.push({points:this.baseElbow,strokeColor:"red",strokeDash:"4 4"});let[t,i]=this.pins;e.lines.push({points:[{x:t.x,y:t.y},{x:i.x,y:i.y}],strokeColor:"blue",strokeDash:"5 5"});for(let{path:r,collisionChipIds:s}of this.queue)e.lines.push({points:r,strokeColor:"teal",strokeDash:"2 2"});return this.solvedTracePath?e.lines.push({points:this.solvedTracePath,strokeColor:"green"}):this.queue.length>0&&e.lines.push({points:this.queue[0].path,strokeColor:"orange"}),e}},g9t=class extends Tr{constructor(e){super();f(this,"inputProblem");f(this,"mspConnectionPairs");f(this,"dcConnMap");f(this,"globalConnMap");f(this,"queuedConnectionPairs");f(this,"chipMap");f(this,"currentConnectionPair",null);f(this,"solvedTracePaths",[]);f(this,"failedConnectionPairs",[]);this.inputProblem=e.inputProblem,this.mspConnectionPairs=e.mspConnectionPairs,this.dcConnMap=e.dcConnMap,this.globalConnMap=e.globalConnMap,this.chipMap=e.chipMap,this.queuedConnectionPairs=[...this.mspConnectionPairs]}getConstructorParams(){return{inputProblem:this.inputProblem,chipMap:this.chipMap,mspConnectionPairs:this.mspConnectionPairs,dcConnMap:this.dcConnMap,globalConnMap:this.globalConnMap}}_step(){if(this.activeSubSolver?.solved&&(this.solvedTracePaths.push({...this.currentConnectionPair,tracePath:this.activeSubSolver.solvedTracePath,mspConnectionPairIds:[this.currentConnectionPair.mspPairId],pinIds:[this.currentConnectionPair.pins[0].pinId,this.currentConnectionPair.pins[1].pinId]}),this.activeSubSolver=null,this.currentConnectionPair=null),this.activeSubSolver?.failed&&(this.currentConnectionPair&&this.failedConnectionPairs.push({...this.currentConnectionPair,error:this.activeSubSolver.error||void 0}),this.activeSubSolver=null,this.currentConnectionPair=null),this.activeSubSolver){this.activeSubSolver.step();return}let e=this.queuedConnectionPairs.shift();if(!e){this.solved=!0;return}this.currentConnectionPair=e;let{pins:t}=e;this.activeSubSolver=new ttt({inputProblem:this.inputProblem,pins:t,chipMap:this.chipMap})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=us(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let{mspPairId:t,tracePath:i}of this.solvedTracePaths)e.lines.push({points:i,strokeColor:"green"});for(let t of this.failedConnectionPairs)e.lines.push({points:[{x:t.pins[0].x,y:t.pins[0].y},{x:t.pins[1].x,y:t.pins[1].y}],strokeColor:"red",strokeDash:"4 2"});return e}},x9t=({pts:n,segmentIndex:e,offset:t,JOG_SIZE:i,EPS:r=1e-6})=>{if(e!==0&&e!==n.length-2)return;let s=n[e],o=n[e+1],a=Math.abs(s.x-o.x)<r,c=Math.abs(s.y-o.y)<r;if(!a&&!c)return;let l=a?o.y>s.y?1:-1:o.x>s.x?1:-1;if(e===0)if(a){let u=s.y+l*i;n.splice(1,1,{x:s.x,y:u},{x:s.x+t,y:u},{x:o.x+t,y:o.y})}else{let u=s.x+l*i;n.splice(1,1,{x:u,y:s.y},{x:u,y:s.y+t},{x:o.x,y:o.y+t})}else if(a){let u=o.y-l*i;n.splice(e,1,{x:s.x+t,y:s.y},{x:o.x+t,y:u},{x:o.x,y:u})}else{let u=o.x-l*i;n.splice(e,1,{x:s.x,y:s.y+t},{x:u,y:o.y+t},{x:u,y:o.y})}},b9t=class extends Tr{constructor(e){super();f(this,"overlappingTraceSegments");f(this,"traceNetIslands");f(this,"SHIFT_DISTANCE",.1);f(this,"correctedTraceMap",{});this.overlappingTraceSegments=e.overlappingTraceSegments,this.traceNetIslands=e.traceNetIslands;for(let{connNetId:t,pathsWithOverlap:i}of this.overlappingTraceSegments)for(let{solvedTracePathIndex:r,traceSegmentIndex:s}of i){let o=this.traceNetIslands[t][r].mspPairId;this.correctedTraceMap[o]=this.traceNetIslands[t][r]}}_step(){let t=this.overlappingTraceSegments.map((s,o)=>{let a=Math.floor(o/2)+1;return(o%2===0?-a:a)*this.SHIFT_DISTANCE}),i=(s,o)=>Math.abs(s-o)<1e-6,r=(s,o)=>!!s&&!!o&&i(s.x,o.x)&&i(s.y,o.y);this.overlappingTraceSegments.forEach((s,o)=>{let a=t[o],c=new Map;for(let l of s.pathsWithOverlap)c.has(l.solvedTracePathIndex)||c.set(l.solvedTracePathIndex,new Set),c.get(l.solvedTracePathIndex).add(l.traceSegmentIndex);for(let[l,u]of c){let p=this.traceNetIslands[s.connNetId][l],d=this.correctedTraceMap[p.mspPairId]??p,_=d.tracePath.map(P=>({...P})),g=Array.from(u).sort((P,T)=>P-T),x=Array.from(u).sort((P,T)=>P-T).reverse(),v=this.SHIFT_DISTANCE;for(let P of x)if(!(P<0||P>=_.length-1))if(P===0||P===_.length-2)x9t({pts:_,segmentIndex:P,offset:a,JOG_SIZE:v,EPS:1e-6});else{let T=_[P],k=_[P+1],N=Math.abs(T.x-k.x)<1e-6,E=Math.abs(T.y-k.y)<1e-6;if(!N&&!E)continue;N?(T.x+=a,k.x+=a):(T.y+=a,k.y+=a)}let S=[];for(let P of _)(S.length===0||!r(S[S.length-1],P))&&S.push(P);this.correctedTraceMap[p.mspPairId]={...d,tracePath:S}}}),this.solved=!0}visualize(){let e={lines:[],points:[],rects:[],circles:[]};for(let t of this.overlappingTraceSegments)for(let{solvedTracePathIndex:i,traceSegmentIndex:r}of t.pathsWithOverlap){let s=this.traceNetIslands[t.connNetId][i],o=s.tracePath[r],a=s.tracePath[r+1];e.lines.push({points:[o,a],strokeColor:"red"})}for(let t of Object.values(this.correctedTraceMap))e.lines.push({points:t.tracePath,strokeColor:"blue",strokeDash:"4 2"});return e}},v9t=class extends Tr{constructor(e){super();f(this,"inputProblem");f(this,"inputTracePaths");f(this,"globalConnMap");f(this,"traceNetIslands",{});f(this,"correctedTraceMap",{});f(this,"cleanupPhase",null);this.inputProblem=e.inputProblem,this.inputTracePaths=e.inputTracePaths,this.globalConnMap=e.globalConnMap;for(let t of this.inputTracePaths){let{mspPairId:i}=t;this.correctedTraceMap[i]=t}this.traceNetIslands=this.computeTraceNetIslands()}getConstructorParams(){return{inputProblem:this.inputProblem,inputTracePaths:this.inputTracePaths,globalConnMap:this.globalConnMap}}computeTraceNetIslands(){let e={};for(let t of this.inputTracePaths){let i=this.correctedTraceMap[t.mspPairId]??t,r=i.globalConnNetId;e[r]||(e[r]=[]),e[r].push(i)}return e}findNextOverlapIssue(){let t=Object.keys(this.traceNetIslands);for(let i=0;i<t.length;i++)for(let r=i+1;r<t.length;r++){let s=t[i],o=t[r],a=this.traceNetIslands[s]||[],c=this.traceNetIslands[o]||[],l=[],u=[],p=new Set,d=new Set,_=(g,x,v,S)=>{let P=Math.min(g,x),T=Math.max(g,x),k=Math.min(v,S),N=Math.max(v,S);return Math.min(T,N)-Math.max(P,k)>.002};for(let g=0;g<a.length;g++){let v=a[g].tracePath;for(let S=0;S<v.length-1;S++){let P=v[S],T=v[S+1],k=Math.abs(P.x-T.x)<.002,N=Math.abs(P.y-T.y)<.002;if(!(!k&&!N))for(let E=0;E<c.length;E++){let M=c[E].tracePath;for(let A=0;A<M.length-1;A++){let R=M[A],B=M[A+1],j=Math.abs(R.x-B.x)<.002,U=Math.abs(R.y-B.y)<.002;if(!(!j&&!U)){if(k&&j){if(Math.abs(P.x-R.x)<.002&&_(P.y,T.y,R.y,B.y)){let X=`${g}:${S}`,W=`${E}:${A}`;p.has(X)||(l.push({solvedTracePathIndex:g,traceSegmentIndex:S}),p.add(X)),d.has(W)||(u.push({solvedTracePathIndex:E,traceSegmentIndex:A}),d.add(W))}}else if(N&&U&&Math.abs(P.y-R.y)<.002&&_(P.x,T.x,R.x,B.x)){let X=`${g}:${S}`,W=`${E}:${A}`;p.has(X)||(l.push({solvedTracePathIndex:g,traceSegmentIndex:S}),p.add(X)),d.has(W)||(u.push({solvedTracePathIndex:E,traceSegmentIndex:A}),d.add(W))}}}}}}if(l.length>0&&u.length>0)return{overlappingTraceSegments:[{connNetId:s,pathsWithOverlap:l},{connNetId:o,pathsWithOverlap:u}]}}return null}findNextDiagonalSegment(){for(let t in this.correctedTraceMap){let i=this.correctedTraceMap[t].tracePath;for(let r=0;r<i.length-1;r++){let s=i[r],o=i[r+1],a=Math.abs(s.y-o.y)<.002,c=Math.abs(s.x-o.x)<.002;if(!a&&!c)return{mspPairId:t,tracePath:i,i:r,p1:s,p2:o}}}return null}findAndFixNextDiagonalSegment(){let e=this.findNextDiagonalSegment();if(!e)return!1;let{mspPairId:t,tracePath:i,i:r,p1:s,p2:o}=e,a=.002,c=r>0?i[r-1]:null,l=r+2<i.length?i[r+2]:null,u=c?Math.abs(c.x-s.x)<a:!1,p=c?Math.abs(c.y-s.y)<a:!1,d=l?Math.abs(o.x-l.x)<a:!1,_=l?Math.abs(o.y-l.y)<a:!1,g={x:s.x,y:o.y},x={x:o.x,y:s.y},v=0;u&&v++,_&&v++;let S=0;p&&S++,d&&S++;let P=v<S?g:x;return i.splice(r+1,0,P),!0}_step(){if(this.activeSubSolver?.solved){for(let[i,r]of Object.entries(this.activeSubSolver.correctedTraceMap))this.correctedTraceMap[i]=r;this.activeSubSolver=null,this.traceNetIslands=this.computeTraceNetIslands()}if(this.activeSubSolver){this.activeSubSolver.step();return}let e=this.findNextOverlapIssue();if(e===null){if(this.cleanupPhase===null&&(this.cleanupPhase="diagonals"),this.cleanupPhase==="diagonals"){this.findAndFixNextDiagonalSegment()||(this.cleanupPhase="done",this.solved=!0);return}this.solved=!0;return}let{overlappingTraceSegments:t}=e;this.activeSubSolver=new b9t({overlappingTraceSegments:t,traceNetIslands:this.traceNetIslands})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=us(this.inputProblem);e.circles=e.circles||[];for(let t of Object.values(this.correctedTraceMap))e.lines.push({points:t.tracePath,strokeColor:"purple"});if(this.cleanupPhase==="diagonals"){let t=this.findNextDiagonalSegment();t&&e.lines.push({points:[t.p1,t.p2],strokeColor:"red",strokeWidth:.05})}return e}},w9t=class{constructor(n){f(this,"chips");f(this,"spatialIndex");f(this,"spatialIndexIdToChip");this.chips=n.map(e=>({...e,bounds:FA(e),spatialIndexId:null})),this.spatialIndexIdToChip=new Map,this.spatialIndex=new T1(n.length);for(let e of this.chips)e.spatialIndexId=this.spatialIndex.add(e.bounds.minX,e.bounds.minY,e.bounds.maxX,e.bounds.maxY),this.spatialIndexIdToChip.set(e.spatialIndexId,e);this.spatialIndex.finish()}getChipsInBounds(n){return this.spatialIndex.search(n.minX,n.minY,n.maxX,n.maxY).map(t=>this.spatialIndexIdToChip.get(t))}doesOrthogonalLineIntersectChip(n,e={}){let t=e.excludeChipIds??[],[i,r]=n,{x:s,y:o}=i,{x:a,y:c}=r;return this.getChipsInBounds({minX:Math.min(s,a),minY:Math.min(o,c),maxX:Math.max(s,a),maxY:Math.max(o,c)}).filter(u=>!t.includes(u.chipId)).length>0}},S9t=.45,VQ=.2;function RA(n){let{orientation:e,netLabelWidth:t}=n,i=typeof t=="number"?t:S9t;return e==="y+"||e==="y-"?{width:VQ,height:i}:{width:i,height:VQ}}function OA(n,e,t,i){switch(e){case"x+":return{x:n.x+t/2,y:n.y};case"x-":return{x:n.x-t/2,y:n.y};case"y+":return{x:n.x,y:n.y+i/2};case"y-":return{x:n.x,y:n.y-i/2}}}function Nd(n,e,t){return{minX:n.x-e/2,minY:n.y-t/2,maxX:n.x+e/2,maxY:n.y+t/2}}function ett(n,e,t,i=1e-9){let r=Math.abs(n.x-e.x)<i,s=Math.abs(n.y-e.y)<i;if(!r&&!s)return!1;if(r){let o=n.x;if(o<t.minX-i||o>t.maxX+i)return!1;let a=Math.min(n.y,e.y),c=Math.max(n.y,e.y);return Math.min(c,t.maxY)-Math.max(a,t.minY)>i}else{let o=n.y;if(o<t.minY-i||o>t.maxY+i)return!1;let a=Math.min(n.x,e.x),c=Math.max(n.x,e.x);return Math.min(c,t.maxX)-Math.max(a,t.minX)>i}}function ntt(n,e,t,i){for(let[r,s]of Object.entries(e)){let o=s.tracePath;for(let a=0;a<o.length-1;a++)if(!(r===t&&a===i)&&ett(o[a],o[a+1],n))return{hasIntersection:!0,mspPairId:r,segIndex:a}}return{hasIntersection:!1}}function GQ(n){let e=0,t=n.tracePath;for(let i=0;i<t.length-1;i++)e+=Math.abs(t[i+1].x-t[i].x)+Math.abs(t[i+1].y-t[i].y);return e}function itt(n){let{inputProblem:e,inputTraceMap:t,globalConnNetId:i,fallbackTrace:r,mspConnectionPairIds:s}=n,o=Object.fromEntries(e.chips.map(d=>[d.chipId,d])),a=Object.values(t).filter(d=>d.globalConnNetId===i);if(s&&s.length>0){let d=new Set(s);a=a.filter(_=>_.mspConnectionPairIds.some(g=>d.has(g)))}let c=new Set;for(let d of a)c.add(d.pins[0].chipId),c.add(d.pins[1].chipId);let l=null,u=-1;for(let d of c){let g=o[d]?.pins?.length??0;g>u&&(u=g,l=d)}let p=l==null?[]:a.filter(d=>d.pins[0].chipId===l||d.pins[1].chipId===l);return p.length>0?p.reduce((d,_)=>GQ(d)>=GQ(_)?d:_):r}function P9t(n,e){return[{x:n.x,y:n.y},{x:(n.x+e.x)/2,y:(n.y+e.y)/2},{x:e.x,y:e.y}]}function k9t(n){let{inputProblem:e,inputTraceMap:t,chipObstacleSpatialIndex:i,overlappingSameNetTraceGroup:r,availableOrientations:s,netLabelWidth:o}=n,a=r.portOnlyPinId;if(!a)return{placement:null,testedCandidates:[],error:"No portOnlyPinId provided"};let c=null,l=null;for(let E of e.chips){let C=E.pins.find(M=>M.pinId===a);if(C){c={x:C.x,y:C.y},l=C._facingDirection||E1(C,E);break}}if(!c||!l)return{placement:null,testedCandidates:[],error:`Port-only pin not found: ${a}`};let u=s.length>0?s:["x+","x-","y+","y-"],p={x:c.x,y:c.y},d=E=>E==="x+"?{x:1,y:0}:E==="x-"?{x:-1,y:0}:E==="y+"?{x:0,y:1}:{x:0,y:-1},_=[];for(let E of u){let{width:C,height:M}=RA({orientation:E,netLabelWidth:o}),A=OA(p,E,C,M),R=d(E),B=.001,j={x:A.x+R.x*B,y:A.y+R.y*B},U=Nd(j,C,M);if(i.getChipsInBounds(U).length>0){_.push({center:j,width:C,height:M,bounds:U,anchor:p,orientation:E,status:"chip-collision",hostSegIndex:-1});continue}if(ntt(U,t,"",-1).hasIntersection){_.push({center:j,width:C,height:M,bounds:U,anchor:p,orientation:E,status:"trace-collision",hostSegIndex:-1});continue}return _.push({center:j,width:C,height:M,bounds:U,anchor:p,orientation:E,status:"ok",hostSegIndex:-1}),{placement:{globalConnNetId:r.globalConnNetId,dcConnNetId:void 0,netId:r.netId,mspConnectionPairIds:[],pinIds:[a],orientation:E,anchorPoint:p,width:C,height:M,center:j},testedCandidates:_}}let g=l,{width:x,height:v}=RA({orientation:g,netLabelWidth:o}),S=OA(p,g,x,v),P=d(g),T=.001,k={x:S.x+P.x*T,y:S.y+P.y*T};return{placement:{globalConnNetId:r.globalConnNetId,dcConnNetId:void 0,netId:r.netId,mspConnectionPairIds:[],pinIds:[a],orientation:g,anchorPoint:p,width:x,height:v,center:k},testedCandidates:_}}function T9t(n){let e=us(n.inputProblem),t=n.overlappingSameNetTraceGroup.globalConnNetId,i=itt({inputProblem:n.inputProblem,inputTraceMap:n.inputTraceMap,globalConnNetId:t,fallbackTrace:n.overlappingSameNetTraceGroup.overlappingTraces}),r=Ls(t,.9),s=Ls(t,.5);for(let o of Object.values(n.inputTraceMap)){let a=i?o.mspPairId===i.mspPairId:!1;e.lines.push({points:o.tracePath})}for(let o of n.testedCandidates){let a=o.status==="ok"?"rgba(0, 180, 0, 0.25)":o.status==="chip-collision"?"rgba(220, 0, 0, 0.25)":o.status==="trace-collision"?"rgba(220, 140, 0, 0.25)":"rgba(120, 120, 120, 0.15)",c=o.status==="ok"?"green":o.status==="chip-collision"?"red":o.status==="trace-collision"?"orange":"gray";e.rects.push({center:{x:(o.bounds.minX+o.bounds.maxX)/2,y:(o.bounds.minY+o.bounds.maxY)/2},width:o.width,height:o.height,fill:a,strokeColor:c}),e.points.push({x:o.anchor.x,y:o.anchor.y,color:c})}if(n.netLabelPlacement){let o=n.netLabelPlacement;e.rects.push({center:o.center,width:o.width,height:o.height,fill:"rgba(0, 128, 255, 0.35)",strokeColor:"blue"}),e.points.push({x:o.anchorPoint.x,y:o.anchorPoint.y,color:"blue"})}return e}var WQ=class extends Tr{constructor(e){super();f(this,"inputProblem");f(this,"inputTraceMap");f(this,"overlappingSameNetTraceGroup");f(this,"availableOrientations");f(this,"chipObstacleSpatialIndex");f(this,"netLabelWidth");f(this,"netLabelPlacement",null);f(this,"testedCandidates",[]);this.inputProblem=e.inputProblem,this.inputTraceMap=e.inputTraceMap,this.overlappingSameNetTraceGroup=e.overlappingSameNetTraceGroup,this.availableOrientations=e.availableOrientations,this.netLabelWidth=e.netLabelWidth,this.chipObstacleSpatialIndex=e.inputProblem._chipObstacleSpatialIndex??new w9t(e.inputProblem.chips)}getConstructorParams(){return{inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth}}_step(){if(this.netLabelPlacement){this.solved=!0;return}if(this.overlappingSameNetTraceGroup.portOnlyPinId){let d=k9t({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,chipObstacleSpatialIndex:this.chipObstacleSpatialIndex,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth});if(this.testedCandidates.push(...d.testedCandidates),d.placement){this.netLabelPlacement=d.placement,this.solved=!0;return}this.failed=!0,this.error=d.error??"Could not place net label at port without collisions";return}let e=this.overlappingSameNetTraceGroup.globalConnNetId,t=itt({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,globalConnNetId:e,fallbackTrace:this.overlappingSameNetTraceGroup.overlappingTraces,mspConnectionPairIds:this.overlappingSameNetTraceGroup.mspConnectionPairIds});if(!t){this.failed=!0,this.error="No host trace found for net label placement";return}let i=new Set(this.overlappingSameNetTraceGroup.mspConnectionPairIds??[]),r=Object.values(this.inputTraceMap).filter(d=>d.globalConnNetId===e&&(i.size===0||d.mspConnectionPairIds.some(_=>i.has(_)))),s=this.availableOrientations.length===1?[t,...r.filter(d=>d.mspPairId!==t.mspPairId)]:[t],o=this.availableOrientations.length>0?this.availableOrientations:["x+","x-","y+","y-"],a=this.availableOrientations.length===1,c=(d,_)=>{switch(d){case"y+":return _.y;case"y-":return-_.y;case"x+":return _.x;case"x-":return-_.x}},l=null,u=-1/0,p=1e-6;for(let d of s){let _=d.tracePath.slice();for(let g=0;g<_.length-1;g++){let x=_[g],v=_[g+1],S=Math.abs(x.y-v.y)<p,P=Math.abs(x.x-v.x)<p;if(!S&&!P)continue;let T=S?["y+","y-"]:["x+","x-"],k=o.filter(E=>T.includes(E));if(k.length===0)continue;let N=P9t(x,v);for(let E of N)for(let C of k){let{width:M,height:A}=RA({orientation:C,netLabelWidth:this.netLabelWidth}),R=OA(E,C,M,A),B=C==="x+"?{x:1,y:0}:C==="x-"?{x:-1,y:0}:C==="y+"?{x:0,y:1}:{x:0,y:-1},j=1e-4,U={x:R.x+B.x*j,y:R.y+B.y*j},X=Nd(U,M,A);if(this.chipObstacleSpatialIndex.getChipsInBounds(X).length>0){this.testedCandidates.push({center:U,width:M,height:A,bounds:X,anchor:E,orientation:C,status:"chip-collision",hostSegIndex:g});continue}if(ntt(X,this.inputTraceMap,d.mspPairId,g).hasIntersection){this.testedCandidates.push({center:U,width:M,height:A,bounds:X,anchor:E,orientation:C,status:"trace-collision",hostSegIndex:g});continue}if(this.testedCandidates.push({center:U,width:M,height:A,bounds:X,anchor:E,orientation:C,status:"ok",hostSegIndex:g}),a){let nt=c(C,E);nt>u+1e-9&&(u=nt,l={anchor:E,orientation:C,width:M,height:A,center:R,hostSegIndex:g,dcConnNetId:d.dcConnNetId,mspPairId:d.mspPairId,pinIds:[d.pins[0].pinId,d.pins[1].pinId]});continue}this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:d.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[d.mspPairId],pinIds:[d.pins[0].pinId,d.pins[1].pinId],orientation:C,anchorPoint:E,width:M,height:A,center:R},this.solved=!0;return}}}if(a&&l){this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:l.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[l.mspPairId],pinIds:l.pinIds,orientation:l.orientation,anchorPoint:l.anchor,width:l.width,height:l.height,center:l.center},this.solved=!0;return}this.failed=!0,this.error="Could not place net label without collisions"}visualize(){return T9t(this)}},HQ=class extends Tr{constructor(e){super();f(this,"inputProblem");f(this,"inputTraceMap");f(this,"overlappingSameNetTraceGroups");f(this,"queuedOverlappingSameNetTraceGroups");f(this,"netLabelPlacements",[]);f(this,"currentGroup",null);f(this,"triedAnyOrientationFallbackForCurrentGroup",!1);this.inputProblem=e.inputProblem,this.inputTraceMap=e.inputTraceMap,this.overlappingSameNetTraceGroups=this.computeOverlappingSameNetTraceGroups(),this.queuedOverlappingSameNetTraceGroups=[...this.overlappingSameNetTraceGroups]}computeOverlappingSameNetTraceGroups(){let e={};for(let c of Object.values(this.inputTraceMap)){let l=c.globalConnNetId;e[l]||(e[l]=[]),e[l].push(c)}let{netConnMap:t}=LA(this.inputProblem),i=new Map;for(let c of this.inputProblem.chips)for(let l of c.pins)i.set(l.pinId,l);let r={};for(let c of this.inputProblem.directConnections)if(c.netId){let[l,u]=c.pinIds;r[l]=c.netId,r[u]=c.netId}for(let c of this.inputProblem.netConnections)for(let l of c.pinIds)r[l]=c.netId;let s=[],o=this.inputProblem.chips.flatMap(c=>c.pins.map(l=>l.pinId)),a=new Set;for(let c of o){let l=t.getNetConnectedToId(c);l&&a.add(l)}for(let c of a){let u=t.getIdsConnectedToNet(c).filter(_=>i.has(_)),p={};for(let _ of u)p[_]=new Set;for(let _ of e[c]??[]){let g=_.pins[0].pinId,x=_.pins[1].pinId;p[g]&&p[x]&&(p[g].add(x),p[x].add(g))}let d=new Set;for(let _ of u){if(d.has(_))continue;let g=[_],x=new Set;for(d.add(_);g.length>0;){let S=g.pop();x.add(S);for(let P of p[S]??[])d.has(P)||(d.add(P),g.push(P))}let v=(e[c]??[]).filter(S=>x.has(S.pins[0].pinId)&&x.has(S.pins[1].pinId));if(v.length>0){let S=C=>{let M=0,A=C.tracePath;for(let R=0;R<A.length-1;R++)M+=Math.abs(A[R+1].x-A[R].x)+Math.abs(A[R+1].y-A[R].y);return M},P=v[0],T=S(P);for(let C=1;C<v.length;C++){let M=S(v[C]);M>T&&(P=v[C],T=M)}let k=v.find(C=>C.userNetId!=null)?.userNetId;if(!k){for(let C of x)if(r[C]){k=r[C];break}}let N=Array.from(new Set(v.flatMap(C=>C.mspConnectionPairIds??[C.mspPairId]))),E={globalConnNetId:c,netId:k,overlappingTraces:P,mspConnectionPairIds:N};s.push(E)}else for(let S of x){let P=r[S];P&&s.push({globalConnNetId:c,netId:P,portOnlyPinId:S})}}}return s}_step(){if(this.activeSubSolver?.solved){this.netLabelPlacements.push(this.activeSubSolver.netLabelPlacement),this.activeSubSolver=null,this.currentGroup=null,this.triedAnyOrientationFallbackForCurrentGroup=!1;return}if(this.activeSubSolver?.failed){let r=["x+","x-","y+","y-"],s=this.activeSubSolver.availableOrientations,o=s.length===4&&r.every(a=>s.includes(a));if(!this.triedAnyOrientationFallbackForCurrentGroup&&!o&&this.currentGroup){this.triedAnyOrientationFallbackForCurrentGroup=!0;let a=this.currentGroup.netId?this.inputProblem.netConnections.find(c=>c.netId===this.currentGroup.netId)?.netLabelWidth:void 0;this.activeSubSolver=new WQ({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.currentGroup,availableOrientations:r,netLabelWidth:a});return}this.failed=!0,this.error=this.activeSubSolver.error;return}if(this.activeSubSolver){this.activeSubSolver.step();return}let e=this.queuedOverlappingSameNetTraceGroups.shift();if(!e){this.solved=!0;return}let t=e.netId??e.globalConnNetId;this.currentGroup=e,this.triedAnyOrientationFallbackForCurrentGroup=!1;let i=this.currentGroup.netId?this.inputProblem.netConnections.find(r=>r.netId===this.currentGroup.netId)?.netLabelWidth:void 0;this.activeSubSolver=new WQ({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:e,availableOrientations:this.inputProblem.availableNetLabelOrientations[t]??["x+","x-","y+","y-"],netLabelWidth:i})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=us(this.inputProblem);for(let t of Object.values(this.inputTraceMap))e.lines.push({points:t.tracePath,strokeColor:"purple"});for(let t of this.netLabelPlacements)e.rects.push({center:t.center,width:t.width,height:t.height,fill:Ls(t.globalConnNetId,.35),strokeColor:Ls(t.globalConnNetId,.9)}),e.points.push({x:t.anchorPoint.x,y:t.anchorPoint.y,color:Ls(t.globalConnNetId,.9)});return e}},E9t=class extends Tr{constructor(e){super();f(this,"input");f(this,"output");f(this,"inputProblem");f(this,"traces");this.input=e,this.inputProblem=e.inputProblem,this.traces=e.traces,this.output={netLabelPlacements:e.netLabelPlacements,mergedLabelNetIdMap:{}}}_step(){let e=this.input.netLabelPlacements,t={};if(!e||e.length===0){this.output={netLabelPlacements:[],mergedLabelNetIdMap:{}},this.solved=!0;return}let i={};for(let s of e){if(s.pinIds.length===0)continue;let o=s.pinIds[0].split(".")[0];if(!o)continue;let a=`${o}-${s.orientation}`;a in i||(i[a]=[]),i[a].push(s)}let r=[];for(let[s,o]of Object.entries(i)){if(o.length<=1){r.push(...o);continue}let a=1/0,c=1/0,l=-1/0,u=-1/0;for(let v of o){let S=Nd(v.center,v.width,v.height);a=Math.min(a,S.minX),c=Math.min(c,S.minY),l=Math.max(l,S.maxX),u=Math.max(u,S.maxY)}let p=l-a,d=u-c,_=o[0],g=`merged-group-${s}`,x=new Set(o.map(v=>v.globalConnNetId));t[g]=x,r.push({..._,globalConnNetId:g,width:p,height:d,center:{x:a+p/2,y:c+d/2},pinIds:[...new Set(o.flatMap(v=>v.pinIds))],mspConnectionPairIds:[...new Set(o.flatMap(v=>v.mspConnectionPairIds))]})}this.output={netLabelPlacements:r,mergedLabelNetIdMap:t},this.solved=!0}getOutput(){return this.output}visualize(){let e=us(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});e.rects||(e.rects=[]),e.lines||(e.lines=[]),e.points||(e.points=[]),e.texts||(e.texts=[]);let t=new Map;for(let i of this.input.netLabelPlacements)t.set(i.globalConnNetId,i);for(let i of this.traces){let r={points:i.tracePath.map(s=>({x:s.x,y:s.y})),strokeColor:"blue"};e.lines.push(r)}for(let i of this.output.netLabelPlacements){let r=i.globalConnNetId.startsWith("merged-group-"),s=Ls(i.globalConnNetId);if(r){e.rects.push({center:i.center,width:i.width,height:i.height,fill:s.replace(/, 1\)/,", 0.2)"),stroke:s,label:i.globalConnNetId});let o=this.output.mergedLabelNetIdMap[i.globalConnNetId];if(o)for(let a of o){let c=t.get(a);if(c){let l=Nd(c.center,c.width,c.height),u={x:l.minX,y:l.minY},p={x:l.maxX,y:l.minY},d={x:l.maxX,y:l.maxY},_={x:l.minX,y:l.maxY};e.lines.push({points:[u,p,d,_,u],strokeColor:s,strokeDash:"4 4"}),e.lines.push({points:[c.center,i.center],strokeColor:s,strokeDash:"2 2"})}}}else e.rects.push({center:i.center,width:i.width,height:i.height,stroke:s,label:i.globalConnNetId})}return e}},M9t=(n,e)=>{let t=[];for(let i of n)for(let r of e){let s=Nd(r.center,r.width,r.height);for(let o=0;o<i.tracePath.length-1;o++){let a=i.tracePath[o],c=i.tracePath[o+1];if(ett(a,c,s)){if(i.globalConnNetId===r.globalConnNetId)break;t.push({trace:i,label:r});break}}}return t},C9t=(n,e)=>{let t=s=>s.x>e.minX&&s.x<e.maxX&&s.y>e.minY&&s.y<e.maxY,i=-1,r=-1;for(let s=0;s<n.length;s++)t(n[s])&&(i===-1&&(i=s),r=s);return{firstInsideIndex:i,lastInsideIndex:r}},I9t=({initialTrace:n,firstInsideIndex:e,lastInsideIndex:t,labelBounds:i,paddingBuffer:r,detourCount:s})=>{if(e<=0||t>=n.tracePath.length-1)return[];let o=n.tracePath[e-1],a=n.tracePath[t+1],c=n.tracePath.slice(0,e),l=n.tracePath.slice(t+1),u=[];o.x!==a.x&&o.y!==a.y?(u.push([{x:a.x,y:o.y}]),u.push([{x:o.x,y:a.y}])):(o.x===a.x||o.y===a.y)&&u.push([]);let p=r+s*r,d=i.minX-p,_=i.maxX+p,g=i.maxY+p,x=i.minY-p;return(o.x<=i.minX||a.x<=i.minX)&&o.x<i.maxX&&a.x<i.maxX&&u.push([{x:d,y:o.y},{x:d,y:a.y}]),(o.x>=i.maxX||a.x>=i.maxX)&&o.x>i.minX&&a.x>i.minX&&u.push([{x:_,y:o.y},{x:_,y:a.y}]),(o.y>=i.maxY||a.y>=i.maxY)&&o.y>i.minY&&a.y>i.minY&&u.push([{x:o.x,y:g},{x:a.x,y:g}]),(o.y<=i.minY||a.y<=i.minY)&&o.y<i.maxY&&a.y<i.maxY&&u.push([{x:o.x,y:x},{x:a.x,y:x}]),u.map(v=>[...c,...v,...l])},N9t=({initialTrace:n,label:e,labelBounds:t,paddingBuffer:i,detourCount:r})=>{let s=-1;for(let p=0;p<n.tracePath.length-1;p++)if(C1(n.tracePath[p],n.tracePath[p+1],t)){s=p;break}if(s===-1)return[];let o=n.tracePath[s],a=n.tracePath[s+1];if(!o||!a)return[];let c=[],l=Nd(e.center,e.width,e.height),u=i+r*i;if(Ba(o,a)){let p=[l.maxX+u,l.minX-u];for(let d of p)c.push(a.y>o.y?[{x:o.x,y:l.minY-u},{x:d,y:l.minY-u},{x:d,y:l.maxY+u},{x:a.x,y:l.maxY+u}]:[{x:o.x,y:l.maxY+u},{x:d,y:l.maxY+u},{x:d,y:l.minY-u},{x:a.x,y:l.minY-u}])}else{let p=[l.maxY+u,l.minY-u];for(let d of p)c.push(a.x>o.x?[{x:l.minX-u,y:o.y},{x:l.minX-u,y:d},{x:l.maxX+u,y:d},{x:l.maxX+u,y:a.y}]:[{x:l.maxX+u,y:o.y},{x:l.maxX+u,y:d},{x:l.minX-u,y:d},{x:l.minX-u,y:a.y}])}return c.map(p=>[...n.tracePath.slice(0,s+1),...p,...n.tracePath.slice(s+1)])},M1=n=>{if(n.length<3)return n;let e=[n[0]];for(let i=1;i<n.length-1;i++){let r=e[e.length-1],s=n[i],o=n[i+1];Ba(r,s)&&Ba(s,o)||ml(r,s)&&ml(s,o)||e.push(s)}if(e.push(n[n.length-1]),e.length<3)return e;let t=[e[0]];for(let i=1;i<e.length-1;i++){let r=t[t.length-1],s=e[i],o=e[i+1];Ba(r,s)&&Ba(s,o)||ml(r,s)&&ml(s,o)||t.push(s)}return t.push(e[e.length-1]),t},A9t=({trace:n,label:e,paddingBuffer:t,detourCount:i})=>{let r={...n,tracePath:M1(n.tracePath)};if(n.globalConnNetId===e.globalConnNetId)return[r.tracePath];let s=t,o=Nd(e.center,e.width,e.height),a={minX:o.minX-s,minY:o.minY-s,maxX:o.maxX+s,maxY:o.maxY+s,chipId:`netlabel-${e.netId}`},c=N9t({initialTrace:r,label:e,labelBounds:a,paddingBuffer:t,detourCount:i}),{firstInsideIndex:l,lastInsideIndex:u}=C9t(r.tracePath,a),p=I9t({initialTrace:r,firstInsideIndex:l,lastInsideIndex:u,labelBounds:a,paddingBuffer:t,detourCount:i});return[...c,...p]},R9t=class extends Tr{constructor(e){super();f(this,"queuedCandidatePaths");f(this,"solvedTracePath",null);f(this,"initialTrace");f(this,"problem");f(this,"obstacles");f(this,"label");this.initialTrace=e.trace,this.problem=e.problem,this.label=e.label;let t=A9t({...e}),i=r=>{let s=0;for(let o=0;o<r.length-1;o++){let a=r[o+1].x-r[o].x,c=r[o+1].y-r[o].y;s+=Math.sqrt(a*a+c*c)}return s};this.queuedCandidatePaths=t.sort((r,s)=>i(r)-i(s)),this.obstacles=US(this.problem)}_step(){if(this.queuedCandidatePaths.length===0){this.failed=!0;return}let e=this.queuedCandidatePaths.shift(),t=M1(e);d9t(t,this.obstacles)||(this.solvedTracePath=t,this.solved=!0)}visualize(){let e=us(this.problem,{chipAlpha:.1,connectionAlpha:.1});return e.lines||(e.lines=[]),e.rects||(e.rects=[]),e.lines.push({points:this.initialTrace.tracePath,strokeColor:"red",strokeDash:"4 4"}),e.rects.push({center:this.label.center,width:this.label.width,height:this.label.height,fill:"rgba(255, 0, 0, 0.2)"}),this.queuedCandidatePaths.length>0&&e.lines.push({points:this.queuedCandidatePaths[0],strokeColor:"orange"}),this.solvedTracePath&&e.lines.push({points:this.solvedTracePath,strokeColor:"green"}),e}},O9t=class extends Tr{constructor(e){super();f(this,"inputProblem");f(this,"netLabelPlacements");f(this,"mergedLabelNetIdMap");f(this,"allTraces");f(this,"modifiedTraces",[]);f(this,"detourCountByLabel",{});f(this,"PADDING_BUFFER",.1);f(this,"activeSubSolver",null);f(this,"overlapQueue",[]);f(this,"recentlyFailed",new Set);this.inputProblem=e.inputProblem,this.netLabelPlacements=e.netLabelPlacements,this.mergedLabelNetIdMap=e.mergedLabelNetIdMap,this.allTraces=[...e.traces]}_step(){if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){let r=this.activeSubSolver.solvedTracePath;if(r){let s=this.allTraces.findIndex(o=>o.mspPairId===this.activeSubSolver.initialTrace.mspPairId);s!==-1&&(this.allTraces[s].tracePath=r,this.modifiedTraces.push(this.allTraces[s]))}this.activeSubSolver=null,this.recentlyFailed.clear()}else if(this.activeSubSolver.failed){let r=`${this.activeSubSolver.initialTrace.mspPairId}-${this.activeSubSolver.label.globalConnNetId}`;this.recentlyFailed.add(r),this.activeSubSolver=null}return}let e=M9t(this.allTraces,this.netLabelPlacements).filter(r=>{let s=this.mergedLabelNetIdMap[r.label.globalConnNetId];return s?!s.has(r.trace.globalConnNetId):r.trace.globalConnNetId!==r.label.globalConnNetId});if(e.length===0){this.solved=!0;return}let t=e.filter(r=>{let s=`${r.trace.mspPairId}-${r.label.globalConnNetId}`;return!this.recentlyFailed.has(s)});if(t.length===0){this.solved=!0;return}this.overlapQueue=t;let i=this.overlapQueue.shift();if(i){let r=this.allTraces.find(s=>s.mspPairId===i.trace.mspPairId);if(r){let s=i.label.globalConnNetId,o=this.detourCountByLabel[s]||0;this.detourCountByLabel[s]=o+1,this.activeSubSolver=new R9t({trace:r,label:i.label,problem:this.inputProblem,paddingBuffer:this.PADDING_BUFFER,detourCount:o})}}}getOutput(){return{allTraces:this.allTraces,modifiedTraces:this.modifiedTraces}}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=us(this.inputProblem);e.lines||(e.lines=[]);for(let t of this.allTraces)e.lines.push({points:t.tracePath,strokeColor:"purple"});return e}},L9t=class extends Tr{constructor(e){super();f(this,"inputProblem");f(this,"traces");f(this,"netLabelPlacements");f(this,"labelMergingSolver");f(this,"overlapAvoidanceSolver");f(this,"pipelineStepIndex",0);this.inputProblem=e.inputProblem,this.traces=e.traces,this.netLabelPlacements=e.netLabelPlacements}_step(){if(this.activeSubSolver){this.activeSubSolver.step(),this.activeSubSolver.solved?(this.activeSubSolver=null,this.pipelineStepIndex++):this.activeSubSolver.failed&&(this.failed=!0,this.activeSubSolver=null);return}switch(this.pipelineStepIndex){case 0:this.labelMergingSolver=new E9t({netLabelPlacements:this.netLabelPlacements,inputProblem:this.inputProblem,traces:this.traces}),this.activeSubSolver=this.labelMergingSolver;break;case 1:this.overlapAvoidanceSolver=new O9t({inputProblem:this.inputProblem,traces:this.traces,netLabelPlacements:this.labelMergingSolver.getOutput().netLabelPlacements,mergedLabelNetIdMap:this.labelMergingSolver.getOutput().mergedLabelNetIdMap}),this.activeSubSolver=this.overlapAvoidanceSolver;break;default:this.solved=!0;break}}getOutput(){return{traces:this.overlapAvoidanceSolver?.getOutput().allTraces??this.traces,netLabelPlacements:this.labelMergingSolver?.getOutput().netLabelPlacements??this.netLabelPlacements}}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=us(this.inputProblem);e.lines||(e.lines=[]),e.rects||(e.rects=[]);let t=this.getOutput();for(let i of t.traces)e.lines.push({points:i.tracePath,strokeColor:"purple"});for(let i of t.netLabelPlacements){let r=Ls(i.globalConnNetId,.3);e.rects.push({center:i.center,width:i.width,height:i.height,fill:r,stroke:r.replace("0.3","1"),label:i.globalConnNetId})}return e}},F9t=n=>{for(let e of n.chips){let t=FA(e);for(let i of e.pins){if(!(i.x>t.minX&&i.x<t.maxX&&i.y>t.minY&&i.y<t.maxY))continue;let s=i.x-t.minX,o=t.maxX-i.x,a=i.y-t.minY,c=t.maxY-i.y,l=Math.min(s,o,a,c);l===s?i.x=t.minX:l===o?i.x=t.maxX:l===a?i.y=t.minY:i.y=t.maxY,i._facingDirection=void 0}}},$9t=n=>{for(let e of n.chips){let t=e.width/2,i=e.height/2,r=0,s=0;for(let c of e.pins){let l=Math.abs(c.x-e.center.x),u=Math.abs(c.y-e.center.y);l>r&&(r=l),u>s&&(s=u)}let o=Math.max(t,r),a=Math.max(i,s);if(o>t||a>i){e.width=o*2,e.height=a*2;for(let c of e.pins)c._facingDirection=void 0}}};function z9t(n,e){for(let t=0;t<n.length-1;t++){let i=n[t],r=n[t+1];for(let s of e)for(let o=0;o<s.tracePath.length-1;o++){let a=s.tracePath[o],c=s.tracePath[o+1];if(Ti(i,r,a,c))return!0}}return!1}var D9t=3,j9t=(n,e)=>Math.sqrt(Math.pow(n.x-e.x,2)+Math.pow(n.y-e.y,2)),B9t=class extends Tr{constructor(e){super();f(this,"solvedLongDistanceTraces",[]);f(this,"queuedCandidatePairs",[]);f(this,"currentCandidatePair",null);f(this,"subSolver",null);f(this,"chipMap",{});f(this,"inputProblem");f(this,"netConnMap");f(this,"newlyConnectedPinIds",new Set);f(this,"allSolvedTraces",[]);this.params=e;let{inputProblem:t,primaryMspConnectionPairs:i,alreadySolvedTraces:r}=this.params;this.inputProblem=t,this.allSolvedTraces=[...r];let s=new Set;for(let u of i)s.add(u.pins[0].pinId),s.add(u.pins[1].pinId);let{netConnMap:o}=LA(t);this.netConnMap=o;let a=new Map;for(let u of t.chips){this.chipMap[u.chipId]=u;for(let p of u.pins)a.set(p.pinId,{...p,chipId:u.chipId})}let c=[],l=new Set;for(let u of Object.keys(o.netMap)){let p=o.getIdsConnectedToNet(u);if(p.length<2)continue;let d=p.filter(_=>!s.has(_));for(let _ of d){let g=a.get(_);if(!g)continue;let x=p.filter(v=>v!==_).flatMap(v=>{let S=a.get(v);return S?[{pin:S,distance:j9t(g,S)}]:[]}).sort((v,S)=>v.distance-S.distance).slice(0,D9t);for(let v of x){let S=[g,v.pin],P=S.map(T=>T.pinId).sort().join("--");l.has(P)||(c.push(S),l.add(P))}}}this.queuedCandidatePairs=c}getConstructorParams(){return this.params}_step(){if(this.subSolver?.solved){let e=this.subSolver.solvedTracePath;if(e&&this.currentCandidatePair&&!z9t(e,this.allSolvedTraces)){let[i,r]=this.currentCandidatePair,s=this.netConnMap.getNetConnectedToId(i.pinId),o=`${i.pinId}-${r.pinId}`,a={mspPairId:o,dcConnNetId:s,globalConnNetId:s,pins:[i,r],tracePath:e,mspConnectionPairIds:[o],pinIds:[i.pinId,r.pinId]};this.solvedLongDistanceTraces.push(a),this.allSolvedTraces.push(a),this.newlyConnectedPinIds.add(i.pinId),this.newlyConnectedPinIds.add(r.pinId)}this.subSolver=null,this.currentCandidatePair=null}else this.subSolver?.failed&&(this.subSolver=null,this.currentCandidatePair=null);if(this.subSolver){this.subSolver.step();return}for(;this.queuedCandidatePairs.length>0;){let e=this.queuedCandidatePairs.shift(),[t,i]=e;if(!(this.newlyConnectedPinIds.has(t.pinId)||this.newlyConnectedPinIds.has(i.pinId))){this.currentCandidatePair=e,this.subSolver=new ttt({inputProblem:this.params.inputProblem,pins:this.currentCandidatePair,chipMap:this.chipMap});return}}this.solved=!0}visualize(){if(this.subSolver)return this.subSolver.visualize();let e=us(this.inputProblem);for(let t of this.solvedLongDistanceTraces)e.lines.push({points:t.tracePath,strokeColor:"purple"});for(let[t,i]of this.queuedCandidatePairs)e.lines.push({points:[t,i],strokeColor:"gray",strokeDash:"4 4"});return e}getOutput(){return this.solved?{newTraces:this.solvedLongDistanceTraces,allTracesMerged:[...this.params.alreadySolvedTraces,...this.solvedLongDistanceTraces]}:{newTraces:[],allTracesMerged:this.params.alreadySolvedTraces}}},CA=(n,e)=>{for(let t=0;t<n.length-1;t++){let i=n[t],r=n[t+1];for(let s of e){let o={center:{x:s.minX+(s.maxX-s.minX)/2,y:s.minY+(s.maxY-s.minY)/2},width:s.maxX-s.minX,height:s.maxY-s.minY};if(Iw(i,r,o)<=0)return!0}}return!1},IA=n=>{let e=0;for(let t=1;t<n.length-1;t++){let i=n[t-1],r=n[t],s=n[t+1],o=i.x===r.x,a=r.x===s.x;o!==a&&e++}return e},qQ=(n,e)=>{let t=[];return n.x===e.x||n.y===e.y?t.push([n,e]):(t.push([n,{x:e.x,y:n.y},e]),t.push([n,{x:n.x,y:e.y},e])),t},NA=(n,e)=>{for(let t=0;t<n.length-1;t++){let i=n[t],r=n[t+1];for(let s of e)if(C1(i,r,s))return!0}return!1},Y9t=(n,e)=>{if(e>=n.length-3)return-1;let t=e,i=!0;for(let r=e;r<n.length-2&&r<e+10&&!(r+2>=n.length);r++){let s=n[r],o=n[r+1],a=n[r+2],c=s.x===o.x,l=o.x===a.x;if(c===l)break;let u=Math.sign(c?o.y-s.y:o.x-s.x);if(r>e){let p=n[r-1],d=p.x===s.x,_=Math.sign(d?s.y-p.y:s.x-p.x);if(c&&d&&u!==_||!c&&!d&&u!==_){i=!1;break}}t=r+2}return i&&t-e>=3?t:-1},L_=(n,e,t)=>{if(t.length<2)return!1;let i=t[0],r=t[t.length-1];return n.x===i.x&&n.y===i.y&&e.x===t[1].x&&e.y===t[1].y||n.x===t[t.length-2].x&&n.y===t[t.length-2].y&&e.x===r.x&&e.y===r.y},X9t=({path:n,obstacles:e,labelBounds:t,originalPath:i})=>{if(n.length<=2)return n;let r=[...n],s=IA(r),o=!0;for(;o;){o=!1;for(let c=0;c<r.length-3;c++){let l=Y9t(r,c);if(l>0){if(L_(r[c],r[c+1],i)||L_(r[l-1],r[l],i))continue;let u=r[c],p=r[l],d=qQ(u,p);for(let _ of d){let g=[...r.slice(0,c+1),..._.slice(1,-1),...r.slice(l)],x=CA(_,e),v=NA(_,t);if(!x&&!v){let S=IA(g);r=g,s=S,o=!0;break}}if(o)break}}if(!o)for(let c=0;c<r.length-2;c++){let l=Math.min(r.length-c-2,r.length-2);for(let u=1;u<=l;u++){let p=c+u+1;if(p>=r.length||L_(r[c],r[c+1],i)||L_(r[p-1],r[p],i))continue;let d=r[c],_=r[p],g=qQ(d,_);for(let x of g){let v=[...r.slice(0,c+1),...x.slice(1,-1),...r.slice(p)],S=x,P=CA(S,e),T=NA(S,t);if(!P&&!T){let k=IA(v);if(k<s||k===s&&v.length<r.length){r=v,s=k,o=!0;break}}}if(o)break}if(o)break}if(!o)for(let c=0;c<r.length-2;c++){let l=r[c],u=r[c+1],p=r[c+2];if(L_(l,u,i)||L_(u,p,i))continue;let d=l.x===u.x&&u.x===p.x,_=l.y===u.y&&u.y===p.y;if(d||_){let g=[...r.slice(0,c+1),...r.slice(c+2)],x=CA([l,p],e),v=NA([l,p],t);if(!x&&!v){r=g,o=!0;break}}}}return M1(r)},U9t=({targetMspConnectionPairId:n,traces:e,inputProblem:t,allLabelPlacements:i,mergedLabelNetIdMap:r,paddingBuffer:s})=>{let o=e.find(P=>P.mspPairId===n);if(!o)throw new Error(`Target trace ${n} not found`);let a=e.filter(P=>P.mspPairId!==n),c=.01,l=a.flatMap((P,T)=>P.tracePath.slice(0,-1).map((k,N)=>{let E=P.tracePath[N+1];return{chipId:`trace-obstacle-${T}-${N}`,minX:Math.min(k.x,E.x)-c/2,minY:Math.min(k.y,E.y)-c/2,maxX:Math.max(k.x,E.x)+c/2,maxY:Math.max(k.y,E.y)+c/2}})),u=US(t),p=.01,_=[...u.map(P=>({...P,minX:P.minX-p,minY:P.minY-p,maxX:P.maxX+p,maxY:P.maxY+p})),...l],g=o.tracePath,v=i.filter(P=>{let T=r[P.globalConnNetId];return T?!T.has(o.globalConnNetId):P.globalConnNetId!==o.globalConnNetId}).map(P=>({minX:P.center.x-P.width/2-s,maxX:P.center.x+P.width/2+s,minY:P.center.y-P.height/2-s,maxY:P.center.y+P.height/2+s})),S=X9t({path:g,obstacles:_,labelBounds:v,originalPath:g});return{...o,tracePath:S}},V9t=({targetMspConnectionPairId:n,traces:e,inputProblem:t,allLabelPlacements:i,mergedLabelNetIdMap:r,paddingBuffer:s})=>{let o=e.find(P=>P.mspPairId===n);if(!o)throw new Error(`Target trace ${n} not found`);let a=1e-5,c=e.filter(P=>P.mspPairId!==n),l=.01,u=c.flatMap((P,T)=>P.tracePath.slice(0,-1).map((k,N)=>{let E=P.tracePath[N+1];return{chipId:`trace-obstacle-${T}-${N}`,minX:Math.min(k.x,E.x)-l/2,minY:Math.min(k.y,E.y)-l/2,maxX:Math.max(k.x,E.x)+l/2,maxY:Math.max(k.y,E.y)+l/2}})),d=[...US(t).map(P=>({...P,minX:P.minX+a,maxX:P.maxX-a,minY:P.minY+a,maxY:P.maxY-a})),...u],_=(P,T,k)=>{for(let N of k)if(C1(P,T,N))return!0;return!1},x=i.filter(P=>{let T=r[P.globalConnNetId];return T?!T.has(o.globalConnNetId):P.globalConnNetId!==o.globalConnNetId}).map(P=>({minX:P.center.x-P.width/2+a,maxX:P.center.x+P.width/2-a,minY:P.center.y-P.height/2+a,maxY:P.center.y+P.height/2-a})),v=[...o.tracePath];if(v.length<4)return{...o};if(v.length===4){let[P,T,k,N]=v,E,C;if(P.y===T.y&&T.x===k.x&&k.y===N.y){let R=(P.x+N.x)/2;E={x:R,y:T.y},C={x:R,y:k.y}}else{let R=(P.y+N.y)/2;E={x:T.x,y:R},C={x:k.x,y:R}}return _(P,E,d)||_(E,C,d)||_(C,N,d)||_(P,E,x)||_(E,C,x)||_(C,N,x)||(v[1]=E,v[2]=C),{...o,tracePath:M1(v)}}for(let P=1;P<v.length-4;P++){let T=v[P],k=v[P+1],N=v[P+2],E=v[P+3],C=T.y===k.y&&k.x===N.x&&N.y===E.y,M=T.x===k.x&&k.y===N.y&&N.x===E.x,A=T.y===k.y&&k.y===N.y&&N.y===E.y,R=T.x===k.x&&k.x===N.x&&N.x===E.x,B=A||R,j=!1;if(C?j=Math.sign(k.x-T.x)===Math.sign(E.x-N.x):M&&(j=Math.sign(k.y-T.y)===Math.sign(E.y-N.y)),!((C||M)&&!B&&j))continue;let X,W,et=Math.abs(C?T.x-k.x:T.y-k.y),nt=Math.abs(C?N.x-E.x:N.y-E.y);if(Math.abs(et-nt)<.001)continue;if(C){let G=(T.x+E.x)/2;X={x:G,y:k.y},W={x:G,y:N.y}}else{let G=(T.y+E.y)/2;X={x:k.x,y:G},W={x:N.x,y:G}}_(T,X,d)||_(X,W,d)||_(W,E,d)||_(T,X,x)||_(X,W,x)||_(W,E,x)||(v[P+1]=X,v[P+2]=W,P=0)}let S=M1(v);return{...o,tracePath:S}},G9t=n=>{let e=[];if(n.length<3)return e;for(let t=0;t<n.length-2;t++){let i=n[t],r=n[t+1],s=n[t+2],o=r.x-i.x,a=r.y-i.y,c=s.x-r.x,l=s.y-r.y;(o===0&&l===0&&a!==0&&c!==0||a===0&&c===0&&o!==0&&l!==0)&&o*o+a*a>=.25&&c*c+l*l>=.25&&e.push({p1:i,p2:r,p3:s})}return e},W9t=(n,e)=>{let t=[];for(let i of n)i.mspPairId!==e&&t.push({points:i.tracePath});return t},ZQ=(n,e,t)=>{let i=[];for(let r of t){let s=r.points;for(let o=0;o<s.length-1;o++){let a=s[o],c=s[o+1];if(!a||!c)continue;let l=pd(n,e,a,c);l&&i.push(l)}}return i},ja=1e-6,dl=(n,e,t=ja)=>Math.abs(n.x-e.x)<t,H9t=({lShape:n,rectangle:e,padding:t=.5,interactionPoint1:i,interactionPoint2:r})=>{let{p1:s,p2:o,p3:a}=n,{x:c,y:l,width:u,height:p}=e,d,_=i,g=r;if(Math.abs(o.x-c)<ja&&Math.abs(o.y-(l+p))<ja)d={x:c+u+t,y:l-t},dl(s,o)?_={x:i.x,y:i.y-t}:_={x:i.x+t,y:i.y},dl(o,a)?g={x:r.x,y:r.y-t}:g={x:r.x+t,y:r.y};else if(Math.abs(o.x-(c+u))<ja&&Math.abs(o.y-(l+p))<ja)d={x:c-t,y:l-t},dl(s,o)?_={x:i.x,y:i.y-t}:_={x:i.x-t,y:i.y},dl(o,a)?g={x:r.x,y:r.y-t}:g={x:r.x-t,y:r.y};else if(Math.abs(o.x-c)<ja&&Math.abs(o.y-l)<ja)d={x:c+u+t,y:l+p+t},dl(s,o)?_={x:i.x,y:i.y+t}:_={x:i.x+t,y:i.y},dl(o,a)?g={x:r.x,y:r.y+t}:g={x:r.x+t,y:r.y};else if(Math.abs(o.x-(c+u))<ja&&Math.abs(o.y-l)<ja)d={x:c-t,y:l+p+t},dl(s,o)?_={x:i.x,y:i.y+t}:_={x:i.x-t,y:i.y},dl(o,a)?g={x:r.x,y:r.y+t}:g={x:r.x-t,y:r.y};else return[];return[[_,d,g]]},q9t=(n,e,t)=>{if(n.length<2)return{isColliding:!1};for(let i=0;i<n.length-1;i++){let r=n[i],s=n[i+1];for(let o of e)if(o.mspPairId!==t)for(let a=0;a<o.tracePath.length-1;a++){let c=o.tracePath[a],l=o.tracePath[a+1],u=pd(r,s,c,l);if(u)return{isColliding:!0,collidingTraceId:o.mspPairId,collisionPoint:u}}}return{isColliding:!1}},Z9t=(n,e)=>{let t=[];for(let i of n)for(let r of e){let s=Math.min(i.x,r.x),o=Math.min(i.y,r.y),a=Math.max(i.x,r.x),c=Math.max(i.y,r.y),l=a-s,u=c-o;l>1e-6&&u>1e-6&&t.push({rect:{x:s,y:o,width:l,height:u},i1:i,i2:r})}return t},XS=n=>{let e={circles:[],lines:[]},t=Array.isArray(n)?n:[n];for(let i of t)e.circles.push({center:{x:i.p2.x,y:i.p2.y},radius:.01,fill:"blue"}),e.lines.push({points:[i.p1,i.p2,i.p3],strokeColor:"lightblue"});return e},KQ=(n,e="red")=>{let t={circles:[]};for(let i of n)t.circles.push({center:{x:i.x,y:i.y},radius:.01,fill:e});return t},JQ=n=>{let e={rects:[]};return e.rects.push({center:{x:n.x+n.width/2,y:n.y+n.height/2},width:n.width,height:n.height,stroke:"green"}),e},K9t=(n,e="gray",t=[])=>{let i={lines:[],circles:[]};for(let r of n)i.lines.push({points:r,strokeColor:e});for(let r of t)i.circles.push({center:r,radius:.01,fill:"green"});return i},AA=n=>{let e={lines:[],points:[],rects:[],circles:[],texts:[]};for(let t of n)t&&(t.lines&&e.lines.push(...t.lines),t.points&&e.points.push(...t.points),t.rects&&e.rects.push(...t.rects),t.circles&&e.circles.push(...t.circles),t.texts&&e.texts.push(...t.texts));return e},J9t=n=>{let e={circles:[]};return n?.isColliding&&n.collisionPoint&&e.circles.push({center:n.collisionPoint,radius:.01,fill:"red"}),e},Q9t=class extends Tr{constructor(e){super();f(this,"input");f(this,"lShapesToProcess",[]);f(this,"visualizationMode","l_shapes");f(this,"currentLShape",null);f(this,"intersectionPoints",[]);f(this,"tightRectangle",null);f(this,"candidates",[]);f(this,"bestRoute",null);f(this,"lastCollision",null);f(this,"collidingCandidate",null);f(this,"rectangleCandidates",[]);f(this,"currentRectangleIndex",0);f(this,"isInitialStep",!0);f(this,"currentCandidateIndex",0);f(this,"lShapeProcessingStep","idle");f(this,"lShapeJustProcessed",!1);f(this,"bestRouteFound",null);this.input=e,this.visualizationMode="l_shapes";for(let t of this.input.allTraces){let i=G9t(t.tracePath);this.lShapesToProcess.push(...i.map(r=>({...r,traceId:t.mspPairId})))}}_step(){if(this.isInitialStep){this.isInitialStep=!1;return}if(this.lShapeJustProcessed){this._resetAfterLShapProcessing();return}if(this.lShapesToProcess.length===0&&this.currentLShape===null){this.solved=!0;return}switch(this.lShapeProcessingStep){case"idle":this._handleIdleStep();break;case"intersections":this._handleIntersectionsStep();break;case"rectangle_selection":this._handleRectangleSelectionStep();break;case"candidate_evaluation":this._handleCandidateEvaluationStep();break}}_resetAfterLShapProcessing(){this.lShapeProcessingStep="idle",this.currentLShape=null,this.currentCandidateIndex=0,this.lShapeJustProcessed=!1,this.visualizationMode="l_shapes",this.intersectionPoints=[],this.tightRectangle=null,this.candidates=[],this.bestRoute=null,this.lastCollision=null,this.collidingCandidate=null}_handleIdleStep(){if(this.currentLShape=this.lShapesToProcess.shift(),!this.currentLShape){this.solved=!0;return}this.lShapeProcessingStep="intersections",this.visualizationMode="l_shapes"}_handleIntersectionsStep(){if(!this.currentLShape.traceId){this.lShapeProcessingStep="idle";return}let e=W9t(this.input.allTraces,this.currentLShape.traceId),t=ZQ(this.currentLShape.p1,this.currentLShape.p2,e),i=ZQ(this.currentLShape.p2,this.currentLShape.p3,e);if(this.intersectionPoints=[...t,...i],t.length===0||i.length===0){this.lShapeProcessingStep="idle";return}this.rectangleCandidates=Z9t(t,i),this.currentRectangleIndex=0,this.lShapeProcessingStep="rectangle_selection"}_handleRectangleSelectionStep(){if(this.currentRectangleIndex>=this.rectangleCandidates.length){this.lShapeProcessingStep="idle";return}let{rect:e,i1:t,i2:i}=this.rectangleCandidates[this.currentRectangleIndex];this.tightRectangle=e,this.candidates=H9t({lShape:this.currentLShape,rectangle:this.tightRectangle,padding:2*this.input.paddingBuffer,interactionPoint1:t,interactionPoint2:i}),this.currentCandidateIndex=0,this.lastCollision=null,this.collidingCandidate=null,this.visualizationMode="candidates",this.lShapeProcessingStep="candidate_evaluation"}_handleCandidateEvaluationStep(){if(this.visualizationMode="candidates",this.bestRouteFound){this._applyBestRoute(this.bestRouteFound),this.bestRouteFound=null;return}if(this.currentCandidateIndex>=this.candidates.length){this.currentRectangleIndex++,this.lShapeProcessingStep="rectangle_selection";return}let e=this.candidates[this.currentCandidateIndex],t=q9t(e,this.input.allTraces,this.currentLShape.traceId);t?.isColliding?(this.lastCollision=t,this.collidingCandidate=e,this.currentCandidateIndex++):(this.bestRouteFound=e,this.lastCollision=null,this.collidingCandidate=null)}_applyBestRoute(e){this.bestRoute=e,this.collidingCandidate=null,this.lastCollision=null;let t=this.input.allTraces.findIndex(i=>i.mspPairId===this.currentLShape.traceId);if(t!==-1){let i=this.input.allTraces[t],r=i.tracePath.findIndex(s=>s.x===this.currentLShape.p2.x&&s.y===this.currentLShape.p2.y);if(r!==-1){let s=[...i.tracePath.slice(0,r),...e,...i.tracePath.slice(r+1)];this.input.allTraces[t]={...i,tracePath:s},this.lShapesToProcess=this.lShapesToProcess.filter(o=>o.traceId!==this.currentLShape.traceId)}}this.lShapeJustProcessed=!0}getOutput(){return{traces:this.input.allTraces}}visualize(){switch(this.visualizationMode){case"l_shapes":return XS(this.lShapesToProcess);case"intersection_points":return AA([this.currentLShape?XS(this.currentLShape):void 0,KQ(this.intersectionPoints)]);case"tight_rectangle":return AA([this.currentLShape?XS(this.currentLShape):void 0,KQ(this.intersectionPoints),this.tightRectangle?JQ(this.tightRectangle):void 0]);case"candidates":{if(this.lShapeJustProcessed){let i={lines:[]};for(let r of this.input.allTraces){let s=r.mspPairId===this.currentLShape?.traceId;for(let o=0;o<r.tracePath.length-1;o++)i.lines.push({points:[r.tracePath[o],r.tracePath[o+1]],strokeColor:s?"green":"#ccc"})}return i}let e={lines:[]};for(let i of this.input.allTraces)for(let r=0;r<i.tracePath.length-1;r++)e.lines.push({points:[i.tracePath[r],i.tracePath[r+1]],strokeColor:"#ccc"});let t;return this.bestRouteFound?t=this.bestRouteFound:this.lastCollision?.isColliding?t=this.collidingCandidate??void 0:this.currentCandidateIndex<this.candidates.length&&(t=this.candidates[this.currentCandidateIndex]),AA([e,this.currentLShape?XS(this.currentLShape):void 0,this.tightRectangle?JQ(this.tightRectangle):void 0,t?K9t([t],this.bestRouteFound?"green":"blue",this.intersectionPoints):void 0,this.lastCollision?J9t(this.lastCollision):void 0])}default:return{}}}},t6t=n=>{if(n.length!==4)return!1;let[e,t,i,r]=n,s=e.y===t.y&&t.x===i.x&&i.y===r.y&&e.x===r.x,o=e.x===t.x&&t.y===i.y&&i.x===r.x&&e.y===r.y;return s||o},e6t=class extends Tr{constructor(e){super();f(this,"input");f(this,"outputTraces");f(this,"traceIdQueue");f(this,"tracesMap");f(this,"pipelineStep","untangling_traces");f(this,"activeTraceId",null);f(this,"activeSubSolver",null);this.input=e,this.outputTraces=[...e.allTraces],this.tracesMap=new Map(this.outputTraces.map(t=>[t.mspPairId,t])),this.traceIdQueue=Array.from(e.allTraces.map(t=>t.mspPairId))}_step(){if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){let e=this.activeSubSolver.getOutput();this.outputTraces=e.traces,this.tracesMap=new Map(this.outputTraces.map(t=>[t.mspPairId,t])),this.activeSubSolver=null,this.pipelineStep="minimizing_turns"}else this.activeSubSolver.failed&&(this.activeSubSolver=null,this.pipelineStep="minimizing_turns");return}switch(this.pipelineStep){case"untangling_traces":this._runUntangleTracesStep();break;case"minimizing_turns":this._runMinimizeTurnsStep();break;case"balancing_l_shapes":this._runBalanceLShapesStep();break}}_runUntangleTracesStep(){this.activeSubSolver=new Q9t({...this.input,allTraces:Array.from(this.tracesMap.values())})}_runMinimizeTurnsStep(){if(this.traceIdQueue.length===0){this.pipelineStep="balancing_l_shapes",this.traceIdQueue=Array.from(this.input.allTraces.map(e=>e.mspPairId));return}this._processTrace("minimizing_turns")}_runBalanceLShapesStep(){if(this.traceIdQueue.length===0){this.solved=!0;return}this._processTrace("balancing_l_shapes")}_processTrace(e){let t=this.traceIdQueue.shift();this.activeTraceId=t;let i=this.tracesMap.get(t);if(t6t(i.tracePath))return;let r=Array.from(this.tracesMap.values()),s;e==="minimizing_turns"?s=U9t({...this.input,targetMspConnectionPairId:t,traces:r}):s=V9t({...this.input,targetMspConnectionPairId:t,traces:r}),this.tracesMap.set(t,s),this.outputTraces=Array.from(this.tracesMap.values())}getOutput(){return{traces:this.outputTraces}}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=us(this.input.inputProblem,{chipAlpha:.1,connectionAlpha:.1});e.lines||(e.lines=[]),e.points||(e.points=[]),e.rects||(e.rects=[]),e.circles||(e.circles=[]),e.texts||(e.texts=[]);for(let t of this.outputTraces){let i={points:t.tracePath.map(r=>({x:r.x,y:r.y})),strokeColor:t.mspPairId===this.activeTraceId?"red":"blue"};e.lines.push(i)}return e}};function fl(n,e,t,i={}){return{solverName:n,solverClass:e,getConstructorParams:t,onSolved:i.onSolved,shouldSkip:i.shouldSkip}}var rtt=class extends Tr{constructor(e){super();f(this,"mspConnectionPairSolver");f(this,"schematicTraceLinesSolver");f(this,"longDistancePairSolver");f(this,"traceOverlapShiftSolver");f(this,"netLabelPlacementSolver");f(this,"labelMergingSolver");f(this,"traceLabelOverlapAvoidanceSolver");f(this,"traceCleanupSolver");f(this,"startTimeOfPhase");f(this,"endTimeOfPhase");f(this,"timeSpentOnPhase");f(this,"firstIterationOfPhase");f(this,"inputProblem");f(this,"pipelineDef",[fl("mspConnectionPairSolver",u9t,()=>[{inputProblem:this.inputProblem}],{onSolved:e=>{}}),fl("schematicTraceLinesSolver",g9t,()=>[{mspConnectionPairs:this.mspConnectionPairSolver.mspConnectionPairs,dcConnMap:this.mspConnectionPairSolver.dcConnMap,globalConnMap:this.mspConnectionPairSolver.globalConnMap,inputProblem:this.inputProblem,chipMap:this.mspConnectionPairSolver.chipMap}]),fl("longDistancePairSolver",B9t,e=>[{inputProblem:e.inputProblem,primaryMspConnectionPairs:e.mspConnectionPairSolver.mspConnectionPairs,alreadySolvedTraces:e.schematicTraceLinesSolver.solvedTracePaths}],{onSolved:e=>{}}),fl("traceOverlapShiftSolver",v9t,()=>[{inputProblem:this.inputProblem,inputTracePaths:this.longDistancePairSolver?.getOutput().allTracesMerged,globalConnMap:this.mspConnectionPairSolver.globalConnMap}],{onSolved:e=>{}}),fl("netLabelPlacementSolver",HQ,()=>[{inputProblem:this.inputProblem,inputTraceMap:this.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(this.longDistancePairSolver.getOutput().allTracesMerged.map(e=>[e.mspPairId,e]))}],{onSolved:e=>{}}),fl("traceLabelOverlapAvoidanceSolver",L9t,e=>{let t=e.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(e.longDistancePairSolver.getOutput().allTracesMerged.map(s=>[s.mspPairId,s])),i=Object.values(t),r=e.netLabelPlacementSolver.netLabelPlacements;return[{inputProblem:e.inputProblem,traces:i,netLabelPlacements:r}]}),fl("traceCleanupSolver",e6t,e=>{let i=e.traceLabelOverlapAvoidanceSolver.getOutput().traces,r=e.traceLabelOverlapAvoidanceSolver.labelMergingSolver.getOutput();return[{inputProblem:e.inputProblem,allTraces:i,allLabelPlacements:r.netLabelPlacements,mergedLabelNetIdMap:r.mergedLabelNetIdMap,paddingBuffer:.1}]}),fl("netLabelPlacementSolver",HQ,e=>{let t=e.traceCleanupSolver?.getOutput().traces??e.traceLabelOverlapAvoidanceSolver.getOutput().traces;return[{inputProblem:e.inputProblem,inputTraceMap:Object.fromEntries(t.map(i=>[i.mspPairId,i]))}]})]);f(this,"currentPipelineStepIndex",0);this.inputProblem=this.cloneAndCorrectInputProblem(e),this.MAX_ITERATIONS=1e6,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={},this.firstIterationOfPhase={}}getConstructorParams(){return this.inputProblem}cloneAndCorrectInputProblem(e){let t=structuredClone({...e,_chipObstacleSpatialIndex:void 0});return $9t(t),F9t(t),t}_step(){let e=this.pipelineDef[this.currentPipelineStepIndex];if(!e){this.solved=!0;return}if(this.activeSubSolver){this.activeSubSolver.step(),this.activeSubSolver.solved?(this.endTimeOfPhase[e.solverName]=performance.now(),this.timeSpentOnPhase[e.solverName]=this.endTimeOfPhase[e.solverName]-this.startTimeOfPhase[e.solverName],e.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++):this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let t=e.getConstructorParams(this);this.activeSubSolver=new e.solverClass(...t),this[e.solverName]=this.activeSubSolver,this.timeSpentOnPhase[e.solverName]=0,this.startTimeOfPhase[e.solverName]=performance.now(),this.firstIterationOfPhase[e.solverName]=this.iterations}solveUntilPhase(e){for(;this.getCurrentPhase().toLowerCase()!==e.toLowerCase();)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let e=[us(this.inputProblem),...this.pipelineDef.map(i=>this[i.solverName]?.visualize()).filter(Boolean).map((i,r)=>{for(let s of i.rects??[])s.step=r;for(let s of i.points??[])s.step=r;for(let s of i.circles??[])s.step=r;for(let s of i.texts??[])s.step=r;for(let s of i.lines??[])s.step=r;return i})];return e.length===1?e[0]:{points:e.flatMap(i=>i.points||[]),rects:e.flatMap(i=>i.rects||[]),lines:e.flatMap(i=>i.lines||[]),circles:e.flatMap(i=>i.circles||[]),texts:e.flatMap(i=>i.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}};var Xnt=Vt(In(),1);var Unt=Vt(In(),1);var Vnt=Vt(In(),1);ir();Ae();var n6t=n=>{let e=[];e.push(n.title),n.models.size>0&&e.push(...Array.from(n.models.values()));for(let t of n.components)e.push(t.toSpiceString());for(let t of n.subcircuits)e.push(t.toSpiceString());return n.printStatements.length>0&&e.push(...n.printStatements),n.controls.length>0&&(e.push(".control"),e.push(...n.controls),e.push(".endc")),n.tranCommand&&!e.some(t=>t.trim().toLowerCase().startsWith(".tran"))&&e.push(n.tranCommand),e.push(".END"),e.join(`
247
247
  `)},i6t=class{constructor(n="Circuit Netlist"){f(this,"title");f(this,"components");f(this,"nodes");f(this,"controls");f(this,"subcircuits");f(this,"models");f(this,"tranCommand");f(this,"printStatements");this.title=n,this.components=[],this.nodes=new Set,this.controls=[],this.subcircuits=[],this.models=new Map,this.tranCommand=null,this.printStatements=[]}addComponent(n){this.components.push(n);for(let e of n.nodes)this.nodes.add(e)}addSubcircuit(n){this.subcircuits.find(e=>e.name===n.name)||this.subcircuits.push(n)}toSpiceString(){return n6t(this)}},Ho=class{constructor(n,e,t){f(this,"name");f(this,"command");f(this,"nodes");this.name=n,this.command=e,this.nodes=t}toSpiceString(){return this.command.toSpiceString()}},r6t=class{constructor(n){f(this,"commandName","resistor");f(this,"props");this.props=n}toSpiceString(){let{name:n,positiveNode:e,negativeNode:t,model:i,value:r}=this.props,s=`R${n} ${e} ${t}`;return i&&(s+=` ${i}`),s+=` ${r}`,s}},s6t=class{constructor(n){f(this,"commandName","capacitor");f(this,"props");this.props=n}toSpiceString(){let{name:n,positiveNode:e,negativeNode:t,modelName:i,value:r,initialCondition:s}=this.props,o=`C${n} ${e} ${t}`;return i&&(o+=` ${i}`),o+=` ${r}`,s&&(o+=` IC=${s}`),o}},zA=class{constructor(n){f(this,"commandName","voltage_source");f(this,"props");this.props=n}toSpiceString(){let{name:n,positiveNode:e,negativeNode:t,value:i,acMagnitude:r,acPhase:s}=this.props,o=`V${n} ${e} ${t}`;return i&&(o+=` ${i}`),r&&(o+=` AC ${r}`,s&&(o+=` ${s}`)),o}},o6t=class{constructor(n){f(this,"commandName","bjt");f(this,"props");this.props=n}toSpiceString(){let{name:n,collector:e,base:t,emitter:i,substrate:r,model:s,area:o}=this.props,a=`Q${n} ${e} ${t} ${i}`;return r&&(a+=` ${r}`),a+=` ${s}`,o&&(a+=` ${o}`),a}},a6t=class{constructor(n){f(this,"commandName","diode");f(this,"props");this.props=n}toSpiceString(){let{name:n,positiveNode:e,negativeNode:t,model:i,area:r}=this.props,s=`D${n} ${e} ${t} ${i}`;return r&&(s+=` ${r}`),s}},c6t=class{constructor(n){f(this,"commandName","inductor");f(this,"props");this.props=n}toSpiceString(){let{name:n,positiveNode:e,negativeNode:t,model:i,value:r,initialCondition:s}=this.props,o=`L${n} ${e} ${t}`;return i&&(o+=` ${i}`),o+=` ${r}`,s&&(o+=` IC=${s}`),o}},stt=class{constructor(n){f(this,"commandName","voltage_controlled_switch");f(this,"props");this.props=n}toSpiceString(){let{name:n,positiveNode:e,negativeNode:t,positiveControl:i,negativeControl:r,model:s}=this.props;return`S${n} ${e} ${t} ${i} ${r} ${s}`}};function ott(n){let e=new i6t("* Circuit JSON to SPICE Netlist"),t=Ce(n).source_component.list(),i=Ce(n).source_port.list(),r=Ce(n).source_trace.list(),s=n.filter(T=>T.type==="simulation_voltage_probe"),o=n.filter(T=>T.type==="simulation_switch").map(T=>T),a=new Map;for(let T of o)T.source_component_id&&a.set(T.source_component_id,T);let c=yW(n),l=new Map,u=new Map,p=1,d=new Set;if(s.length>0)for(let T of s)T.name&&d.add(T.name);let _=[...d].map(T=>/^N(\d+)$/i.exec(T)).filter(T=>T!==null).map(T=>parseInt(T[1],10));_.length>0&&(p=Math.max(..._)+1);let g=new Set,x=new Set(Ce(n).source_net.list().filter(T=>T.name?.toLowerCase().includes("gnd")).map(T=>T.source_net_id));if(x.size>0){for(let T of Ce(n).source_trace.list())if(T.connected_source_port_ids.length>0&&T.connected_source_net_ids.some(N=>x.has(N))){let N=T.connected_source_port_ids[0],E=c.getNetConnectedToId(N);E&&g.add(E)}}let v=i.filter(T=>T.name?.toLowerCase()==="gnd");for(let T of v){let k=c.getNetConnectedToId(T.source_port_id);k&&g.add(k)}for(let T of Ce(n).simulation_voltage_source.list()){let k=T.negative_source_port_id??T.terminal2_source_port_id;if(k){let N=c.getNetConnectedToId(k);N&&g.add(N)}}for(let T of g)u.set(T,"0");if(s.length>0)for(let T of s){if(!T.name||T.reference_input_source_port_id||T.reference_input_source_net_id)continue;let k,N=T.signal_input_source_port_id,E=T.signal_input_source_net_id;if(N)k=c.getNetConnectedToId(N);else if(E){let C=r.find(M=>M.connected_source_net_ids.includes(E));if(C&&C.connected_source_port_ids.length>0){let M=C.connected_source_port_ids[0];k=c.getNetConnectedToId(M)}}k?u.has(k)||u.set(k,T.name):N&&T.name&&l.set(N,T.name)}for(let T of i){let k=T.source_port_id,N=c.getNetConnectedToId(k);N&&(u.has(N)||u.set(N,`N${p++}`),l.set(k,u.get(N)))}for(let T of i){let k=T.source_port_id;l.has(k)||l.set(k,`N${p++}`)}for(let T of t){if(T.type!=="source_component")continue;let k=Ce(n).source_port.list({source_component_id:T.source_component_id}).sort((E,C)=>(E.pin_number??0)-(C.pin_number??0)),N=k.map(E=>l.get(E.source_port_id)||"0");if("ftype"in T){let E=null;switch(T.ftype){case"simple_resistor":{if("resistance"in T&&"name"in T){let C=new r6t({name:T.name,positiveNode:N[0]||"0",negativeNode:N[1]||"0",value:l6t(T.resistance)});E=new Ho(T.name,C,N)}break}case"simple_switch":{let C=h6t(T.name??T.source_component_id,"SW"),M=N[0]||"0",A=N[1]||"0",R=`NCTRL_${C}`,B=`SW_${C}`,j=a.get(T.source_component_id),U=d6t(j),X=new stt({name:C,positiveNode:M,negativeNode:A,positiveControl:R,negativeControl:"0",model:B});E=new Ho(C,X,[M,A,R,"0"]),e.models.has(B)||e.models.set(B,`.MODEL ${B} SW(Ron=0.1 Roff=1e9 Vt=2.5 Vh=0.1)`);let W=`CTRL_${C}`,et=new zA({name:W,positiveNode:R,negativeNode:"0",value:U}),nt=new Ho(W,et,[R,"0"]);e.addComponent(nt);break}case"simple_capacitor":{if("capacitance"in T&&"name"in T){let C=new s6t({name:T.name,positiveNode:N[0]||"0",negativeNode:N[1]||"0",value:u6t(T.capacitance)});E=new Ho(T.name,C,N)}break}case"simple_diode":{if("name"in T){let C=k.find(U=>U.name?.toLowerCase()==="anode"||U.port_hints?.includes("anode")),M=k.find(U=>U.name?.toLowerCase()==="cathode"||U.port_hints?.includes("cathode")),A=l.get(C?.source_port_id??"")||"0",R=l.get(M?.source_port_id??"")||"0",B="D",j=new a6t({name:T.name,positiveNode:A,negativeNode:R,model:B});e.models.set(B,`.MODEL ${B} D`),E=new Ho(T.name,j,[A,R])}break}case"simple_inductor":{if("inductance"in T&&"name"in T){let C=new c6t({name:T.name,positiveNode:N[0]||"0",negativeNode:N[1]||"0",value:p6t(T.inductance)});E=new Ho(T.name,C,N)}break}case"simple_mosfet":{if("name"in T){let C=k.find(W=>W.name?.toLowerCase()==="drain"||W.port_hints?.includes("drain")),M=k.find(W=>W.name?.toLowerCase()==="gate"||W.port_hints?.includes("gate")),A=k.find(W=>W.name?.toLowerCase()==="source"||W.port_hints?.includes("source")),R=l.get(C?.source_port_id??"")||"0",B=l.get(M?.source_port_id??"")||"0",j=l.get(A?.source_port_id??"")||"0",U="SWMOD",X=new stt({name:T.name,positiveNode:R,negativeNode:j,positiveControl:B,negativeControl:j,model:U});e.models.set(U,`.MODEL ${U} SW`),E=new Ho(T.name,X,[R,B,j])}break}case"simple_transistor":{if("name"in T){let C=k.find(et=>et.name?.toLowerCase()==="collector"||et.port_hints?.includes("collector")),M=k.find(et=>et.name?.toLowerCase()==="base"||et.port_hints?.includes("base")),A=k.find(et=>et.name?.toLowerCase()==="emitter"||et.port_hints?.includes("emitter"));if(!C||!M||!A)throw new Error(`Transistor ${T.name} is missing required ports (collector, base, emitter)`);let R=l.get(C.source_port_id)||"0",B=l.get(M.source_port_id)||"0",j=l.get(A.source_port_id)||"0",U=T.transistor_type??"npn",X=U.toUpperCase();e.models.has(X)||e.models.set(X,`.MODEL ${X} ${U.toUpperCase()}`);let W=new o6t({name:T.name,collector:R,base:B,emitter:j,model:X});E=new Ho(T.name,W,[R,B,j])}break}}E&&e.addComponent(E)}}let S=Ce(n).simulation_voltage_source.list();for(let T of S)if(T.type==="simulation_voltage_source")if(T.is_dc_source===!1){if("terminal1_source_port_id"in T&&"terminal2_source_port_id"in T&&T.terminal1_source_port_id&&T.terminal2_source_port_id){let k=l.get(T.terminal1_source_port_id)||"0",N=l.get(T.terminal2_source_port_id)||"0",E="",C=T.wave_shape;if(C==="sinewave"){let A=T.voltage??0,R=T.frequency??0,B=0,j=0,U=T.phase??0;R>0?E=`SIN(0 ${A} ${R} ${B} ${j} ${U})`:E=`DC ${T.voltage??0}`}else if(C==="square"){let A=T.voltage??0,R=T.frequency??0,B=R===0?1/0:1/R,j=T.period??B,U=T.duty_cycle??.5,X=j*U;E=`PULSE(0 ${A} 0 1n 1n ${X} ${j})`}else T.voltage!==void 0&&(E=`DC ${T.voltage}`);if(E){let M=new zA({name:T.simulation_voltage_source_id,positiveNode:k,negativeNode:N,value:E}),A=new Ho(T.simulation_voltage_source_id,M,[k,N]);e.addComponent(A)}}}else{let k=T.positive_source_port_id??T.terminal1_source_port_id,N=T.negative_source_port_id??T.terminal2_source_port_id;if(k&&N&&"voltage"in T&&T.voltage!==void 0){let E=l.get(k)||"0",C=l.get(N)||"0",M=new zA({name:T.simulation_voltage_source_id,positiveNode:E,negativeNode:C,value:`DC ${T.voltage}`}),A=new Ho(T.simulation_voltage_source_id,M,[E,C]);e.addComponent(A)}}let P=n.find(T=>T.type==="simulation_experiment");if(P){if(s.length>0){let E=new Set,C=M=>r.find(R=>R.connected_source_net_ids.includes(M))?.connected_source_port_ids[0];for(let M of s){let A=M.signal_input_source_port_id;if(!A){let j=M.signal_input_source_net_id;j&&(A=C(j))}if(!A)continue;let R=l.get(A);if(!R)continue;let B=M.reference_input_source_port_id;if(!B&&M.reference_input_source_net_id&&(B=C(M.reference_input_source_net_id)),B){let j=l.get(B);j&&j!=="0"?E.add(`V(${R},${j})`):R!=="0"&&E.add(`V(${R})`)}else R!=="0"&&E.add(`V(${R})`)}E.size>0&&P.experiment_type?.includes("transient")&&e.printStatements.push(`.PRINT TRAN ${[...E].join(" ")}`)}let T=P.time_per_step,k=P.end_time_ms,N=P.start_time_ms;if(T&&k){let E=(N??0)/1e3,C=`.tran ${Vi(T/1e3)} ${Vi(k/1e3)}`;E>0&&(C+=` ${Vi(E)}`),C+=" UIC",e.tranCommand=C}}return e}function l6t(n){return n>=1e6?`${n/1e6}MEG`:n>=1e3?`${n/1e3}K`:n.toString()}function u6t(n){return n>=.001?`${n*1e3}M`:n>=1e-6?`${n*1e6}U`:n>=1e-9?`${n*1e9}N`:n>=1e-12?`${n*1e12}P`:n.toString()}function p6t(n){return n>=1?n.toString():n>=.001?`${n*1e3}m`:n>=1e-6?`${n*1e6}u`:n>=1e-9?`${n*1e9}n`:n>=1e-12?`${n*1e12}p`:n.toString()}function h6t(n,e){if(!n)return e;let t=n.replace(/[^A-Za-z0-9_]/g,"_");return t?/^[0-9]/.test(t)?`${e}_${t}`:t:e}function d6t(n){if(!n)return"DC 0";let s=n.starts_closed??!1,o=n.closes_at??0,a=n.opens_at,c=n.switching_frequency,[l,u]=s?[5,0]:[0,5];if(c&&c>0){let p=1/c,d=a&&a>o?Math.min(a-o,p):0,_=d>0?d:Math.max(p/2,1e-9);return`PULSE(${Vi(l)} ${Vi(u)} ${Vi(o)} 1n 1n ${Vi(_)} ${Vi(p)})`}if(a!==void 0&&a>o){let p=Math.max(a-o,1e-9),d=o+p*2;return`PULSE(${Vi(l)} ${Vi(u)} ${Vi(o)} 1n 1n ${Vi(p)} ${Vi(d)})`}if(o>0){let p=o*2,d=Math.max(p/2,1e-9);return`PULSE(${Vi(l)} ${Vi(u)} ${Vi(o)} 1n 1n ${Vi(d)} ${Vi(p)})`}return`DC ${s?5:0}`}function Vi(n){if(!Number.isFinite(n))return`${n}`;if(n===0)return"0";let e=Math.abs(n);return e>=1e3||e<=.001?Number(n.toExponential(6)).toString():Number(n.toPrecision(6)).toString()}var Gnt=Vt(In(),1);var ci=1e-15,f6t=class{constructor(){f(this,"map");f(this,"rev");this.map=new Map([["0",0]]),this.rev=["0"]}getOrCreate(n){let e=String(n),t=e.toUpperCase();if(this.map.has(t))return this.map.get(t);let i=this.rev.length;return this.map.set(t,i),this.rev.push(e),i}get(n){return this.map.get(String(n).toUpperCase())}count(){return this.rev.length}matrixIndexOfNode(n){return n===0?-1:n-1}};function yr(n){if(n==null)return NaN;let e=String(n).trim();if(e==="")return NaN;if(/^[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?$/.test(e))return parseFloat(e);let t={t:1e12,g:1e9,meg:1e6,k:1e3,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15},i=e.match(/^([+-]?\d*\.?\d+(?:[eE][+-]?\d+)?)([a-zA-Z]+)$/);if(!i)return parseFloat(e);let[,r,s]=i;if(r==null)return parseFloat(e);let o=parseFloat(r),a=(s??"").toLowerCase();return a=a.replace(/(ohm|v|a|s|h|f)$/g,""),a==="meg"?o*t.meg:a.length===1&&a in t?o*t[a]:o}function m6t(n){let i=n.trim().replace(/^pulse\s*\(/i,"(").replace(/^\(/,"").replace(/\)$/,"").trim().split(/[\s,]+/).filter(s=>s.length);if(i.length<7)throw new Error("PULSE(...) requires 7 or 8 args");let r=i.map(s=>yr(s));if(r.some(s=>Number.isNaN(s)))throw new Error("Invalid PULSE() numeric value");return{v1:r[0],v2:r[1],td:r[2],tr:r[3],tf:r[4],ton:r[5],period:r[6],ncycles:i[7]!=null?r[7]:1/0}}function _6t(n){let i=n.trim().replace(/^pwl\s*\(/i,"(").replace(/^\(/,"").replace(/\)$/,"").trim().split(/[\s,]+/).filter(s=>s.length);if(i.length===0||i.length%2!==0)throw new Error("PWL(...) requires an even number of time/value pairs");let r=[];for(let s=0;s<i.length;s+=2){let o=yr(i[s]),a=yr(i[s+1]);if(Number.isNaN(o)||Number.isNaN(a))throw new Error("Invalid PWL() numeric value");r.push({t:o,v:a})}return r}function y6t(n,e){if(e<n.td)return n.v1;let t=e-n.td,i=Math.floor(t/n.period);if(i>=n.ncycles)return n.v1;let r=t-i*n.period;if(r<n.tr){let s=r/Math.max(n.tr,ci);return n.v1+(n.v2-n.v1)*s}if(r<n.tr+n.ton)return n.v2;if(r<n.tr+n.ton+n.tf){let s=(r-(n.tr+n.ton))/Math.max(n.tf,ci);return n.v2+(n.v1-n.v2)*s}return n.v1}function g6t(n,e){if(n.length===0)return 0;if(e<=n[0].t)return n[0].v;for(let t=1;t<n.length;t++){let i=n[t-1],r=n[t];if(e<=r.t){let s=Math.max(r.t-i.t,ci),o=(e-i.t)/s;return i.v+(r.v-i.v)*o}}return n[n.length-1].v}function x6t(n){let e=/"[^"]*"|\w+\s*\([^)]*\)|\([^()]*\)|\S+/g,t=[],i;for(;(i=e.exec(n))!==null;)t.push(i[0]);return t}function pn(n,e,t){let i=n[e];if(i==null)throw new Error(t);return i}function b6t(n){let e=new Map,t=new Map,i={nodes:new f6t,R:[],C:[],L:[],V:[],S:[],D:[],analyses:{ac:null,tran:null},probes:{tran:[]},skipped:[],models:{vswitch:e,diode:t}},r=n.split(/\r?\n/),s=!1;for(let a of r){let c=a.trim();if(!c||/^\*/.test(c))continue;if(/^\s*\.end\b/i.test(c))break;c=c.replace(/\/\/.*$/,""),c=c.replace(/;.*$/,"");let l=x6t(c);if(l.length===0)continue;let u=l[0];if(u.length===0)continue;if(!s&&!/^[rclvgsmiqd]\w*$/i.test(u)&&!/^\./.test(u)){s=!0;continue}if(/^\./.test(u)){let _=u.toLowerCase();if(_===".ac"){let g=pn(l,1,".ac missing mode").toLowerCase();if(g!=="dec"&&g!=="lin")throw new Error(".ac supports 'dec' or 'lin'");let x=parseInt(pn(l,2,".ac missing point count"),10),v=yr(pn(l,3,".ac missing start frequency")),S=yr(pn(l,4,".ac missing stop frequency"));i.analyses.ac={mode:g,N:x,f1:v,f2:S}}else if(_===".tran"){let g=yr(pn(l,1,".tran missing timestep")),x=yr(pn(l,2,".tran missing stop time"));i.analyses.tran={dt:g,tstop:x}}else if(_===".print")if(pn(l,1,".print missing analysis type").toLowerCase()==="tran"){let x=l.slice(2);for(let v of x){let S=v.match(/^v\(([^)]+)\)$/i);if(S&&S[1]){let P=S[1];i.probes.tran.some(T=>T.toUpperCase()===P.toUpperCase())||i.probes.tran.push(P)}}}else i.skipped.push(c);else if(_===".model"){let g=pn(l,1,".model missing name"),v=pn(l,2,".model missing type"),S="";if(v.includes("(")){let T=v.indexOf("(");S=v.slice(T+1),v=v.slice(0,T)}if(!S)S=l.slice(3).join(" ").replace(/^\(/,"").replace(/\)$/,"");else{let T=l.slice(3).join(" ").replace(/\)$/,"");S=`${S} ${T}`.trim()}S=S.replace(/^\(/,"").replace(/\)$/,"").trim();let P=v.toLowerCase();if(P==="vswitch"||P==="sw"){let T={name:g,Ron:1,Roff:1e12,Von:0,Voff:0},k,N;if(S.length>0){let E=S.split(/[\s,]+/).filter(Boolean);for(let C of E){let[M,A]=C.split("=");if(!M||A==null)continue;let R=M.toLowerCase(),B=yr(A);Number.isNaN(B)||(R==="ron"?T.Ron=B:R==="roff"?T.Roff=B:R==="von"?T.Von=B:R==="voff"?T.Voff=B:R==="vt"?k=B:R==="vh"&&(N=B))}}if(k!==void 0){let E=N??0;T.Von=k+E/2,T.Voff=k-E/2}e.set(g.toLowerCase(),T)}else if(P==="d"){let T={name:g,Is:1e-14,N:1};if(S.length>0){let k=S.split(/[\s,]+/).filter(Boolean);for(let N of k){let[E,C]=N.split("=");if(!E||C==null)continue;let M=E.toLowerCase(),A=yr(C);Number.isNaN(A)||(M==="is"?T.Is=A:M==="n"&&(T.N=A))}}t.set(g.toLowerCase(),T)}else i.skipped.push(c)}else i.skipped.push(c);continue}let p=u.charAt(0).toLowerCase(),d=u;try{if(p==="r"){let _=i.nodes.getOrCreate(pn(l,1,"Resistor missing node")),g=i.nodes.getOrCreate(pn(l,2,"Resistor missing node")),x=yr(pn(l,3,"Resistor missing value"));i.R.push({name:d,n1:_,n2:g,R:x})}else if(p==="c"){let _=i.nodes.getOrCreate(pn(l,1,"Capacitor missing node")),g=i.nodes.getOrCreate(pn(l,2,"Capacitor missing node")),x=yr(pn(l,3,"Capacitor missing value"));i.C.push({name:d,n1:_,n2:g,C:x,vPrev:0})}else if(p==="l"){let _=i.nodes.getOrCreate(pn(l,1,"Inductor missing node")),g=i.nodes.getOrCreate(pn(l,2,"Inductor missing node")),x=yr(pn(l,3,"Inductor missing value"));i.L.push({name:d,n1:_,n2:g,L:x,iPrev:0})}else if(p==="v"){let _=i.nodes.getOrCreate(pn(l,1,"Voltage source missing node")),g=i.nodes.getOrCreate(pn(l,2,"Voltage source missing node")),x={dc:0,acMag:0,acPhaseDeg:0,waveform:null,index:-1},v=3;for(v<l.length&&!/^[a-zA-Z]/.test(l[v])&&(x.dc=yr(l[v]),v++);v<l.length;){let S=l[v].toLowerCase();if(S==="dc"){let P=pn(l,v+1,"DC value missing");x.dc=yr(P),v+=2}else if(S==="ac"){let P=pn(l,v+1,"AC magnitude missing");x.acMag=yr(P);let T=l[v+2];T!=null&&/^[+-]?\d/.test(T)?(x.acPhaseDeg=yr(T),v+=3):v+=2}else if(S.startsWith("pulse")){let P=S.includes("(")?S:pn(l,v+1,"PULSE() missing arguments");if(!P||!/\(.*\)/.test(P))throw new Error("Malformed PULSE() specification");let T=m6t(P);x.waveform=k=>y6t(T,k),v+=S.includes("(")?1:2}else if(S.startsWith("pwl")){let P=S.includes("(")?S:pn(l,v+1,"PWL() missing arguments");if(!P||!/\(.*\)/.test(P))throw new Error("Malformed PWL() specification");let T=_6t(P);x.waveform=k=>g6t(T,k),v+=S.includes("(")?1:2}else/^\(.*\)$/.test(S),v++}i.V.push({name:d,n1:_,n2:g,dc:x.dc,acMag:x.acMag,acPhaseDeg:x.acPhaseDeg,waveform:x.waveform,index:x.index??-1})}else if(p==="s"){let _=i.nodes.getOrCreate(pn(l,1,"Switch missing node")),g=i.nodes.getOrCreate(pn(l,2,"Switch missing node")),x=i.nodes.getOrCreate(pn(l,3,"Switch missing control node")),v=i.nodes.getOrCreate(pn(l,4,"Switch missing control node")),S=pn(l,5,"Switch missing model");i.S.push({name:d,n1:_,n2:g,ncPos:x,ncNeg:v,modelName:S.toLowerCase(),model:null,isOn:!1})}else if(p==="d")if(l.length===4){let _=i.nodes.getOrCreate(pn(l,1,"Diode missing node")),g=i.nodes.getOrCreate(pn(l,2,"Diode missing node")),x=pn(l,3,"Diode missing model");i.D.push({name:d,nPlus:_,nMinus:g,modelName:x.toLowerCase(),model:null,vdPrev:0})}else i.skipped.push(c);else i.skipped.push(c)}catch(_){throw _ instanceof Error?new Error(`Parse error on line: "${c}"
248
248
  ${_.message}`):_}}let o=i.nodes.count()-1;for(let a=0;a<i.V.length;a++){let c=i.V[a];c&&(c.index=o+a)}for(let a of i.S){let c=e.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by switch ${a.name}`);a.model=c,a.isOn=!1}for(let a of i.D){let c=t.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by diode ${a.name}`);a.model=c}return i}var hn=class Ya{constructor(e=0,t=0){f(this,"re");f(this,"im");this.re=e,this.im=t}static from(e,t=0){return new Ya(e,t)}static fromPolar(e,t=0){let i=t*Math.PI/180;return new Ya(e*Math.cos(i),e*Math.sin(i))}clone(){return new Ya(this.re,this.im)}add(e){return new Ya(this.re+e.re,this.im+e.im)}sub(e){return new Ya(this.re-e.re,this.im-e.im)}mul(e){return new Ya(this.re*e.re-this.im*e.im,this.re*e.im+this.im*e.re)}div(e){let t=e.re*e.re+e.im*e.im;if(t<ci)throw new Error("Complex divide by ~0");return new Ya((this.re*e.re+this.im*e.im)/t,(this.im*e.re-this.re*e.im)/t)}inv(){let e=this.re*this.re+this.im*this.im;if(e<ci)throw new Error("Complex invert by ~0");return new Ya(this.re/e,-this.im/e)}abs(){return Math.hypot(this.re,this.im)}phaseDeg(){return Math.atan2(this.im,this.re)*180/Math.PI}};function v6t(n,e){let t=n.length;for(let r=0;r<t;r++){let s=n[r],o=e[r];if(!s||!o)throw new Error("Matrix dimensions mismatch");let a=s.map(c=>c.clone());a.push(o.clone()),n[r]=a}for(let r=0;r<t;r++){let s=r,o=n[r];if(!o)throw new Error("Matrix row missing");let a=o[r]?.abs()??0;for(let u=r+1;u<t;u++){let p=n[u];if(!p)throw new Error("Matrix row missing");let d=p[r]?.abs()??0;d>a&&(a=d,s=u)}if(a<ci)throw new Error("Singular matrix (complex)");if(s!==r){let u=n[r];n[r]=n[s],n[s]=u}let c=n[r];if(!c)throw new Error("Pivot row missing");let l=c[r];if(!l)throw new Error("Zero pivot encountered");for(let u=r+1;u<t;u++){let p=n[u];if(!p)throw new Error("Matrix row missing");let d=p[r];if(!d)continue;let _=d.div(l);if(!(_.abs()<ci))for(let g=r;g<=t;g++){let x=p[g],v=c[g];!x||!v||(p[g]=x.sub(_.mul(v)))}}}let i=new Array(t);for(let r=t-1;r>=0;r--){let s=n[r];if(!s)throw new Error("Matrix row missing");let o=s[t];if(!o)throw new Error("Augmented column missing");for(let c=r+1;c<t;c++){let l=s[c],u=i[c];!l||!u||(o=o.sub(l.mul(u)))}let a=s[r];if(!a)throw new Error("Zero pivot on back-substitution");i[r]=o.div(a)}return i}function w6t(n,e,t){if(n<=0||e<=0)throw new Error(".ac frequencies must be > 0");e<n&&([n,e]=[e,n]);let i=Math.log10(e/n),r=Math.max(1,Math.ceil(i*t)),s=[];for(let a=0;a<=r;a++)s.push(n*Math.pow(10,a/t));let o=s[s.length-1];return(o==null||o<e*(1-ci))&&s.push(e),s}function DA(n,e,t,i,r){let s=e.matrixIndexOfNode(t),o=e.matrixIndexOfNode(i);if(s>=0){let a=n[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=a[s]?.add(r)??r}if(o>=0){let a=n[o];if(!a)throw new Error("Matrix row missing while stamping");a[o]=a[o]?.add(r)??r}if(s>=0&&o>=0){let a=n[s],c=n[o];if(!a||!c)throw new Error("Matrix row missing while stamping");a[o]=a[o]?.sub(r)??hn.from(0,0).sub(r),c[s]=c[s]?.sub(r)??hn.from(0,0).sub(r)}}function S6t(n,e,t,i,r){let s=t.matrixIndexOfNode(i.n1),o=t.matrixIndexOfNode(i.n2),a=i.index,c=hn.from(1,0),l=hn.from(-1,0);if(s>=0){let p=n[s];if(!p)throw new Error("Matrix row missing while stamping voltage source");p[a]=p[a]?.add(c)??c}if(o>=0){let p=n[o];if(!p)throw new Error("Matrix row missing while stamping voltage source");p[a]=p[a]?.sub(c)??l}let u=n[a];if(!u)throw new Error("Branch row missing while stamping voltage source");s>=0&&(u[s]=u[s]?.add(c)??c),o>=0&&(u[o]=u[o]?.sub(c)??l),e[a]=(e[a]??hn.from(0,0)).add(r)}function P6t(n){let{mode:e,N:t,f1:i,f2:r}=n;if(e==="dec")return w6t(i,r,t);let s=[],o=Math.max(2,t),a=(r-i)/(o-1);for(let c=0;c<o;c++)s.push(i+c*a);return s}function k6t(n,e,t){let i=Array.from({length:t},()=>Array.from({length:t},()=>hn.from(0,0))),r=Array.from({length:t},()=>hn.from(0,0)),s=2*Math.PI;for(let o of n.R){if(o.R<=0)throw new Error(`R ${o.name} must be > 0`);let a=hn.from(1/o.R,0);DA(i,n.nodes,o.n1,o.n2,a)}for(let o of n.C){let a=hn.from(0,s*e*o.C);DA(i,n.nodes,o.n1,o.n2,a)}for(let o of n.L){let a=hn.from(0,s*e*o.L),c=a.abs()<ci?hn.from(0,0):hn.from(1,0).div(a);DA(i,n.nodes,o.n1,o.n2,c)}for(let o of n.V){let a=hn.fromPolar(o.acMag||0,o.acPhaseDeg||0);S6t(i,r,n.nodes,o,a)}return{A:i,b:r}}function T6t(n){var d,_,g,x;if(!n.analyses.ac)return null;let{mode:e,N:t,f1:i,f2:r}=n.analyses.ac,s=n.nodes.count()-1,o=n.V.length,a=s+o,c=P6t({mode:e,N:t,f1:i,f2:r}),l={};n.nodes.rev.forEach((v,S)=>{S!==0&&(l[v]=[])});let u={},p=2*Math.PI;for(let v of c){let{A:S,b:P}=k6t(n,v,a),T=v6t(S,P);for(let k=1;k<n.nodes.count();k++){let N=k-1,E=n.nodes.rev[k];if(!E)continue;let C=l[E];C&&C.push(T[N]??hn.from(0,0))}for(let k of n.R){let N=k.n1===0?hn.from(0,0):T[k.n1-1]??hn.from(0,0),E=k.n2===0?hn.from(0,0):T[k.n2-1]??hn.from(0,0),M=hn.from(1/k.R,0).mul(N.sub(E));(u[d=k.name]||(u[d]=[])).push(M)}for(let k of n.C){let N=k.n1===0?hn.from(0,0):T[k.n1-1]??hn.from(0,0),E=k.n2===0?hn.from(0,0):T[k.n2-1]??hn.from(0,0),M=hn.from(0,p*v*k.C).mul(N.sub(E));(u[_=k.name]||(u[_]=[])).push(M)}for(let k of n.L){let N=k.n1===0?hn.from(0,0):T[k.n1-1]??hn.from(0,0),E=k.n2===0?hn.from(0,0):T[k.n2-1]??hn.from(0,0),C=hn.from(0,p*v*k.L),A=(C.abs()<ci?hn.from(0,0):hn.from(1,0).div(C)).mul(N.sub(E));(u[g=k.name]||(u[g]=[])).push(A)}for(let k of n.V){let N=T[k.index]??hn.from(0,0);(u[x=k.name]||(u[x]=[])).push(N)}}return{freqs:c,nodeVoltages:l,elementCurrents:u}}var att=.02585;function E6t(n,e){let t=n.length;for(let r=0;r<t;r++){let s=n[r],o=e[r];if(!s||o==null)throw new Error("Matrix dimensions mismatch");let a=s.slice();a.push(o),n[r]=a}for(let r=0;r<t;r++){let s=r,o=n[r];if(!o)throw new Error("Matrix row missing");let a=Math.abs(o[r]??0);for(let u=r+1;u<t;u++){let p=n[u];if(!p)throw new Error("Matrix row missing");let d=Math.abs(p[r]??0);d>a&&(a=d,s=u)}if(a<ci)throw new Error("Singular matrix (real)");if(s!==r){let u=n[r];n[r]=n[s],n[s]=u}let c=n[r];if(!c)throw new Error("Pivot row missing");let l=c[r];if(l==null)throw new Error("Zero pivot encountered");for(let u=r+1;u<t;u++){let p=n[u];if(!p)throw new Error("Matrix row missing");let d=p[r];if(d==null)continue;let _=d/l;if(!(Math.abs(_)<ci))for(let g=r;g<=t;g++){let x=p[g],v=c[g];x==null||v==null||(p[g]=x-_*v)}}}let i=new Array(t).fill(0);for(let r=t-1;r>=0;r--){let s=n[r];if(!s)throw new Error("Matrix row missing");let o=s[t];if(o==null)throw new Error("Augmented column missing");for(let c=r+1;c<t;c++){let l=s[c],u=i[c];l==null||u==null||(o-=l*u)}let a=s[r];if(a==null)throw new Error("Zero pivot on back-substitution");i[r]=o/a}return i}function I1(n,e,t,i,r){let s=e.matrixIndexOfNode(t),o=e.matrixIndexOfNode(i);if(s>=0){let a=n[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=(a[s]??0)+r}if(o>=0){let a=n[o];if(!a)throw new Error("Matrix row missing while stamping");a[o]=(a[o]??0)+r}if(s>=0&&o>=0){let a=n[s],c=n[o];if(!a||!c)throw new Error("Matrix row missing while stamping");a[o]=(a[o]??0)-r,c[s]=(c[s]??0)-r}}function jA(n,e,t,i,r){let s=e.matrixIndexOfNode(t),o=e.matrixIndexOfNode(i);s>=0&&(n[s]=(n[s]??0)-r),o>=0&&(n[o]=(n[o]??0)+r)}function M6t(n,e,t,i,r){let s=t.matrixIndexOfNode(i.n1),o=t.matrixIndexOfNode(i.n2),a=i.index;if(s>=0){let l=n[s];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)+1}if(o>=0){let l=n[o];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)-1}let c=n[a];if(!c)throw new Error("Branch row missing while stamping voltage source");s>=0&&(c[s]=(c[s]??0)+1),o>=0&&(c[o]=(c[o]??0)-1),e[a]=(e[a]??0)+r}function C6t(n,e){let t=n>ci?n:Math.max(e/1e3,ci),i=Math.max(1,Math.ceil(e/Math.max(t,ci)));return{dt:i>0?e/i:e,steps:i}}function I6t(n,e,t,i,r,s,o){for(let a of t.R){let c=1/a.R;I1(n,t.nodes,a.n1,a.n2,c)}for(let a of t.C){let c=a.C/Math.max(r,ci);I1(n,t.nodes,a.n1,a.n2,c);let l=-c*a.vPrev;jA(e,t.nodes,a.n1,a.n2,l)}for(let a of t.L){let c=Math.max(r,ci)/a.L;I1(n,t.nodes,a.n1,a.n2,c),jA(e,t.nodes,a.n1,a.n2,a.iPrev)}for(let a of t.S){let c=a.model;if(!c)continue;let l=a.isOn?c.Ron:c.Roff,p=1/Math.max(Math.abs(l),ci);I1(n,t.nodes,a.n1,a.n2,p)}for(let a of t.V){let c=a.waveform?a.waveform(i):a.dc||0;M6t(n,e,t.nodes,a,c)}for(let a of t.D){let c=a.model;if(!c)continue;let{nPlus:l,nMinus:u}=a,p=t.nodes.matrixIndexOfNode(l),d=t.nodes.matrixIndexOfNode(u),_=l===0?0:s[p]??0,g=u===0?0:s[d]??0,x=_-g,v=o===0?a.vdPrev:x,S=c.N*att,P=v;v>.8&&(P=.8),v<-1&&(P=-1);let T=Math.exp(P/S),k=c.Is*(T-1),N=Math.max(c.Is/S*T,1e-12),E=k-N*P;I1(n,t.nodes,l,u,N),jA(e,t.nodes,l,u,E)}}function N6t(n,e){let t=!1;for(let i of n.S){let r=i.model;if(!r)continue;let s=i.ncPos===0?0:e[i.ncPos-1]??0,o=i.ncNeg===0?0:e[i.ncNeg-1]??0,a=s-o,c=i.isOn;i.isOn?a<r.Voff&&(c=!1):a>r.Von&&(c=!0),c!==i.isOn&&(i.isOn=c,t=!0)}return t}function A6t(n){var d,_,g,x,v,S;if(!n.analyses.tran)return null;let{dt:e,tstop:t}=n.analyses.tran,{dt:i,steps:r}=C6t(e,t),s=n.nodes.count()-1,o=n.V.length,a=s+o,c=[],l={};n.nodes.rev.forEach((P,T)=>{T!==0&&(l[P]=[])});let u={},p=0;for(let P=0;P<=r;P++,p=P*i){c.push(p);let T=new Array(a).fill(0);for(let k=0;k<20;k++){let N=Array.from({length:a},()=>new Array(a).fill(0)),E=new Array(a).fill(0);if(I6t(N,E,n,p,i,T,k),T=E6t(N,E),!N6t(n,T)||k===19)break}for(let k=1;k<n.nodes.count();k++){let N=k-1,E=n.nodes.rev[k];if(!E)continue;let C=l[E];C&&C.push(T[N]??0)}for(let k of n.R){let N=k.n1===0?0:T[k.n1-1]??0,E=k.n2===0?0:T[k.n2-1]??0,C=(N-E)/k.R;(u[d=k.name]||(u[d]=[])).push(C)}for(let k of n.C){let N=k.n1===0?0:T[k.n1-1]??0,E=k.n2===0?0:T[k.n2-1]??0,C=k.C*(N-E-k.vPrev)/Math.max(i,ci);(u[_=k.name]||(u[_]=[])).push(C)}for(let k of n.L){let N=k.n1===0?0:T[k.n1-1]??0,E=k.n2===0?0:T[k.n2-1]??0,M=Math.max(i,ci)/k.L*(N-E)+k.iPrev;(u[g=k.name]||(u[g]=[])).push(M)}for(let k of n.V){let N=T[k.index]??0;(u[x=k.name]||(u[x]=[])).push(N)}for(let k of n.S){let N=k.model;if(!N)continue;let E=k.n1===0?0:T[k.n1-1]??0,C=k.n2===0?0:T[k.n2-1]??0,M=k.isOn?N.Ron:N.Roff,A=Math.max(Math.abs(M),ci),R=(E-C)/A;(u[v=k.name]||(u[v]=[])).push(R)}for(let k of n.D){if(!k.model)continue;let{nPlus:N,nMinus:E,model:C}=k,M=N===0?0:T[N-1]??0,A=E===0?0:T[E-1]??0,R=M-A,B=C.N*att,j=Math.exp(R/B),U=C.Is*(j-1);(u[S=k.name]||(u[S]=[])).push(U)}for(let k of n.C){let N=k.n1===0?0:T[k.n1-1]??0,E=k.n2===0?0:T[k.n2-1]??0;k.vPrev=N-E}for(let k of n.L){let N=k.n1===0?0:T[k.n1-1]??0,E=k.n2===0?0:T[k.n2-1]??0,C=Math.max(i,ci)/k.L;k.iPrev=C*(N-E)+k.iPrev}for(let k of n.D){let N=k.nPlus===0?0:T[k.nPlus-1]??0,E=k.nMinus===0?0:T[k.nMinus-1]??0;k.vdPrev=N-E}}if(n.probes.tran.length>0){let P={},T=n.probes.tran.map(k=>k.toUpperCase());for(let k in l)T.includes(k.toUpperCase())&&(P[k]=l[k]);return{times:c,nodeVoltages:P,elementCurrents:u}}return{times:c,nodeVoltages:l,elementCurrents:u}}function ctt(n){let e=b6t(n),t=T6t(e),i=A6t(e);return{circuit:e,ac:t,tran:i}}function ltt(n,e,t){if(!n||!e.analyses.tran)return[];let{dt:i,tstop:r}=e.analyses.tran,{times:s,nodeVoltages:o}=n,a=[];for(let c in o){let l=o[c];a.push({type:"simulation_transient_voltage_graph",simulation_transient_voltage_graph_id:`stvg_${t}_${c}`,simulation_experiment_id:t,timestamps_ms:s.map(u=>u*1e3),voltage_levels:l,time_per_step:i*1e3,start_time_ms:0,end_time_ms:r*1e3,name:`${c}`})}return a}Ae();var BA=[{value:1e12,symbol:"T"},{value:1e9,symbol:"G"},{value:1e6,symbol:"M"},{value:1e3,symbol:"k"},{value:1,symbol:""},{value:.001,symbol:"m"},{value:1e-6,symbol:"\xB5"},{value:1e-9,symbol:"n"},{value:1e-12,symbol:"p"}];function xi(n){if(n==null)return"";if(n===0)return"0";let e=Math.abs(n),t=BA.find(s=>{let o=e/s.value;return o>=1&&o<1e3})||BA[BA.length-1],r=(n/t.value).toPrecision(3);return r.includes(".")&&!/\.0+$/.test(r)&&(r=r.replace(/0+$/,"")),r=r.replace(/\.0+$/,""),`${r}${t.symbol}`}Ae();wt();ir();Ae();ir();Ae();Ae();wt();Ae();Ae();si();Ae();ir();Ae();ir();Ae();Ae();ir();Ae();function utt(n,e,t,i){return Math.sqrt((t-n)**2+(i-e)**2)}var R6t=n=>{let e=n.filter(s=>s.type==="pcb_port"),t=n.filter(s=>s.type==="pcb_smtpad"),i=n.filter(s=>s.type==="pcb_trace");function r(s,o={}){let a=o.traceWidth||0,c=e.find(l=>utt(l.x,l.y,s.x,s.y)<.01);if(c)return c.pcb_port_id;if(o.isFirstOrLastPoint){let l=t.find(u=>{if(u.shape==="rect")return Math.abs(s.x-u.x)<u.width/2+a/2&&Math.abs(s.y-u.y)<u.height/2+a/2;if(u.shape==="circle")return utt(s.x,s.y,u.x,u.y)<u.radius});if(l)return l.pcb_port_id??null}return null}for(let s of i)for(let o=0;o<s.route.length;o++){let a=s.route[o],c=o===0||o===s.route.length-1;if(a.route_type==="wire"){if(!a.start_pcb_port_id&&o===0){let l=r(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.start_pcb_port_id=l)}if(!a.end_pcb_port_id&&o===s.route.length-1){let l=r(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.end_pcb_port_id=l)}}}};function htt(n){R6t(n);let e=n.filter(o=>o.type==="source_trace"),t=n.filter(o=>o.type==="pcb_port"),i=[],r=nr(n),s=new Map;for(let o of t)s.set(o.source_port_id,o);for(let o of e){let a=o.connected_source_port_ids;if(a.length<2)continue;let c=[],l=[];for(let g of a){let x=s.get(g);x?c.push(x):l.push(g)}if(c.length<2)continue;let u=c[0],p=r.getNetConnectedToId(u.pcb_port_id);r.getIdsConnectedToNet(p).filter(g=>n.some(x=>x.type==="pcb_trace"&&("pcb_trace_id"in x&&x.pcb_trace_id===g||"route_id"in x&&x.route_id===g))).length===0&&new Set(c.map(x=>x.pcb_component_id)).size>1&&i.push({type:"pcb_port_not_connected_error",message:`pcb_port_not_connected_error: Pcb ports [${c.map(x=>x.pcb_port_id).join(", ")}] are not connected together through the same net.`,error_type:"pcb_port_not_connected_error",pcb_port_ids:c.map(x=>x.pcb_port_id),pcb_component_ids:c.map(x=>x.pcb_component_id).filter(x=>x!==void 0),pcb_port_not_connected_error_id:`pcb_port_not_connected_error_trace_${o.source_trace_id}`})}return i}var O6t=class{constructor({objects:n,getBounds:e,getId:t,CELL_SIZE:i}){f(this,"buckets");f(this,"objectsById");f(this,"getBounds");f(this,"getId");f(this,"CELL_SIZE",.4);f(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=e,this.getId=t??(()=>this._getNextId()),this.CELL_SIZE=i??this.CELL_SIZE;for(let r of n)this.addObject(r)}_getNextId(){return`${this._idCounter++}`}addObject(n){let e=this.getBounds(n),t=this.getId(n),i={...n,spatialIndexId:t};this.objectsById.set(t,i);let r=Math.floor(e.minX/this.CELL_SIZE),s=Math.floor(e.minY/this.CELL_SIZE),o=Math.floor(e.maxX/this.CELL_SIZE),a=Math.floor(e.maxY/this.CELL_SIZE);for(let c=r;c<=o;c++)for(let l=s;l<=a;l++){let u=`${c}x${l}`,p=this.buckets.get(u);p?p.push(i):this.buckets.set(u,[i])}}removeObject(n){let e=this.objectsById.get(n);if(!e)return!1;this.objectsById.delete(n);let t=this.getBounds(e),i=Math.floor(t.minX/this.CELL_SIZE),r=Math.floor(t.minY/this.CELL_SIZE),s=Math.floor(t.maxX/this.CELL_SIZE),o=Math.floor(t.maxY/this.CELL_SIZE);for(let a=i;a<=s;a++)for(let c=r;c<=o;c++){let l=`${a}x${c}`,u=this.buckets.get(l);if(u){let p=u.findIndex(d=>d.spatialIndexId===n);p!==-1&&(u.splice(p,1),u.length===0&&this.buckets.delete(l))}}return!0}getBucketKey(n,e){return`${Math.floor(n/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getObjectsInBounds(n,e=0){let t=[],i=new Set,r=Math.floor((n.minX-e)/this.CELL_SIZE),s=Math.floor((n.minY-e)/this.CELL_SIZE),o=Math.floor((n.maxX+e)/this.CELL_SIZE),a=Math.floor((n.maxY+e)/this.CELL_SIZE);for(let c=r;c<=o;c++)for(let l=s;l<=a;l++){let u=`${c}x${l}`,p=this.buckets.get(u)||[];for(let d of p){let _=d.spatialIndexId;i.has(_)||(i.add(_),t.push(d))}}return t}},N1=n=>n.type==="pcb_trace_segment"?{minX:Math.min(n.x1,n.x2),minY:Math.min(n.y1,n.y2),maxX:Math.max(n.x1,n.x2),maxY:Math.max(n.y1,n.y2)}:l_([n]),YA=.1,L6t=.15;var F6t=.2,$6t=.3,A1=.005;function z6t(n){let e=new Set;for(let t of n.route)t.route_type==="wire"&&(t.start_pcb_port_id&&e.add(t.start_pcb_port_id),t.end_pcb_port_id&&e.add(t.end_pcb_port_id));return Array.from(e)}function XA(n){let e=new Set;for(let t of n)for(let i of z6t(t))e.add(i);return Array.from(e)}var D6t=(n,e)=>{let t={x:n.x1,y:n.y1},i={x:n.x2,y:n.y2},r={x:e.x1,y:e.y1},s={x:e.x2,y:e.y2},o={x:i.x-t.x,y:i.y-t.y},a={x:s.x-r.x,y:s.y-r.y},c=o.x*o.x+o.y*o.y,l=a.x*a.x+a.y*a.y;if(c===0||l===0){if(c===0&&l===0)return{x:(t.x+r.x)/2,y:(t.y+r.y)/2};if(c===0){let B=qo(((t.x-r.x)*a.x+(t.y-r.y)*a.y)/l,0,1),j={x:r.x+B*a.x,y:r.y+B*a.y};return{x:(t.x+j.x)/2,y:(t.y+j.y)/2}}let A=qo(((r.x-t.x)*o.x+(r.y-t.y)*o.y)/c,0,1),R={x:t.x+A*o.x,y:t.y+A*o.y};return{x:(R.x+r.x)/2,y:(R.y+r.y)/2}}let u={x:t.x-r.x,y:t.y-r.y},p=o.x*o.x+o.y*o.y,d=o.x*a.x+o.y*a.y,_=o.x*u.x+o.y*u.y,g=a.x*a.x+a.y*a.y,x=a.x*u.x+a.y*u.y,v=p*g-d*d;if(v<1e-10)return j6t(t,i,r,s,o,a,c,l);let S=(d*x-g*_)/v,P=(p*x-d*_)/v;S=qo(S,0,1),P=qo(P,0,1),P=(S*d+x)/g,P=qo(P,0,1),S=(P*d-_)/p,S=qo(S,0,1);let T={x:t.x+S*o.x,y:t.y+S*o.y},k={x:r.x+P*a.x,y:r.y+P*a.y},N=T.x-k.x,E=T.y-k.y,C=Math.sqrt(N*N+E*E);return{x:(T.x+k.x)/2,y:(T.y+k.y)/2}},j6t=(n,e,t,i,r,s,o,a)=>{let c=((t.x-n.x)*r.x+(t.y-n.y)*r.y)/o;c=qo(c,0,1);let l={x:n.x+c*r.x,y:n.y+c*r.y},u=((i.x-n.x)*r.x+(i.y-n.y)*r.y)/o;u=qo(u,0,1);let p={x:n.x+u*r.x,y:n.y+u*r.y},d=((n.x-t.x)*s.x+(n.y-t.y)*s.y)/a;d=qo(d,0,1);let _={x:t.x+d*s.x,y:t.y+d*s.y},g=((e.x-t.x)*s.x+(e.y-t.y)*s.y)/a;g=qo(g,0,1);let x={x:t.x+g*s.x,y:t.y+g*s.y},S=[{pointA:l,pointB:t,distance:Math.sqrt((l.x-t.x)**2+(l.y-t.y)**2)},{pointA:p,pointB:i,distance:Math.sqrt((p.x-i.x)**2+(p.y-i.y)**2)},{pointA:n,pointB:_,distance:Math.sqrt((n.x-_.x)**2+(n.y-_.y)**2)},{pointA:e,pointB:x,distance:Math.sqrt((e.x-x.x)**2+(e.y-x.y)**2)}].reduce((P,T)=>T.distance<P.distance?T:P);return{x:(S.pointA.x+S.pointB.x)/2,y:(S.pointA.y+S.pointB.y)/2}},qo=(n,e,t)=>Math.max(e,Math.min(t,n)),B6t=n=>{if(n.type==="pcb_via"||n.type==="pcb_plated_hole"&&n.shape==="circle")return n.outer_diameter/2;if(n.type==="pcb_hole"&&n.hole_shape==="circle")return n.hole_diameter/2;if(n.type==="pcb_smtpad"&&n.shape==="circle")return n.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(n)}`)},ptt=(n,e)=>{let t={x:n.x1,y:n.y1},i={x:n.x2,y:n.y2},r=e.minX,s=e.minY,o=e.maxX,a=e.maxY;if(t.x===i.x&&t.y===i.y){let M=Math.max(r,Math.min(o,t.x)),A=Math.max(s,Math.min(a,t.y));return M===t.x&&A===t.y?{x:t.x,y:t.y}:{x:M,y:A}}let c=i.x-t.x,l=i.y-t.y,u=c!==0?(r-t.x)/c:Number.NEGATIVE_INFINITY,p=c!==0?(o-t.x)/c:Number.POSITIVE_INFINITY,d=l!==0?(s-t.y)/l:Number.NEGATIVE_INFINITY,_=l!==0?(a-t.y)/l:Number.POSITIVE_INFINITY,g=Math.max(Math.min(u,p),Math.min(d,_)),x=Math.min(Math.max(u,p),Math.max(d,_));if(g<=x&&x>=0&&g<=1){let M=Math.max(0,Math.min(1,g));return{x:t.x+M*c,y:t.y+M*l}}let v={x:Math.max(r,Math.min(o,t.x)),y:Math.max(s,Math.min(a,t.y))},S={x:Math.max(r,Math.min(o,i.x)),y:Math.max(s,Math.min(a,i.y))},P=(v.x-t.x)**2+(v.y-t.y)**2,T=(S.x-i.x)**2+(S.y-i.y)**2,k=[{start:{x:r,y:s},end:{x:o,y:s}},{start:{x:o,y:s},end:{x:o,y:a}},{start:{x:o,y:a},end:{x:r,y:a}},{start:{x:r,y:a},end:{x:r,y:s}}],N=Math.min(P,T),E=P<=T?v:S,C=(M,A,R)=>Math.max(A,Math.min(R,M));for(let M of k){let A={x:i.x-t.x,y:i.y-t.y},R={x:M.end.x-M.start.x,y:M.end.y-M.start.y},B={x:t.x-M.start.x,y:t.y-M.start.y},j=A.x*A.x+A.y*A.y,U=A.x*R.x+A.y*R.y,X=A.x*B.x+A.y*B.y,W=R.x*R.x+R.y*R.y,et=R.x*B.x+R.y*B.y,nt=j*W-U*U;if(Math.abs(nt)<1e-10)continue;let mt=(U*et-W*X)/nt,G=(j*et-U*X)/nt;mt=C(mt,0,1),G=C(G,0,1);let tt={x:t.x+mt*A.x,y:t.y+mt*A.y},J={x:M.start.x+G*R.x,y:M.start.y+G*R.y},ht=tt.x-J.x,pt=tt.y-J.y,St=ht*ht+pt*pt;St<N&&(N=St,E={x:(tt.x+J.x)/2,y:(tt.y+J.y)/2})}return E};function Y6t(n){return n.type==="pcb_trace_segment"?[n.layer]:n.type==="pcb_smtpad"?[n.layer]:n.type==="pcb_plated_hole"?Array.isArray(n.layers)?n.layers:[...Fm]:n.type==="pcb_hole"?[...Fm]:n.type==="pcb_via"?Array.isArray(n.layers)?n.layers:[...Fm]:n.type==="pcb_keepout"?Array.isArray(n.layers)?n.layers:[]:[]}function dtt(n,{connMap:e}={}){let t=[];e??(e=nr(n));let r=Ke(n).pcb_trace.list().flatMap(g=>{let x=[];for(let v=0;v<g.route.length-1;v++){let S=g.route[v],P=g.route[v+1];S.route_type==="wire"&&P.route_type==="wire"&&S.layer===P.layer&&x.push({type:"pcb_trace_segment",pcb_trace_id:g.pcb_trace_id,_pcbTrace:g,thickness:"width"in S?S.width:"width"in P?P.width:L6t,layer:S.layer,x1:S.x,y1:S.y,x2:P.x,y2:P.y})}return x}),s=Ke(n).pcb_smtpad.list(),o=Ke(n).pcb_plated_hole.list(),a=Ke(n).pcb_hole.list(),c=Ke(n).pcb_via.list(),l=Ke(n).pcb_keepout.list(),u=[...r,...s,...o,...a,...c,...l],p=new O6t({objects:u,getBounds:N1}),d=g=>As(n,g),_=new Set;for(let g of r){let x=YA,v=N1(g),S=p.getObjectsInBounds(v,x+g.thickness/2);if(!(g.x1===g.x2&&g.y1===g.y2))for(let P of S){if(!Y6t(P).includes(g.layer))continue;if(P.type==="pcb_trace_segment"){let E=P;if(g.layer!==E.layer||e.areIdsConnected(g.pcb_trace_id,E.pcb_trace_id))continue;let C=c_({x:g.x1,y:g.y1},{x:g.x2,y:g.y2},{x:E.x1,y:E.y1},{x:E.x2,y:E.y2})-g.thickness/2-E.thickness/2;if(C>YA-A1)continue;let M=`overlap_${g.pcb_trace_id}_${E.pcb_trace_id}`,A=`overlap_${E.pcb_trace_id}_${g.pcb_trace_id}`;if(_.has(M)||_.has(A))continue;_.add(M),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(g.pcb_trace_id)} overlaps with ${d(E.pcb_trace_id)} ${C<0?"(accidental contact)":`(gap: ${C.toFixed(3)}mm)`}`,pcb_trace_id:g.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:M,pcb_component_ids:[],center:D6t(g,E),pcb_port_ids:XA([g._pcbTrace,E._pcbTrace])});continue}let T=zo(P);if(e.areIdsConnected(g.pcb_trace_id,"pcb_trace_id"in P?P.pcb_trace_id:T))continue;if(P.type==="pcb_via"||P.type==="pcb_plated_hole"&&P.shape==="circle"||P.type==="pcb_hole"||P.type==="pcb_smtpad"&&P.shape==="circle"){let E=B6t(P),M=Nw({x:g.x1,y:g.y1},{x:g.x2,y:g.y2},{x:P.x,y:P.y,radius:E})-g.thickness/2;if(M>YA-A1)continue;let A=`overlap_${g.pcb_trace_id}_${T}`;if(_.has(A))continue;_.add(A),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(g.pcb_trace_id)} overlaps with ${P.type} "${d(zo(P))}" ${M<0?"(accidental contact)":`(gap: ${M.toFixed(3)}mm)`}`,pcb_trace_id:g.pcb_trace_id,center:ptt(g,N1(P)),source_trace_id:"",pcb_trace_error_id:A,pcb_component_ids:["pcb_component_id"in P?P.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...XA([g._pcbTrace]),"pcb_port_id"in P?P.pcb_port_id:void 0].filter(Boolean)})}let N=$g({x:g.x1,y:g.y1},{x:g.x2,y:g.y2},N1(P))-g.thickness/2;if(N+A1<x){let E=`overlap_${g.pcb_trace_id}_${T}`;if(_.has(E))continue;_.add(E),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(g.pcb_trace_id)} overlaps with ${P.type} "${d(zo(P))}" ${N<0?"(accidental contact)":`(gap: ${N.toFixed(3)}mm)`}`,pcb_trace_id:g.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:E,pcb_component_ids:["pcb_component_id"in P?P.pcb_component_id:void 0].filter(Boolean),center:ptt(g,N1(P)),pcb_port_ids:[...XA([g._pcbTrace]),"pcb_port_id"in P?P.pcb_port_id:void 0].filter(Boolean)})}}}return t}function ftt(n){return n.area()>=0}function mtt({center:n,size:e,rotationDeg:t=0}){let i=n.x,r=n.y,s=e.width/2,o=e.height/2,a=[new Wo(i-s,r-o),new Wo(i+s,r-o),new Wo(i+s,r+o),new Wo(i-s,r+o)],c=new S1(a);if(t){let l=mw(t,i,r),u=a.map(p=>{let d=oe(l,{x:p.x,y:p.y});return new Wo(d.x,d.y)});c=new S1(u)}return ftt(c)||c.reverse(),c}function X6t({board:n}){if(n.outline&&n.outline.length>0){let e=n.outline.map(i=>new Wo(i.x,i.y)),t=new S1(e);return ftt(t)||t.reverse(),t}return n.center&&typeof n.width=="number"&&typeof n.height=="number"?mtt({center:n.center,size:{width:n.width,height:n.height},rotationDeg:0}):null}function U6t({circuitJson:n,component:e}){if(e.source_component_id){let t=n.find(i=>i.type==="source_component"&&i.source_component_id===e.source_component_id);if(t&&"name"in t&&t.name)return t.name}return As(n,e.pcb_component_id)||"Unknown"}function V6t(n,e,t,i,r,s){let o=new Wo(t.x,t.y);if(!e.contains(o)){let x=e.distanceTo(o);return Array.isArray(x)?x[0]:Number(x)||0}let a=i/2,c=r/2,l=[{x:t.x-a,y:t.y-c},{x:t.x+a,y:t.y-c},{x:t.x+a,y:t.y+c},{x:t.x-a,y:t.y+c}],u=[];for(let x=0;x<4;x++){let v=(x+1)%4;u.push({x:(l[x].x+l[v].x)/2,y:(l[x].y+l[v].y)/2})}let p=mw(s,t.x,t.y),d=x=>{let v=oe(p,x);return new Wo(v.x,v.y)},_=l.concat(u).map(d),g=0;for(let x of _)if(!e.contains(x)){let v=e.distanceTo(x),S=Array.isArray(v)?v[0]:Number(v)||0;S>g&&(g=S)}if(g>0)return g;try{let x=mA.intersect(n,e),v=0;x?Array.isArray(x)?v=x.reduce((P,T)=>P+(typeof T.area=="function"?T.area():0),0):typeof x.area=="function"?v=x.area():v=0:v=0;let S=n.area();if(v>0&&v<S){let P=1-v/S,T=Math.abs(i),k=Math.abs(r);return Math.min(T,k)*P}else return .1}catch{return .1}}function _tt(n){let e=n.find(s=>s.type==="pcb_board");if(!e)return[];let t=X6t({board:e});if(!t)return[];let i=n.filter(s=>s.type==="pcb_component");if(i.length===0)return[];let r=[];for(let s of i){if(!s.center||typeof s.width!="number"||typeof s.height!="number"||s.width<=0||s.height<=0)continue;let o=mtt({center:s.center,size:{width:s.width,height:s.height},rotationDeg:s.rotation||0});if(o.area()===0||t.contains(o))continue;let c=V6t(o,t,s.center,s.width,s.height,s.rotation||0),l=U6t({circuitJson:n,component:s}),u=Math.round(c*100)/100;r.push({type:"pcb_component_outside_board_error",error_type:"pcb_component_outside_board_error",pcb_component_outside_board_error_id:`pcb_component_outside_board_${s.pcb_component_id}`,message:`Component ${l} (${s.pcb_component_id}) extends outside board boundaries by ${u}mm`,pcb_component_id:s.pcb_component_id,pcb_board_id:e.pcb_board_id,component_center:s.center,component_bounds:{min_x:o.box.xmin,max_x:o.box.xmax,min_y:o.box.ymin,max_y:o.box.ymax},subcircuit_id:s.subcircuit_id,source_component_id:s.source_component_id})}return r}function G6t(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}function ytt(n,{connMap:e,minSpacing:t=F6t}={}){let i=n.filter(o=>o.type==="pcb_via");if(i.length<2)return[];e??(e=nr(n));let r=[],s=new Set;for(let o=0;o<i.length;o++)for(let a=o+1;a<i.length;a++){let c=i[o],l=i[a];if(!e.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=G6t(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+A1>=t)continue;let p=[c.pcb_via_id,l.pcb_via_id].sort().join("_");s.has(p)||(s.add(p),r.push({type:"pcb_via_clearance_error",pcb_error_id:`same_net_vias_close_${p}`,message:`Vias ${As(n,c.pcb_via_id)} and ${As(n,l.pcb_via_id)} are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:t,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return r}function W6t(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}function gtt(n,{connMap:e,minSpacing:t=$6t}={}){let i=n.filter(o=>o.type==="pcb_via");if(i.length<2)return[];e??(e=nr(n));let r=[],s=new Set;for(let o=0;o<i.length;o++)for(let a=o+1;a<i.length;a++){let c=i[o],l=i[a];if(e.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=W6t(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+A1>=t)continue;let p=[c.pcb_via_id,l.pcb_via_id].sort().join("_");s.has(p)||(s.add(p),r.push({type:"pcb_via_clearance_error",pcb_error_id:`different_net_vias_close_${p}`,message:`Vias ${As(n,c.pcb_via_id)} and ${As(n,l.pcb_via_id)} from different nets are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:t,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return r}var H6t=.2;function q6t(n){if(n.outline&&n.outline.length>0)return n.outline.map(e=>({x:e.x,y:e.y}));if(n.center&&typeof n.width=="number"&&typeof n.height=="number"){let e=n.center.x,t=n.center.y,i=n.width/2,r=n.height/2;return[{x:e-i,y:t-r},{x:e+i,y:t-r},{x:e+i,y:t+r},{x:e-i,y:t+r}]}return null}function xtt(n,e={}){let t=[],i=e.margin??H6t,r=n.find(a=>a.type==="pcb_board");if(!r)return t;let s=q6t(r);if(!s)return t;let o=Ke(n).pcb_trace.list();for(let a of o)if(!(a.route.length<2))for(let c=0;c<a.route.length-1;c++){let l=a.route[c],u=a.route[c+1];if(l.route_type!=="wire"||u.route_type!=="wire")continue;let p="width"in l?l.width:"width"in u?u.width:.1,d={x:l.x,y:l.y},_={x:u.x,y:u.y},g=1/0;for(let v=0;v<s.length;v++){let S=s[v],P=s[(v+1)%s.length],T=c_(d,_,S,P);T<g&&(g=T)}let x=p/2+i;if(g<x){let v={type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:`trace_too_close_to_board_${a.pcb_trace_id}_segment_${c}`,message:`Trace too close to board edge (${g.toFixed(3)}mm < ${x.toFixed(3)}mm required, margin: ${i}mm)`,pcb_trace_id:a.pcb_trace_id,source_trace_id:a.source_trace_id||"",center:{x:(d.x+_.x)/2,y:(d.y+_.y)/2},pcb_component_ids:[],pcb_port_ids:[]};t.push(v)}}return t}function Z6t(n,e){let t=l_([n]),i=l_([e]);return Jc(t,i)}function btt(n){let e=[],t=nr(n),i=Ke(n).pcb_smtpad.list(),r=Ke(n).pcb_plated_hole.list(),s=Ke(n).pcb_hole.list(),o=new Map;for(let c of i){let l=c.pcb_component_id||`standalone_pad_${zo(c)}`;o.has(l)||o.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),o.get(l).elements.push(c)}for(let c of r){let l=c.pcb_component_id||`standalone_plated_hole_${zo(c)}`;o.has(l)||o.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),o.get(l).elements.push(c)}for(let c of s){let l=`standalone_hole_${zo(c)}`;o.set(l,{component_id:l,elements:[c],bounds:{minX:0,minY:0,maxX:0,maxY:0}})}for(let[c,l]of o)l.elements.length>0&&(l.bounds=l_(l.elements));let a=Array.from(o.values());for(let c=0;c<a.length;c++)for(let l=c+1;l<a.length;l++){let u=a[c],p=a[l];if(Jc(u.bounds,p.bounds))for(let d of u.elements)for(let _ of p.elements){let g=zo(d),x=zo(_);if(!(d.type==="pcb_smtpad"&&_.type==="pcb_smtpad"&&t.areIdsConnected(g,x))&&Z6t(d,_)){let v={type:"pcb_footprint_overlap_error",pcb_error_id:`pcb_footprint_overlap_${g}_${x}`,error_type:"pcb_footprint_overlap_error",message:`PCB component ${d.type} "${g}" overlaps with ${_.type} "${x}"`};(d.type==="pcb_smtpad"||_.type==="pcb_smtpad")&&(v.pcb_smtpad_ids=[],d.type==="pcb_smtpad"&&v.pcb_smtpad_ids.push(g),_.type==="pcb_smtpad"&&v.pcb_smtpad_ids.push(x)),(d.type==="pcb_plated_hole"||_.type==="pcb_plated_hole")&&(v.pcb_plated_hole_ids=[],d.type==="pcb_plated_hole"&&v.pcb_plated_hole_ids.push(g),_.type==="pcb_plated_hole"&&v.pcb_plated_hole_ids.push(x)),(d.type==="pcb_hole"||_.type==="pcb_hole")&&(v.pcb_hole_ids=[],d.type==="pcb_hole"&&v.pcb_hole_ids.push(g),_.type==="pcb_hole"&&v.pcb_hole_ids.push(x)),e.push(v)}}}return e}function vtt(n){let e=[],t=n.filter(a=>"source_component_id"in a&&(a.type==="source_component"||a.type.startsWith("source_simple_"))),i=n.filter(a=>a.type==="source_port"),r=n.filter(a=>a.type==="source_trace"),s=new Set;for(let a of r)for(let c of a.connected_source_port_ids??[])s.add(c);let o=new Map;for(let a of t)"internally_connected_source_port_ids"in a&&a.internally_connected_source_port_ids&&o.set(a.source_component_id,a.internally_connected_source_port_ids);for(let a of o.values())for(let c of a)if(c.some(l=>s.has(l)))for(let l of c)s.add(l);for(let a of i)if(a.must_be_connected===!0&&!s.has(a.source_port_id)){let l=t.find(u=>u.source_component_id===a.source_component_id)?.name??"Unknown";e.push({type:"source_pin_must_be_connected_error",source_pin_must_be_connected_error_id:`source_pin_must_be_connected_error_${a.source_port_id}`,error_type:"source_pin_must_be_connected_error",message:`Port ${a.name} on ${l} must be connected but is floating`,source_component_id:a.source_component_id??"",source_port_id:a.source_port_id,subcircuit_id:a.subcircuit_id})}return e}wt();zg();var K6t=n=>{let e=n.board_edge_margin??0;if(n.outline&&n.outline.length>0){let r=new L.Polygon(n.outline.map(s=>L.point(s.x,s.y)));return r.orientation()===L.ORIENTATION.CW&&r.reverse(),r}let{bounds:t}=n,i={minX:t.minX+e,minY:t.minY+e,maxX:t.maxX-e,maxY:t.maxY-e};return i.minX>=i.maxX||i.minY>=i.maxY?new L.Polygon:new L.Polygon(new L.Box(i.minX,i.minY,i.maxX,i.maxY).toPoints())},UA=(n,e=32)=>{let t=[];for(let i=0;i<e;i++){let r=i/e*2*Math.PI;t.push(new L.Point(n.center.x+n.r*Math.cos(r),n.center.y+n.r*Math.sin(r)))}return new L.Polygon(t)},J6t=n=>n.shape==="rect",Q6t=n=>n.shape==="trace",tRt=n=>n.shape==="circle",eRt=n=>n.shape==="polygon",nRt=(n,e,t,i)=>{let r=[],{padMargin:s,traceMargin:o,board_edge_margin:a,cutoutMargin:c}=t;if(i&&i.length>0&&a&&a>0){let l=new L.Polygon(i.map(p=>L.point(p.x,p.y)));l.area()<0&&l.reverse();let u=l.vertices;for(let p=0;p<u.length;p++){let d=u[p===0?u.length-1:p-1],_=u[p],g=u[(p+1)%u.length];if(!d||!_||!g)continue;let x=new L.Vector(d,_),v=new L.Vector(_,g),S=x.cross(v),P=new L.Circle(_,a);if(r.push(UA(P)),S<0){let T=new L.Box(_.x-a,_.y-a,_.x+a,_.y+a);r.push(new L.Polygon(T.toPoints()))}}for(let p=0;p<u.length;p++){let d=u[p],_=u[(p+1)%u.length];if(!d||!_)continue;let g=Math.hypot(d.x-_.x,d.y-_.y);if(g===0)continue;let x=a*2,v=(d.x+_.x)/2,S=(d.y+_.y)/2,P=Math.atan2(_.y-d.y,_.x-d.x)*180/Math.PI,T=g/2,k=x/2,N=P*Math.PI/180,E=Math.cos(N),C=Math.sin(N),A=[{x:-T,y:-k},{x:T,y:-k},{x:T,y:k},{x:-T,y:k}].map(R=>({x:v+R.x*E-R.y*C,y:S+R.x*C+R.y*E}));r.push(new L.Polygon(A.map(R=>L.point(R.x,R.y))))}}for(let l of n){if(l.connectivityKey===e)continue;let p=l.connectivityKey.startsWith("hole:")||l.connectivityKey.startsWith("cutout:");if(tRt(l)){let d=p?c??0:s,_=new L.Circle(new L.Point(l.x,l.y),l.radius+d);r.push(UA(_));continue}if(J6t(l)){let d=p?c??0:s,{bounds:_}=l,g=new L.Box(_.minX-d,_.minY-d,_.maxX+d,_.maxY+d);r.push(new L.Polygon(g.toPoints()));continue}if(eRt(l)){let d=p?c??0:0,_=new Set,g=l.points.filter(T=>{let k=`${T.x},${T.y}`;return _.has(k)?!1:(_.add(k),!0)});if(g.length<3)continue;let x=new L.Polygon(g.map(T=>L.point(T.x,T.y)));if(Math.abs(x.area())<1e-9)continue;if(d<=0){r.push(x);continue}x.area()>0&&x.reverse();let v=[],S=x.vertices;for(let T=0;T<S.length;T++){let k=S[T],N=S[(T+1)%S.length],E=L.segment(k,N);if(E.length===0)continue;let C=L.line(E.start,E.end),M=C.norm,A=C.translate(M.multiply(-d));v.push(A)}let P=[];for(let T=0;T<v.length;T++){let k=v[T],N=v[(T+1)%v.length],E=k.intersect(N);E.length>0&&P.push(E[0])}P.length>=3&&r.push(new L.Polygon(P));continue}if(Q6t(l)){for(let d of l.segments){let _=new L.Circle(new L.Point(d.x,d.y),l.width/2+o);r.push(UA(_))}for(let d=0;d<l.segments.length-1;d++){let _=l.segments[d],g=l.segments[d+1];if(!_||!g)continue;let x=Math.hypot(_.x-g.x,_.y-g.y);if(x===0)continue;let v=l.width+o*2,S=(_.x+g.x)/2,P=(_.y+g.y)/2,T=Math.atan2(g.y-_.y,g.x-_.x)*180/Math.PI,k=x/2,N=v/2,E=T*Math.PI/180,C=Math.cos(E),M=Math.sin(E),R=[{x:-k,y:-N},{x:k,y:-N},{x:k,y:N},{x:-k,y:N}].map(B=>({x:S+B.x*C-B.y*M,y:P+B.x*M+B.y*C}));r.push(new L.Polygon(R.map(B=>L.point(B.x,B.y))))}continue}}return{polygonsToSubtract:r}},wtt=n=>n.edges.map(e=>{let t={x:e.start.x,y:e.start.y};if(e.isArc){let i=Math.tan(e.shape.sweep/4);Math.abs(i)>1e-9&&(t.bulge=i)}return t}),iRt=n=>{let e=[],t=Array.isArray(n)?n:[n];for(let i of t){let r=i.splitToIslands();for(let s of r){if(s.isEmpty())continue;let o=[...s.faces],a=o.find(p=>p.orientation()===L.ORIENTATION.CCW),c=o.filter(p=>p.orientation()===L.ORIENTATION.CW);if(!a)continue;a.reverse();let l=wtt(a),u=c.map(p=>(p.reverse(),{vertices:wtt(p)}));e.push({outer_ring:{vertices:l},inner_rings:u})}}return e},Stt=class extends yQ{constructor(e){super(e);f(this,"pipelineDef",[]);this.input=e}getOutput(){let e=[];for(let t of this.input.regionsForPour){let i=K6t(t),r=this.input.pads.filter(c=>c.layer===t.layer),{polygonsToSubtract:s}=nRt(r,t.connectivityKey,{padMargin:t.padMargin,traceMargin:t.traceMargin,board_edge_margin:t.board_edge_margin,cutoutMargin:t.cutout_margin},t.outline),o=i;for(let c of s){let l=Array.isArray(o)?o:[o],u=[];for(let p of l){let d=L.BooleanOperations.subtract(p,c);d&&(Array.isArray(d)?u.push(...d.filter(_=>!_.isEmpty())):d.isEmpty()||u.push(d))}o=u}let a=iRt(o);e.push(...a)}return{brep_shapes:e}}},Ptt=(n,e)=>{let t=n.filter(T=>T.type==="source_port"),i=n.filter(T=>T.type==="pcb_port"),r=n.filter(T=>T.type==="source_trace"),s=n.filter(T=>T.type==="pcb_trace"),o=n.filter(T=>T.type==="source_net"),a=n.find(T=>T.type==="pcb_board");if(!a)throw new Error("No pcb_board found in circuit json");let c=Object.fromEntries(t.map(T=>[T.source_port_id,T.subcircuit_connectivity_map_key])),l=Object.fromEntries(i.map(T=>[T.pcb_port_id,c[T.source_port_id]])),u={};for(let T of i)T.pcb_port_id&&(u[T.pcb_port_id]=l[T.pcb_port_id]);let p=Object.fromEntries(r.map(T=>[T.source_trace_id,T.subcircuit_connectivity_map_key])),d=Object.fromEntries(o.map(T=>[T.source_net_id,T.subcircuit_connectivity_map_key])),_={...p,...d},g=Object.fromEntries(s.map(T=>[T.pcb_trace_id,T.source_trace_id?_[T.source_trace_id]:void 0]).filter(T=>!!T[1])),x=[];for(let T of n)if(T.type==="pcb_smtpad"){let k=T;if(k.layer!==e.layer)continue;let N;k.pcb_port_id&&(N=l[k.pcb_port_id]),N||(N=`unconnected:${k.pcb_smtpad_id}`),k.shape==="rect"?x.push({shape:"rect",padId:k.pcb_smtpad_id,layer:k.layer,connectivityKey:N,bounds:{minX:k.x-k.width/2,minY:k.y-k.height/2,maxX:k.x+k.width/2,maxY:k.y+k.height/2}}):k.shape==="circle"&&x.push({shape:"circle",padId:k.pcb_smtpad_id,layer:k.layer,connectivityKey:N,x:k.x,y:k.y,radius:k.radius})}else if(T.type==="pcb_plated_hole"){let k=T;if(k.shape!=="circle"||!k.layers.includes(e.layer))continue;let N=u[k.pcb_plated_hole_id];N||(N=`unconnected-plated-hole:${k.pcb_plated_hole_id}`),x.push({shape:"circle",padId:k.pcb_plated_hole_id,layer:e.layer,connectivityKey:N,x:k.x,y:k.y,radius:k.outer_diameter/2})}else if(T.type==="pcb_hole"){let k=T;if(k.hole_shape!=="circle")continue;x.push({shape:"circle",padId:k.pcb_hole_id,layer:e.layer,connectivityKey:`hole:${k.pcb_hole_id}`,x:k.x,y:k.y,radius:k.hole_diameter/2})}else if(T.type==="pcb_cutout"){let k=T;k.shape==="rect"?x.push({shape:"rect",padId:k.pcb_cutout_id,layer:e.layer,connectivityKey:`cutout:${k.pcb_cutout_id}`,bounds:{minX:k.center.x-k.width/2,minY:k.center.y-k.height/2,maxX:k.center.x+k.width/2,maxY:k.center.y+k.height/2}}):k.shape==="circle"?x.push({shape:"circle",padId:k.pcb_cutout_id,layer:e.layer,connectivityKey:`cutout:${k.pcb_cutout_id}`,x:k.center.x,y:k.center.y,radius:k.radius}):k.shape==="polygon"&&x.push({shape:"polygon",padId:k.pcb_cutout_id,layer:e.layer,connectivityKey:`cutout:${k.pcb_cutout_id}`,points:k.points})}else if(T.type==="pcb_via"){let k=T;if(!k.layers.includes(e.layer))continue;let N=k.subcircuit_connectivity_map_key??g[k.pcb_trace_id??""]??`unconnected-via:${k.pcb_via_id}`;x.push({shape:"circle",padId:k.pcb_via_id,layer:e.layer,connectivityKey:N,x:k.x,y:k.y,radius:k.outer_diameter/2})}else if(T.type==="pcb_trace"){let k=T;if(!k.source_trace_id)continue;let N=_[k.source_trace_id];if(!N)continue;let E=[],C=null,M=()=>{E.length>1&&x.push({shape:"trace",padId:`${k.pcb_trace_id}-${x.length}`,layer:e.layer,connectivityKey:N,segments:E,width:C}),E=[],C=null};for(let A of k.route){let R=A;R.route_type==="wire"&&R.layer===e.layer?(C===null&&(C=R.width),E.push({x:R.x,y:R.y})):M()}M()}let{width:v,height:S}=a,P=[{shape:"rect",layer:e.layer,bounds:{minX:-v/2,minY:-S/2,maxX:v/2,maxY:S/2},outline:a.outline,connectivityKey:e.pour_connectivity_key,padMargin:e.pad_margin,traceMargin:e.trace_margin,board_edge_margin:e.board_edge_margin??0,cutout_margin:e.cutout_margin}];return{pads:x,regionsForPour:P}};Ia();wt();Ae();var Xit=Vt(Js(),1);var k9=Vt(In(),1),W_=Vt(Js(),1),G0e=Vt(Js(),1);var Fd=Vt(_l(),1);var Uit=Vt(_l(),1),Vit=Vt(_l(),1);var Git=Vt(_l(),1);var Wit=Vt(_l(),1);var Hit=Vt(_l(),1),qit=Vt(Js(),1);var rLt=Object.defineProperty,sLt=(n,e)=>{for(var t in e)rLt(n,t,{get:e[t],enumerable:!0})},ynt={};sLt(ynt,{AnalogSimulation:()=>Bit,Battery:()=>wit,Board:()=>gP,Breakout:()=>fit,BreakoutPoint:()=>mit,CadAssembly:()=>Rnt,CadModel:()=>Ant,Capacitor:()=>L9,Chip:()=>Z1,Constraint:()=>iit,CopperPour:()=>vit,Crystal:()=>Eit,Cutout:()=>W1,Diode:()=>F9,FabricationNoteDimension:()=>ait,FabricationNotePath:()=>sit,FabricationNoteRect:()=>rit,FabricationNoteText:()=>oit,Footprint:()=>Cnt,Fuse:()=>Znt,Group:()=>Sl,Hole:()=>H_,Inductor:()=>$9,Interconnect:()=>Jnt,Jumper:()=>Knt,Keepout:()=>cP,Led:()=>tit,Mosfet:()=>Mit,Net:()=>M9,NetLabel:()=>_it,NormalComponent:()=>Bn,Panel:()=>Hnt,PcbNoteDimension:()=>hit,PcbNoteLine:()=>cit,PcbNotePath:()=>pit,PcbNoteRect:()=>lit,PcbNoteText:()=>uit,PcbTrace:()=>I9,PinHeader:()=>Sit,Pinout:()=>qnt,PlatedHole:()=>Ld,Port:()=>Wi,Potentiometer:()=>kit,PowerSource:()=>eit,PrimitiveComponent:()=>Me,PushButton:()=>Tit,Renderable:()=>T9,Resistor:()=>z9,Resonator:()=>Pit,SchematicArc:()=>Oit,SchematicBox:()=>Fit,SchematicCell:()=>Dit,SchematicCircle:()=>Lit,SchematicLine:()=>Ait,SchematicRect:()=>Rit,SchematicRow:()=>zit,SchematicTable:()=>$it,SchematicText:()=>Nit,SilkscreenCircle:()=>yit,SilkscreenLine:()=>xit,SilkscreenPath:()=>C9,SilkscreenRect:()=>git,SilkscreenText:()=>fP,SmtPad:()=>G1,SolderJumper:()=>Qnt,Subcircuit:()=>dit,Switch:()=>Cit,Symbol:()=>jit,TestPoint:()=>Iit,Trace:()=>zs,TraceHint:()=>R9,Transistor:()=>D9,Via:()=>bit,VoltageProbe:()=>Yit,VoltageSource:()=>nit});var oLt=(0,bnt.default)("tscircuit:renderable"),Ga=["ReactSubtreesRender","InflateSubcircuitCircuitJson","SourceNameDuplicateComponentRemoval","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","AssignFallbackProps","CreateTracesFromProps","CreateTracesFromNetLabels","CreateTraceHintsFromProps","SourceGroupRender","AssignNameToUnnamedComponents","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SourceDesignRuleChecks","SimulationRender","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicComponentSizeCalculation","SchematicLayout","SchematicTraceRender","SchematicReplaceNetLabelsWithSymbols","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbComponentSizeCalculation","PcbComponentAnchorAlignment","PcbLayout","PcbBoardAutoSize","PanelLayout","PcbTraceHintRender","PcbManualTraceRender","PcbTraceRender","PcbRouteNetIslands","PcbCopperPourRender","PcbDesignRuleChecks","SilkscreenOverlapAdjustment","CadModelRender","PartsEngineRender","SimulationSpiceEngineRender"],aLt={PcbFootprintLayout:["PcbFootprintStringRender"],PcbComponentSizeCalculation:["PcbFootprintStringRender"],PcbLayout:["PcbFootprintStringRender"],PcbBoardAutoSize:["PcbFootprintStringRender"],PcbTraceHintRender:["PcbFootprintStringRender"],PcbManualTraceRender:["PcbFootprintStringRender"],PcbCopperPourRender:["PcbFootprintStringRender","PcbTraceRender","PcbRouteNetIslands"],PcbTraceRender:["PcbFootprintStringRender"],PcbRouteNetIslands:["PcbFootprintStringRender"],PcbDesignRuleChecks:["PcbFootprintStringRender"],SilkscreenOverlapAdjustment:["PcbFootprintStringRender"],CadModelRender:["PcbFootprintStringRender"],PartsEngineRender:["PcbFootprintStringRender"],PcbComponentAnchorAlignment:["PcbFootprintStringRender"]},cLt=0,T9=class vnt{constructor(e){f(this,"renderPhaseStates");f(this,"shouldBeRemoved",!1);f(this,"children");f(this,"isPcbPrimitive",!1);f(this,"isSchematicPrimitive",!1);f(this,"_renderId");f(this,"_currentRenderPhase",null);f(this,"_asyncEffects",[]);f(this,"parent",null);this._renderId=`${cLt++}`,this.children=[],this.renderPhaseStates={};for(let t of Ga)this.renderPhaseStates[t]={initialized:!1,dirty:!1}}_markDirty(e){this.renderPhaseStates[e].dirty=!0;let t=Ga.indexOf(e);for(let i=t+1;i<Ga.length;i++)this.renderPhaseStates[Ga[i]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(e)}_queueAsyncEffect(e,t){let i={promise:t(),phase:this._currentRenderPhase,effectName:e,complete:!1};this._asyncEffects.push(i),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:e,componentDisplayName:this.getString(),phase:i.phase}),i.promise.then(()=>{i.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:i.phase})}).catch(r=>{console.error(`Async effect error in ${i.phase} "${e}":
249
249
  ${r.stack}`),i.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:i.phase,error:r.toString()})})}_emitRenderLifecycleEvent(e,t){oLt(`${e}:${t} ${this.getString()}`);let i=`renderable:renderLifecycle:${e}:${t}`,r={renderId:this._renderId,componentDisplayName:this.getString(),type:i};"root"in this&&this.root&&(this.root.emit(i,r),this.root.emit("renderable:renderLifecycle:anyEvent",{...r,type:i}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(e=>!e.complete)?!0:this.children.some(e=>typeof e._hasIncompleteAsyncEffects=="function"?e._hasIncompleteAsyncEffects():!1)}_hasIncompleteAsyncEffectsInSubtreeForPhase(e){for(let t of this._asyncEffects)if(!t.complete&&t.phase===e)return!0;for(let t of this.children)if(t._hasIncompleteAsyncEffectsInSubtreeForPhase(e))return!0;return!1}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(e=>e.getRenderGraph())}}getTopLevelRenderable(){let e=this;for(;e.parent&&e.parent instanceof vnt;)e=e.parent;return e}runRenderCycle(){for(let e of Ga)this.runRenderPhaseForChildren(e),this.runRenderPhase(e)}runRenderPhase(e){this._currentRenderPhase=e;let t=this.renderPhaseStates[e],i=t.initialized,r=t.dirty;if(!i&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&i){this._emitRenderLifecycleEvent(e,"start"),this?.[`remove${e}`]?.(),t.initialized=!1,t.dirty=!1,this._emitRenderLifecycleEvent(e,"end");return}let s=Ga.indexOf(e)-1;if(s>=0){let a=Ga[s];if(this._asyncEffects.filter(l=>l.phase===a).some(l=>!l.complete))return}let o=aLt[e]||[];if(o.length>0){let a=this.getTopLevelRenderable();for(let c of o)if(a._hasIncompleteAsyncEffectsInSubtreeForPhase(c))return}if(this._emitRenderLifecycleEvent(e,"start"),i){r&&(this?.[`update${e}`]?.(),t.dirty=!1),this._emitRenderLifecycleEvent(e,"end");return}t.dirty=!1,this?.[`doInitial${e}`]?.(),t.initialized=!0,this._emitRenderLifecycleEvent(e,"end")}runRenderPhaseForChildren(e){for(let t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}renderError(e){throw typeof e=="string"?new Error(e):new Error(JSON.stringify(e,null,2))}},aP={},wnt=n=>{let e=Object.fromEntries(Object.entries(n).map(([t,i])=>[t.toLowerCase(),i]));Object.assign(aP,n),Object.assign(aP,e)},lLt=class extends Error{constructor(n,e,t){let i,r=Object.keys(t).filter(c=>c!=="_errors"),s=[],o=e.pinLabels;if(o)for(let[c,l]of Object.entries(o)){let u=Array.isArray(l)?l:[l];for(let p of u)typeof p=="string"&&(p.startsWith(" ")||p.endsWith(" "))&&s.push(`pinLabels.${c} ("${p}" has leading or trailing spaces)`)}let a=r.map(c=>c==="pinLabels"&&s.length>0?s.join(", "):t[c]._errors[0]?`${c} (${t[c]._errors[0]})`:`${c} (${JSON.stringify(t[c])})`).join(", ");"name"in e?i=`Invalid props for ${n} "${e.name}": ${a}`:"footprint"in e&&typeof e.footprint=="string"?i=`Invalid props for ${n} (unnamed ${e.footprint} component): ${a}`:i=`Invalid props for ${n} (unnamed): ${a}`,super(i),this.componentName=n,this.originalProps=e,this.formattedError=t}};function l9(n,e){let t=e.match(/^#(\w+)/);if(t)return n.props.id===t[1];let i=e.match(/^\.(\w+)/);if(i)return n.isMatchingNameOrAlias(i[1]);let[r,...s]=e.split(/(?=[#.[])/);return r==="pin"&&(r="port"),r&&r!=="*"&&n.lowercaseComponentName!==r.toLowerCase()?!1:s.every(o=>{if(o.startsWith("#"))return n.props.id===o.slice(1);if(o.startsWith("."))return n.isMatchingNameOrAlias(o.slice(1));let a=o.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!a)return!0;let[,c,l]=a;return n.props[c].toString()===l})}var uLt={mm:1};function pLt(n,e){let{knownVariables:t,units:i}=e,r={...uLt,...i??{}},s=hLt(n),o=dLt(s,r);return fLt(o,t)}function hLt(n){let e=n.trim();if(!e.toLowerCase().startsWith("calc"))return e;let t=e.match(/^calc\s*\((.*)\)$/is);if(!t)throw new Error(`Invalid calc() expression: "${n}"`);return t[1].trim()}function dLt(n,e){let t=[],i=0,r=a=>a>="0"&&a<="9",s=a=>a>="A"&&a<="Z"||a>="a"&&a<="z"||a==="_",o=a=>s(a)||r(a)||a===".";for(;i<n.length;){let a=n[i];if(a===" "||a===" "||a===`
250
250
  `||a==="\r"){i++;continue}if(r(a)||a==="."&&i+1<n.length&&r(n[i+1])){let c=i;for(i++;i<n.length;){let d=n[i];if(r(d)||d===".")i++;else break}let l=n.slice(c,i),u=Number(l);if(Number.isNaN(u))throw new Error(`Invalid number: "${l}"`);let p=i;for(;i<n.length&&/[A-Za-z]/.test(n[i]);)i++;if(i>p){let d=n.slice(p,i),_=e[d];if(_==null)throw new Error(`Unknown unit: "${d}"`);u*=_}t.push({type:"number",value:u});continue}if(s(a)){let c=i;for(i++;i<n.length&&o(n[i]);)i++;let l=n.slice(c,i);t.push({type:"identifier",value:l});continue}if(a==="("||a===")"){t.push({type:"paren",value:a}),i++;continue}if(a==="+"||a==="-"||a==="*"||a==="/"){t.push({type:"operator",value:a}),i++;continue}throw new Error(`Unexpected character "${a}" in expression "${n}"`)}return t}function fLt(n,e){let t=0,i=()=>n[t],r=()=>n[t++],s=()=>{let u=i();if(!u)throw new Error("Unexpected end of expression");if(u.type==="number")return r(),u.value;if(u.type==="identifier"){r();let p=e[u.value];if(p==null)throw new Error(`Unknown variable: "${u.value}"`);return p}if(u.type==="paren"&&u.value==="("){r();let p=c(),d=i();if(!d||d.type!=="paren"||d.value!==")")throw new Error('Expected ")"');return r(),p}throw new Error(`Unexpected token "${u.value}"`)},o=()=>{let u=i();if(u&&u.type==="operator"&&(u.value==="+"||u.value==="-")){r();let p=o();return u.value==="+"?p:-p}return s()},a=()=>{let u=o();for(;;){let p=i();if(!p||p.type!=="operator"||p.value!=="*"&&p.value!=="/")break;r();let d=o();p.value==="*"?u*=d:u/=d}return u},c=()=>{let u=a();for(;;){let p=i();if(!p||p.type!=="operator"||p.value!=="+"&&p.value!=="-")break;r();let d=a();p.value==="+"?u+=d:u-=d}return u},l=c();if(t<n.length){let u=n.slice(t).map(p=>"value"in p?p.value:"?").join(" ");throw new Error(`Unexpected tokens at end of expression: ${u}`)}return l}var E9={isTag:n=>!0,getParent:n=>n.parent,getChildren:n=>n.children,getName:n=>n.lowercaseComponentName,getAttributeValue:(n,e)=>{if(e==="class"&&"getNameAndAliases"in n)return n.getNameAndAliases().join(" ");if(e==="name"&&n._parsedProps?.name)return n._parsedProps.name;if(n._parsedProps&&e in n._parsedProps){let i=n._parsedProps[e];return typeof i=="string"?i:i!=null?String(i):null}if(e in n){let i=n[e];return typeof i=="string"?i:i!=null?String(i):null}let t=n._attributeLowerToCamelNameMap;if(t){let i=t[e];if(i&&i in n){let r=n[i];return typeof r=="string"?r:r!=null?String(r):null}}return null},hasAttrib:(n,e)=>{if(e==="class")return!!n._parsedProps?.name;if(n._parsedProps&&e in n._parsedProps||e in n)return!0;let t=n._attributeLowerToCamelNameMap;if(t){let i=t[e];if(i&&i in n)return!0}return!1},getSiblings:n=>n.parent?n.parent.children:[],prevElementSibling:n=>{if(!n.parent)return null;let e=n.parent.children,t=e.indexOf(n);return t>0?e[t-1]:null},getText:()=>"",removeSubsets:n=>n.filter((e,t)=>!n.some((i,r)=>t!==r&&i!==e&&i.getDescendants().includes(e))),existsOne:(n,e)=>e.some(n),findAll:(n,e)=>{let t=[],i=r=>{n(r)&&t.push(r);for(let s of r.children)i(s)};for(let r of e)i(r);return t},findOne:(n,e)=>{for(let t of e){if(n(t))return t;let i=t.children;if(i.length>0){let r=E9.findOne(n,i);if(r)return r}}return null},equals:(n,e)=>n._renderId===e._renderId,isHovered:n=>!1,isVisited:n=>!1,isActive:n=>!1},mLt={...E9,getChildren:n=>n.children.filter(e=>!e.isSubcircuit)},Det={...E9,getChildren:n=>n.children.filter(e=>e.isSubcircuit)},_Lt=(n,e)=>{let t=n.split("net.")[1]?.split(/[ >]/)[0]??n;return`Net names cannot contain "+" or "-" (component "${e?.componentName??"Unknown component"}" received "${t}" via "${n}"). Try using underscores instead, e.g. VCC_P`},jet=(n,e)=>{if(/net\.[^\s>]*\./.test(n))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(n))throw new Error(_Lt(n,e));if(/net\.[0-9]/.test(n)){let t=n.match(/net\.([^ >]+)/),i=t?t[1]:"";throw new Error(`Net name "${i}" cannot start with a number, try using a prefix like "VBUS1"`)}return n.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(t,i,r,s)=>{let o=/^\d+$/.test(s)?`pin${s}`:s;return`${i}.${r} > .${o}`}).trim()},u9={adapter:mLt,cacheResults:!0},Me=class extends T9{constructor(e){super(e);f(this,"parent",null);f(this,"children");f(this,"childrenPendingRemoval");f(this,"props");f(this,"_parsedProps");f(this,"externallyAddedAliases");f(this,"isPrimitiveContainer",!1);f(this,"canHaveTextChildren",!1);f(this,"source_group_id",null);f(this,"source_component_id",null);f(this,"schematic_component_id",null);f(this,"pcb_component_id",null);f(this,"cad_component_id",null);f(this,"fallbackUnassignedName");f(this,"_cachedSelectAllQueries",new Map);f(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=e??{},this.externallyAddedAliases=[];let i=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(e??{});if(i.success)this._parsedProps=i.data;else throw new lLt(this.lowercaseComponentName,this.props,i.error.format())}get config(){return{componentName:"",zodProps:h.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(e){let t=this;for(;t;){if(t._parsedProps&&e in t._parsedProps)return t._parsedProps[e];t=t.parent}if(this.root?.platform&&e in this.root.platform)return this.root.platform[e]}getInheritedMergedProperty(e){let t=this.parent?.getInheritedMergedProperty?.(e),i=this._parsedProps?.[e];return{...t,...i}}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(e){let t=this.config.zodProps.parse({...this.props,...e}),i=this.props;this.props=t,this._parsedProps=this.config.zodProps.parse(e),this.onPropsChange({oldProps:i,newProps:t,changedProps:Object.keys(e)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation:e}=this.props;return typeof e=="string"?parseFloat(e):e??null}getResolvedPcbPositionProp(){return{pcbX:this._resolvePcbCoordinate(this._parsedProps.pcbX,"pcbX"),pcbY:this._resolvePcbCoordinate(this._parsedProps.pcbY,"pcbY")}}_resolvePcbCoordinate(e,t,i={}){if(e==null)return 0;if(typeof e=="number")return e;if(typeof e!="string")throw new Error(`Invalid ${t} value for ${this.componentName}: ${String(e)}`);let r=i.allowBoardVariables??this._isNormalComponent===!0,s=e.includes("board."),o={};if(r){let a=this._getBoard(),c=a?._getBoardCalcVariables()??{};if(s&&!a)throw new Error(`Cannot resolve ${t} for ${this.componentName}: no board found for board.* variables`);if(s&&a&&Object.keys(c).length===0)throw new Error("Cannot do calculations based on board size when the board is auto-sized");Object.assign(o,c)}try{return pLt(e,{knownVariables:o})}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`Invalid ${t} value for ${this.componentName}: ${c}`)}}computePcbPropsTransform(){let e=this._getPcbRotationBeforeLayout()??0,{pcbX:t,pcbY:i}=this.getResolvedPcbPositionProp();return ii(kn(t,i),Oo(e*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let e=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(e&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let t=this._getPcbRotationBeforeLayout()??0;return ii(this.parent?._computePcbGlobalTransformBeforeLayout()??Pr(),ii(kn(e.x,e.y),Oo(t*Math.PI/180)))}if(this.isPcbPrimitive){let t=this.getPrimitiveContainer();if(t&&t._parsedProps.layer==="bottom")return ii(this.parent?._computePcbGlobalTransformBeforeLayout()??Pr(),HB(),this.computePcbPropsTransform())}return ii(this.parent?._computePcbGlobalTransformBeforeLayout()??Pr(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}getParentNormalComponent(){let e=this.parent;for(;e;){if(e.isPrimitiveContainer&&e.doInitialPcbComponentRender)return e;e=e.parent}return null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let e=this.getPrimitiveContainer(),t=e?e._parsedProps.layer==="bottom":!1;return{isFlipped:t,maybeFlipLayer:r=>t?r==="top"?"bottom":"top":r}}_setPositionFromLayout(e){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:e}=this;return ii(kn(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){let e=this._getSchematicGlobalManualPlacementTransform(this);return e||ii(this.parent?.computeSchematicGlobalTransform?.()??Pr(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:e}=this,t=this.config.schematicSymbolName,i={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},r=e.schOrientation!==void 0?i[e.schOrientation]:e.schRotation;if(r===void 0&&(r=0),r=r%360,r<0&&(r+=360),e.schRotation!==void 0&&r%90!==0)throw new Error(`Schematic rotation ${e.schRotation} is not supported for ${this.componentName}`);let s=`${t}_horz`,o=`${t}_vert`,a=`${t}_up`,c=`${t}_down`,l=`${t}_left`,u=`${t}_right`;if(u in yi&&r===0)return u;if(a in yi&&r===90)return a;if(l in yi&&r===180)return l;if(c in yi&&r===270)return c;if(s in yi&&(r===0||r===180))return s;if(o in yi&&(r===90||r===270))return o;if(t in yi)return t}_getSchematicSymbolNameOrThrow(){let e=this._getSchematicSymbolName();if(!e)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return e}getSchematicSymbol(){let e=this._getSchematicSymbolName();return e?yi[e]??null:null}_getPcbManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let t=this.props.manualEdits;if(!t)return null;let i=t?.pcb_placements;if(!i)return null;for(let r of i)if(l9(e,r.selector)||e.props.name===r.selector)return De(this._computePcbGlobalTransformBeforeLayout(),r.center);return null}_getSchematicManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let t=this.props.manualEdits;if(!t)return null;let i=t.schematic_placements;if(!i)return null;for(let r of i)if(l9(e,r.selector)||e.props.name===r.selector)return De(this.computeSchematicGlobalTransform(),r.center);return null}_getSchematicGlobalManualPlacementTransform(e){let t=this.getSubcircuit()?._parsedProps.manualEdits;if(!t)return null;for(let i of t.schematic_placements??[])if((l9(e,i.selector)||e.props.name===i.selector)&&i.relative_to==="group_center")return ii(this.parent?._computePcbGlobalTransformBeforeLayout()??Pr(),kn(i.center.x,i.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return De(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return De(this.computeSchematicGlobalTransform(),{x:0,y:0})}_getBoard(){let e=this;for(;e;){let t=e;if(t.componentName==="Board")return t;e=e.parent??null}return this.root?._getBoard()}get root(){return this.parent?.root??null}onAddToParent(e){this.parent=e}onPropsChange(e){}onChildChanged(e){this.parent?.onChildChanged?.(e)}add(e){let t=e.__text;if(typeof t=="string"){if(this.canHaveTextChildren||t.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${t}"`)}if(Object.keys(e).length!==0){if(this.lowercaseComponentName==="board"&&e.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(e.lowercaseComponentName==="panel")throw new Error("<panel> must be a root-level element");if(!e.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(e)}"`);e.onAddToParent(this),e.parent=this,this.children.push(e)}}addAll(e){for(let t of e)this.add(t)}remove(e){this.children=this.children.filter(t=>t!==e),this.childrenPendingRemoval.push(e),e.shouldBeRemoved=!0}getSubcircuitSelector(){let e=this.name,t=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?t:`${this.parent.getSubcircuitSelector()} > ${t}`}getFullPathSelector(){let e=this.name,t=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName,i=this.parent?.getFullPathSelector?.();return i?`${i} > ${t}`:t}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(e){return this.getNameAndAliases().includes(e)}isMatchingAnyOf(e){return this.getNameAndAliases().some(t=>e.map(i=>i.toString()).includes(t))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(e){let t=[this.componentName,this.lowercaseComponentName],i=[this.name].filter(Boolean),r=e.trim().split(/\> /)[0],s=r[0];return r.length>1?!1:!!(e==="*"||e[0]==="#"&&e.slice(1)===this.props.id||e[0]==="."&&i.includes(e.slice(1))||/^[a-zA-Z0-9_]/.test(s)&&t.includes(s))}getSubcircuit(){if(this.isSubcircuit)return this;let e=this.parent?.getSubcircuit?.();if(!e)throw new Error("Component is not inside an opaque group (no board?)");return e}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let e=this.selectAll("port");for(let t of e){let r=(t.getParentNormalComponent?.()??t.parent)?.getNameAndAliases(),s=t.getNameAndAliases();if(r)for(let o of r)for(let a of s){let c=[`.${o} > .${a}`,`.${o} .${a}`];for(let l of c){let u=this._cachedSelectAllQueries.get(l);u?u.push(t):this._cachedSelectAllQueries.set(l,[t])}}}for(let[t,i]of this._cachedSelectAllQueries.entries())i.length===1&&this._cachedSelectOneQueries.set(t,i[0])}selectAll(e){if(this._cachedSelectAllQueries.has(e))return this._cachedSelectAllQueries.get(e);let t=jet(e,this),i=i4(t,this,u9);if(i.length>0)return this._cachedSelectAllQueries.set(e,i),i;let[r,...s]=t.split(" "),o=dw(r,this,{adapter:Det});if(!o)return[];let a=o.selectAll(s.join(" "));return this._cachedSelectAllQueries.set(e,a),a}selectOne(e,t){if(this._cachedSelectOneQueries.has(e))return this._cachedSelectOneQueries.get(e);let i=jet(e,this);t?.port&&(t.type="port");let r=null;if(t?.type&&(r=i4(i,this,u9).find(l=>l.lowercaseComponentName===t.type)),r??(r=dw(i,this,u9)),r)return this._cachedSelectOneQueries.set(e,r),r;let[s,...o]=i.split(" "),a=dw(s,this,{adapter:Det});return a?(r=a.selectOne(o.join(" "),t),this._cachedSelectOneQueries.set(e,r),r):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:e}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[e(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?[...this.root?._getBoard()?.allLayers??["top","bottom"]]:[]}return[]}getDescendants(){let e=[];for(let t of this.children)e.push(t),e.push(...t.getDescendants());return e}getSelectableDescendants(){let e=[];for(let t of this.children)t.isSubcircuit?e.push(t):(e.push(t),e.push(...t.getSelectableDescendants()));return e}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this;return{schWidth:e.schWidth,schHeight:e.schHeight}}renderError(e){if(typeof e=="string")return super.renderError(e);switch(e.type){case"pcb_placement_error":this.root?.db.pcb_placement_error.insert(e);break;case"pcb_via_clearance_error":this.root?.db.pcb_via_clearance_error.insert(e);break;case"pcb_trace_error":this.root?.db.pcb_trace_error.insert(e);break;case"pcb_manual_edit_conflict_warning":this.root?.db.pcb_manual_edit_conflict_warning.insert(e);break;default:this.root?.db.pcb_placement_error.insert(e)}}getString(){let{lowercaseComponentName:e,_parsedProps:t,parent:i}=this;return t?.pinNumber!==void 0&&i?.props?.name&&t?.name?`<${e}#${this._renderId}(pin:${t.pinNumber} .${i?.props.name}>.${t.name}) />`:i?.props?.name&&t?.name?`<${e}#${this._renderId}(.${i?.props.name}>.${t?.name}) />`:t?.from&&t?.to?`<${e}#${this._renderId}(from:${t.from} to:${t?.to}) />`:t?.name?`<${e}#${this._renderId} name=".${t?.name}" />`:t?.portHints?`<${e}#${this._renderId}(${t.portHints.map(r=>`.${r}`).join(", ")}) />`:`<${e}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},yLt=class extends Me{constructor(n,e){super(n);let t=(i,r)=>{if(typeof i=="number")return i;if(typeof i=="string")try{return this._resolvePcbCoordinate(i,r,{allowBoardVariables:!1})}catch{return 0}return 0};this._parsedProps={...n,error:e,type:n.type||"unknown",component_name:n.name,error_type:"source_failed_to_create_component_error",message:e instanceof Error?e.message:String(e),pcbX:t(n.pcbX,"pcbX"),pcbY:t(n.pcbY,"pcbY"),schX:n.schX,schY:n.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:h.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let n=this._getGlobalPcbPositionBeforeLayout(),e=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:n,schematic_center:e})}}};function gLt(n,e){return new yLt(n,e)}function xLt(n,e){let t=n;return t.__tsci={...e},n}var bLt={supportsMutation:!0,createInstance(n,e){let t=aP[n];if(!t)throw Object.keys(aP).length===0?new Error("No components registered in catalogue, did you forget to import lib/register-catalogue in your test file?"):new Error(`Unsupported component type "${n}". No element with this name is registered in the @tscircuit/core catalogue. Check for typos or see https://docs.tscircuit.com/category/built-in-elements for a list of valid components. To add your own component, see docs/CREATING_NEW_COMPONENTS.md`);try{return xLt(new t(e),{})}catch(i){return gLt({...e,componentType:n},i)}},createTextInstance(n){return{__text:n}},appendInitialChild(n,e){n.add(e)},appendChild(n,e){n.add(e)},appendChildToContainer(n,e){n.add(e)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(n){return n},preparePortalMount(n){throw new Error("Function not implemented.")},scheduleTimeout(n,e){throw new Error("Function not implemented.")},cancelTimeout(n){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(n){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(n,e)=>{throw new Error("Function not implemented.")},getInstanceFromScope:n=>{throw new Error("Function not implemented.")},detachDeletedInstance:n=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>iP.DefaultEventPriority,getCurrentUpdatePriority:()=>iP.DefaultEventPriority,resolveUpdatePriority:()=>iP.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},QS=(0,xnt.default)(bLt),Snt=n=>{let e={children:[],props:{name:"$root"},add(s){s.parent=this,this.children.push(s)},computePcbGlobalTransform(){return Pr()}},t=[],i=QS.createContainer(e,0,null,!1,null,"tsci",s=>{console.log("Error in createContainer"),console.error(s),t.push(s)},null);if(QS.updateContainerSync(n,i,null,()=>{}),QS.flushSyncWork(),t.length>0)throw t[0];let r=QS.getPublicRootInstance(i);return r||e.children[0]},H1=(n,e)=>{if(typeof n=="number")return n;if(n.startsWith("pin"))return Number(n.slice(3));if(!e)throw new Error(`No pin labels provided and pin number or label is not a number: "${n}"`);for(let t in e)if((Array.isArray(e[t])?e[t]:[e[t]]).includes(n))return Number(t.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${n}"`)},vLt=(n,e)=>{if(!n)return;let t={},i={};for(let[r,s]of Object.entries(n)){let o=H1(r,e);i[o]={...i[o],...s}}for(let[r,s]of Object.entries(i)){let o=`pin${r}`;t[o]={bottom_margin:s.bottomMargin,left_margin:s.leftMargin,right_margin:s.rightMargin,top_margin:s.topMargin}}return t},wLt=n=>{if(n){if("leftSide"in n||"rightSide"in n||"topSide"in n||"bottomSide"in n)return{left_side:n.leftSide,right_side:n.rightSide,top_side:n.topSide,bottom_side:n.bottomSide};if("leftPinCount"in n||"rightPinCount"in n||"topPinCount"in n||"bottomPinCount"in n)return{left_size:n.leftPinCount,right_size:n.rightPinCount,top_size:n.topPinCount,bottom_size:n.bottomPinCount};if("leftSize"in n||"rightSize"in n||"topSize"in n||"bottomSize"in n)return{left_size:n.leftSize,right_size:n.rightSize,top_size:n.topSize,bottom_size:n.bottomSize}}};function Pnt(n){let e=[];for(let t=0;t<n.length-1;t++)e.push([n[t],n[t+1]]);return e}var SLt=h.object({name:h.string().refine(n=>!/[+-]/.test(n),n=>({message:`Net names cannot contain "+" or "-" (component "Net" received "${n}"). Try using underscores instead, e.g. VCC_P`}))}),M9=class extends Me{constructor(){super(...arguments);f(this,"source_net_id");f(this,"subcircuit_connectivity_map_key",null)}get config(){return{componentName:"Net",zodProps:SLt}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=t.name.startsWith("GND"),r=t.name.startsWith("V"),s=e.source_net.insert({name:t.name,member_source_group_ids:[],is_ground:i,is_power:r,is_positive_voltage_source:r});this.source_net_id=s.source_net_id}doInitialSourceParentAttachment(){let e=this.getSubcircuit();if(!e)return;let{db:t}=this.root;t.source_net.update(this.source_net_id,{subcircuit_id:e.subcircuit_id})}getAllConnectedPorts(){let e=this.getSubcircuit().selectAll("port"),t=[];for(let i of e){let r=i._getDirectlyConnectedTraces();for(let s of r)if(s._isExplicitlyConnectedToNet(this)){t.push(i);break}}return t}_getAllDirectlyConnectedTraces(){let e=this.getSubcircuit().selectAll("trace"),t=[];for(let i of e)i._isExplicitlyConnectedToNet(this)&&t.push(i);return t}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getAllDirectlyConnectedTraces().filter(o=>(o._portsRoutedOnPcb?.length??0)>0),r=[];for(let o of i){let a=o._portsRoutedOnPcb,c=r.find(l=>a.some(u=>l.ports.includes(u)));if(!c){r.push({ports:[...a],traces:[o]});continue}c.traces.push(o),c.ports.push(...a)}if(r.length===0)return;let s=Pnt(r);for(let[o,a]of s){let c=o.ports.map(S=>S._getGlobalPcbPositionBeforeLayout()),l=a.ports.map(S=>S._getGlobalPcbPositionBeforeLayout()),u=1/0,p=[-1,-1];for(let S=0;S<c.length;S++){let P=c[S];for(let T=0;T<l.length;T++){let k=l[T],N=Math.sqrt((P.x-k.x)**2+(P.y-k.y)**2);N<u&&(u=N,p=[S,T])}}let d=o.ports[p[0]],_=a.ports[p[1]],g=e.toArray().filter(S=>S.type==="pcb_smtpad"||S.type==="pcb_trace"||S.type==="pcb_plated_hole"||S.type==="pcb_hole"||S.type==="source_port"||S.type==="pcb_port"),{solution:x}=FW(g.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[d.source_port_id,_.source_port_id]}])),v=x[0];if(!v){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[d.pcb_component_id,_.pcb_component_id].filter(Boolean),pcb_port_ids:[d.pcb_port_id,_.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}e.pcb_trace.insert(v)}}renderError(e){if(typeof e=="string")return super.renderError(e);this.root?.db.pcb_trace_error.insert(e)}},hP=(n,e)=>{for(let t of e)if(typeof t=="string"&&t.startsWith("net.")){if(/net\.[^\s>]*\./.test(t))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(t)){let r=t.split("net.")[1],s=`Net names cannot contain "+" or "-" (component "${n.componentName}" received "${r}" via "${t}"). Try using underscores instead, e.g. VCC_P`;throw new Error(s)}if(/net\.[0-9]/.test(t)){let r=t.split("net.")[1];throw new Error(`Net name "${r}" cannot start with a number, try using a prefix like "VBUS1"`)}let i=n.getSubcircuit();if(!i.selectOne(t)){let r=new M9({name:t.split("net.")[1]});i.add(r)}}},G1=class extends Me{constructor(){super(...arguments);f(this,"pcb_smtpad_id",null);f(this,"matchedPort",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:uH}}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="rotated_rect"){let i=(e.ccwRotation??0)*Math.PI/180,r=Math.cos(i),s=Math.sin(i),o=Math.abs(e.width*r)+Math.abs(e.height*s),a=Math.abs(e.width*s)+Math.abs(e.height*r);return{width:o,height:a}}if(e.shape==="polygon"){let t=e.points,i=t.map(l=>l.x),r=t.map(l=>l.y),s=Math.min(...i),o=Math.max(...i),a=Math.min(...r),c=Math.max(...r);return{width:o-s,height:c-a}}if(e.shape==="pill")return{width:e.width,height:e.height};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let t of e)if(t.isMatchingAnyOf(this.props.portHints)){this.matchedPort=t,t.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=t.coveredWithSolderMask??!1,r=!i,s=t.solderMaskMargin,o=this.getSubcircuit(),a=this._getGlobalPcbPositionBeforeLayout(),c=this._computePcbGlobalTransformBeforeLayout(),p=(io(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,d=.01,_=Math.abs(p)<d||Math.abs(p-180)<d||Math.abs(p-360)<d,g=Math.abs(p-90)<d||Math.abs(p-270)<d,x=Math.abs(p-360)<d?0:p,v=x,{maybeFlipLayer:S,isFlipped:P}=this._getPcbPrimitiveFlippedHelpers();P&&(x=(360-x+360)%360);let T=t.portHints?.map(E=>E.toString())??[],k=null,N=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(t.shape==="circle")k=e.pcb_smtpad.insert({pcb_component_id:N,pcb_port_id:this.matchedPort?.pcb_port_id,layer:S(t.layer??"top"),shape:"circle",radius:t.radius,port_hints:T,is_covered_with_solder_mask:i,soldermask_margin:s,x:a.x,y:a.y,subcircuit_id:o?.subcircuit_id??void 0}),r&&e.pcb_solder_paste.insert({layer:k.layer,shape:"circle",radius:k.radius*.7,x:k.x,y:k.y,pcb_component_id:k.pcb_component_id,pcb_smtpad_id:k.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});else if(t.shape==="rect")!_&&!g?k=e.pcb_smtpad.insert({pcb_component_id:N,pcb_port_id:this.matchedPort?.pcb_port_id,layer:S(t.layer??"top"),shape:"rotated_rect",width:t.width,height:t.height,corner_radius:t.cornerRadius??void 0,x:a.x,y:a.y,ccw_rotation:x,port_hints:T,is_covered_with_solder_mask:i,soldermask_margin:s,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):k=e.pcb_smtpad.insert({pcb_component_id:N,pcb_port_id:this.matchedPort?.pcb_port_id,layer:S(t.layer??"top"),shape:"rect",width:g?t.height:t.width,height:g?t.width:t.height,corner_radius:t.cornerRadius??void 0,port_hints:T,is_covered_with_solder_mask:i,soldermask_margin:s,x:a.x,y:a.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&(k.shape==="rect"?e.pcb_solder_paste.insert({layer:S(t.layer??"top"),shape:"rect",width:k.width*.7,height:k.height*.7,x:k.x,y:k.y,pcb_component_id:k.pcb_component_id,pcb_smtpad_id:k.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):k.shape==="rotated_rect"&&e.pcb_solder_paste.insert({layer:S(t.layer??"top"),shape:"rotated_rect",width:k.width*.7,height:k.height*.7,x:k.x,y:k.y,ccw_rotation:k.ccw_rotation,pcb_component_id:k.pcb_component_id,pcb_smtpad_id:k.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));else if(t.shape==="rotated_rect"){let E=t.ccwRotation??0,C=(v+E+360)%360,M=P?(360-C+360)%360:C;k=e.pcb_smtpad.insert({pcb_component_id:N,pcb_port_id:this.matchedPort?.pcb_port_id,layer:S(t.layer??"top"),shape:"rotated_rect",width:t.width,height:t.height,corner_radius:t.cornerRadius??void 0,x:a.x,y:a.y,ccw_rotation:M,port_hints:T,is_covered_with_solder_mask:i,soldermask_margin:s,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&e.pcb_solder_paste.insert({layer:S(t.layer??"top"),shape:"rotated_rect",width:k.width*.7,height:k.height*.7,x:a.x,y:a.y,ccw_rotation:M,pcb_component_id:N,pcb_smtpad_id:k.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(t.shape==="polygon"){let E=t.points.map(C=>{let M=De(c,{x:V.parse(C.x),y:V.parse(C.y)});return{x:M.x,y:M.y}});k=e.pcb_smtpad.insert({pcb_component_id:N,pcb_port_id:this.matchedPort?.pcb_port_id,layer:S(t.layer??"top"),shape:"polygon",points:E,port_hints:T,is_covered_with_solder_mask:i,soldermask_margin:s,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else t.shape==="pill"&&(k=e.pcb_smtpad.insert({pcb_component_id:N,pcb_port_id:this.matchedPort?.pcb_port_id,layer:S(t.layer??"top"),shape:"pill",x:a.x,y:a.y,radius:t.radius,height:t.height,width:t.width,port_hints:T,is_covered_with_solder_mask:i,soldermask_margin:s,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));k&&(this.pcb_smtpad_id=k.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_smtpad.get(this.pcb_smtpad_id);if(t.shape==="rect")return{center:{x:t.x,y:t.y},bounds:{left:t.x-t.width/2,top:t.y+t.height/2,right:t.x+t.width/2,bottom:t.y-t.height/2},width:t.width,height:t.height};if(t.shape==="rotated_rect"){let i=t.ccw_rotation*Math.PI/180,r=Math.cos(i),s=Math.sin(i),o=t.width/2,a=t.height/2,c=Math.abs(o*r)+Math.abs(a*s),l=Math.abs(o*s)+Math.abs(a*r);return{center:{x:t.x,y:t.y},bounds:{left:t.x-c,right:t.x+c,top:t.y-l,bottom:t.y+l},width:c*2,height:l*2}}if(t.shape==="circle")return{center:{x:t.x,y:t.y},bounds:{left:t.x-t.radius,top:t.y-t.radius,right:t.x+t.radius,bottom:t.y+t.radius},width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){let i=t.points,r=i.map(u=>u.x),s=i.map(u=>u.y),o=Math.min(...r),a=Math.max(...r),c=Math.min(...s),l=Math.max(...s);return{center:{x:(o+a)/2,y:(c+l)/2},bounds:{left:o,top:l,right:a,bottom:c},width:a-o,height:l-c}}if(t.shape==="pill"){let i=t.width/2,r=t.height/2;return{center:{x:t.x,y:t.y},bounds:{left:t.x-i,top:t.y-r,right:t.x+i,bottom:t.y+r},width:t.width,height:t.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${t.shape}"`)}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{x:e.x,y:e.y});let i=t.pcb_solder_paste.list().find(r=>r.pcb_smtpad_id===this.pcb_smtpad_id);i&&t.pcb_solder_paste.update(i.pcb_solder_paste_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}},C9=class extends Me{constructor(){super(...arguments);f(this,"pcb_silkscreen_path_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:JH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let s=this._computePcbGlobalTransformBeforeLayout(),o=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=e.pcb_silkscreen_path.insert({pcb_component_id:a,layer:r,route:t.route.map(l=>{let u=De(s,{x:l.x,y:l.y});return{...l,x:u.x,y:u.y}}),stroke_width:t.strokeWidth??.1,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=c.pcb_silkscreen_path_id}_setPositionFromLayout(e){let{db:t}=this.root,{_parsedProps:i}=this,r=t.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!r)return;let s=0,o=0;for(let u of r.route)s+=u.x,o+=u.y;s/=r.route.length,o/=r.route.length;let a=e.x-s,c=e.y-o,l=r.route.map(u=>({...u,x:u.x+a,y:u.y+c}));t.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:l})}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let o of e.route)t=Math.min(t,o.x),i=Math.max(i,o.x),r=Math.min(r,o.y),s=Math.max(s,o.y);return{width:i-t,height:s-r}}},PLt=h.object({route:h.array(nb),source_trace_id:h.string().optional()}),I9=class extends Me{constructor(){super(...arguments);f(this,"pcb_trace_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:PLt}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getPrimitiveContainer(),r=this.getSubcircuit(),{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),o=this._computePcbGlobalTransformBeforeLayout(),a=t.route.map(l=>{let{x:u,y:p,...d}=l,_=De(o,{x:u,y:p});return l.route_type==="wire"&&l.layer?{..._,...d,layer:s(l.layer)}:{..._,...d}}),c=e.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:t.source_trace_id,route:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=c.pcb_trace_id}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let o of e.route)t=Math.min(t,o.x),i=Math.max(i,o.x),r=Math.min(r,o.y),s=Math.max(s,o.y),o.route_type==="wire"&&(t=Math.min(t,o.x-o.width/2),i=Math.max(i,o.x+o.width/2),r=Math.min(r,o.y-o.width/2),s=Math.max(s,o.y+o.width/2));return t===1/0||i===-1/0||r===1/0||s===-1/0?{width:0,height:0}:{width:i-t,height:s-r}}},Ld=class extends Me{constructor(){super(...arguments);f(this,"pcb_plated_hole_id",null);f(this,"matchedPort",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:tH}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.outerDiameter,height:e.outerDiameter};if(e.shape==="oval"||e.shape==="pill")return{width:e.outerWidth,height:e.outerHeight};if(e.shape==="circular_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};if(e.shape==="pill_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};if(e.shape==="hole_with_polygon_pad"){if(!e.padOutline||e.padOutline.length===0)throw new Error("padOutline is required for hole_with_polygon_pad shape");let t=e.padOutline.map(c=>typeof c.x=="number"?c.x:parseFloat(String(c.x))),i=e.padOutline.map(c=>typeof c.y=="number"?c.y:parseFloat(String(c.y))),r=Math.min(...t),s=Math.max(...t),o=Math.min(...i),a=Math.max(...i);return{width:s-r,height:a-o}}throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_plated_hole.get(this.pcb_plated_hole_id),i=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-i.width/2,top:t.y+i.height/2,right:t.x+i.width/2,bottom:t.y-i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let t of e)if(t.isMatchingAnyOf(this.props.portHints)){this.matchedPort=t,t.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,s=this.getSubcircuit(),o=t.solderMaskMargin,a=t.coveredWithSolderMask??!1;if(t.shape==="circle"){let c=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:t.outerDiameter,hole_diameter:t.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],soldermask_margin:o,is_covered_with_solder_mask:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=c.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:t.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:t.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(t.shape==="pill"&&t.rectPad){let c=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:t.outerWidth,outer_height:t.outerHeight,hole_width:t.holeWidth,hole_height:t.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:i.x,y:i.y,layers:["top","bottom"],soldermask_margin:o,is_covered_with_solder_mask:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:t.pcbRotation??0,rect_ccw_rotation:t.pcbRotation??0,rect_pad_width:t.outerWidth,rect_pad_height:t.outerHeight,hole_offset_x:t.holeOffsetX,hole_offset_y:t.holeOffsetY});this.pcb_plated_hole_id=c.pcb_plated_hole_id}else if(t.shape==="pill"||t.shape==="oval"){let c=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:t.outerWidth,outer_height:t.outerHeight,hole_width:t.holeWidth,hole_height:t.holeHeight,shape:t.shape,port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],soldermask_margin:o,is_covered_with_solder_mask:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:t.pcbRotation??0});this.pcb_plated_hole_id=c.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:t.shape,width:t.outerWidth,height:t.outerHeight,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:t.shape,width:t.outerWidth,height:t.outerHeight,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(t.shape==="circular_hole_with_rect_pad"){let c=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:t.holeDiameter,rect_pad_width:t.rectPadWidth,rect_pad_height:t.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],soldermask_margin:o,is_covered_with_solder_mask:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:t.holeOffsetX,hole_offset_y:t.holeOffsetY,rect_border_radius:t.rectBorderRadius??0});this.pcb_plated_hole_id=c.pcb_plated_hole_id}else if(t.shape==="pill_hole_with_rect_pad"){let c=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:t.holeWidth,hole_height:t.holeHeight,rect_pad_width:t.rectPadWidth,rect_pad_height:t.rectPadHeight,hole_offset_x:t.holeOffsetX,hole_offset_y:t.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],soldermask_margin:o,is_covered_with_solder_mask:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=c.pcb_plated_hole_id}else if(t.shape==="hole_with_polygon_pad"){let c=(t.padOutline||[]).map(u=>{let p=typeof u.x=="number"?u.x:parseFloat(String(u.x)),d=typeof u.y=="number"?u.y:parseFloat(String(u.y));return{x:p,y:d}}),l=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,shape:"hole_with_polygon_pad",hole_shape:t.holeShape||"circle",hole_diameter:t.holeDiameter,hole_width:t.holeWidth,hole_height:t.holeHeight,pad_outline:c,hole_offset_x:typeof t.holeOffsetX=="number"?t.holeOffsetX:parseFloat(String(t.holeOffsetX||0)),hole_offset_y:typeof t.holeOffsetY=="number"?t.holeOffsetY:parseFloat(String(t.holeOffsetY||0)),port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],soldermask_margin:o,is_covered_with_solder_mask:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=l.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},cP=class extends Me{constructor(){super(...arguments);f(this,"pcb_keepout_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:LH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let e=this.getSubcircuit(),{db:t}=this.root,{_parsedProps:i}=this,r=this._getGlobalPcbPositionBeforeLayout(),s=io(this._computePcbGlobalTransformBeforeLayout()),o=Math.abs(s.rotation.angle*(180/Math.PI)-90)%180<.01,a=null;i.shape==="circle"?a=t.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:r.x,y:r.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0}):i.shape==="rect"&&(a=t.pcb_keepout.insert({layers:["top"],shape:"rect",...o?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:r.x,y:r.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0})),a&&(this.pcb_keepout_id=a.pcb_keepout_id)}},H_=class extends Me{constructor(){super(...arguments);f(this,"pcb_hole_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:pH}}getPcbSize(){let{_parsedProps:e}=this,t=e.shape==="pill",i=e.shape==="rect";return t?{width:e.width,height:e.height}:i?{width:e.width,height:e.height}:{width:e.diameter,height:e.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=this._getGlobalPcbPositionBeforeLayout(),s=t.solderMaskMargin,o=t.coveredWithSolderMask??!1;if(t.shape==="pill")if(t.pcbRotation&&t.pcbRotation!==0){let a=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"rotated_pill",hole_width:t.width,hole_height:t.height,x:r.x,y:r.y,ccw_rotation:t.pcbRotation,soldermask_margin:s,is_covered_with_solder_mask:o,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=a.pcb_hole_id}else{let a=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"pill",hole_width:t.width,hole_height:t.height,x:r.x,y:r.y,soldermask_margin:s,is_covered_with_solder_mask:o,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=a.pcb_hole_id}else if(t.shape==="rect"){let a=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"rect",hole_width:t.width,hole_height:t.height,x:r.x,y:r.y,soldermask_margin:s,is_covered_with_solder_mask:o,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=a.pcb_hole_id}else{let a=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"circle",hole_diameter:t.diameter,x:r.x,y:r.y,soldermask_margin:s,is_covered_with_solder_mask:o,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=a.pcb_hole_id}}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_hole.get(this.pcb_hole_id),i=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-i.width/2,top:t.y-i.height/2,right:t.x+i.width/2,bottom:t.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_hole.update(this.pcb_hole_id,{x:e.x,y:e.y})}};function dP(n){return n.replace(/\\n/g,`
251
251
  `)}var fP=class extends Me{constructor(){super(...arguments);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:KH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getPrimitiveContainer(),r=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:s,isFlipped:o}=this._getPcbPrimitiveFlippedHelpers(),a=this.getSubcircuit(),c=0;if(t.pcbRotation!==void 0&&t.pcbRotation!==0)c=t.pcbRotation;else{let d=this._computePcbGlobalTransformBeforeLayout();c=io(d).rotation.angle*180/Math.PI}o&&(c=(c+180)%360);let l=new Set(t.layers);t.layer&&l.add(t.layer);let u=l.size>0?Array.from(l):["top"],p=t.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1;for(let d of u)e.pcb_silkscreen_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:r.x,y:r.y},font:t.font??"tscircuit2024",font_size:p,layer:s(d),text:dP(t.text??""),ccw_rotation:c,pcb_component_id:i.pcb_component_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:e}=this,t=e.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1,r=(e.text??"").length*t,s=t;return{width:r*t,height:s*t}}},W1=class extends Me{constructor(){super(...arguments);f(this,"pcb_cutout_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:lH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=this.getGroup()?.pcb_group_id??void 0,s=this._getGlobalPcbPositionBeforeLayout(),a=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,c;if(t.shape==="rect"){let l=typeof a=="string"?parseInt(a.replace("deg",""),10):a,u=Math.abs(l%180)===90,p={shape:"rect",center:s,width:u?t.height:t.width,height:u?t.width:t.height,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=e.pcb_cutout.insert(p)}else if(t.shape==="circle"){let l={shape:"circle",center:s,radius:t.radius,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=e.pcb_cutout.insert(l)}else if(t.shape==="polygon"){let l=this._computePcbGlobalTransformBeforeLayout(),p={shape:"polygon",points:t.points.map(d=>De(l,d)),subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=e.pcb_cutout.insert(p)}c&&(this.pcb_cutout_id=c.pcb_cutout_id)}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="polygon"){if(e.points.length===0)return{width:0,height:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let o of e.points)t=Math.min(t,o.x),i=Math.max(i,o.x),r=Math.min(r,o.y),s=Math.max(s,o.y);return{width:i-t,height:s-r}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,t=e.pcb_cutout.get(this.pcb_cutout_id);if(!t)return super._getPcbCircuitJsonBounds();if(t.shape==="rect")return{center:t.center,bounds:{left:t.center.x-t.width/2,top:t.center.y+t.height/2,right:t.center.x+t.width/2,bottom:t.center.y-t.height/2},width:t.width,height:t.height};if(t.shape==="circle")return{center:t.center,bounds:{left:t.center.x-t.radius,top:t.center.y+t.radius,right:t.center.x+t.radius,bottom:t.center.y-t.radius},width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){if(t.points.length===0)return super._getPcbCircuitJsonBounds();let i=1/0,r=-1/0,s=1/0,o=-1/0;for(let a of t.points)i=Math.min(i,a.x),r=Math.max(r,a.x),s=Math.min(s,a.y),o=Math.max(o,a.y);return{center:{x:(i+r)/2,y:(s+o)/2},bounds:{left:i,top:o,right:r,bottom:s},width:r-i,height:o-s}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(e){if(!this.pcb_cutout_id)return;let{db:t}=this.root,i=t.pcb_cutout.get(this.pcb_cutout_id);if(i){if(i.shape==="rect"||i.shape==="circle")t.pcb_cutout.update(this.pcb_cutout_id,{...i,center:e});else if(i.shape==="polygon"){let r=this._getPcbCircuitJsonBounds().center,s=e.x-r.x,o=e.y-r.y,a=i.points.map(c=>({x:c.x+s,y:c.y+o}));t.pcb_cutout.update(this.pcb_cutout_id,{...i,points:a})}}}},kLt=({elm:n,pinLabels:e,layer:t,readableRotation:i,anchorAlignment:r})=>{let s=n.text.replace(/[{}]/g,"").toLowerCase(),o=s;if(Array.isArray(e)){let a=parseInt(s.replace(/[^\d]/g,""),10)-1;o=String(e[a]??s)}else typeof e=="object"&&(o=String(e[s]??s));return new fP({anchorAlignment:r||"center",text:o??s,layer:t||"top",fontSize:n.font_size+.2,pcbX:isNaN(n.anchor_position.x)?0:n.anchor_position.x,pcbY:n.anchor_position.y,pcbRotation:i??0})},TLt=(n,e)=>{let t=parseInt(n||"0",10),i;return e!=null?i=e-t:i=t,(i%360+360)%360},q_=({componentName:n,componentRotation:e,footprinterString:t,pinLabels:i,pcbPinLabels:r},s)=>{let o=[];for(let a of s)if(a.type==="pcb_smtpad"&&a.shape==="rect")o.push(new G1({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"rect",height:a.height,width:a.width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius}));else if(a.type==="pcb_smtpad"&&a.shape==="circle")o.push(new G1({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"circle",radius:a.radius,portHints:a.port_hints}));else if(a.type==="pcb_smtpad"&&a.shape==="pill")o.push(new G1({shape:"pill",height:a.height,width:a.width,radius:a.radius,portHints:a.port_hints,pcbX:a.x,pcbY:a.y,layer:a.layer}));else if(a.type==="pcb_silkscreen_path")o.push(new C9({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?o.push(new Ld({pcbX:a.x,pcbY:a.y,shape:"circle",holeDiameter:a.hole_diameter,outerDiameter:a.outer_diameter,portHints:a.port_hints})):a.shape==="circular_hole_with_rect_pad"?o.push(new Ld({pcbX:a.x,pcbY:a.y,shape:"circular_hole_with_rect_pad",holeDiameter:a.hole_diameter,rectPadHeight:a.rect_pad_height,rectPadWidth:a.rect_pad_width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y})):a.shape==="pill"||a.shape==="oval"?o.push(new Ld({pcbX:a.x,pcbY:a.y,shape:a.shape,holeWidth:a.hole_width,holeHeight:a.hole_height,outerWidth:a.outer_width,outerHeight:a.outer_height,portHints:a.port_hints})):a.shape==="pill_hole_with_rect_pad"?o.push(new Ld({pcbX:a.x,pcbY:a.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:a.hole_width,holeHeight:a.hole_height,rectPadWidth:a.rect_pad_width,rectPadHeight:a.rect_pad_height,portHints:a.port_hints,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y})):a.shape==="hole_with_polygon_pad"&&o.push(new Ld({pcbX:a.x,pcbY:a.y,shape:"hole_with_polygon_pad",holeShape:a.hole_shape||"circle",holeDiameter:a.hole_diameter,holeWidth:a.hole_width,holeHeight:a.hole_height,padOutline:a.pad_outline||[],holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y,portHints:a.port_hints}));else if(a.type==="pcb_keepout"&&a.shape==="circle")o.push(new cP({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius}));else if(a.type==="pcb_keepout"&&a.shape==="rect")o.push(new cP({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height}));else if(a.type==="pcb_hole"&&a.hole_shape==="circle")o.push(new H_({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_hole"&&a.hole_shape==="rect")o.push(new H_({pcbX:a.x,pcbY:a.y,shape:"rect",width:a.hole_width,height:a.hole_height}));else if(a.type==="pcb_hole"&&a.hole_shape==="pill")o.push(new H_({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height}));else if(a.type==="pcb_hole"&&a.hole_shape==="rotated_pill")o.push(new H_({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height,pcbRotation:a.ccw_rotation}));else if(a.type==="pcb_cutout")a.shape==="rect"?o.push(new W1({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height})):a.shape==="circle"?o.push(new W1({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius})):a.shape==="polygon"&&o.push(new W1({shape:"polygon",points:a.points}));else if(a.type==="pcb_silkscreen_text"){let c=TLt(e,a.ccw_rotation);t?.includes("pinrow")&&a.text.includes("PIN")?o.push(kLt({elm:a,pinLabels:r??i??{},layer:a.layer,readableRotation:c,anchorAlignment:a.anchor_alignment})):o.push(new fP({anchorAlignment:a.anchor_alignment||"center",text:n||a.text,fontSize:a.font_size+.2,pcbX:Number.isNaN(a.anchor_position.x)?0:a.anchor_position.x,pcbY:a.anchor_position.y,pcbRotation:c??0}))}else a.type==="pcb_trace"&&o.push(new I9({route:a.route}));return o};function mP(n){let e=1/0,t=1/0,i=-1/0,r=-1/0,s=!1;for(let c of n)if(c.isPcbPrimitive&&!c.componentName.startsWith("Silkscreen")){let{x:l,y:u}=c._getGlobalPcbPositionBeforeLayout(),{width:p,height:d}=c.getPcbSize();e=Math.min(e,l-p/2),t=Math.min(t,u-d/2),i=Math.max(i,l+p/2),r=Math.max(r,u+d/2),s=!0}else if(c.children.length>0){let l=mP(c.children);(l.width>0||l.height>0)&&(e=Math.min(e,l.minX),t=Math.min(t,l.minY),i=Math.max(i,l.maxX),r=Math.max(r,l.maxY),s=!0)}if(!s)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let o=i-e,a=r-t;return o<0&&(o=0),a<0&&(a=0),{minX:e,minY:t,maxX:i,maxY:r,width:o,height:a}}function Bet(n){let e=n%360;return e<0?e+360:e}function ELt(n,e,t,i){return i==="counterclockwise"?t>=e?n>=e&&n<=t:n>=e||n<=t:t<=e?n<=e&&n>=t:n<=e||n>=t}function MLt(n){let e=n.center,t=n.radius,i=n.start_angle_degrees,r=n.end_angle_degrees,s=n.direction??"counterclockwise";if(!e||typeof e.x!="number"||typeof e.y!="number"||typeof t!="number"||typeof i!="number"||typeof r!="number")return null;let o=Bet(i),a=Bet(r),c=new Set([o,a]),l=[0,90,180,270];for(let g of l)ELt(g,o,a,s)&&c.add(g);let u=1/0,p=1/0,d=-1/0,_=-1/0;for(let g of c){let x=g*Math.PI/180,v=e.x+t*Math.cos(x),S=e.y+t*Math.sin(x);u=Math.min(u,v),d=Math.max(d,v),p=Math.min(p,S),_=Math.max(_,S)}return!Number.isFinite(u)||!Number.isFinite(p)?null:{minX:u,maxX:d,minY:p,maxY:_}}function knt(n){let e=1/0,t=1/0,i=-1/0,r=-1/0;for(let s of n){let o,a,c,l;if(s.type==="schematic_component")o=s.center?.x,a=s.center?.y,c=s.size?.width,l=s.size?.height;else if(s.type==="schematic_box")o=s.x,a=s.y,c=s.width,l=s.height;else if(s.type==="schematic_port")o=s.center?.x,a=s.center?.y,c=.2,l=.2;else if(s.type==="schematic_text")o=s.position?.x,a=s.position?.y,c=(s.text?.length??0)*.1,l=.2;else if(s.type==="schematic_line"){let u=s.x1??0,p=s.y1??0,d=s.x2??0,_=s.y2??0;o=(u+d)/2,a=(p+_)/2,c=Math.abs(d-u),l=Math.abs(_-p)}else if(s.type==="schematic_rect")o=s.center?.x,a=s.center?.y,c=s.width,l=s.height;else if(s.type==="schematic_circle"){o=s.center?.x,a=s.center?.y;let u=s.radius;typeof u=="number"&&(c=u*2,l=u*2)}else if(s.type==="schematic_arc"){let u=MLt(s);u&&(e=Math.min(e,u.minX),i=Math.max(i,u.maxX),t=Math.min(t,u.minY),r=Math.max(r,u.maxY));continue}typeof o=="number"&&typeof a=="number"&&typeof c=="number"&&typeof l=="number"&&(e=Math.min(e,o-c/2),i=Math.max(i,o+c/2),t=Math.min(t,a-l/2),r=Math.max(r,a+l/2))}return{minX:e,maxX:i,minY:t,maxY:r}}function CLt(n,e){let t=e.x-n.x,i=e.y-n.y;return Math.abs(t)>Math.abs(i)?t>=0?"right":"left":i>=0?"up":"down"}var Yet=n=>{if(n.length<=1)return!0;let e=n.map(s=>{let o=s._getPcbCircuitJsonBounds();return{left:o.bounds.left,right:o.bounds.right,top:o.bounds.top,bottom:o.bounds.bottom}}),t=Array(e.length).fill(!1).map(()=>Array(e.length).fill(!1));for(let s=0;s<e.length;s++)for(let o=s+1;o<e.length;o++){let a=e[s],c=e[o];t[s][o]=t[o][s]=!(a.right<c.left||a.left>c.right||a.bottom>c.top||a.top<c.bottom)}let i=new Set,r=s=>{i.add(s);for(let o=0;o<e.length;o++)t[s][o]&&!i.has(o)&&r(o)};return r(0),i.size===e.length},Xet=n=>{if(n.length===0)throw new Error("Cannot get center of empty PCB primitives array");let e=n.map(r=>r._getPcbCircuitJsonBounds().center).filter(Boolean),t=e.reduce((r,s)=>r+s.x,0),i=e.reduce((r,s)=>r+s.y,0);return{x:t/e.length,y:i/e.length}},ILt=h.object({name:h.string().optional(),pinNumber:h.number().optional(),aliases:h.array(h.string()).optional(),layer:h.string().optional(),layers:h.array(h.string()).optional(),schX:h.number().optional(),schY:h.number().optional(),direction:h.enum(["up","down","left","right"]).optional(),connectsTo:h.union([h.string(),h.array(h.string())]).optional()}),Wi=class extends Me{constructor(e,t={}){if(!e.name&&e.pinNumber!==void 0&&(e.name=`pin${e.pinNumber}`),!e.name)throw new Error("Port must have a name or a pinNumber");super(e);f(this,"source_port_id",null);f(this,"pcb_port_id",null);f(this,"schematic_port_id",null);f(this,"schematicSymbolPortDef",null);f(this,"matchedComponents");f(this,"facingDirection",null);f(this,"originDescription",null);t.originDescription&&(this.originDescription=t.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:ILt}}isGroupPort(){return this.parent?.componentName==="Group"}isComponentPort(){return!this.isGroupPort()}_getConnectedPortsFromConnectsTo(){let{_parsedProps:e}=this,t=e.connectsTo;if(!t)return[];let i=[],r=Array.isArray(t)?t:[t];for(let s of r){let o=this.getSubcircuit().selectOne(s,{type:"port"});o&&i.push(o)}return i}_isBoardPinoutFromAttributes(){let e=this.parent;if(e?._parsedProps?.pinAttributes){let t=e._parsedProps.pinAttributes;for(let i of this.getNameAndAliases())if(t[i]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let e=this.matchedComponents.find(i=>i.isPcbPrimitive),t=this.parent;if(t&&!t.props.footprint)throw new Error(`${t.componentName} "${t.props.name}" does not have a footprint. Add a footprint prop, e.g. <${t.componentName.toLowerCase()} footprint="..." />`);if(!e)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return e?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,t=e.pcb_port.get(this.pcb_port_id);return{center:{x:t.x,y:t.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let e=this.parent;if(!e||!e._getInternallyConnectedPins)return[];let t=e._getInternallyConnectedPins();for(let i of t)if(i.some(r=>r===this))return i;return[]}_hasSchematicPort(){let{schX:e,schY:t}=this._parsedProps;if(e!==void 0&&t!==void 0)return!0;let i=this.getParentNormalComponent();if(i?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(a=>a.schematicSymbolPortDef));let s=i?._getSchematicBoxDimensions();return!!(s&&this.props.pinNumber!==void 0&&s.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let{schX:e,schY:t}=this._parsedProps;if(e!==void 0&&t!==void 0)return{x:e,y:t};let i=this.getParentNormalComponent(),r=i?.getSchematicSymbol();if(r){let o=this.schematicSymbolPortDef;if(!o&&(o=this._getPortsInternallyConnectedToThisPort().find(c=>c.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!o))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);let a=ii(i.computeSchematicGlobalTransform(),kn(-r.center.x,-r.center.y));return De(a,o)}let s=i?._getSchematicBoxDimensions();if(s&&this.props.pinNumber!==void 0){let o=s.getPortPositionByPinNumber(this.props.pinNumber);if(!o)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return De(i.computeSchematicGlobalTransform(),o)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:e}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let t=e.schematic_port.get(this.schematic_port_id);if(!t)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return t.center}registerMatch(e){this.matchedComponents.push(e)}getNameAndAliases(){let{_parsedProps:e}=this;return Array.from(new Set([...e.name?[e.name]:[],...e.aliases??[],...typeof e.pinNumber=="number"?[`pin${e.pinNumber}`,e.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let e=this.parent?._parsedProps?.pinAttributes;if(!e)return[];let t=[];for(let i of this.getNameAndAliases()){let r=e[i];r&&t.push(r)}return t}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(e=>e.includeInBoardPinout===!0)}isMatchingPort(e){return this.isMatchingAnyOf(e.getNameAndAliases())}getPortSelector(){return`.${(this.getParentNormalComponent()??this.parent)?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:e,layers:t}=this._parsedProps;return t||(e?[e]:Array.from(new Set(this.matchedComponents.flatMap(i=>i.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(i=>!i._couldNotFindPort).filter(i=>i._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=this.getNameAndAliases(),r=this.getParentNormalComponent(),o=(this.parent?.source_component_id?this.parent:r)?.source_component_id??null,a=this._getMatchingPinAttributes(),c={};for(let u of a)u.mustBeConnected!==void 0&&(c.must_be_connected=u.mustBeConnected);let l=e.source_port.insert({name:t.name,pin_number:t.pinNumber,port_hints:i,source_component_id:o,subcircuit_id:this.getSubcircuit()?.subcircuit_id,...c});this.source_port_id=l.source_port_id}doInitialSourceParentAttachment(){let{db:e}=this.root,t=this.getParentNormalComponent(),i=this.parent?.source_component_id?this.parent:t;if(this.isGroupPort()){e.source_port.update(this.source_port_id,{source_component_id:null,subcircuit_id:this.getSubcircuit()?.subcircuit_id});return}if(!i?.source_component_id)throw new Error(`${this.getString()} has no parent source component (parent: ${this.parent?.getString()})`);e.source_port.update(this.source_port_id,{source_component_id:i.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=i.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{matchedComponents:t}=this;if(this.isGroupPort()){let a=this._getConnectedPortsFromConnectsTo();if(a.length===0)return;let c=a[0];if(!c.pcb_port_id)return;let l=e.pcb_port.get(c.pcb_port_id),u={x:l.x,y:l.y},p=this.getSubcircuit(),d=e.pcb_port.insert({pcb_component_id:void 0,layers:c.getAvailablePcbLayers(),subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...u,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=d.pcb_port_id;return}let i=this.getParentNormalComponent(),r=this.parent?.pcb_component_id?this.parent:i;if(!r?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()}, parentNormalComponent: ${i?.getString()})`);let s=t.filter(a=>a.isPcbPrimitive);if(s.length===0)return;let o=null;if(s.length===1&&(o=s[0]._getPcbCircuitJsonBounds().center),s.length>1){if(!Yet(s))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${s.map(a=>a.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);o=Xet(s)}if(o){let a=this.getSubcircuit(),c=this._shouldIncludeInBoardPinout(),l=e.pcb_port.insert({pcb_component_id:r.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...c?{is_board_pinout:!0}:{},...o,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=l.pcb_port_id}else{let a=s[0];throw new Error(`${a.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;if(this.pcb_port_id)return;if(this.isGroupPort()){let l=this._getConnectedPortsFromConnectsTo();if(l.length===0)return;let u=l[0];if(!u.pcb_port_id)return;let p=e.pcb_port.get(u.pcb_port_id),d={x:p.x,y:p.y},_=this.getSubcircuit(),g=e.pcb_port.insert({pcb_component_id:void 0,layers:u.getAvailablePcbLayers(),subcircuit_id:_?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...d,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=g.pcb_port_id;return}let t=this.matchedComponents.filter(l=>l.isPcbPrimitive);if(t.length===0)return;let i=null;if(t.length===1&&(i=t[0]._getPcbCircuitJsonBounds().center),t.length>1)try{Yet(t)&&(i=Xet(t))}catch{}if(!i)return;let r=this.getParentNormalComponent(),s=this.parent?.pcb_component_id?this.parent:r,o=this.getSubcircuit(),a=this._shouldIncludeInBoardPinout(),c=e.pcb_port.insert({pcb_component_id:s?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...a?{is_board_pinout:!0}:{},...i,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=c.pcb_port_id}_getBestDisplayPinLabel(){let{db:e}=this.root,t=e.source_port.get(this.source_port_id),i=[];for(let o of t?.port_hints??[])o.match(/^(pin)?\d+$/)||o.match(/^(left|right)/)&&!t?.name.match(/^(left|right)/)||i.push(o);if(this.getParentNormalComponent()?.props?.showPinAliases&&i.length>0)return i.join("/");if(i.length>0)return i[0]}doInitialSchematicPortRender(){let{db:e}=this.root,{_parsedProps:t}=this,{schX:i,schY:r}=t,s=i!==void 0&&r!==void 0?this.getParentNormalComponent():this.getPrimitiveContainer();if(!s||!this._hasSchematicPort())return;let o=s._getGlobalSchematicPositionBeforeLayout(),a=this._getGlobalSchematicPositionBeforeLayout(),c=null,l=s._getSchematicBoxDimensions();l&&t.pinNumber!==void 0&&(c=l.getPortPositionByPinNumber(t.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&e.schematic_debug_object.insert({shape:"rect",center:a,size:{width:.1,height:.1},label:"obstacle"}),c?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[c.side]:this.facingDirection=CLt(o,a);let u=this._getBestDisplayPinLabel(),d={type:"schematic_port",schematic_component_id:this.getParentNormalComponent()?.schematic_component_id,center:a,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:c?.side,pin_number:t.pinNumber,true_ccw_index:c?.trueIndex,display_pin_label:u,is_connected:!1};for(let g of this._getMatchingPinAttributes())g.requiresPower&&(d.has_input_arrow=!0),g.providesPower&&(d.has_output_arrow=!0);let _=e.schematic_port.insert(d);this.schematic_port_id=_.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(e){let{db:t}=this.root;this.pcb_port_id&&t.pcb_port.update(this.pcb_port_id,{x:e.x,y:e.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(e=>e.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},Tnt=n=>{let e=n.find(t=>/^(pin)?\d+$/.test(t));return e?Number.parseInt(e.replace(/^pin/,"")):null};function Y1(n,e){let t=Tnt(n);if(!t)return null;let r=[...n.filter(s=>s.toString()!==t.toString()&&s!==`pin${t}`),...e?.additionalAliases?.[`pin${t}`]??[]];return new Wi({pinNumber:t,aliases:r})}var NLt=n=>{for(let e of["leftSide","rightSide","topSide","bottomSide"])if(e in n&&typeof n[e]=="number")throw new Error(`A number was specified for "${e}", you probably meant to use "size" not "side"`);return"leftSide"in n||"rightSide"in n||"topSide"in n||"bottomSide"in n},ALt=n=>{if(NLt(n))return{leftSize:n.leftSide?.pins.length??0,rightSize:n.rightSide?.pins.length??0,topSize:n.topSide?.pins.length??0,bottomSize:n.bottomSide?.pins.length??0};let{leftSize:e=0,rightSize:t=0,topSize:i=0,bottomSize:r=0}=n;return{leftSize:e,rightSize:t,topSize:i,bottomSize:r}},tP=.4;function Ent(n){let e=n;return e.leftSide!==void 0||e.rightSide!==void 0||e.topSide!==void 0||e.bottomSide!==void 0}var RLt=n=>{let e=n.portDistanceFromEdge??.4,t=n.schPortArrangement?ALt(n.schPortArrangement):null,i={left:0,right:0,top:0,bottom:0},r=n.pinCount??null;if(r===null)if(t)r=t.leftSize+t.rightSize+t.topSize;else throw new Error("Could not determine pin count for the schematic box");if(r&&!t){let g=Math.floor(r/2);t={leftSize:r-g,rightSize:g,topSize:0,bottomSize:0}}t||(t={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let s=({side:g,sideIndex:x,truePinIndex:v})=>{if(!n.schPortArrangement||!Ent(n.schPortArrangement))return v+1;let S={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[g],P=n.schPortArrangement?.[`${g}Side`]?.direction??S,T=n.schPortArrangement?.[`${g}Side`]?.pins,k=x;return P!==S&&(k=T.length-x-1),H1(T[k],n.pinLabels)},o=[],a=0,c=0;for(let g=0;g<t.leftSize;g++){let x=s({side:"left",sideIndex:g,truePinIndex:c}),v=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];v?.topMargin&&(a+=v.topMargin),o.push({trueIndex:c,pinNumber:x,side:"left",distanceFromOrthogonalEdge:a}),v?.bottomMargin&&(a+=v.bottomMargin),g===t.leftSize-1?i.left=a:a+=n.schPinSpacing,c++}a=0;for(let g=0;g<t.bottomSize;g++){let x=s({side:"bottom",sideIndex:g,truePinIndex:c}),v=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];v?.leftMargin&&(a+=v.leftMargin),o.push({trueIndex:c,pinNumber:x,side:"bottom",distanceFromOrthogonalEdge:a}),v?.rightMargin&&(a+=v.rightMargin),g===t.bottomSize-1?i.bottom=a:a+=n.schPinSpacing,c++}a=0;for(let g=0;g<t.rightSize;g++){let x=s({side:"right",sideIndex:g,truePinIndex:c}),v=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];v?.bottomMargin&&(a+=v.bottomMargin),o.push({trueIndex:c,pinNumber:x,side:"right",distanceFromOrthogonalEdge:a}),v?.topMargin&&(a+=v.topMargin),g===t.rightSize-1?i.right=a:a+=n.schPinSpacing,c++}a=0;for(let g=0;g<t.topSize;g++){let x=s({side:"top",sideIndex:g,truePinIndex:c}),v=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];v?.rightMargin&&(a+=v.rightMargin),o.push({trueIndex:c,pinNumber:x,side:"top",distanceFromOrthogonalEdge:a}),v?.leftMargin&&(a+=v.leftMargin),g===t.topSize-1?i.top=a:a+=n.schPinSpacing,c++}let l=n.schWidth;if(l===void 0){l=Math.max(i.top+tP,i.bottom+tP),n.pinLabels&&o.filter(P=>P.side==="left"||P.side==="right").some(P=>n.pinLabels?.[`pin${P.pinNumber}`]||n.pinLabels?.[P.pinNumber])&&(l=Math.max(l,.5));let g=n.pinLabels?Math.max(...Object.values(n.pinLabels).map(v=>v.length*.1)):0,x=g>0?1.1:0;l=Math.max(l,g+x)}let u=n.schHeight;u||(u=Math.max(i.left+tP,i.right+tP));let p={left:{x:-l/2-e,y:i.left/2},bottom:{x:-i.bottom/2,y:-u/2-e},right:{x:l/2+e,y:-i.right/2},top:{x:i.top/2,y:u/2+e}},d={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},_=o.map(g=>{let{distanceFromOrthogonalEdge:x,side:v}=g,S=p[v],P=d[v];return{x:S.x+x*P.x,y:S.y+x*P.y,...g}});return{getPortPositionByPinNumber(g){let x=_.find(v=>v.pinNumber.toString()===g.toString());return x||null},getSize(){return{width:l,height:u}},getSizeIncludingPins(){return{width:l+(t.leftSize||t.rightSize?.4:0),height:u+(t.topSize||t.bottomSize?.4:0)}},pinCount:r}},OLt=(0,Mnt.default)("tscircuit:core:footprint"),Cnt=class extends Me{get config(){return{componentName:"Footprint",zodProps:dH}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let n=this.children.filter(p=>p.componentName==="Constraint");if(n.length===0)return;let{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers(),t=p=>e&&"left"in p&&"right"in p?{...p,left:p.right,right:p.left}:p,i=n.flatMap(p=>p._getAllReferencedComponents().componentsWithSelectors).map(({component:p,selector:d,componentSelector:_,edge:g})=>({component:p,selector:d,componentSelector:_,edge:g,bounds:p._getPcbCircuitJsonBounds()}));if(i.some(p=>p.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function r(p){return i.find(({selector:d})=>d===p)}let s=new a_,o={};function a(p){return p in o||(o[p]=new Oa(p),s.addEditVariable(o[p],On.weak)),o[p]}for(let{selector:p,bounds:d}of i){let _=a(`${p}_x`),g=a(`${p}_y`);s.suggestValue(_,d.center.x),s.suggestValue(g,d.center.y)}for(let p of n){let d=p._parsedProps;if("xDist"in d){let{xDist:_,left:g,right:x,edgeToEdge:v,centerToCenter:S}=t(d),P=a(`${g}_x`),T=a(`${x}_x`),k=r(g)?.bounds,N=r(x)?.bounds;if(S){let E=new Dn(T,[-1,P]);s.addConstraint(new ki(E,ai.Eq,d.xDist,On.required))}else if(v){let E=new Dn(T,-N.width/2,[-1,P],-k.width/2);s.addConstraint(new ki(E,ai.Eq,d.xDist,On.required))}}else if("yDist"in d){let{yDist:_,top:g,bottom:x,edgeToEdge:v,centerToCenter:S}=d,P=a(`${g}_y`),T=a(`${x}_y`),k=r(g)?.bounds,N=r(x)?.bounds;if(S){let E=new Dn(P,[-1,T]);s.addConstraint(new ki(E,ai.Eq,d.yDist,On.required))}else if(v){let E=new Dn(P,k.height/2,[-1,T],-N.height/2);s.addConstraint(new ki(E,ai.Eq,d.yDist,On.required))}}else if("sameY"in d){let{for:_}=d;if(_.length<2)continue;let g=_.map(v=>a(`${v}_y`)),x=new Dn(...g.slice(1));s.addConstraint(new ki(x,ai.Eq,g[0],On.required))}else if("sameX"in d){let{for:_}=d;if(_.length<2)continue;let g=_.map(v=>a(`${v}_x`)),x=new Dn(...g.slice(1));s.addConstraint(new ki(x,ai.Eq,g[0],On.required))}}s.updateVariables(),OLt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(o).map(([p,d])=>({var:p,val:d.value()}))));let c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:p,bounds:{width:d,height:_}}of i){let g=a(`${p}_x`),x=a(`${p}_y`),v=g.value()-d/2,S=g.value()+d/2,P=x.value()+_/2,T=x.value()-_/2;c.left=Math.min(c.left,v),c.right=Math.max(c.right,S),c.top=Math.max(c.top,P),c.bottom=Math.min(c.bottom,T)}let l={x:-(c.right+c.left)/2,y:-(c.top+c.bottom)/2},u=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();l.x+=u.x,l.y+=u.y;for(let{component:p,selector:d}of i){let _=a(`${d}_x`),g=a(`${d}_y`);p._setPositionFromLayout({x:_.value()+l.x,y:g.value()+l.y})}}},Int=n=>{if(!n)return null;let t=n.split("?")[0].split("#")[0],i=t.split("/").pop()??t;return i.includes(".")?i.split(".").pop()?.toLowerCase()??null:null},LLt=(n,e)=>{let t=n.replace(/\/+$/,""),i=e.replace(/^\/+/,"");return`${t}/${i}`},Nnt=(n,e)=>{if(!e||!n.startsWith("/"))return n;try{let t=new URL(e);return t.pathname!=="/"&&n.startsWith(t.pathname)?new URL(n,t.origin).toString():LLt(e,n)}catch{return n}},p9=h.union([h.number(),h.string()]),Uet=h.object({x:p9,y:p9,z:p9}),Ant=class extends Me{get config(){return{componentName:"CadModel",zodProps:zH}}doInitialCadModelRender(){let n=this._findParentWithPcbComponent();if(!n||!n.pcb_component_id)return;let{db:e}=this.root,{boardThickness:t=0}=this.root?._getBoard()??{},i=n._getPcbCircuitJsonBounds(),r=e.pcb_component.get(n.pcb_component_id),s=this._parsedProps;if(!s||typeof s.modelUrl!="string"&&typeof s.stepUrl!="string")return;let o=n._computePcbGlobalTransformBeforeLayout(),c=io(o).rotation.angle*180/Math.PI,l=Uet.parse({x:0,y:0,z:0});if(typeof s.rotationOffset=="number")l.z=Number(s.rotationOffset);else if(typeof s.rotationOffset=="object"){let P=Uet.parse(s.rotationOffset);l.x=Number(P.x),l.y=Number(P.y),l.z=Number(P.z)}let{pcbX:u,pcbY:p}=this.getResolvedPcbPositionProp(),d=Sw.parse({x:u,y:p,z:s.pcbZ??0,...typeof s.positionOffset=="object"?s.positionOffset:{}}),_=s.zOffsetFromSurface!==void 0?V.parse(s.zOffsetFromSurface):0,g=n.props.layer==="bottom"?"bottom":"top",x=s.modelUrl?Int(s.modelUrl):void 0,v={};if(x==="stl"?v.model_stl_url=this._addCachebustToModelUrl(s.modelUrl):x==="obj"?v.model_obj_url=this._addCachebustToModelUrl(s.modelUrl):x==="gltf"?v.model_gltf_url=this._addCachebustToModelUrl(s.modelUrl):x==="glb"?v.model_glb_url=this._addCachebustToModelUrl(s.modelUrl):x==="step"||x==="stp"?v.model_step_url=this._addCachebustToModelUrl(s.modelUrl):x==="wrl"||x==="vrml"?v.model_wrl_url=this._addCachebustToModelUrl(s.modelUrl):v.model_stl_url=this._addCachebustToModelUrl(s.modelUrl),s.stepUrl){let P=this._addCachebustToModelUrl(s.stepUrl);P&&(v.model_step_url=P)}let S=e.cad_component.insert({position:{x:i.center.x+Number(d.x),y:i.center.y+Number(d.y),z:(g==="bottom"?-t/2:t/2)+(g==="bottom"?-_:_)+Number(d.z)},rotation:{x:Number(l.x),y:(g==="top"?0:180)+Number(l.y),z:g==="bottom"?-(c+Number(l.z))+180:c+Number(l.z)},pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,model_unit_to_mm_scale_factor:typeof s.modelUnitToMmScale=="number"?s.modelUnitToMmScale:void 0,show_as_translucent_model:n._parsedProps.showAsTranslucentModel,...v});this.cad_component_id=S.cad_component_id}_findParentWithPcbComponent(){let n=this.parent;for(;n&&!n.pcb_component_id;)n=n.parent;return n}_addCachebustToModelUrl(n){if(!n)return n;let e=this.root?.platform?.projectBaseUrl,t=Nnt(n,e);if(!t.includes("modelcdn.tscircuit.com"))return t;let i=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(i)}`}},Rnt=class extends Me{constructor(){super(...arguments);f(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:$H}}},FLt=(n,e)=>{if(!n)return;let t={};for(let[i,r]of Object.entries(n)){let s=H1(i,e),o={leftMargin:r.marginLeft??r.leftMargin,rightMargin:r.marginRight??r.rightMargin,topMargin:r.marginTop??r.topMargin,bottomMargin:r.marginBottom??r.bottomMargin};t[`pin${s}`]={...t[`pin${s}`],...o}}return t},Vet=class{constructor({input:n}){f(this,"input");this.input=n}solveAndMapToTraces(){let n=[];for(let e of this.input.connections){if(e.pointsToConnect.length!==2)continue;let[t,i]=e.pointsToConnect,r={type:"pcb_trace",pcb_trace_id:"",connection_name:e.name,route:[{route_type:"wire",x:t.x,y:t.y,layer:"top",width:.1},{route_type:"wire",x:i.x,y:i.y,layer:"top",width:.1}]};n.push(r)}return n}},$Lt=n=>{let e=Math.min(...n.map(s=>s.center.x)),t=Math.max(...n.map(s=>s.center.x)),i=Math.min(...n.map(s=>s.center.y)),r=Math.max(...n.map(s=>s.center.y));return{minX:e,maxX:t,minY:i,maxY:r}},Get=["top","bottom","inner1","inner2"],rP=(n,e=[])=>{let t=[];if(e.length===0){let a=n[0].layers;for(let c of a)t.push(...rP(n.slice(1),[c]));return t}if(n.length===0)return[];let i=n[0],r=i.via||i.optional_via,s=e[e.length-1];if(n.length===1){let a=i;return a.layers&&r?a.layers.map(c=>({layer_path:[...e,c]})):a.layers?.includes(s)?[{layer_path:[...e,s]}]:[]}if(!r)return i.layers&&!i.layers.includes(s)?[]:rP(n.slice(1),e.concat([s]));let o=(i.optional_via?Get:Get.filter(a=>a!==s)).filter(a=>!i.layers||i.layers?.includes(a));for(let a of o)t.push(...rP(n.slice(1),e.concat(a)));return t};function Wet(n){let e={x:n.to.x-n.from.x,y:n.to.y-n.from.y},t=Math.abs(e.x),i=Math.abs(e.y);return t>i?e.x>0?"right":"left":e.y>0?"down":"up"}function X_(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}var zLt=n=>{if(n.length===1)return n[0];if(n.some(c=>c.length===0))throw new Error("Cannot merge routes with zero length");let e=[],t=n[0][0],i=n[0][n[0].length-1],r=n[1][0],s=n[1][n[1].length-1],o=Math.min(X_(t,r),X_(t,s)),a=Math.min(X_(i,r),X_(i,s));o<a?e.push(...n[0].reverse()):e.push(...n[0]);for(let c=1;c<n.length;c++){let l=e[e.length-1],u=n[c],p=u[0],d=u[u.length-1],_=X_(l,p),g=X_(l,d);_<g?e.push(...u):e.push(...u.reverse())}for(let c=1;c<e.length-1;c++){let l=e[c-1],u=e[c];l.route_type==="wire"&&u.route_type==="wire"&&l.layer!==u.layer&&e.splice(c,0,{x:l.x,y:l.y,from_layer:l.layer,to_layer:u.layer,route_type:"via"})}return e},DLt=(n,e)=>{let t="_getGlobalPcbPositionBeforeLayout"in n?n._getGlobalPcbPositionBeforeLayout():n,i="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((t.x-i.x)**2+(t.y-i.y)**2)};function jLt(n,e){if(e.length===0)throw new Error("No candidates given to getClosest method");let t=e[0],i=1/0;for(let r of e){let s=DLt(n,r);s<i&&(t=r,i=s)}return t}var BLt=(n,e)=>{let t=0;t+=n.length??0,t+=e.filter(i=>i.is_crossing).length;for(let i=1;i<e.length;i++){let r=e[i-1],s=e[i],o=Math.abs(r.from.x-r.to.x)<.01,a=Math.abs(s.from.x-s.to.x)<.01;o!==a&&t++}return t},q1=n=>({up:"bottom",down:"top",left:"right",right:"left"})[n]??null,y9=({firstEdge:n,firstEdgePort:e,firstDominantDirection:t,lastEdge:i,lastEdgePort:r,lastDominantDirection:s})=>{if(n&&e)return y9({lastEdge:{from:n.to,to:n.from},lastEdgePort:e,lastDominantDirection:t}).reverse().map(a=>({from:a.to,to:a.from}));let o=[];if(i&&r){let a={x:i.to.x,y:i.to.y};s==="left"||s==="right"?(a.x=r.position.x,o.push({from:i.to,to:{...a}}),o.push({from:a,to:{...r.position}})):(a.y=r.position.y,o.push({from:i.to,to:{...a}}),o.push({from:a,to:{...r.position}}))}return o=o.filter(a=>zi(a.from,a.to)>.01),o};function YLt(n){try{return[n(),null]}catch(e){return[null,e]}}var XLt=(n,{db:e})=>{let t=n.map(i=>{let r=e.source_port.get(i.source_port_id);if(!r?.source_component_id)return null;let s=e.source_component.get(r.source_component_id);return s?.ftype==="simple_capacitor"?s.max_decoupling_trace_length:null}).filter(i=>i!==null);if(t.length!==0)return Math.min(...t)};function ULt({ports:n,nets:e}){if(n.length>=2)return`${n[0]?.selector} to ${n[1]?.selector}`;if(n.length===1&&e.length===1)return`${n[0]?.selector} to net.${e[0]._parsedProps.name}`}var VLt=(n,{db:e})=>{let t=e.pcb_board.list()[0];if(t.outline){let c=t.outline,l=(u,p)=>{let d=!1;for(let _=0,g=p.length-1;_<p.length;g=_++){let x=p[_].x,v=p[_].y,S=p[g].x,P=p[g].y;v>u.y!=P>u.y&&u.x<(S-x)*(u.y-v)/(P-v)+x&&(d=!d)}return d};return n.some(u=>!l(u,c))}let i=t.width,r=t.height,s=t.center.x,o=t.center.y;return n.some(c=>c.x<s-i/2||c.y<o-r/2||c.x>s+i/2||c.y>o+r/2)},Het=(n,e)=>Math.abs(n-e)<1e-4,GLt=(n,e,{viaDiameter:t=.5}={})=>{let i=[];for(let r=0;r<n.length-1;r++){let[s,o]=[n[r],n[r+1]],a=r-1>=0?n[r-1]:null,c=Het(s.y,o.y),l=Het(s.x,o.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${s.x}, ${s.y}), end: (${o.x}, ${o.y})`);let u={type:"rect",layers:[s.layer],center:{x:(s.x+o.x)/2,y:(s.y+o.y)/2},width:c?Math.abs(s.x-o.x):.1,height:l?Math.abs(s.y-o.y):.1,connectedTo:[e]};if(i.push(u),a&&a.layer===s.layer&&s.layer!==o.layer){let p={type:"rect",layers:[s.layer,o.layer],center:{x:s.x,y:s.y},connectedTo:[e],width:t,height:t};i.push(p)}}return i};function WLt(n,e=4){let{center:t,width:i,height:r,rotation:s}=n,o=[],a=s*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(s%360+360)%360;if(r<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/e;for(let _=0;_<e;_++){let g=(_-e/2+.5)*d,x=-g*c,v=-g*l,S=d*1.1,P=Math.abs(r*c)+Math.abs(d*l);o.push({center:{x:t.x+x,y:t.y+v},width:S,height:P})}}else{let d=r/e;for(let _=0;_<e;_++){let g=(_-e/2+.5)*d,x=-g*l,v=g*c,S=Math.abs(i*c)+Math.abs(d*l),P=d*1.1;o.push({center:{x:t.x+x,y:t.y+v},width:S,height:P})}}return o}function HLt(n,e={}){if(n.length<3)return[];let{rectHeight:t=.1}=e,i=[],r=n.map(a=>a.y),s=Math.min(...r),o=Math.max(...r);for(let a=s;a<o;a+=t){let c=a+t/2,l=[];for(let u=0;u<n.length;u++){let p=n[u],d=n[(u+1)%n.length];if(p.y<=c&&d.y>c||d.y<=c&&p.y>c){let _=(c-p.y)*(d.x-p.x)/(d.y-p.y)+p.x;l.push(_)}}l.sort((u,p)=>u-p);for(let u=0;u<l.length;u+=2)if(u+1<l.length){let p=l[u],_=l[u+1]-p;_>1e-6&&i.push({center:{x:p+_/2,y:c},width:_,height:t})}}return i}function qLt(n,e={}){let{center:t,radius:i}=n,{rectHeight:r=.1}=e,s=[],o=Math.ceil(i*2/r);for(let a=0;a<o;a++){let c=t.y-i+(a+.5)*r,l=c-t.y,u=Math.sqrt(i*i-l*l);u>0&&s.push({center:{x:t.x,y:c},width:u*2,height:r})}return s}var Zo=["top","inner1","inner2","bottom"],Ont=(n,e)=>{let t=r=>e?r.concat(r.map(s=>e?.getNetConnectedToId(s)).filter(Boolean)):r,i=[];for(let r of n)if(r.type==="pcb_smtpad"){if(r.shape==="circle")i.push({type:"oval",layers:[r.layer],center:{x:r.x,y:r.y},width:r.radius*2,height:r.radius*2,connectedTo:t([r.pcb_smtpad_id])});else if(r.shape==="rect")i.push({type:"rect",layers:[r.layer],center:{x:r.x,y:r.y},width:r.width,height:r.height,connectedTo:t([r.pcb_smtpad_id])});else if(r.shape==="rotated_rect"){let s={center:{x:r.x,y:r.y},width:r.width,height:r.height,rotation:r.ccw_rotation},o=WLt(s);for(let a of o)i.push({type:"rect",layers:[r.layer],center:a.center,width:a.width,height:a.height,connectedTo:t([r.pcb_smtpad_id])})}}else if(r.type==="pcb_keepout")r.shape==="circle"?i.push({type:"oval",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.radius*2,height:r.radius*2,connectedTo:[]}):r.shape==="rect"&&i.push({type:"rect",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.type==="pcb_cutout"){if(r.shape==="rect")i.push({type:"rect",layers:Zo,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.shape==="circle"){let s=qLt({center:r.center,radius:r.radius},{rectHeight:.6});for(let o of s)i.push({type:"rect",layers:Zo,center:o.center,width:o.width,height:o.height,connectedTo:[]})}else if(r.shape==="polygon"){let s=HLt(r.points,{rectHeight:.6});for(let o of s)i.push({type:"rect",layers:Zo,center:o.center,width:o.width,height:o.height,connectedTo:[]})}}else if(r.type==="pcb_hole")r.hole_shape==="oval"?i.push({type:"oval",center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="rect"?i.push({type:"rect",layers:Zo,center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="square"?i.push({type:"rect",layers:Zo,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]}):(r.hole_shape==="round"||r.hole_shape==="circle")&&i.push({type:"rect",layers:Zo,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]});else if(r.type==="pcb_plated_hole"){if(r.shape==="circle")i.push({type:"oval",layers:Zo,center:{x:r.x,y:r.y},width:r.outer_diameter,height:r.outer_diameter,connectedTo:t([r.pcb_plated_hole_id])});else if(r.shape==="circular_hole_with_rect_pad")i.push({type:"rect",layers:Zo,center:{x:r.x,y:r.y},width:r.rect_pad_width,height:r.rect_pad_height,connectedTo:t([r.pcb_plated_hole_id])});else if(r.shape==="oval"||r.shape==="pill")i.push({type:"oval",layers:Zo,center:{x:r.x,y:r.y},width:r.outer_width,height:r.outer_height,connectedTo:t([r.pcb_plated_hole_id])});else if(r.shape==="hole_with_polygon_pad"&&"pad_outline"in r&&r.pad_outline&&r.pad_outline.length>0){let s=r.pad_outline.map(_=>r.x+_.x),o=r.pad_outline.map(_=>r.y+_.y),a=Math.min(...s),c=Math.max(...s),l=Math.min(...o),u=Math.max(...o),p=(a+c)/2,d=(l+u)/2;i.push({type:"rect",layers:Zo,center:{x:p,y:d},width:c-a,height:u-l,connectedTo:t([r.pcb_plated_hole_id])})}}else if(r.type==="pcb_trace"){let s=GLt(r.route.map(o=>({x:o.x,y:o.y,layer:"layer"in o?o.layer:o.from_layer})),r.source_trace_id);i.push(...s)}else if(r.type==="pcb_via"){let s=!!(r.net_is_assignable??r.netIsAssignable);i.push({type:"rect",layers:r.layers,center:{x:r.x,y:r.y},connectedTo:[],width:r.outer_diameter,height:r.outer_diameter,netIsAssignable:s||void 0})}return i},wl=({anchor_position:n,anchor_side:e,text:t,font_size:i=.18})=>{let r=.1*(i/.18),s=t.length*r,o=i,a={...n};switch(e){case"right":a.x-=s/2;break;case"left":a.x+=s/2;break;case"top":a.y-=o/2;break;case"bottom":a.y+=o/2;break}return a},N9=({db:n,source_trace_id:e,sameNetOnly:t,differentNetOnly:i})=>{!t&&!i&&(i=!0);let r=n.source_trace.get(e),s=[];for(let o of n.schematic_trace.list()){if(o.source_trace_id===e)continue;let c=n.source_trace.get(o.source_trace_id)?.subcircuit_connectivity_map_key===r.subcircuit_connectivity_map_key;i&&c||t&&!c||s.push(o)}return s},ZLt=({edges:n,otherEdges:e})=>{let t=[...n];for(let i=0;i<t.length;i++){if(i>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let r=t[i],s=Math.abs(r.from.x-r.to.x)<.01?"vertical":r.from.y===r.to.y?"horizontal":"not-orthogonal";if(s==="not-orthogonal")continue;let o=[];for(let x of e){let v=x.from.x===x.to.x?"vertical":x.from.y===x.to.y?"horizontal":"not-orthogonal";if(v==="not-orthogonal"||s===v)continue;if(La([r.from,r.to],[x.from,x.to],{lineThickness:.01})){let P=s==="vertical"?r.from.x:x.from.x,T=s==="vertical"?x.from.y:r.from.y,k={x:P,y:T};o.push({otherEdge:x,crossingPoint:k,distanceFromEdgeFrom:zi(r.from,k)})}}if(o.length===0)continue;let a=o[0];for(let x of o)x.distanceFromEdgeFrom<a.distanceFromEdgeFrom&&(a=x);let c=a.crossingPoint,l=.075;if(c.x===r.from.x&&c.y===r.from.y)continue;let u=Rw(r.from,c),p={x:c.x-u.x*l/2,y:c.y-u.y*l/2},d={x:c.x+u.x*l/2,y:c.y+u.y*l/2},_=zi(d,r.to)<l,g=[{from:r.from,to:p},{from:p,to:d,is_crossing:!0},{from:d,to:r.to}];t.splice(i,1,...g),i+=g.length-2,_&&i++}return t},g9=.001,U_=(n,e)=>{let t=Math.min(e.from.x,e.to.x),i=Math.max(e.from.x,e.to.x),r=Math.min(e.from.y,e.to.y),s=Math.max(e.from.y,e.to.y);return n.x>=t&&n.x<=i&&n.y>=r&&n.y<=s},qet=n=>{let e=Math.abs(n.from.x-n.to.x)<g9,t=Math.abs(n.from.y-n.to.y)<g9;return e?"vertical":t?"horizontal":"diagonal"},KLt=(n,e)=>{let t=qet(n),i=qet(e);if(t===i)return null;if(t==="vertical"&&i==="horizontal"||t==="horizontal"&&i==="vertical"){let p=t==="vertical"?n:e,d=t==="horizontal"?n:e,_=p.from.x,g=d.from.y,x={x:_,y:g};return U_(x,n)&&U_(x,e)?x:null}if(t==="vertical"||i==="vertical"){let p=t==="vertical"?n:e,d=t==="vertical"?e:n,_=p.from.x,g=(d.to.y-d.from.y)/(d.to.x-d.from.x),x=d.from.y-g*d.from.x,v=g*_+x,S={x:_,y:v};return U_(S,n)&&U_(S,e)?S:null}let r=(n.to.y-n.from.y)/(n.to.x-n.from.x),s=n.from.y-r*n.from.x,o=(e.to.y-e.from.y)/(e.to.x-e.from.x),a=e.from.y-o*e.from.x;if(Math.abs(r-o)<g9)return null;let c=(a-s)/(r-o),l=r*c+s,u={x:c,y:l};return U_(u,n)&&U_(u,e)?u:null},JLt=({edges:n,db:e,source_trace_id:t})=>{let i=N9({db:e,source_trace_id:t,sameNetOnly:!0}).flatMap(s=>s.edges),r=new Map;for(let s of n)for(let o of i){let a=KLt(s,o);if(a){let c=`${a.x.toFixed(6)},${a.y.toFixed(6)}`;r.has(c)||r.set(c,a)}}return Array.from(r.values())};function QLt(n,e={}){let{minX:t,maxX:i,minY:r,maxY:s}=n,o=e.padding??1;if(!isFinite(t)||!isFinite(i)||!isFinite(r)||!isFinite(s))return[];let a=t-o,c=i+o,l=s+o,u=r-o,p=.01;return[{type:"rect",layers:["top"],center:{x:(a+c)/2,y:l},width:c-a,height:p,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(a+c)/2,y:u},width:c-a,height:p,connectedTo:[]},{type:"rect",layers:["top"],center:{x:a,y:(l+u)/2},width:p,height:l-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:c,y:(l+u)/2},width:p,height:l-u,connectedTo:[]}]}var t7t=n=>{let e=n.root.db,t=n._findConnectedPorts().ports??[],i=new Set(t.map(o=>o.schematic_port_id)),r=[];for(let o of e.toArray()){if(o.type==="schematic_component"){let a=!!o.symbol_name,c=o.size.width>o.size.height?"horz":"vert";r.push({type:"rect",layers:["top"],center:o.center,width:o.size.width+(a&&c==="horz"?-.5:0),height:o.size.height+(a&&c==="vert"?-.5:0),connectedTo:[]})}if(o.type==="schematic_port"){if(i.has(o.schematic_port_id))continue;let a=o.facing_direction?Ow(o.facing_direction):{x:0,y:0};r.push({type:"rect",layers:["top"],center:{x:o.center.x-a.x*.1,y:o.center.y-a.y*.1},width:.1+Math.abs(a.x)*.3,height:.1+Math.abs(a.y)*.3,connectedTo:[]})}o.type==="schematic_text"&&r.push({type:"rect",layers:["top"],center:o.position,width:(o.text?.length??0)*.1,height:.2,connectedTo:[]}),o.type==="schematic_box"&&r.push({type:"rect",layers:["top"],center:{x:o.x,y:o.y},width:o.width,height:o.height,connectedTo:[]})}let s=knt(e.toArray());return r.push(...QLt(s,{padding:1})),r},e7t=({edges:n,db:e,source_trace_id:t})=>{let i=e.source_trace.get(t),r=N9({db:e,source_trace_id:t,differentNetOnly:!0}).flatMap(o=>o.edges),s=o=>{let{from:a,to:c}=o;return a.x===c.x?"vertical":"horizontal"};for(let o of n){let a=s(o),c=()=>r.find(u=>s(u)===a&&La([o.from,o.to],[u.from,u.to],{lineThickness:.05})),l=c();for(;l;)a==="horizontal"?(o.from.y+=.1,o.to.y+=.1):(o.from.x+=.1,o.to.x+=.1),l=c()}},x9=n=>{switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},n7t=kq.version??"unknown",X1=class extends Error{constructor(n){super(`${n} (capacity-autorouter@${n7t})`),this.name="AutorouterError"}},lP=class extends Error{constructor(n){super(n.message),this.errorData=n,this.name="TraceConnectionError"}},i7t=n=>{if(n.root?._featureMspSchematicTraceRouting||n._couldNotFindPort||n.root?.schematicDisabled)return;let{db:e}=n.root,{_parsedProps:t,parent:i}=n;if(!i)throw new Error("Trace has no parent");let r,s;try{let X=n._findConnectedPorts();r=X.allPortsFound,s=X.portsWithSelectors??[]}catch(X){if(X instanceof lP){e.source_trace_not_connected_error.insert({...X.errorData,error_type:"source_trace_not_connected_error"});return}throw X}let{netsWithSelectors:o}=n._findConnectedNets();if(!r)return;let c=s.map(X=>X.port.schematic_port_id).sort().join(","),l=n.root?._getBoard();if(l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.has(c))return;let u={name:n.source_trace_id,pointsToConnect:[]},p=t7t(n),d=s.filter(({port:X})=>X.schematic_port_id!==null).map(({port:X})=>({port:X,position:X._getGlobalSchematicPositionAfterLayout(),schematic_port_id:X.schematic_port_id??void 0,facingDirection:X.facingDirection}));if(d.length===1&&o.length===1){let X=o[0].net,{port:W,position:et}=d[0],nt=n.getSubcircuit().selectAll("netlabel").find(tt=>{let J=tt._parsedProps.connection??tt._parsedProps.connectsTo;return J?Array.isArray(J)?J.some(pt=>n.getSubcircuit().selectOne(pt,{port:!0})===W):n.getSubcircuit().selectOne(J,{port:!0})===W:!1});if(!nt){let tt=e.schematic_net_label.getWhere({source_trace_id:n.source_trace_id});tt&&(nt=tt)}if(nt){let tt="_getGlobalSchematicPositionBeforeLayout"in nt?nt._getGlobalSchematicPositionBeforeLayout():nt.anchor_position,J=[];et.x===tt.x||et.y===tt.y?J.push({from:et,to:tt}):(J.push({from:et,to:{x:tt.x,y:et.y}}),J.push({from:{x:tt.x,y:et.y},to:tt}));let ht=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:J,junctions:[],subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=ht.schematic_trace_id;return}if(n.props.schDisplayLabel){let tt=q1(W.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel,source_net_id:X.source_net_id,anchor_position:et,center:wl({anchor_position:et,anchor_side:tt,text:n.props.schDisplayLabel}),anchor_side:tt});return}let mt=q1(W.facingDirection)??"bottom",G=e.schematic_net_label.insert({text:X._parsedProps.name,source_net_id:X.source_net_id,anchor_position:et,center:wl({anchor_position:et,anchor_side:mt,text:X._parsedProps.name}),anchor_side:mt});return}if(n.props.schDisplayLabel&&("from"in n.props&&"to"in n.props||"path"in n.props)){n._doInitialSchematicTraceRenderWithDisplayLabel();return}if(d.length<2)return;let x=(()=>{let X=[];for(let et=0;et<d.length-1;et++){let nt=d[et],mt=d[et+1],G=Qc({x:nt.position.x,y:nt.position.y,facingDirection:x9(nt.facingDirection)},{x:mt.position.x,y:mt.position.y,facingDirection:x9(mt.facingDirection)});for(let tt=0;tt<G.length-1;tt++)X.push({from:G[tt],to:G[tt+1]})}let W=(et,nt)=>{let mt=nt.width/2,G=nt.height/2,tt=nt.center.x-mt,J=nt.center.x+mt,ht=nt.center.y-G,pt=nt.center.y+G,St=ot=>ot.x>=tt&&ot.x<=J&&ot.y>=ht&&ot.y<=pt;return St(et.from)||St(et.to)?!0:[[{x:tt,y:ht},{x:J,y:ht}],[{x:J,y:ht},{x:J,y:pt}],[{x:J,y:pt},{x:tt,y:pt}],[{x:tt,y:pt},{x:tt,y:ht}]].some(ot=>La([et.from,et.to],ot,{lineThickness:0}))};for(let et of X)for(let nt of p)if(W(et,nt))return null;return X})();x&&x.length===0&&(x=null),u.pointsToConnect=d.map(({position:X})=>({...X,layer:"top"}));let v=$Lt(p),S=2,P={minTraceWidth:.1,obstacles:p,connections:[u],bounds:{minX:v.minX-S,maxX:v.maxX+S,minY:v.minY-S,maxY:v.maxY+S},layerCount:1},T=bw,k=!1;if(n.getSubcircuit().props._schDirectLineRoutingEnabled&&(T=Vet,k=!0),!x){let W=new T({input:P,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(W.length===0){if(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection()){n._doInitialSchematicTraceRenderWithDisplayLabel();return}W=new Vet({input:P}).solveAndMapToTraces(),k=!0}let[{route:et}]=W;x=[];for(let nt=0;nt<et.length-1;nt++)x.push({from:et[nt],to:et[nt+1]})}let N=n.source_trace_id,E=[];if(!k){e7t({edges:x,db:e,source_trace_id:N});let X=N9({db:e,source_trace_id:N,differentNetOnly:!0}).flatMap(W=>W.edges);x=ZLt({edges:x,otherEdges:X}),E=JLt({edges:x,db:e,source_trace_id:n.source_trace_id})}if(!x||x.length===0)return;let C=x[x.length-1],M=d[d.length-1],A=Wet(C);x.push(...y9({lastEdge:C,lastEdgePort:M,lastDominantDirection:A}));let R=x[0],B=d[0],j=Wet(R);if(x.unshift(...y9({firstEdge:R,firstEdgePort:B,firstDominantDirection:j})),!n.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(n.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&BLt(E,x)>=5&&(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection())){n._doInitialSchematicTraceRenderWithDisplayLabel();return}let U=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:x,junctions:E,subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=U.schematic_trace_id;for(let{port:X}of s)X.schematic_port_id&&e.schematic_port.update(X.schematic_port_id,{is_connected:!0});l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.add(c)};function b9(n){let e=0;for(let t=0;t<n.length;t++){let i=n[t];if(i.route_type==="wire"){let r=n[t+1];if(r){let s=r.x-i.x,o=r.y-i.y;e+=Math.sqrt(s*s+o*o)}}else i.route_type==="via"&&(e+=1.6)}return e}var r7t=.3,s7t=.6,Zet=(n,e)=>{if(n===void 0)return e;if(typeof n=="number")return n;let t=parseFloat(n);return Number.isFinite(t)?t:e},A9=n=>({holeDiameter:Zet(n?.viaHoleDiameter,r7t),padDiameter:Zet(n?.viaPadDiameter,s7t)}),o7t=(n,e)=>{let t=A9(e);return{holeDiameter:n.holeDiameter??t.holeDiameter,padDiameter:n.padDiameter??t.padDiameter}},eP=n=>({...n._getGlobalPcbPositionAfterLayout(),layers:n.getAvailablePcbLayers()}),a7t=!1;function c7t(n){if(n.root?.pcbDisabled)return;let{db:e}=n.root,{_parsedProps:t,parent:i}=n,r=n.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(r._parsedProps.routingDisabled)return;let s=r._parsedProps.pcbRouteCache?.pcbTraces;if(s){let j=e.pcb_trace.insert({route:s.flatMap(U=>U.route),source_trace_id:n.source_trace_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0});n.pcb_trace_id=j.pcb_trace_id;return}if(t.pcbPath&&t.pcbPath.length>0||t.pcbStraightLine||!r._shouldUseTraceByTraceRouting())return;let{allPortsFound:o,ports:a}=n._findConnectedPorts(),c=[];if(!o)return;let l=[];for(let j of a)j._hasMatchedPcbPrimitive()||l.push(j);if(l.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${n} wasn't routed. Missing ports: ${l.map(j=>j.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(j=>j.pcb_port_id).filter(Boolean)});return}let u=n._findConnectedNets().netsWithSelectors;if(a.length===0&&u.length===2){n.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(a.length===1&&u.length===1){let j=a[0],X=u[0].net.getAllConnectedPorts().filter(et=>et!==j);if(X.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let W=jLt(j,X);c.push(W),a.push(W)}else if(a.length>1&&u.length>=1){n.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}let p=a.flatMap(j=>j.matchedComponents.filter(U=>U.componentName==="TraceHint")),d=(n._parsedProps.pcbRouteHints??[]).concat(p.flatMap(j=>j.getPcbRouteHints()));if(a.length>2){n.renderError(`Trace has more than two ports (${a.map(j=>j.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(n.getSubcircuit().selectAll("trace").filter(j=>j.renderPhaseStates.PcbTraceRender.initialized).some(j=>j._portsRoutedOnPcb.length===a.length&&j._portsRoutedOnPcb.every(U=>a.includes(U))))return;let x=[];d.length===0?x=[eP(a[0]),eP(a[1])]:x=[eP(a[0]),...d,eP(a[1])];let v=rP(x);if(a7t&&v.length===0){n.renderError(`Could not find a common layer (using hints) for trace ${n.getString()}`);return}let S=nr(n.root.db.toArray()),[P,T]=YLt(()=>Ont(n.root.db.toArray()));if(T){n.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:n.pcb_trace_id,message:`Error getting obstacles for autorouting: ${T.message}`,source_trace_id:n.source_trace_id,center:{x:0,y:0},pcb_port_ids:a.map(j=>j.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[]});return}for(let j of P)if(j.connectedTo.length>0){let X=S.getNetConnectedToId(j.connectedTo[0]);X&&j.connectedTo.push(X)}let k=[];if(v.length===0)k=x;else{let j=v[0].layer_path;k=x.map((U,X)=>U.via?{...U,via_to_layer:j[X]}:{...U,layers:[j[X]]})}k[0].pcb_port_id=a[0].pcb_port_id,k[k.length-1].pcb_port_id=a[1].pcb_port_id;let N=[];for(let[j,U]of Pnt(k)){let X="via_to_layer"in j?j.via_to_layer:null,W=2,et="layers"in j&&j.layers.length===1?j.layers[0]:X??"top",nt="layers"in U&&U.layers.length===1?U.layers[0]:X??"top",mt="pcb_port_id"in j?j.pcb_port_id:null,G="pcb_port_id"in U?U.pcb_port_id:null,tt=n._getExplicitTraceThickness()??n.getSubcircuit()._parsedProps.minTraceWidth??.16,J=new bw({OBSTACLE_MARGIN:tt*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(mt&&G),connMap:S,input:{obstacles:P,minTraceWidth:tt,connections:[{name:n.source_trace_id,pointsToConnect:[{...j,layer:et,pcb_port_id:mt},{...U,layer:nt,pcb_port_id:G}]}],layerCount:n.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(j.x,U.x)-W,maxX:Math.max(j.x,U.x)+W,minY:Math.min(j.y,U.y)-W,maxY:Math.max(j.y,U.y)+W}}}),ht=null;try{ht=J.solveAndMapToTraces()}catch(Mt){n.renderError({type:"pcb_trace_error",pcb_trace_error_id:n.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${Mt.message}`,source_trace_id:n.pcb_trace_id,center:{x:(j.x+U.x)/2,y:(j.y+U.y)/2},pcb_port_ids:a.map(ot=>ot.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:a.map(ot=>ot.pcb_component_id)})}if(!ht)return;if(ht.length===0){n.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:n.pcb_trace_id,message:`Could not find a route for ${n}`,source_trace_id:n.source_trace_id,center:{x:(j.x+U.x)/2,y:(j.y+U.y)/2},pcb_port_ids:a.map(Mt=>Mt.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:a.map(Mt=>Mt.pcb_component_id)});return}let[pt]=ht;X&&(pt.route=pt.route.map(Mt=>(Mt.route_type==="wire"&&!Mt.layer&&(Mt.layer=X),Mt))),mt&&pt.route[0].route_type==="wire"&&(pt.route[0].start_pcb_port_id=mt);let St=pt.route[pt.route.length-1];G&&St.route_type==="wire"&&(St.end_pcb_port_id=G),N.push(pt.route)}let E=zLt(N),C=b9(E),M=n.getInheritedMergedProperty("pcbStyle"),{holeDiameter:A,padDiameter:R}=A9(M),B=e.pcb_trace.insert({route:E,source_trace_id:n.source_trace_id,subcircuit_id:n.getSubcircuit()?.subcircuit_id,trace_length:C});n._portsRoutedOnPcb=a,n.pcb_trace_id=B.pcb_trace_id;for(let j of E)j.route_type==="via"&&e.pcb_via.insert({pcb_trace_id:B.pcb_trace_id,x:j.x,y:j.y,hole_diameter:A,outer_diameter:R,layers:[j.from_layer,j.to_layer],from_layer:j.from_layer,to_layer:j.to_layer});n._insertErrorIfTraceIsOutsideBoard(E,a)}function Ket(n){let{lineStart:e,lineEnd:t,rectCenter:i,rectWidth:r,rectHeight:s}=n,o=i.x-r/2,a=i.x+r/2,c=i.y+s/2,l=i.y-s/2,u=t.x-e.x,p=t.y-e.y,d=[];if(u!==0){let _=(o-e.x)/u;if(_>=0&&_<=1){let g=e.y+_*p;g>=l&&g<=c&&d.push({x:o,y:g,t:_})}}if(u!==0){let _=(a-e.x)/u;if(_>=0&&_<=1){let g=e.y+_*p;g>=l&&g<=c&&d.push({x:a,y:g,t:_})}}if(p!==0){let _=(l-e.y)/p;if(_>=0&&_<=1){let g=e.x+_*u;g>=o&&g<=a&&d.push({x:g,y:l,t:_})}}if(p!==0){let _=(c-e.y)/p;if(_>=0&&_<=1){let g=e.x+_*u;g>=o&&g<=a&&d.push({x:g,y:c,t:_})}}return d.length===0?null:(d.sort((_,g)=>_.t-g.t),{x:d[0].x,y:d[0].y})}function Jet(n){let{lineStart:e,lineEnd:t,circleCenter:i,circleRadius:r}=n,s=e.x-i.x,o=e.y-i.y,a=t.x-i.x,c=t.y-i.y,l=a-s,u=c-o,p=l*l+u*u,d=2*(s*l+o*u),_=s*s+o*o-r*r,g=d*d-4*p*_;if(g<0)return null;let x=Math.sqrt(g),v=(-d-x)/(2*p),S=(-d+x)/(2*p),P=null;return v>=0&&v<=1?P=v:S>=0&&S<=1&&(P=S),P===null?null:{x:e.x+P*l,y:e.y+P*u}}function Qet(n){let{traceStart:e,traceEnd:t,traceWidth:i,port:r}=n,s=r.matchedComponents.find(d=>d.isPcbPrimitive);if(!s)return t;let o=s._getPcbCircuitJsonBounds(),a=o.width,c=o.height,l=o.center,u=Math.min(a,c);if(i<=u/2)return t;let p=null;if(s.componentName==="SmtPad"){let d=s,_=d._parsedProps.shape;if(_==="circle"){let g=d._parsedProps.radius;p=Jet({lineStart:e,lineEnd:t,circleCenter:l,circleRadius:g})}else(_==="rect"||_==="rotated_rect"||_==="pill"||_==="polygon")&&(p=Ket({lineStart:e,lineEnd:t,rectCenter:l,rectWidth:a,rectHeight:c}))}else if(s.componentName==="PlatedHole"){let d=s;if(d._parsedProps.shape==="circle"){let g=d._parsedProps.outerDiameter;p=Jet({lineStart:e,lineEnd:t,circleCenter:l,circleRadius:g/2})}else p=Ket({lineStart:e,lineEnd:t,rectCenter:l,rectWidth:a,rectHeight:c})}return p??t}function l7t(n){if(n.root?.pcbDisabled)return;let{db:e}=n.root,{_parsedProps:t}=n,i=n.getSubcircuit(),r=t.pcbPath!==void 0,s=!!t.pcbStraightLine;if(!r&&!s)return;let{allPortsFound:o,ports:a,portsWithSelectors:c}=n._findConnectedPorts();if(!o)return;let l=[];for(let k of a)k._hasMatchedPcbPrimitive()||l.push(k);if(l.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${n} wasn't routed. Missing ports: ${l.map(k=>k.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(k=>k.pcb_port_id).filter(Boolean)});return}let u=n._getExplicitTraceThickness()??n.getSubcircuit()._parsedProps.minTraceWidth??.16;if(s&&!r){if(!a||a.length<2){n.renderError("pcbStraightLine requires exactly two connected ports");return}let[k,N]=a,E=k.getAvailablePcbLayers(),C=N.getAvailablePcbLayers(),A=E.find(nt=>C.includes(nt))??E[0]??C[0]??"top",R=k._getGlobalPcbPositionAfterLayout(),B=N._getGlobalPcbPositionAfterLayout(),j=Qet({traceStart:B,traceEnd:R,traceWidth:u,port:k}),U=Qet({traceStart:R,traceEnd:B,traceWidth:u,port:N}),X=[{route_type:"wire",x:j.x,y:j.y,width:u,layer:A,start_pcb_port_id:k.pcb_port_id},{route_type:"wire",x:U.x,y:U.y,width:u,layer:A,end_pcb_port_id:N.pcb_port_id}],W=b9(X),et=e.pcb_trace.insert({route:X,source_trace_id:n.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,trace_length:W});n._portsRoutedOnPcb=a,n.pcb_trace_id=et.pcb_trace_id,n._insertErrorIfTraceIsOutsideBoard(X,a);return}if(!t.pcbPath)return;let p;t.pcbPathRelativeTo&&(p=c.find(k=>k.selector===t.pcbPathRelativeTo)?.port,p||(p=n.getSubcircuit().selectOne(t.pcbPathRelativeTo))),p||(p=a[0]);let d=a.find(k=>k!==p)??a[1],_=p.getAvailablePcbLayers()[0]||"top",g=p._getGlobalPcbPositionAfterLayout(),x=d._getGlobalPcbPositionAfterLayout(),v=[];v.push({route_type:"wire",x:g.x,y:g.y,width:u,layer:_,start_pcb_port_id:p.pcb_port_id});let S=p?._computePcbGlobalTransformBeforeLayout?.()||Pr();for(let k of t.pcbPath){let N,E=!1;if(typeof k=="string"){let M=n.getSubcircuit().selectOne(k,{type:"port"});if(!M){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.source_trace_id,message:`Could not resolve pcbPath selector "${k}" for ${n}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:[]});continue}let A=M._getGlobalPcbPositionAfterLayout();N={x:A.x,y:A.y},E=!0}else N={x:k.x,y:k.y},E=!1;let C=E?N:De(S,N);v.push({route_type:"wire",x:C.x,y:C.y,width:u,layer:_})}v.push({route_type:"wire",x:x.x,y:x.y,width:u,layer:_,end_pcb_port_id:d.pcb_port_id});let P=b9(v),T=e.pcb_trace.insert({route:v,source_trace_id:n.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,trace_length:P});n._portsRoutedOnPcb=a,n.pcb_trace_id=T.pcb_trace_id,n._insertErrorIfTraceIsOutsideBoard(v,a)}function u7t(n){if(n.root?.schematicDisabled)return;let{db:e}=n.root,{_parsedProps:t,parent:i}=n;if(!i)throw new Error("Trace has no parent");let{allPortsFound:r,portsWithSelectors:s}=n._findConnectedPorts();if(!r)return;let o=s.map(({port:k})=>({port:k,position:k._getGlobalSchematicPositionAfterLayout(),schematic_port_id:k.schematic_port_id,facingDirection:k.facingDirection}));if(o.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let a,c,l=o[0].position,u=o[0].port;if("path"in n.props){if(n.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[a,c]=n.props.path}else{if(!("from"in n.props&&"to"in n.props))throw new Error("Missing 'from' or 'to' properties in props.");a=n.props.from,c=n.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${a}).`);let p=o[1].position,d=o[1].port;if(!d.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);let _=e.schematic_net_label.list().find(k=>k.source_net_id===u.source_port_id),g=e.schematic_net_label.list().find(k=>k.source_net_id===d.source_port_id),[x,v]=s.map(({port:k})=>k),P=x.parent?.config.shouldRenderAsSchematicBox?`${x?.parent?.props.name}_${x?.props.name}`:`${v?.parent?.props.name}_${v?.props.name}`,T=n.props.schDisplayLabel??P;if(_&&_.text!==T&&(_.text=`${T} / ${_.text}`),g&&g?.text!==T&&(g.text=`${T} / ${g.text}`),!g){let k=q1(d.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??P,source_net_id:d.source_port_id,anchor_position:p,center:wl({anchor_position:p,anchor_side:k,text:n.props.schDisplayLabel??P}),anchor_side:k})}if(!_){let k=q1(u.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??P,source_net_id:u.source_port_id,anchor_position:l,center:wl({anchor_position:l,anchor_side:k,text:n.props.schDisplayLabel??P}),anchor_side:k})}}function p7t(n){let{_parsedProps:e,parent:t}=n;if(!t)throw new Error("Trace has no parent");let r=n.getTracePortPathSelectors().map(s=>({selector:s,port:n.getSubcircuit().selectOne(s,{type:"port"})??null}));for(let{selector:s,port:o}of r)if(!o){let a,c,l=s.lastIndexOf(".");if(l!==-1&&l>s.lastIndexOf(" "))a=s.slice(0,l),c=s.slice(l+1);else{let k=s.match(/^(.*[ >])?([^ >]+)$/);a=k?.[1]?.trim()??"",c=k?.[2]??s}let u=a?n.getSubcircuit().selectOne(a):null;if(!u&&a&&!/[.#\[]/.test(a)&&(u=n.getSubcircuit().selectOne(`.${a}`)),!u){let k=a?`Could not find port for selector "${s}". Component "${a}" not found`:`Could not find port for selector "${s}"`,N=n.getSubcircuit(),E=N.getGroup();throw new lP({error_type:"source_trace_not_connected_error",message:k,subcircuit_id:N.subcircuit_id??void 0,source_group_id:E?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[s]})}let p=u.children.filter(k=>k.componentName==="Port"),d=c.includes(".")?c.split(".").pop()??"":c,_=p.flatMap(k=>k.getNameAndAliases()),g=_.some(k=>!/^(pin\d+|\d+)$/.test(k)),x=Array.from(new Set(_)).join(", "),v;p.length===0?v="It has no ports":g?v=`It has [${x}]`:v=`It has ${p.length} pins and no pinLabels (consider adding pinLabels)`;let S=`Could not find port for selector "${s}". Component "${u.props.name??a}" found, but does not have pin "${d}". ${v}`,P=n.getSubcircuit(),T=P.getGroup();throw new lP({error_type:"source_trace_not_connected_error",message:S,subcircuit_id:P.subcircuit_id??void 0,source_group_id:T?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[s]})}return r.some(s=>!s.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:r,ports:r.map(({port:s})=>s)}}var zs=class extends Me{constructor(e){super(e);f(this,"source_trace_id",null);f(this,"pcb_trace_id",null);f(this,"schematic_trace_id",null);f(this,"_portsRoutedOnPcb");f(this,"subcircuit_connectivity_map_key",null);f(this,"_traceConnectionHash",null);f(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}_getExplicitTraceThickness(){return this._parsedProps.thickness??this._parsedProps.width}get config(){return{zodProps:hH,componentName:"Trace"}}_getTracePortOrNetSelectorListFromProps(){return"from"in this.props&&"to"in this.props?[typeof this.props.from=="string"?this.props.from:this.props.from.getPortSelector(),typeof this.props.to=="string"?this.props.to:this.props.to.getPortSelector()]:"path"in this.props?this.props.path.map(e=>typeof e=="string"?e:e.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>!e.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>e.includes("net."))}_findConnectedPorts(){return p7t(this)}_resolveNet(e){let t=this.getSubcircuit().selectOne(e,{type:"net"});if(t)return t;let i=e.match(/^net\.(.+)$/),r=i?i[1]:null;if(!r)return null;let s=this.root?._getBoard();return s?s.getDescendants().find(a=>a.componentName==="Net"&&a._parsedProps.name===r)||null:(this.renderError(`Could not find a <board> ancestor for ${this}, so net "${e}" cannot be resolved`),null)}_findConnectedNets(){let e=this.getTracePathNetSelectors().map(i=>({selector:i,net:this._resolveNet(i)})),t=e.filter(i=>!i.net);return t.length>0&&this.renderError(`Could not find net for selector "${t[0].selector}" inside ${this}`),{netsWithSelectors:e,nets:e.map(i=>i.net)}}_getAllTracesConnectedToSameNet(){let e=this.getSubcircuit().selectAll("trace"),t=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return e.filter(r=>{if(r===this)return!1;let s=r._findConnectedNets().nets,o=r._findConnectedPorts().ports??[];return s.some(a=>t.includes(a))||o.some(a=>i.includes(a))})}_isExplicitlyConnectedToPort(e){let{allPortsFound:t,portsWithSelectors:i}=this._findConnectedPorts();return t?i.map(s=>s.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){hP(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();return!e||!t?null:[...t].sort((s,o)=>(s.pcb_port_id||"").localeCompare(o.pcb_port_id||"")).map(s=>s.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:e}=this.root,{_parsedProps:t,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}let r,s;try{let p=this._findConnectedPorts();r=p.allPortsFound,s=p.portsWithSelectors??[]}catch(p){if(p instanceof lP){e.source_trace_not_connected_error.insert({...p.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw p}if(!r)return;this._traceConnectionHash=this._computeTraceConnectionHash();let a=e.source_trace.list().find(p=>p.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&p.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(a){this.source_trace_id=a.source_trace_id;return}let c=this._findConnectedNets().nets,l=ULt({ports:s,nets:c}),u=e.source_trace.insert({connected_source_port_ids:s.map(p=>p.port.source_port_id),connected_source_net_ids:c.map(p=>p.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:XLt(s.map(p=>p.port),{db:e})??t.maxLength,display_name:l,min_trace_thickness:this._getExplicitTraceThickness()});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(e,t){let{db:i}=this.root;VLt(e,{db:i})&&i.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:t.map(s=>s.pcb_port_id)})}doInitialPcbManualTraceRender(){l7t(this)}doInitialPcbTraceRender(){c7t(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){u7t(this)}_isSymbolToChipConnection(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;let[i,r]=t;if(!i?.parent||!r?.parent)return!1;let s=i.parent.config.shouldRenderAsSchematicBox,o=r.parent.config.shouldRenderAsSchematicBox;return s&&!o||!s&&o}_isSymbolToSymbolConnection(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;let[i,r]=t;if(!i?.parent||!r?.parent)return!1;let s=!i.parent.config.shouldRenderAsSchematicBox,o=!r.parent.config.shouldRenderAsSchematicBox;return s&&o}_isChipToChipConnection(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;let[i,r]=t;if(!i?.parent||!r?.parent)return!1;let s=i.parent.config.shouldRenderAsSchematicBox,o=r.parent.config.shouldRenderAsSchematicBox;return s&&o}doInitialSchematicTraceRender(){i7t(this)}},h7t=n=>{let{db:e}=n.root;if(n.pcb_component_id){let t=e.pcb_component.get(n.pcb_component_id);return t?{width:t.width,height:t.height}:null}if(n.pcb_group_id){let t=e.pcb_group.get(n.pcb_group_id);if(!t)return null;if(t.outline&&t.outline.length>0){let i=co(t.outline);return i?{width:i.maxX-i.minX,height:i.maxY-i.minY}:null}return{width:t.width??0,height:t.height??0}}return null},d7t=(n,e)=>{let{db:t}=n.root,i=t.toArray();if(n.pcb_component_id){Lw(i,n.pcb_component_id,e);return}if(n.source_group_id){Fw(i,n.source_group_id,e);return}throw new Error(`Cannot reposition component ${n.getString()}: no pcb_component_id or source_group_id`)},f7t=n=>{let{db:e}=n.root;if(!n.source_component_id)return;let t=n.selectAll("port"),i=e.source_trace.list(),r=new Set;for(let o of i)for(let a of o.connected_source_port_ids)r.add(a);let s=n._getInternallyConnectedPins();for(let o of s)if(o.some(a=>a.source_port_id&&r.has(a.source_port_id)))for(let a of o)a.source_port_id&&r.add(a.source_port_id);for(let o of t)o.source_port_id&&m7t(n,o)&&(r.has(o.source_port_id)||e.source_pin_missing_trace_warning.insert({message:`Port ${o.getNameAndAliases()[0]} on ${n.props.name} is missing a trace`,source_component_id:n.source_component_id,source_port_id:o.source_port_id,subcircuit_id:n.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},m7t=(n,e)=>{if(n.config.componentName==="Chip"){let t=n.props.pinAttributes;if(!t)return!1;for(let i of e.getNameAndAliases()){let r=t[i];if(r?.requiresPower||r?.requiresGround||r?.requiresVoltage!==void 0)return!0}return!1}return!0};function _7t(n){let e=n.font_size,t=n.text.length*e*.6,i=e,r=n.anchor_alignment||"center",s=n.anchor_position.x,o=n.anchor_position.y;switch(r){case"top_left":s=n.anchor_position.x+t/2,o=n.anchor_position.y+i/2;break;case"top_center":s=n.anchor_position.x,o=n.anchor_position.y+i/2;break;case"top_right":s=n.anchor_position.x-t/2,o=n.anchor_position.y+i/2;break;case"center_left":s=n.anchor_position.x+t/2,o=n.anchor_position.y;break;case"center":s=n.anchor_position.x,o=n.anchor_position.y;break;case"center_right":s=n.anchor_position.x-t/2,o=n.anchor_position.y;break;case"bottom_left":s=n.anchor_position.x+t/2,o=n.anchor_position.y-i/2;break;case"bottom_center":s=n.anchor_position.x,o=n.anchor_position.y-i/2;break;case"bottom_right":s=n.anchor_position.x-t/2,o=n.anchor_position.y-i/2;break;default:s=n.anchor_position.x,o=n.anchor_position.y;break}return{x:s-t/2,y:o-i/2,width:t,height:i}}function y7t(n){if(!n._adjustSilkscreenTextAutomatically||n.root?.pcbDisabled||!n.pcb_component_id)return;let{db:e}=n.root,i=n._getPcbCircuitJsonBounds().center,r=e.pcb_silkscreen_text.list({pcb_component_id:n.pcb_component_id}).filter(c=>c.text===n.name);if(r.length===0)return;let a=n.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(c=>c!==n&&c.pcb_component_id).map(c=>{let l=c._getPcbCircuitJsonBounds(),u={center:l.center,width:l.width,height:l.height};return so(u)});for(let c of r){let l=c.anchor_position,u=_7t(c),p={center:{x:u.x+u.width/2,y:u.y+u.height/2},width:u.width,height:u.height},d=so(p);if(!a.some(T=>Jc(d,T)))continue;let g=2*i.x-l.x,x=2*i.y-l.y,v={center:{x:g,y:x},width:u.width,height:u.height},S=so(v);a.some(T=>Jc(S,T))||e.pcb_silkscreen_text.update(c.pcb_silkscreen_text_id,{anchor_position:{x:g,y:x}})}}function g7t(n){if(!n)return{validPinLabels:n,invalidPinLabelsMessages:[]};let e={},t=[];for(let[i,r]of Object.entries(n)){let s=Array.isArray(r)?r.slice():[r],o=[];for(let a of s)x7t(i,a)?o.push(a):t.push(`Invalid pin label: ${i} = '${a}' - excluding from component. Please use a valid pin label.`);o.length>0&&(e[i]=Array.isArray(r)?o:o[0])}return{validPinLabels:Object.keys(e).length>0?e:void 0,invalidPinLabelsMessages:t}}function x7t(n,e){try{let t={name:"test",footprint:"test",pinLabels:{[n]:e}};return o_.safeParse(t).success}catch{return!1}}var Z_=n=>n.startsWith("http://")||n.startsWith("https://"),w9=n=>{if(Z_(n))return null;let e=n.indexOf(":");if(e<=0)return null;let t=n.slice(0,e),i=n.slice(e+1);return!t||!i?null:{footprintLib:t,footprintName:i}},S9=n=>n.startsWith("/"),b7t=(0,Lnt.default)("tscircuit:core:resolveStaticFileImport");async function Fnt(n,e){if(!n)return n;let t=e?.resolveProjectStaticFileImportUrl;if(t&&n.startsWith("/"))try{let i=await t(n);if(i)return i}catch(i){b7t("failed to resolve static file via platform resolver",i)}return Nnt(n,e?.projectBaseUrl)}function v7t(n,e){let{footprint:t}=n.props;if(t??(t=n._getImpliedFootprintString?.()),!t)return;let{pcbRotation:i,pinLabels:r,pcbPinLabels:s}=n.props,o=Int(String(t)),a=o?n.root?.platform?.footprintFileParserMap?.[o]:null;if(typeof t=="string"&&(Z_(t)||S9(t))&&a){if(n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0,e("load-footprint-from-platform-file-parser",async()=>{let c=Z_(t)?t:await Fnt(t,n.root?.platform);try{let l=await a.loadFromUrl(c),u=q_({componentName:n.name,componentRotation:i,footprinterString:c,pinLabels:r,pcbPinLabels:s},l.footprintCircuitJson);n.addAll(u),n._markDirty("InitializePortsFromChildren")}catch(l){let u=n.root?.db;if(u&&n.source_component_id&&n.pcb_component_id){let p=n.getSubcircuit(),d=`${n.getString()} failed to load footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=$m.parse({type:"external_footprint_load_error",message:d,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:p.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof t=="string"&&Z_(t)){if(n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let c=t;e("load-footprint-url",async()=>{try{let l=await fetch(c);if(!l.ok)throw new Error(`Failed to fetch footprint: ${l.status}`);let u=await l.json(),p=q_({componentName:n.name,componentRotation:i,footprinterString:c,pinLabels:r,pcbPinLabels:s},u);n.addAll(p),n._markDirty("InitializePortsFromChildren")}catch(l){let u=n.root?.db;if(u&&n.source_component_id&&n.pcb_component_id){let p=n.getSubcircuit(),d=`${n.getString()} failed to load external footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=$m.parse({type:"external_footprint_load_error",message:d,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:p.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof t=="string"){let c=w9(t);if(!c||n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let u=n.root?.platform?.footprintLibraryMap?.[c.footprintLib],p;if(typeof u=="function"&&(p=u),!p)return;let d=n.getInheritedMergedProperty("pcbStyle");e("load-lib-footprint",async()=>{try{let _=await p(c.footprintName,{resolvedPcbStyle:d}),g=null;if(Array.isArray(_)?g=_:Array.isArray(_.footprintCircuitJson)&&(g=_.footprintCircuitJson),!g)return;let x=q_({componentName:n.name,componentRotation:i,footprinterString:t,pinLabels:r,pcbPinLabels:s},g);n.addAll(x),!Array.isArray(_)&&_.cadModel&&(n._asyncFootprintCadModel=_.cadModel);for(let v of n.children)v.componentName==="Port"&&v._markDirty?.("PcbPortRender");n._markDirty("InitializePortsFromChildren")}catch(_){let g=n.root?.db;if(g&&n.source_component_id&&n.pcb_component_id){let x=n.getSubcircuit(),v=`${n.getString()} failed to load external footprint "${t}": `+(_ instanceof Error?_.message:String(_)),S=$m.parse({type:"external_footprint_load_error",message:v,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:x.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,footprinter_string:t});g.external_footprint_load_error.insert(S)}throw _}});return}if(!(0,v9.isValidElement)(t)&&t.componentName==="Footprint"&&n.add(t),Array.isArray(t)&&!(0,v9.isValidElement)(t)&&t.length>0){try{let c=q_({componentName:n.name,componentRotation:i,footprinterString:"",pinLabels:r,pcbPinLabels:s},t);n.addAll(c)}catch(c){let l=n.root?.db;if(l&&n.source_component_id&&n.pcb_component_id){let u=n.getSubcircuit(),p=`${n.getString()} failed to load json footprint: `+(c instanceof Error?c.message:String(c)),d=rb.parse({type:"circuit_json_footprint_load_error",message:p,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:u.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0});l.circuit_json_footprint_load_error.insert(d)}throw c}return}}function w7t(n){if(n.root?.pcbDisabled||!n.pcb_component_id)return;let{pcbX:e,pcbY:t}=n._parsedProps,i=n.props?.pcbPositionAnchor;if(!i||e===void 0&&t===void 0)return;let r=mP(n.children);if(r.width===0||r.height===0)return;let o={...{x:(r.minX+r.maxX)/2,y:(r.minY+r.maxY)/2}},a=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(i)){let u={left:r.minX,right:r.maxX,top:r.minY,bottom:r.maxY};switch(i){case"center":a=o;break;case"top_left":a={x:u.left,y:u.top};break;case"top_center":a={x:o.x,y:u.top};break;case"top_right":a={x:u.right,y:u.top};break;case"center_left":a={x:u.left,y:o.y};break;case"center_right":a={x:u.right,y:o.y};break;case"bottom_left":a={x:u.left,y:u.bottom};break;case"bottom_center":a={x:o.x,y:u.bottom};break;case"bottom_right":a={x:u.right,y:u.bottom};break}}else try{let u=n.portMap[i];u&&(a=u._getGlobalPcbPositionBeforeLayout())}catch{}if(!a)return;let l={...o};e!==void 0&&(l.x+=e-a.x),t!==void 0&&(l.y+=t-a.y),(Math.abs(l.x-o.x)>1e-6||Math.abs(l.y-o.y)>1e-6)&&n._repositionOnPcb(l)}var S7t=(0,gnt.default)("tscircuit:core"),P7t=h.object({x:tn,y:tn,z:tn}),Bn=class extends Me{constructor(e){let t={...e},i=[];if(t.pinLabels&&!Array.isArray(t.pinLabels)){let{validPinLabels:r,invalidPinLabelsMessages:s}=g7t(t.pinLabels);t.pinLabels=r,i=s}super(t);f(this,"reactSubtrees",[]);f(this,"_impliedFootprint");f(this,"isPrimitiveContainer",!0);f(this,"_isNormalComponent",!0);f(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});f(this,"_asyncSupplierPartNumbers");f(this,"_asyncFootprintCadModel");f(this,"_isCadModelChild");f(this,"pcb_missing_footprint_error_id");f(this,"_hasStartedFootprintUrlLoad",!1);f(this,"_invalidPinLabelMessages",[]);f(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=i,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(t=>t.map(i=>typeof i=="number"?`pin${i}`:i))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let e=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(r=>r!==this&&r._isNormalComponent&&r.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let r=this._getGlobalPcbPositionBeforeLayout(),s=this._getGlobalSchematicPositionBeforeLayout();e.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:r,schematic_center:s}),this.shouldBeRemoved=!0;let o=[...this.children];for(let a of o)this.remove(a)}}initPorts(e={}){if(this.root?.schematicDisabled)return;let{config:t}=this,i=[],r=this._getSchematicPortArrangement();if(r&&!this._parsedProps.pinLabels){for(let l in r){let u=r[l].pins;if(Array.isArray(u))for(let p of u){let d=H1(p,this._parsedProps.pinLabels);i.push(new Wi({pinNumber:d,aliases:e.additionalAliases?.[`pin${d}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let a=["left","right","top","bottom"],c=1;for(let l of a){let u=r[`${l}Size`];for(let p=0;p<u;p++)i.push(new Wi({pinNumber:c++,aliases:e.additionalAliases?.[`pin${c}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let s=this._parsedProps.pinLabels;if(s)for(let[a,c]of Object.entries(s)){a=a.replace("pin","");let l=i.find(d=>d._parsedProps.pinNumber===Number(a)),u=Array.isArray(c)?c[0]:c,p=Array.isArray(c)?c.slice(1):[];l?(l.externallyAddedAliases.push(u,...p),l.props.name=u):(l=new Wi({pinNumber:parseInt(a),name:u,aliases:[...p,...e.additionalAliases?.[`pin${parseInt(a)}`]??[]]},{originDescription:`pinLabels:pin${a}`}),i.push(l))}if(t.schematicSymbolName&&!e.ignoreSymbolPorts){let a=yi[this._getSchematicSymbolNameOrThrow()];if(!a)return;for(let c of a.ports){let l=Tnt(c.labels);if(!l)continue;let u=i.find(p=>p._parsedProps.pinNumber===Number(l));if(u)u.schematicSymbolPortDef=c;else{let p=Y1(c.labels.concat(e.additionalAliases?.[`pin${l}`]??[]));p&&(p.originDescription=`schematicSymbol:labels[0]:${c.labels[0]}`,p.schematicSymbolPortDef=c,i.push(p))}}this.addAll(i)}if(!this._getSchematicPortArrangement()){let a=this.getPortsFromFootprint(e);for(let c of a)i.some(l=>l.isMatchingAnyOf(c.getNameAndAliases()))||i.push(c)}let o=e.pinCount??this._getPinCount()??0;for(let a=1;a<=o;a++){if(i.find(l=>l._parsedProps.pinNumber===a))continue;if(!r){i.push(new Wi({pinNumber:a,aliases:e.additionalAliases?.[`pin${a}`]??[]}));continue}let c=[...r.leftSide?.pins??[],...r.rightSide?.pins??[],...r.topSide?.pins??[],...r.bottomSide?.pins??[]].map(l=>H1(l,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(l=>l in r)&&(c=Array.from({length:this._getPinCount()},(l,u)=>u+1)),c.includes(a)&&i.push(new Wi({pinNumber:a,aliases:e.additionalAliases?.[`pin${a}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${a}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:e,pinLabels:t,pcbPinLabels:i}=this.props,{footprint:r}=this.props;if(r??(r=this._getImpliedFootprintString?.()),!!r&&typeof r=="string"){if(Z_(r)||S9(r)||w9(r))return;let s=F3.string(r).soup(),o=q_({componentName:this.name??this.componentName,componentRotation:e,footprinterString:r,pinLabels:t,pcbPinLabels:i},s);this.addAll(o)}}get portMap(){return new Proxy({},{get:(e,t)=>{let i=this.children.find(r=>r.componentName==="Port"&&r.isMatchingNameOrAlias(t));if(!i)throw new Error(`There was an issue finding the port "${t.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return i}})}getInstanceForReactElement(e){for(let t of this.reactSubtrees)if(t.element===e)return t.component;return null}doInitialSourceRender(){let e=this.config.sourceFtype;if(!e)return;let{db:t}=this.root,{_parsedProps:i}=this,r=t.source_component.insert({ftype:e,name:this.name,manufacturer_part_number:i.manufacturerPartNumber??i.mfn,supplier_part_numbers:i.supplierPartNumbers});this.source_component_id=r.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let s of this._invalidPinLabelMessages){let o="pinLabels",a=s.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);a&&(o=`pinLabels['${a[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:o,message:s,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:t}=this.config,{_parsedProps:i}=this;i.symbol&&(0,Wa.isValidElement)(i.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(i.symbol):t?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let r=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&r){if(!this.schematic_component_id)return;let s=eb.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});e.schematic_manual_edit_conflict_warning.insert(s)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let e=[];for(let t of this.internallyConnectedPinNames){let i=[];for(let r of t)i.push(this.portMap[r]);e.push(i)}return e}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getSchematicSymbolNameOrThrow(),r=yi[i],s=this._getGlobalSchematicPositionBeforeLayout();if(r){let o=e.schematic_component.insert({center:s,size:r.size,source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name:i,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=o.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(e){if(this.root?.schematicDisabled)return;let{db:t}=this.root,i=this._getGlobalSchematicPositionBeforeLayout(),r=t.schematic_component.insert({center:i,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1});this.schematic_component_id=r.schematic_component_id}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getSchematicBoxDimensions(),r={};if(Array.isArray(t.pinLabels))t.pinLabels.forEach((_,g)=>{r[String(g+1)]=_});else for(let[_,g]of Object.entries(t.pinLabels??{}))r[_]=Array.isArray(g)?g[0]:g;let s=this._getGlobalSchematicPositionBeforeLayout(),o=this._getSchematicPortArrangement(),a=e.schematic_component.insert({center:s,rotation:t.schRotation??0,size:i.getSize(),port_arrangement:wLt(o),pin_spacing:t.schPinSpacing??.2,pin_styles:vLt(t.schPinStyle,t.pinLabels),port_labels:r,source_component_id:this.source_component_id}),c=o?.topSide!==void 0||o?.bottomSide!==void 0,l=i?.getSize().width,u=i?.getSize().height,p=e.schematic_text.insert({text:t.manufacturerPartNumber??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?s.x+(l??0)/2+.1:s.x-(l??0)/2,y:c?s.y+(u??0)/2+.35:s.y-(u??0)/2-.13},color:"#006464",font_size:.18}),d=e.schematic_text.insert({text:t.name??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?s.x+(l??0)/2+.1:s.x-(l??0)/2,y:c?s.y+(u??0)/2+.55:s.y+(u??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=a.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=t.layer??"top";if(r!=="top"&&r!=="bottom"){let p=zm.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${r}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:r,subcircuit_id:i.subcircuit_id??void 0});e.pcb_component_invalid_layer_error.insert(p)}let s=this._computePcbGlobalTransformBeforeLayout(),a=io(s).rotation.angle*180/Math.PI,c=e.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:r==="top"||r==="bottom"?r:"top",rotation:t.pcbRotation??a,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});if(!(t.footprint??this._getImpliedFootprintString())&&!this.isGroup){let p=e.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=p.pcb_missing_footprint_error_id}this.pcb_component_id=c.pcb_component_id;let u=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&u){let p=sb.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0});e.pcb_manual_edit_conflict_warning.insert(p)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:e}=this.root,{_parsedProps:t}=this,i=mP(this.children);if(i.width===0||i.height===0)return;let r={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};e.pcb_component.update(this.pcb_component_id,{center:r,width:i.width,height:i.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db:e}=this.root;if(!e.schematic_component.get(this.schematic_component_id))return;let i=[],r=u=>{for(let p of u){if(p.isSchematicPrimitive&&p.componentName==="SchematicLine"){let d=e.schematic_line.get(p.schematic_line_id);d&&i.push(d)}if(p.isSchematicPrimitive&&p.componentName==="SchematicRect"){let d=e.schematic_rect.get(p.schematic_rect_id);d&&i.push(d)}if(p.isSchematicPrimitive&&p.componentName==="SchematicCircle"){let d=e.schematic_circle.get(p.schematic_circle_id);d&&i.push(d)}if(p.isSchematicPrimitive&&p.componentName==="SchematicArc"){let d=e.schematic_arc.get(p.schematic_arc_id);d&&i.push(d)}if(p.isSchematicPrimitive&&p.componentName==="SchematicText"){let d=e.schematic_text.get(p.schematic_text_id);d&&i.push(d)}p.children&&p.children.length>0&&r(p.children)}};if(r(this.children),i.length===0)return;let s=knt(i),o=Math.abs(s.maxX-s.minX),a=Math.abs(s.maxY-s.minY);if(o===0&&a===0)return;let c=(s.minX+s.maxX)/2,l=(s.minY+s.maxY)/2;e.schematic_component.update(this.schematic_component_id,{center:{x:c,y:l},size:{width:o,height:a}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){w7t(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(e){let t=Snt(e);return{element:e,component:t}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let e=this.props.footprint;(0,Wa.isValidElement)(e)&&(this.children.some(s=>s.componentName==="Footprint")||this.add(e));let t=this.props.symbol;(0,Wa.isValidElement)(t)&&(this.children.some(s=>s.componentName==="Symbol")||this.add(t));let i=this.props.cadModel;if((0,Wa.isValidElement)(i)){this._isCadModelChild=!0;let r=this.children.some(o=>o.componentName==="CadAssembly"),s=this.children.some(o=>o.componentName==="CadModel");!r&&!s&&this.add(i)}}doInitialPcbFootprintStringRender(){v7t(this,(e,t)=>this._queueAsyncEffect(e,t))}_hasExistingPortExactly(e){return this.children.filter(i=>i.componentName==="Port").some(i=>{let r=e.getNameAndAliases(),s=i.getNameAndAliases();return r.length===s.length&&r.every(o=>s.includes(o))})}add(e){let t;if((0,Wa.isValidElement)(e)){let i=this._renderReactSubtree(e);this.reactSubtrees.push(i),t=i.component}else t=e;if(t.componentName==="Port"){if(this._hasExistingPortExactly(t))return;let r=this.children.filter(s=>s.componentName==="Port").find(s=>s.isMatchingAnyOf(t.getNameAndAliases()));r&&S7t(`Similar ports added. Port 1: ${r}, Port 2: ${t}`)}super.add(t)}getPortsFromFootprint(e){let{footprint:t}=this.props;if((!t||(0,Wa.isValidElement)(t))&&(t=this.children.find(r=>r.componentName==="Footprint")),typeof t=="string"){if(Z_(t))return[];if(S9(t))return[];if(w9(t))return[];let r=F3.string(t).soup(),s=[];for(let o of r)if("port_hints"in o&&o.port_hints){let a=Y1(o.port_hints,e);if(!a)continue;a.originDescription=`footprint:string:${t}:port_hints[0]:${o.port_hints[0]}`,s.push(a)}return s}if(!(0,Wa.isValidElement)(t)&&t&&t.componentName==="Footprint"){let r=t,s=1,o=[];for(let a of r.children){if(!a.props.portHints)continue;let c=a.props.portHints;c.some(p=>p.startsWith("pin"))||(c=[...c,`pin${s}`]),s++;let u=Y1(c);u&&(u.originDescription=`footprint:${t}`,o.push(u))}return o}let i=[];if(!t){for(let r of this.children)if(r.props.portHints&&r.isPcbPrimitive){let s=Y1(r.props.portHints);s&&i.push(s)}}return i}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:e}=this;if(!e.schematicSymbolName)return[];let t=yi[e.schematicSymbolName];if(!t)return[];let i=[];for(let r of t.ports){let s=Y1(r.labels);s&&(s.schematicSymbolPortDef=r,i.push(s))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:e}=this,t=[];if(e.connections)for(let[i,r]of Object.entries(e.connections)){let s=Array.isArray(r)?r:[r];for(let o of s)t.push(String(o))}return t}_createNetsFromProps(e){hP(this,e)}_getPcbCircuitJsonBounds(){let{db:e}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let t=e.pcb_component.get(this.pcb_component_id);return{center:{x:t.center.x,y:t.center.y},bounds:{left:t.center.x-t.width/2,top:t.center.y-t.height/2,right:t.center.x+t.width/2,bottom:t.center.y+t.height/2},width:t.width,height:t.height}}_getPinCountFromSchematicPortArrangement(){let e=this._getSchematicPortArrangement();if(!e)return 0;if(!Ent(e))return(e.leftSize??e.leftPinCount??0)+(e.rightSize??e.rightPinCount??0)+(e.topSize??e.topPinCount??0)+(e.bottomSize??e.bottomPinCount??0);let{leftSide:i,rightSide:r,topSide:s,bottomSide:o}=e;return Math.max(...i?.pins??[],...r?.pins??[],...s?.pins??[],...o?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let t=this.getPortsFromFootprint();if(t.length>0)return t.length;let{pinLabels:i}=this._parsedProps;if(i){if(Array.isArray(i))return i.length;let r=Object.keys(i).map(s=>s.startsWith("pin")?parseInt(s.slice(3)):parseInt(s)).filter(s=>!Number.isNaN(s));return r.length>0?Math.max(...r):Object.keys(i).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getPinLabelsFromPorts(){let e=this.selectAll("port"),t={};for(let i of e){let r=i.props.pinNumber;if(r!==void 0){let s=i._getBestDisplayPinLabel();s&&(t[`pin${r}`]=s)}}return t}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this,t=this._getPinCount(),i=e.schPinSpacing??.2,s={...this._getPinLabelsFromPorts(),...e.pinLabels};return RLt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:i,numericSchPinStyle:FLt(e.schPinStyle,s),pinCount:t,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:s})}getFootprinterString(){return typeof this._parsedProps.footprint=="string"?this._parsedProps.footprint:null}doInitialCadModelRender(){if(this._isCadModelChild||this.props.doNotPlace)return;let{db:e}=this.root,{boardThickness:t=0}=this.root?._getBoard()??{},i=this._parsedProps.cadModel,r=i===void 0?this._asyncFootprintCadModel:i,s=this.getFootprinterString()??this._getImpliedFootprintString();if(!this.pcb_component_id||!r&&!s||r===null)return;let o=this._getPcbCircuitJsonBounds();if(typeof r=="string")throw new Error("String cadModel not yet implemented");let a=P7t.parse({x:0,y:0,z:typeof r?.rotationOffset=="number"?r.rotationOffset:0,...typeof r?.rotationOffset=="object"?r.rotationOffset??{}:{}}),c=Uh.parse({x:0,y:0,z:0,...typeof r?.positionOffset=="object"?r.positionOffset:{}}),l=r&&typeof r=="object"&&"zOffsetFromSurface"in r&&r.zOffsetFromSurface!==void 0?V.parse(r.zOffsetFromSurface):0,u=this.props.layer==="bottom"?"bottom":"top",p=this._computePcbGlobalTransformBeforeLayout(),_=io(p).rotation.angle*180/Math.PI,g=u==="bottom",x=_+(a.z??0),v=hd(x),S=e.cad_component.insert({position:{x:o.center.x+c.x,y:o.center.y+c.y,z:(u==="bottom"?-t/2:t/2)+(u==="bottom"?-l:l)+c.z},rotation:{x:a.x,y:a.y+(g?180:0),z:hd(g?-v:v)},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(r??{})?this._addCachebustToModelUrl(r.stlUrl):void 0,model_obj_url:"objUrl"in(r??{})?this._addCachebustToModelUrl(r.objUrl):void 0,model_mtl_url:"mtlUrl"in(r??{})?this._addCachebustToModelUrl(r.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(r??{})?this._addCachebustToModelUrl(r.gltfUrl):void 0,model_glb_url:"glbUrl"in(r??{})?this._addCachebustToModelUrl(r.glbUrl):void 0,model_step_url:"stepUrl"in(r??{})?this._addCachebustToModelUrl(r.stepUrl):void 0,model_wrl_url:"wrlUrl"in(r??{})?this._addCachebustToModelUrl(r.wrlUrl):void 0,model_jscad:"jscad"in(r??{})?r.jscad:void 0,model_unit_to_mm_scale_factor:typeof r?.modelUnitToMmScale=="number"?r.modelUnitToMmScale:void 0,footprinter_string:typeof s=="string"&&!r?s:void 0,show_as_translucent_model:this._parsedProps.showAsTranslucentModel});this.cad_component_id=S.cad_component_id}_addCachebustToModelUrl(e){if(!e||!e.includes("modelcdn.tscircuit.com"))return e;let t=this.root?.getClientOrigin()??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(t)}`}_getPartsEngineCacheKey(e,t){return JSON.stringify({ftype:e.ftype,name:e.name,manufacturer_part_number:e.manufacturer_part_number,footprinterString:t})}async _getSupplierPartNumbers(e,t,i){if(this.props.doNotPlace)return{};let r=this.root?.platform?.localCacheEngine,s=this._getPartsEngineCacheKey(t,i);if(r){let c=await r.getItem(s);if(c)try{return JSON.parse(c)}catch{}}let o=await Promise.resolve(e.findPart({sourceComponent:t,footprinterString:i}));if(typeof o=="string"){if(o.includes("<!DOCTYPE")||o.includes("<html"))throw new Error(`Failed to fetch supplier part numbers: Received HTML response instead of JSON. Response starts with: ${o.substring(0,100)}`);if(o==="Not found")return{};throw new Error(`Invalid supplier part numbers format: Expected object but got string: "${o}"`)}if(!o||Array.isArray(o)||typeof o!="object"){let c=o===null?"null":Array.isArray(o)?"array":typeof o;throw new Error(`Invalid supplier part numbers format: Expected object but got ${c}`)}let a=o;if(r)try{await r.setItem(s,JSON.stringify(a))}catch{}return a}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let e=this.getInheritedProperty("partsEngine");if(!e)return;let{db:t}=this.root,i=t.source_component.get(this.source_component_id);if(!i||i.supplier_part_numbers)return;let r;this.props.footprint&&typeof this.props.footprint=="string"&&(r=this.props.footprint);let s=this._getSupplierPartNumbers(e,i,r);if(!(s instanceof Promise)){t.source_component.update(this.source_component_id,{supplier_part_numbers:s});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{await s.then(o=>{this._asyncSupplierPartNumbers=o,this._markDirty("PartsEngineRender")}).catch(o=>{this._asyncSupplierPartNumbers={};let a=Qx.parse({type:"unknown_error_finding_part",message:`Failed to fetch supplier part numbers for ${this.getString()}: ${o.message}`,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});t.unknown_error_finding_part.insert(a),this._markDirty("PartsEngineRender")})})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:e}=this.root,t=e.source_component.get(this.source_component_id);if(t&&!t.supplier_part_numbers&&this._asyncSupplierPartNumbers){e.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:e}=this;e.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:e}=this;if(e.connections)for(let[t,i]of Object.entries(e.connections)){let r=Array.isArray(i)?i:[i];for(let s of r)this.add(new zs({from:`.${this.name} > .${t}`,to:String(s)}))}}doInitialSourceDesignRuleChecks(){f7t(this)}_getMinimumFlexContainerSize(){return h7t(this)}_repositionOnPcb(e){return d7t(this,e)}doInitialSilkscreenOverlapAdjustment(){return y7t(this)}isRelativelyPositioned(){return this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0}},k7t=({boardAnchorPosition:n,boardAnchorAlignment:e,width:t,height:i})=>{let{x:r,y:s}=n,o=r,a=s;switch(e){case"top_left":o=r+t/2,a=s-i/2;break;case"top_right":o=r-t/2,a=s-i/2;break;case"bottom_left":o=r+t/2,a=s+i/2;break;case"bottom_right":o=r-t/2,a=s+i/2;break;case"top":o=r,a=s-i/2;break;case"bottom":o=r,a=s+i/2;break;case"left":o=r+t/2,a=s;break;case"right":o=r-t/2,a=s;break;case"center":default:break}return{x:o,y:a}},T7t=class{constructor(n,e={}){f(this,"input");f(this,"isRouting",!1);f(this,"solver");f(this,"eventHandlers",{complete:[],error:[],progress:[]});f(this,"cycleCount",0);f(this,"stepDelay");f(this,"timeoutId");this.input=n;let{capacityDepth:t,targetMinCapacity:i,stepDelay:r=0,useAssignableViaSolver:s=!1}=e,{AutoroutingPipelineSolver:o,AssignableViaAutoroutingPipelineSolver:a}=uN,c=s?a:o;this.solver=new c(n,{capacityDepth:t,targetMinCapacity:i,cacheProvider:null}),this.stepDelay=r}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new X1(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let n=Date.now(),e=this.solver.iterations;for(;Date.now()-n<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let t=(this.solver.iterations-e)/(Date.now()-n)*1e3;this.cycleCount++;let i=this.solver?.preview()||void 0,r=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:t,progress:r,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(n){this.emitEvent({type:"error",error:n instanceof Error?new X1(n.message):new X1(String(n))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(n,e){n==="complete"?this.eventHandlers.complete.push(e):n==="error"?this.eventHandlers.error.push(e):n==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(n){if(n.type==="complete")for(let e of this.eventHandlers.complete)e(n);else if(n.type==="error")for(let e of this.eventHandlers.error)e(n);else if(n.type==="progress")for(let e of this.eventHandlers.progress)e(n)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new X1(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},R9=class extends Me{constructor(){super(...arguments);f(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:nq}}doInitialPortMatching(){let{db:e}=this.root,{_parsedProps:t,parent:i}=this;if(!i)return;if(i.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!i)throw new Error("TraceHint has no parent");if(!t.for){this.renderError(`TraceHint has no for property (${this})`);return}let r=i.selectOne(t.for,{type:"port"});r||this.renderError(`${this} could not find port for selector "${t.for}"`),this.matchedPort=r,r.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:e}=this,t=e.offset?[e.offset]:e.offsets;if(!t)return[];let i=this._computePcbGlobalTransformBeforeLayout();return t.map(r=>({...De(i,r),via:r.via,to_layer:r.to_layer,trace_width:r.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this;e.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},$nt=({circuitJson:n,editEvents:e,manualEditsFile:t})=>{let i={...t,pcb_placements:[...t.pcb_placements??[]]};for(let r of e)if(r.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:s,new_center:o}=r,a=Ce(n).pcb_component.get(s);if(!a)continue;let c=Ce(n).source_component.get(a.source_component_id);if(!c)continue;let l=i.pcb_placements?.findIndex(p=>p.selector===c.name),u={selector:c.name,center:o,relative_to:"group_center"};l>=0?i.pcb_placements[l]=u:i.pcb_placements.push(u)}return i},znt=({circuitJson:n,editEvents:e,manualEditsFile:t})=>{let i={...t,schematic_placements:[...t.schematic_placements??[]]};for(let r of e)if(r.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:s,new_center:o}=r,a=Ce(n).schematic_component.get(s);if(!a||!a.source_component_id)continue;let c=Ce(n).source_component.get(a.source_component_id);if(!c)continue;let l=i.schematic_placements?.findIndex(p=>p.selector===c.name),u={selector:c.name,center:o,relative_to:"group_center"};l>=0?i.schematic_placements[l]=u:i.schematic_placements.push(u)}return i},E7t=({circuitJson:n,editEvents:e,manualEditsFile:t})=>{let i=e.filter(o=>o.edit_event_type==="edit_schematic_component_location"),r=e.filter(o=>o.edit_event_type==="edit_pcb_component_location"),s=t;return i.length>0&&(s=znt({circuitJson:n,editEvents:i,manualEditsFile:s})),r.length>0&&(s=$nt({circuitJson:n,editEvents:r,manualEditsFile:s})),s},M7t=(n,e)=>{if(Ce(n).pcb_trace_hint.get(e.pcb_trace_hint_id))n=n.map(i=>i.pcb_trace_hint_id===e.pcb_trace_hint_id?{...i,route:e.route}:i);else{let i=Ce(n).pcb_port.get(e.pcb_port_id);n=n.filter(r=>!(r.type==="pcb_trace_hint"&&r.pcb_port_id===e.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:e.pcb_trace_hint_id,route:e.route,pcb_port_id:e.pcb_port_id,pcb_component_id:i?.pcb_component_id}])}return n},C7t=({circuitJson:n,editEvents:e})=>{n=JSON.parse(JSON.stringify(n));for(let t of e)if(t.edit_event_type==="edit_pcb_component_location"){let i=n.find(s=>s.type==="pcb_component"&&s.pcb_component_id===t.pcb_component_id);if((!i||i.center.x!==t.new_center.x||i.center.y!==t.new_center.y)&&t.original_center){let s=kn(t.new_center.x-t.original_center.x,t.new_center.y-t.original_center.y);n=n.map(o=>o.pcb_component_id!==t.pcb_component_id?o:L4(o,s))}}else t.edit_event_type==="edit_schematic_component_location"?n=n.map(i=>i.type==="schematic_component"&&i.schematic_component_id===t.schematic_component_id?{...i,center:t.new_center}:i):t.edit_event_type==="edit_pcb_trace_hint"&&(n=M7t(n,t));return n},Dnt=(n,e)=>{let t=n.source_group.list(),i=[],r=s=>{let o=t.filter(a=>a.parent_subcircuit_id===s);for(let a of o)a.subcircuit_id&&(i.push(a.subcircuit_id),r(a.subcircuit_id))};return r(e),i},P9=({db:n,circuitJson:e,subcircuit_id:t,minTraceWidth:i=.1})=>{if(!n&&e&&(n=Ce(e)),!n)throw new Error("db or circuitJson is required");let r=n.pcb_trace_hint.list(),s=t?new Set([t]):null;if(t){let C=Dnt(n,t);for(let M of C)s.add(M)}let o=(e??n.toArray()).filter(C=>!t||"subcircuit_id"in C&&s.has(C.subcircuit_id)),a=n.pcb_board.list()[0];n=Ce(o);let c=nr(o),l=Ont([...n.pcb_component.list(),...n.pcb_smtpad.list(),...n.pcb_plated_hole.list(),...n.pcb_hole.list(),...n.pcb_via.list(),...n.pcb_cutout.list()].filter(C=>!t||s?.has(C.subcircuit_id)),c);for(let C of l){let M=C.connectedTo.flatMap(A=>c.getIdsConnectedToNet(A));C.connectedTo.push(...M)}let u=l.flatMap(C=>[{x:C.center.x-C.width/2,y:C.center.y-C.height/2},{x:C.center.x+C.width/2,y:C.center.y+C.height/2}]).concat(a?.outline??[]),p;if(a&&!a.outline?p={minX:a.center.x-a.width/2,maxX:a.center.x+a.width/2,minY:a.center.y-a.height/2,maxY:a.center.y+a.height/2}:p={minX:Math.min(...u.map(C=>C.x))-1,maxX:Math.max(...u.map(C=>C.x))+1,minY:Math.min(...u.map(C=>C.y))-1,maxY:Math.max(...u.map(C=>C.y))+1},t){let C=n.pcb_group.getWhere({subcircuit_id:t});if(C?.width&&C.height){let M={minX:C.center.x-C.width/2,maxX:C.center.x+C.width/2,minY:C.center.y-C.height/2,maxY:C.center.y+C.height/2};p={minX:Math.min(p.minX,M.minX),maxX:Math.max(p.maxX,M.maxX),minY:Math.min(p.minY,M.minY),maxY:Math.max(p.maxY,M.maxY)}}}let d=new Set(n.pcb_trace.list().map(C=>C.source_trace_id).filter(C=>!!C)),_=n.source_trace.list().filter(C=>!d.has(C.source_trace_id)).map(C=>{let M=C.connected_source_port_ids.map(W=>{let et=n.source_port.get(W),nt=n.pcb_port.getWhere({source_port_id:W});return{...et,...nt}});if(M.length<2)return null;let[A,R]=M;if(A.x===void 0||A.y===void 0)return console.error(`(source_port_id: ${A.source_port_id}) for trace ${C.source_trace_id} does not have x/y coordinates. Skipping this trace.`),null;if(R.x===void 0||R.y===void 0)return console.error(`(source_port_id: ${R.source_port_id}) for trace ${C.source_trace_id} does not have x/y coordinates. Skipping this trace.`),null;let B=A.layers?.[0]??"top",j=R.layers?.[0]??"top",U=r.filter(W=>W.pcb_port_id===A.pcb_port_id||W.pcb_port_id===R.pcb_port_id),X=[];for(let W of U){let nt=n.pcb_port.get(W.pcb_port_id)?.layers?.[0]??"top";for(let mt of W.route)X.push({x:mt.x,y:mt.y,layer:nt})}return{name:C.source_trace_id??c.getNetConnectedToId(C.source_trace_id)??"",source_trace_id:C.source_trace_id,width:C.min_trace_thickness,pointsToConnect:[{x:A.x,y:A.y,layer:B,pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},...X,{x:R.x,y:R.y,layer:j,pointId:R.pcb_port_id,pcb_port_id:R.pcb_port_id}]}}).filter(C=>C!==null),g=new Map(_.map(C=>[C.source_trace_id,C])),x=n.source_net.list().filter(C=>!t||s?.has(C.subcircuit_id)),v=[];for(let C of x){let M=n.source_trace.list().filter(A=>A.connected_source_net_ids?.includes(C.source_net_id));v.push({name:C.source_net_id??c.getNetConnectedToId(C.source_net_id),pointsToConnect:M.flatMap(A=>n.pcb_port.list().filter(B=>A.connected_source_port_ids.includes(B.source_port_id)).map(B=>({x:B.x,y:B.y,layer:B.layers?.[0]??"top",pointId:B.pcb_port_id,pcb_port_id:B.pcb_port_id})))})}let S=n.pcb_breakout_point.list().filter(C=>!t||s?.has(C.subcircuit_id)),P=[],T=new Map;for(let C of S){let M={x:C.x,y:C.y,layer:"top"};if(C.source_trace_id){let A=g.get(C.source_trace_id)??T.get(C.source_trace_id);if(A)A.pointsToConnect.push(M);else{let R={name:C.source_trace_id,source_trace_id:C.source_trace_id,pointsToConnect:[M]};P.push(R),T.set(C.source_trace_id,R)}}else if(C.source_net_id){let A=v.find(R=>R.name===C.source_net_id);A?A.pointsToConnect.push(M):P.push({name:C.source_net_id,pointsToConnect:[M]})}else if(C.source_port_id){let A=n.pcb_port.getWhere({source_port_id:C.source_port_id});A&&P.push({name:C.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:A.x,y:A.y,layer:A.layers?.[0]??"top",pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},M]})}}let k=[..._,...v,...P],N=new Map;for(let C of k)for(let M of C.pointsToConnect)M.pointId&&N.set(M.pointId,C);let E=n.pcb_trace.list().filter(C=>!t||s?.has(C.subcircuit_id));for(let C of E){let M=new Set;for(let B of C.route)B.start_pcb_port_id&&M.add(B.start_pcb_port_id),B.end_pcb_port_id&&M.add(B.end_pcb_port_id);if(M.size<2)continue;let A=M.values().next().value;if(!A)continue;let R=N.get(A);R&&[...M].every(B=>N.get(B)===R)&&(R.externallyConnectedPointIds??(R.externallyConnectedPointIds=[]),R.externallyConnectedPointIds.push([...M]))}return{simpleRouteJson:{bounds:p,obstacles:l,connections:k,layerCount:a?.num_layers??2,minTraceWidth:i,outline:a?.outline?.map(C=>({...C}))},connMap:c}},I7t=n=>{let e={};if(!n)return e;for(let i of Ga)e[i]=0;let t=new Map;for(let i of n){let[,,r,s]=i.type.split(":");if(s==="start"){t.set(`${r}:${i.renderId}`,i);continue}if(s==="end"){let o=t.get(`${r}:${i.renderId}`);if(o){let a=i.createdAt-o.createdAt;e[r]=(e[r]||0)+a}}}return e},N7t=n=>{let e=n.map(c=>[...new Set(c)]),t=e.map(()=>[]),i=e.map(()=>null);for(let c=0;c<e.length;c++)for(let l of e[c])if(/^\d+$/.test(l)){i[c]=Number.parseInt(l);break}let r=0,s=new Set;for(let c=0;c<i.length;c++){let l=i[c];if(l===null||l<1)continue;if(!s.has(l)){s.add(l),t[c].push(`pin${l}`),r=Math.max(r,l);continue}let u=0;for(let p of t[c])p.startsWith(`pin${l}_alt`)&&u++;t[c].push(`pin${l}_alt${u+1}`)}for(let c=0;c<t.length;c++)t[c][0]?.includes("_alt")&&(r++,t[c].unshift(`pin${r}`));for(let c=0;c<t.length;c++)t[c].length===0&&(r++,t[c].push(`pin${r}`));let o={};for(let c of e)for(let l of c)/^\d+$/.test(l)||(o[l]=(o[l]??0)+1);let a={};for(let c=0;c<e.length;c++){let l=e[c];for(let u of l)/^\d+$/.test(u)||(o[u]===1?t[c].push(u):(a[u]=(a[u]??0)+1,t[c].push(`${u}${a[u]}`)))}return t};function O9({db:n,schematicComponentId:e,deltaX:t,deltaY:i}){let r=n.schematic_rect.list({schematic_component_id:e});for(let c of r)c.center.x+=t,c.center.y+=i;let s=n.schematic_line.list({schematic_component_id:e});for(let c of s)c.x1+=t,c.y1+=i,c.x2+=t,c.y2+=i;let o=n.schematic_circle.list({schematic_component_id:e});for(let c of o)c.center.x+=t,c.center.y+=i;let a=n.schematic_arc.list({schematic_component_id:e});for(let c of a)c.center.x+=t,c.center.y+=i}var tnt=(0,jnt.default)("Group_doInitialSchematicLayoutMatchAdapt");function A7t(n){let{db:e}=n.root,t=Dg(e.toArray(),{source_group_id:n.source_group_id}),i=pN(t);tnt.enabled&&global?.debugGraphics&&global.debugGraphics?.push(ll(i,{title:`floatingBpcGraph-${n.name}`}));let r=pN(t),s={boxes:r.boxes,pins:r.pins.map(c=>({...c,color:c.color.replace("not_connected","normal")}))},{result:o}=SJ([{variantName:"default",floatingGraph:r},{variantName:"noNotConnected",floatingGraph:s}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(r.boxes.filter(c=>r.pins.filter(p=>p.boxId===c.boxId).filter(p=>!p.color.includes("center")).length<=2).map(c=>c.boxId)),corpus:{}});tnt.enabled&&global?.debugGraphics&&global.debugGraphics?.push(ll(o,{title:`laidOutBpcGraph-${n.name}`}));let a=n._getGlobalSchematicPositionBeforeLayout();for(let c of o.boxes){if(!c.center)continue;let l=e.schematic_component.get(c.boxId);if(l){let p={x:c.center.x+a.x,y:c.center.y+a.y},d=e.schematic_port.list({schematic_component_id:l.schematic_component_id}),_=e.schematic_text.list({schematic_component_id:l.schematic_component_id}),g={x:p.x-l.center.x,y:p.y-l.center.y};for(let x of d)x.center.x+=g.x,x.center.y+=g.y;for(let x of _)x.position.x+=g.x,x.position.y+=g.y;O9({db:e,schematicComponentId:l.schematic_component_id,deltaX:g.x,deltaY:g.y}),l.center=p;continue}let u=e.schematic_net_label.get(c.boxId);if(u){let p=o.pins.find(_=>_.boxId===c.boxId&&_.color==="netlabel_center");if(!p)throw new Error(`No pin found for net label: ${c.boxId}`);let d={x:c.center.x+a.x,y:c.center.y+a.y};u.center=d,u.anchor_position={x:d.x+p.offset.x,y:d.y+p.offset.y};continue}console.error(`No schematic element found for box: ${c.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var be=(0,Bnt.default)("Group_doInitialSchematicLayoutMatchpack");function ent(n){switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function nnt(n,e){let t=["right","up","left","down"],i=t.indexOf(n);if(i===-1)return n;let r=Math.round(e/90),s=(i+r)%4;return t[s<0?s+4:s]}function R7t(n,e,t){let i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};be(`[${t.name}] Processing ${n.childNodes.length} child nodes for input problem`),n.childNodes.forEach((s,o)=>{if(be(`[${t.name}] Processing child ${o}: nodeType=${s.nodeType}`),s.nodeType==="component"?be(`[${t.name}] - Component: ${s.sourceComponent?.name}`):s.nodeType==="group"&&be(`[${t.name}] - Group: ${s.sourceGroup?.name}`),s.nodeType==="component"&&s.sourceComponent){let a=s.sourceComponent.name||`chip_${o}`,c=e.schematic_component.getWhere({source_component_id:s.sourceComponent.source_component_id});if(!c)return;let l=t.children.find(P=>P.source_component_id===s.sourceComponent?.source_component_id),u=[0,90,180,270];l?._parsedProps?.schOrientation&&(u=[0]),l?._parsedProps?.schRotation!==void 0&&(u=[0]),l?._parsedProps?.facingDirection&&(u=[0]),l?._parsedProps?.schFacingDirection&&(u=[0]),l?.componentName==="Chip"&&(u=[0]);let p=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,d=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,_=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,g=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0;l?.config.shouldRenderAsSchematicBox&&(_+=.4,g+=.4);let x=(d-p)/2,v=(_-g)/2;i.chipMap[a]={chipId:a,pins:[],size:{x:(c.size?.width||1)+p+d,y:(c.size?.height||1)+_+g},availableRotations:u};let S=e.schematic_port.list({schematic_component_id:c.schematic_component_id});for(let P of S){let T=e.source_port.get(P.source_port_id);if(!T)continue;let k=`${a}.${T.pin_number||T.name||P.schematic_port_id}`;i.chipMap[a].pins.push(k);let N=ent(P.facing_direction);i.chipPinMap[k]={pinId:k,offset:{x:(P.center?.x||0)-(c.center.x||0)+x,y:(P.center?.y||0)-(c.center.y||0)+v},side:N}}}else if(s.nodeType==="group"&&s.sourceGroup){let a=s.sourceGroup.name||`group_${o}`;be(`[${t.name}] Processing nested group: ${a}`);let c=e.schematic_group?.getWhere?.({source_group_id:s.sourceGroup.source_group_id}),l=t.children.find(u=>u.source_group_id===s.sourceGroup?.source_group_id);if(be(`[${t.name}] Found schematic_group for ${a}:`,c),c){be(`[${t.name}] Treating group ${a} as composite chip`);let u=e.schematic_component.list({schematic_group_id:c.schematic_group_id});be(`[${t.name}] Group ${a} has ${u.length} components:`,u.map(A=>A.source_component_id));let p=1/0,d=-1/0,_=1/0,g=-1/0,x=!1;for(let A of u)if(A.center&&A.size){x=!0;let R=A.size.width/2,B=A.size.height/2;p=Math.min(p,A.center.x-R),d=Math.max(d,A.center.x+R),_=Math.min(_,A.center.y-B),g=Math.max(g,A.center.y+B)}let v=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,S=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,P=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,T=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0,k=(S-v)/2,N=(P-T)/2,E=(x?d-p:2)+v+S,C=(x?g-_:2)+P+T;be(`[${t.name}] Group ${a} computed size: ${E} x ${C}`);let M=[];for(let A of u){let R=e.schematic_port.list({schematic_component_id:A.schematic_component_id});for(let B of R){let j=e.source_port.get(B.source_port_id);if(!j)continue;let U=`${a}.${j.pin_number||j.name||B.schematic_port_id}`;M.push(U);let X=c.center||{x:0,y:0},W=ent(B.facing_direction);i.chipPinMap[U]={pinId:U,offset:{x:(B.center?.x||0)-X.x+k,y:(B.center?.y||0)-X.y+N},side:W}}}be(`[${t.name}] Group ${a} has ${M.length} pins:`,M),i.chipMap[a]={chipId:a,pins:M,size:{x:E,y:C}},be(`[${t.name}] Added group ${a} to chipMap`)}else be(`[${t.name}] Warning: No schematic_group found for group ${a}`)}}),be(`[${t.name}] Creating connections using connectivity keys`);let r=new Map;for(let[s,o]of Object.entries(i.chipMap))for(let a of o.pins){let c=a.split(".").pop(),l=n.childNodes.find(u=>u.nodeType==="component"&&u.sourceComponent?u.sourceComponent.name===s:u.nodeType==="group"&&u.sourceGroup?`group_${n.childNodes.indexOf(u)}`===s:!1);if(l?.nodeType==="group"&&l.sourceGroup){let u=e.schematic_group?.getWhere?.({source_group_id:l.sourceGroup.source_group_id});if(u){let p=e.schematic_component.list({schematic_group_id:u.schematic_group_id});for(let d of p){let _=e.source_port.list({source_component_id:d.source_component_id});for(let g of _){let x=g.pin_number||g.name;if(String(x)===String(c))if(g.subcircuit_connectivity_map_key){let v=g.subcircuit_connectivity_map_key;r.has(v)||r.set(v,[]),r.get(v).push(a),be(`[${t.name}] \u2713 Pin ${a} has connectivity key: ${v}`)}else be(`[${t.name}] Pin ${a} has no connectivity key`)}}}}else if(l?.nodeType==="component"&&l.sourceComponent){let u=e.source_port.list({source_component_id:l.sourceComponent.source_component_id});for(let p of u){let d=p.pin_number||p.name;if(String(d)===String(c)&&p.subcircuit_connectivity_map_key){let _=p.subcircuit_connectivity_map_key;r.has(_)||r.set(_,[]),r.get(_).push(a),be(`[${t.name}] Pin ${a} has connectivity key: ${_}`)}}}}be(`[${t.name}] Found ${r.size} connectivity groups:`,Array.from(r.entries()).map(([s,o])=>({key:s,pins:o})));for(let[s,o]of r)if(o.length>=2){let a=e.source_trace.list().filter(u=>u.subcircuit_connectivity_map_key===s),c=a.some(u=>u.connected_source_net_ids&&u.connected_source_net_ids.length>0),l=a.some(u=>u.connected_source_port_ids&&u.connected_source_port_ids.length>=2);if(be(`[${t.name}] Connectivity ${s}: hasNetConnections=${c}, hasDirectConnections=${l}`),l){for(let u of a)if(u.connected_source_port_ids&&u.connected_source_port_ids.length>=2){let p=[];for(let d of u.connected_source_port_ids)for(let _ of o){let g=_.split(".").pop(),x=e.source_port.get(d);if(x&&String(x.pin_number||x.name)===String(g)){let v=_.split(".")[0],S=n.childNodes.find(P=>P.nodeType==="component"&&P.sourceComponent?P.sourceComponent.name===v:P.nodeType==="group"&&P.sourceGroup?`group_${n.childNodes.indexOf(P)}`===v:!1);S?.nodeType==="component"&&S.sourceComponent&&e.source_port.list({source_component_id:S.sourceComponent.source_component_id}).some(T=>T.source_port_id===d)&&p.push(_)}}for(let d=0;d<p.length;d++)for(let _=d+1;_<p.length;_++){let g=p[d],x=p[_];i.pinStrongConnMap[`${g}-${x}`]=!0,i.pinStrongConnMap[`${x}-${g}`]=!0,be(`[${t.name}] Created strong connection: ${g} <-> ${x}`)}}}if(c){let u=e.source_net.getWhere({subcircuit_connectivity_map_key:s}),p=u?.is_ground??!1,d=u?.is_power??!1;i.netMap[s]={netId:s,isGround:p,isPositiveVoltageSource:d};for(let _ of o)i.netConnMap[`${_}-${s}`]=!0;be(`[${t.name}] Created net ${s} with ${o.length} pins:`,o)}}return i}function O7t(n){let{db:e}=n.root,t=u_(e.toArray(),{source_group_id:n.source_group_id});if(be(`[${n.name}] Starting matchpack layout with ${t.childNodes.length} children`),be(`[${n.name}] Tree structure:`,JSON.stringify(t,null,2)),t.childNodes.length<=1){be(`[${n.name}] Only ${t.childNodes.length} children, skipping layout`);return}be("Converting circuit tree to InputProblem...");let i=R7t(t,e,n);be.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${n.name}`,content:JSON.stringify(i,null,2)});let r=new NQ(i);if(be("Starting LayoutPipelineSolver..."),be.enabled&&global?.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-initial-${n.name}`})}if(r.solve(),be(`Solver completed in ${r.iterations} iterations`),be(`Solved: ${r.solved}, Failed: ${r.failed}`),r.failed)throw be(`Solver failed with error: ${r.error}`),new Error(`Matchpack layout solver failed: ${r.error}`);let s=r.getOutputLayout();if(be("OutputLayout:",JSON.stringify(s,null,2)),be("Solver completed successfully:",!r.failed),be.enabled&&global?.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-final-${n.name}`})}let o=r.checkForOverlaps(s);if(o.length>0){be(`Warning: Found ${o.length} overlapping components:`);for(let c of o)be(` ${c.chip1} overlaps ${c.chip2} (area: ${c.overlapArea})`)}let a=n._getGlobalSchematicPositionBeforeLayout();be(`Group offset: x=${a.x}, y=${a.y}`),be(`Applying layout results for ${Object.keys(s.chipPlacements).length} chip placements`);for(let[c,l]of Object.entries(s.chipPlacements)){be(`Processing placement for chip: ${c} at (${l.x}, ${l.y})`);let u=t.childNodes.find(d=>{if(d.nodeType==="component"&&d.sourceComponent){let _=d.sourceComponent.name===c;return be(` Checking component ${d.sourceComponent.name}: matches=${_}`),_}if(d.nodeType==="group"&&d.sourceGroup){let _=d.sourceGroup.name,g=`group_${t.childNodes.indexOf(d)}`,x=g===c;return be(` Checking group ${_} (expected chipId: ${g}): matches=${x}`),x}return!1});if(!u){be(`Warning: No tree node found for chip: ${c}`),be("Available tree nodes:",t.childNodes.map((d,_)=>({type:d.nodeType,name:d.nodeType==="component"?d.sourceComponent?.name:d.sourceGroup?.name,expectedChipId:d.nodeType==="group"?`group_${_}`:d.sourceComponent?.name})));continue}let p={x:l.x+a.x,y:l.y+a.y};if(u.nodeType==="component"&&u.sourceComponent){let d=e.schematic_component.getWhere({source_component_id:u.sourceComponent.source_component_id});if(d){be(`Moving component ${c} to (${p.x}, ${p.y})`);let _=e.schematic_port.list({schematic_component_id:d.schematic_component_id}),g=e.schematic_text.list({schematic_component_id:d.schematic_component_id}),x={x:p.x-d.center.x,y:p.y-d.center.y};for(let v of _)v.center.x+=x.x,v.center.y+=x.y;for(let v of g)v.position.x+=x.x,v.position.y+=x.y;if(O9({db:e,schematicComponentId:d.schematic_component_id,deltaX:x.x,deltaY:x.y}),d.center=p,l.ccwRotationDegrees!==0){be(`Component ${c} has rotation: ${l.ccwRotationDegrees}\xB0`);let v=l.ccwRotationDegrees*Math.PI/180,S=Math.cos(v),P=Math.sin(v);for(let T of _){let k=T.center.x-p.x,N=T.center.y-p.y,E=k*S-N*P,C=k*P+N*S;T.center.x=p.x+E,T.center.y=p.y+C;let M=T.facing_direction||"right";T.facing_direction=nnt(M,l.ccwRotationDegrees),T.side_of_component=(T.facing_direction==="up"?"top":T.facing_direction==="down"?"bottom":T.facing_direction)||T.side_of_component}for(let T of g){let k=T.position.x-p.x,N=T.position.y-p.y,E=k*S-N*P,C=k*P+N*S;T.position.x=p.x+E,T.position.y=p.y+C}if(d.symbol_name){let T=d.symbol_name.match(/_(right|left|up|down)$/);T&&(d.symbol_name=d.symbol_name.replace(T[0],`_${nnt(T[1],l.ccwRotationDegrees)}`))}}}}else if(u.nodeType==="group"&&u.sourceGroup){let d=e.schematic_group?.getWhere?.({source_group_id:u.sourceGroup.source_group_id});if(d){be(`Moving group ${c} to (${p.x}, ${p.y}) from (${d.center?.x}, ${d.center?.y})`);let _=e.schematic_component.list({schematic_group_id:d.schematic_group_id});be(`Group ${c} has ${_.length} components to move`);let g=d.center||{x:0,y:0},x={x:p.x-g.x,y:p.y-g.y};be(`Position delta for group ${c}: (${x.x}, ${x.y})`);for(let v of _)if(v.center){let S={...v.center};v.center.x+=x.x,v.center.y+=x.y,be(`Moved component ${v.source_component_id} from (${S.x}, ${S.y}) to (${v.center.x}, ${v.center.y})`);let P=e.schematic_port.list({schematic_component_id:v.schematic_component_id}),T=e.schematic_text.list({schematic_component_id:v.schematic_component_id});for(let k of P)k.center&&(k.center.x+=x.x,k.center.y+=x.y);for(let k of T)k.position&&(k.position.x+=x.x,k.position.y+=x.y)}d.center=p,be(`Updated group ${c} center to (${p.x}, ${p.y})`)}}}be("Matchpack layout completed successfully")}function L7t(n){if(!n.isSubcircuit)return;let{db:e}=n.root,t=n.selectAll("trace"),i=n.selectAll("via"),r=n.selectAll("net"),s=new n_({});s.addConnections(t.map(u=>{let p=e.source_trace.get(u.source_trace_id);return p?[p.source_trace_id,...p.connected_source_port_ids,...p.connected_source_net_ids]:null}).filter(u=>u!==null));let o=e.source_net.list().filter(u=>u.subcircuit_id===n.subcircuit_id);for(let u of o)s.addConnections([[u.source_net_id]]);let{name:a}=n._parsedProps;for(let u of t){if(!u.source_trace_id)continue;let p=s.getNetConnectedToId(u.source_trace_id);p&&(u.subcircuit_connectivity_map_key=`${a??`unnamedsubcircuit${n._renderId}`}_${p}`,e.source_trace.update(u.source_trace_id,{subcircuit_connectivity_map_key:u.subcircuit_connectivity_map_key}))}let c=new Set;for(let u of t){if(!u.source_trace_id)continue;let p=e.source_trace.get(u.source_trace_id);if(p)for(let d of p.connected_source_port_ids)c.add(d)}for(let u of c){let p=s.getNetConnectedToId(u);if(!p)continue;let d=`${a??`unnamedsubcircuit${n._renderId}`}_${p}`;e.source_port.update(u,{subcircuit_connectivity_map_key:d})}let l=new Set;for(let u of t){if(!u.source_trace_id)continue;let p=e.source_trace.get(u.source_trace_id);if(p)for(let d of p.connected_source_net_ids)l.add(d)}for(let u of o)l.add(u.source_net_id);for(let u of l){let p=s.getNetConnectedToId(u);if(!p)continue;let d=`${a??`unnamedsubcircuit${n._renderId}`}_${p}`;e.source_net.update(u,{subcircuit_connectivity_map_key:d});let _=r.find(g=>g.source_net_id===u);_&&(_.subcircuit_connectivity_map_key=d)}for(let u of i){let p=u._getConnectedNetOrTrace();p&&p.subcircuit_connectivity_map_key&&(u.subcircuit_connectivity_map_key=p.subcircuit_connectivity_map_key)}}function F7t(n){let{db:e}=n.root,t=n._parsedProps,i=n.children.filter(N=>{let E=N._parsedProps?.schX!==void 0||N._parsedProps?.schY!==void 0;return N.schematic_component_id&&!E});if(i.length===0)return;let r=0,s=0;for(let N of i){let E=e.schematic_component.get(N.schematic_component_id);E?.size&&(r=Math.max(r,E.size.width),s=Math.max(s,E.size.height))}r===0&&i.length>0&&(r=1),s===0&&i.length>0&&(s=1);let o=t.gridCols,a,c=t.gridGap,l=t.gridRowGap,u=t.gridColumnGap;t.schLayout?.grid&&(o=t.schLayout.grid.cols??o,a=t.schLayout.grid.rows,c=t.schLayout.gridGap??c,l=t.schLayout.gridRowGap??l,u=t.schLayout.gridColumnGap??u);let p,d;o!==void 0&&a!==void 0?(p=o,d=a):o!==void 0?(p=o,d=Math.ceil(i.length/p)):a!==void 0?(d=a,p=Math.ceil(i.length/d)):(p=Math.ceil(Math.sqrt(i.length)),d=Math.ceil(i.length/p)),p===0&&i.length>0&&(p=1),d===0&&i.length>0&&(d=i.length);let _,g,x=N=>{if(N!==void 0)return typeof N=="number"?N:D.parse(N)};if(l!==void 0||u!==void 0){let N=typeof c=="object"&&c!==null?c.x:c,E=typeof c=="object"&&c!==null?c.y:c;_=x(u??N)??1,g=x(l??E)??1}else if(typeof c=="number")_=c,g=c;else if(typeof c=="string"){let N=D.parse(c);_=N,g=N}else if(typeof c=="object"&&c!==null){let N=c.x,E=c.y;_=typeof N=="number"?N:D.parse(N??"0mm"),g=typeof E=="number"?E:D.parse(E??"0mm")}else _=1,g=1;let v=p*r+Math.max(0,p-1)*_,S=d*s+Math.max(0,d-1)*g,P=n._getGlobalSchematicPositionBeforeLayout(),T=P.x-v/2+r/2,k=P.y+S/2-s/2;for(let N=0;N<i.length;N++){let E=i[N];if(!E.schematic_component_id)continue;let C=Math.floor(N/p),M=N%p;if(C>=d||M>=p){console.warn(`Schematic grid layout: Child ${E.getString()} at index ${N} (row ${C}, col ${M}) exceeds specified grid dimensions (${d}x${p}). Skipping placement.`);continue}let A=T+M*(r+_),R=k-C*(s+g),B=e.schematic_component.get(E.schematic_component_id);if(B){let j=B.center,U={x:A,y:R};e.schematic_component.update(E.schematic_component_id,{center:U});let X=U.x-j.x,W=U.y-j.y,et=e.schematic_port.list({schematic_component_id:E.schematic_component_id});for(let mt of et)e.schematic_port.update(mt.schematic_port_id,{center:{x:mt.center.x+X,y:mt.center.y+W}});let nt=e.schematic_text.list({schematic_component_id:E.schematic_component_id});for(let mt of nt)e.schematic_text.update(mt.schematic_text_id,{position:{x:mt.position.x+X,y:mt.position.y+W}});O9({db:e,schematicComponentId:E.schematic_component_id,deltaX:X,deltaY:W})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:v,height:S,center:P})}var int=(n,e)=>{let{sourceComponent:t,sourceGroup:i}=e;if(e.nodeType==="component"){let r=n.schematic_component.getWhere({source_component_id:t?.source_component_id});return r?.size?{width:r.size.width,height:r.size.height}:null}if(e.nodeType==="group"){let r=n.schematic_group.getWhere({source_group_id:i?.source_group_id});if(r?.width&&r?.height)return{width:r.width,height:r.height};let s=n.schematic_component.list({schematic_group_id:r?.schematic_group_id}),o=1/0,a=-1/0,c=1/0,l=-1/0;for(let d of s)if(d.center&&d.size){let _=d.size.width/2,g=d.size.height/2;o=Math.min(o,d.center.x-_),a=Math.max(a,d.center.x+_),c=Math.min(c,d.center.y-g),l=Math.max(l,d.center.y+g)}let u=a-o,p=l-c;return{width:u,height:p}}return null},$7t=n=>{let{db:e}=n.root,t=n._parsedProps,i=u_(e.toArray(),{source_group_id:n.source_group_id}),r=t.schJustifyContent??t.justifyContent,s=t.schAlignItems??t.alignItems,o=t.schFlexGap??t.schGap??t.gap,a=t.schFlexDirection??"row",c={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[r??"space-between"],l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[s??"center"];if(!c)throw new Error(`Invalid justifyContent value: "${r}"`);if(!l)throw new Error(`Invalid alignItems value: "${s}"`);let u=0,p=0;typeof o=="object"?(u=o.y??0,p=o.x??0):typeof o=="number"?(u=o,p=o):typeof o=="string"&&(u=D.parse(o),p=D.parse(o));let d,_=t.width??t.schWidth??void 0,g=t.height??t.schHeight??void 0;(_===void 0||g===void 0)&&(d=$w(i.childNodes.map(k=>int(e,k)).filter(k=>k!==null),{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:p}),_=d.width,g=d.height);let v=new jS(_,g,{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:p});for(let k of i.childNodes){let N=int(e,k);v.addChild({metadata:k,width:N?.width??0,height:N?.height??0,flexBasis:N?a==="row"?N.width:N.height:void 0})}v.build();let S={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let k of v.children)S.minX=Math.min(S.minX,k.position.x),S.minY=Math.min(S.minY,k.position.y),S.maxX=Math.max(S.maxX,k.position.x+k.size.width),S.maxY=Math.max(S.maxY,k.position.y+k.size.height);S.width=S.maxX-S.minX,S.height=S.maxY-S.minY;let P={x:-(S.maxX+S.minX)/2,y:-(S.maxY+S.minY)/2},T=e.toArray();for(let k of v.children){let{sourceComponent:N,sourceGroup:E}=k.metadata;if(N){let C=e.schematic_component.getWhere({source_component_id:N.source_component_id});if(!C)continue;Oq(T,C.schematic_component_id,{x:k.position.x+k.size.width/2+P.x,y:k.position.y+k.size.height/2+P.y})}if(E){if(!e.schematic_group.getWhere({source_group_id:E.source_group_id}))continue;Fq(T,E.source_group_id,{x:k.position.x+k.size.width/2+P.x,y:k.position.y+k.size.height/2+P.y})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:S.width,height:S.height})},h9=1;function z7t(n){let{db:e}=n.root,t=n._parsedProps,i=D7t(n);if(i.length===0)return;let r=j7t({db:e,pcbChildren:i}),s=B7t(t),o=Y7t({props:t,pcbChildren:i,childDimensions:r,gridConfig:s}),a=V7t({pcbChildren:i,childDimensions:r,gridLayout:o,gridConfig:s}),{itemCoordinates:c}=a.layout();G7t({db:e,group:n,pcbChildren:i,itemCoordinates:c,gridLayout:o}),W7t({db:e,group:n,props:t,gridLayout:o})}function D7t(n){return n.children.filter(e=>e.pcb_component_id||e.pcb_group_id)}function j7t(n){let{db:e,pcbChildren:t}=n,i=0,r=0;for(let s of t){let o=0,a=0;if(s.pcb_group_id){let c=e.pcb_group.get(s.pcb_group_id);o=c?.width??0,a=c?.height??0}else if(s.pcb_component_id){let c=e.pcb_component.get(s.pcb_component_id);o=c?.width??0,a=c?.height??0}i=Math.max(i,o),r=Math.max(r,a)}return{width:i,height:r}}function B7t(n){let e=n.pcbGridCols??n.gridCols??n.pcbLayout?.grid?.cols,t=n.pcbGridRows??n.pcbLayout?.grid?.rows,i=n.pcbGridTemplateColumns,r=n.pcbGridTemplateRows,s=p=>p===void 0?h9:typeof p=="number"?p:D.parse(p),o=n.pcbGridGap??n.gridGap??n.pcbLayout?.gridGap,a=n.pcbGridRowGap??n.gridRowGap??n.pcbLayout?.gridRowGap,c=n.pcbGridColumnGap??n.gridColumnGap??n.pcbLayout?.gridColumnGap,l=h9,u=h9;if(a!==void 0||c!==void 0){let p=typeof o=="object"?o?.x:o,d=typeof o=="object"?o?.y:o;l=s(c??p),u=s(a??d)}else if(typeof o=="object"&&o!==null)l=s(o.x),u=s(o.y);else{let p=s(o);l=p,u=p}return{cols:e,rows:t,gapX:l,gapY:u,templateColumns:i,templateRows:r}}function Y7t(n){let{props:e,pcbChildren:t,childDimensions:i,gridConfig:r}=n;return e.pcbGridTemplateColumns||e.pcbGridTemplateRows?X7t({props:e,gridConfig:r,pcbChildren:t,childDimensions:i}):U7t({gridConfig:r,pcbChildren:t,childDimensions:i})}function X7t(n){let{props:e,gridConfig:t,pcbChildren:i,childDimensions:r}=n,s=e.pcbGridTemplateColumns??"",o=e.pcbGridTemplateRows??"",a=d=>{let _=d.match(/repeat\((\d+),/);return _?parseInt(_[1]):Math.ceil(Math.sqrt(i.length))},c=e.pcbGridTemplateColumns?a(s):Math.ceil(Math.sqrt(i.length)),l=e.pcbGridTemplateRows?a(o):Math.ceil(i.length/c),u=c*r.width+Math.max(0,c-1)*t.gapX,p=l*r.height+Math.max(0,l-1)*t.gapY;return{gridTemplateColumns:s,gridTemplateRows:o,containerWidth:u,containerHeight:p}}function U7t(n){let{gridConfig:e,pcbChildren:t,childDimensions:i}=n,r,s;e.cols!==void 0&&e.rows!==void 0?(r=e.cols,s=e.rows):e.cols!==void 0?(r=e.cols,s=Math.ceil(t.length/r)):e.rows!==void 0?(s=e.rows,r=Math.ceil(t.length/s)):(r=Math.ceil(Math.sqrt(t.length)),s=Math.ceil(t.length/r)),r=Math.max(1,r),s=Math.max(1,s);let o=r*i.width+Math.max(0,r-1)*e.gapX,a=s*i.height+Math.max(0,s-1)*e.gapY,c=`repeat(${r}, ${i.width}px)`,l=`repeat(${s}, ${i.height}px)`;return{gridTemplateColumns:c,gridTemplateRows:l,containerWidth:o,containerHeight:a}}function V7t(n){let{pcbChildren:e,childDimensions:t,gridLayout:i,gridConfig:r}=n,s=e.map((o,a)=>({key:o.getString()||`child-${a}`,contentWidth:t.width,contentHeight:t.height}));return new jQ({containerWidth:i.containerWidth,containerHeight:i.containerHeight,gridTemplateColumns:i.gridTemplateColumns,gridTemplateRows:i.gridTemplateRows,gap:[r.gapY,r.gapX],children:s})}function G7t(n){let{db:e,group:t,pcbChildren:i,itemCoordinates:r,gridLayout:s}=n,o=t._getGlobalPcbPositionBeforeLayout(),a=e.toArray();for(let c=0;c<i.length;c++){let l=i[c],u=l.getString()||`child-${c}`,p=r[u];if(!p){console.warn(`PCB grid layout: No coordinates found for child ${u}`);continue}let d=o.x-s.containerWidth/2+p.x+p.width/2,_=o.y+s.containerHeight/2-p.y-p.height/2;if(l.pcb_component_id)Lw(a,l.pcb_component_id,{x:d,y:_});else{let g=l;g.pcb_group_id&&g.source_group_id&&Fw(a,g.source_group_id,{x:d,y:_})}}}function W7t(n){let{db:e,group:t,props:i,gridLayout:r}=n;if(t.pcb_group_id){let s=t._getGlobalPcbPositionBeforeLayout();e.pcb_group.update(t.pcb_group_id,{width:i.width??r.containerWidth,height:i.height??r.containerHeight,center:s})}}function H7t(n){let e={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof n=="object"&&!n.preset)return{local:!(n.serverUrl||n.serverMode||n.serverCacheEnabled),...e,...n};let t=typeof n=="object"?n.preset:n,i=typeof n=="object"?n:{};switch(typeof t=="string"?t.replace(/_/g,"-"):t){case"auto-local":return{local:!0,groupMode:"subcircuit"};case"sequential-trace":return{local:!0,groupMode:"sequential-trace"};case"subcircuit":return{local:!0,groupMode:"subcircuit"};case"auto-cloud":{let{preset:s,local:o,groupMode:a,...c}=i;return{local:!1,groupMode:"subcircuit",...e,...c}}case"laser-prefab":{let{preset:s,local:o,groupMode:a,...c}=i;return{local:!0,groupMode:"subcircuit",preset:"laser_prefab",...c}}default:return{local:!0,groupMode:"subcircuit"}}}var q7t=(n,e)=>{let t=n.children.filter(p=>p.componentName==="Constraint"&&p._parsedProps.pcb),i=new Map,r={},s=p=>(r[p]!==p&&(r[p]=s(r[p])),r[p]),o=(p,d)=>{let _=s(p),g=s(d);_!==g&&(r[g]=_)},a=p=>{p in r||(r[p]=p)},c=p=>{let d=p.startsWith(".")?p.slice(1):p;return n.children.find(g=>g.name===d)?.pcb_component_id??void 0};for(let p of t){let d=p._parsedProps;if("left"in d&&"right"in d){let _=c(d.left),g=c(d.right);_&&g&&(a(_),a(g),o(_,g))}else if("top"in d&&"bottom"in d){let _=c(d.top),g=c(d.bottom);_&&g&&(a(_),a(g),o(_,g))}else if("for"in d&&Array.isArray(d.for)){let _=d.for.map(g=>c(g)).filter(g=>!!g);for(let g of _)a(g);for(let g=1;g<_.length;g++)o(_[0],_[g])}}for(let p of Object.keys(r)){let d=s(p);i.has(d)||i.set(d,{componentIds:[],constraints:[]}),i.get(d).componentIds.push(p)}for(let p of t){let d=p._parsedProps,_;if("left"in d?_=c(d.left):"top"in d?_=c(d.top):"for"in d&&(_=c(d.for[0])),!_)continue;let g=s(_);i.get(g)?.constraints.push(p)}let l={},u=Object.fromEntries(e.components.map(p=>[p.componentId,p]));for(let[p,d]of i.entries()){if(d.componentIds.length<=1)continue;let _=new a_,g={},x=(A,R)=>{let B=`${A}_${R}`;return g[B]||(g[B]=new Oa(B)),g[B]},v=d.componentIds[0];_.addConstraint(new ki(x(v,"x"),ai.Eq,0,On.required)),_.addConstraint(new ki(x(v,"y"),ai.Eq,0,On.required));for(let A of d.constraints){let R=A._parsedProps;if("xDist"in R){let B=c(R.left),j=c(R.right);B&&j&&_.addConstraint(new ki(new Dn(x(j,"x"),[-1,x(B,"x")]),ai.Eq,R.xDist,On.required))}else if("yDist"in R){let B=c(R.top),j=c(R.bottom);B&&j&&_.addConstraint(new ki(new Dn(x(B,"y"),[-1,x(j,"y")]),ai.Eq,R.yDist,On.required))}else if("sameX"in R&&Array.isArray(R.for)){let B=R.for.map(j=>c(j)).filter(j=>!!j);if(B.length>1){let j=x(B[0],"x");for(let U=1;U<B.length;U++)_.addConstraint(new ki(new Dn(x(B[U],"x"),[-1,j]),ai.Eq,0,On.required))}}else if("sameY"in R&&Array.isArray(R.for)){let B=R.for.map(j=>c(j)).filter(j=>!!j);if(B.length>1){let j=x(B[0],"y");for(let U=1;U<B.length;U++)_.addConstraint(new ki(new Dn(x(B[U],"y"),[-1,j]),ai.Eq,0,On.required))}}}_.updateVariables();let S={};for(let A of d.componentIds)S[A]={x:x(A,"x").value(),y:x(A,"y").value()};let P=1/0,T=1/0,k=-1/0,N=-1/0;for(let A of d.componentIds){let R=u[A],B=S[A];if(R)for(let j of R.pads){let U=B.x+j.offset.x,X=B.y+j.offset.y;P=Math.min(P,U-j.size.x/2),k=Math.max(k,U+j.size.x/2),T=Math.min(T,X-j.size.y/2),N=Math.max(N,X+j.size.y/2)}}let E={x:(P+k)/2,y:(T+N)/2},C=[],M={};for(let A of d.componentIds){let R=u[A],B=S[A];if(R){M[A]={x:B.x-E.x,y:B.y-E.y};for(let j of R.pads)C.push({padId:j.padId,networkId:j.networkId,type:j.type,size:j.size,offset:{x:B.x+j.offset.x-E.x,y:B.y+j.offset.y-E.y}})}}e.components=e.components.filter(A=>!d.componentIds.includes(A.componentId)),e.components.push({componentId:d.componentIds[0],pads:C,availableRotationDegrees:[0]}),d.relativeCenters=M,l[d.componentIds[0]]=d}return l},rnt=({db:n,pcbComponentId:e,rotationDegrees:t,layer:i})=>{if(t==null||!n?.cad_component?.list)return;let r=n.cad_component.getWhere({pcb_component_id:e});if(!r)return;let s=i?.toLowerCase?.()==="bottom"?-t:t,o=r.rotation?.z??0,a={...r.rotation??{x:0,y:0,z:0},z:hd(o+s)};n.cad_component.update(r.cad_component_id,{rotation:a}),r.rotation=a},U1=(n,e,t)=>{if(e===t)return!0;let i=n.source_group.get(e);return!i||!i.parent_source_group_id?!1:U1(n,i.parent_source_group_id,t)},Z7t=(n,e,t)=>{let{db:i}=n.root;for(let r of e.components){let{center:s,componentId:o,ccwRotationOffset:a,ccwRotationDegrees:c}=r,l=t[o];if(l){let v=c??a??0,S=v*Math.PI/180;for(let P of l.componentIds){let T=l.relativeCenters[P];if(!T)continue;let k={x:T.x*Math.cos(S)-T.y*Math.sin(S),y:T.x*Math.sin(S)+T.y*Math.cos(S)},N=i.pcb_component.get(P);if(!N)continue;let E=N.center,C=ii(n._computePcbGlobalTransformBeforeLayout(),kn(s.x+k.x,s.y+k.y),Oo(S),kn(-E.x,-E.y)),M=i.toArray().filter(A=>"pcb_component_id"in A&&A.pcb_component_id===P);tl(M,C),rnt({db:i,pcbComponentId:P,rotationDegrees:v,layer:N.layer})}continue}let u=i.pcb_component.get(o);if(u){let v=n.source_group_id,P=i.source_component.get(u.source_component_id)?.source_group_id;if(P!==void 0&&!U1(i,P,v))continue;let T=u.center,k=c??a??0,N=ii(n._computePcbGlobalTransformBeforeLayout(),kn(s.x,s.y),Oo(k*Math.PI/180),kn(-T.x,-T.y)),E=i.toArray().filter(C=>"pcb_component_id"in C&&C.pcb_component_id===o);tl(E,N),rnt({db:i,pcbComponentId:o,rotationDegrees:k,layer:u.layer});continue}let p=i.pcb_group.list().find(v=>v.source_group_id===o);if(!p)continue;let d=p.center,_=c??a??0,g=ii(n._computePcbGlobalTransformBeforeLayout(),kn(s.x,s.y),Oo(_*Math.PI/180),kn(-d.x,-d.y)),x=i.toArray().filter(v=>{if("source_group_id"in v&&v.source_group_id&&(v.source_group_id===o||U1(i,v.source_group_id,o)))return!0;if("source_component_id"in v&&v.source_component_id){let S=i.source_component.get(v.source_component_id);if(S?.source_group_id&&(S.source_group_id===o||U1(i,S.source_group_id,o)))return!0}if("pcb_component_id"in v&&v.pcb_component_id){let S=i.pcb_component.get(v.pcb_component_id);if(S?.source_component_id){let P=i.source_component.get(S.source_component_id);if(P?.source_group_id&&(P.source_group_id===o||U1(i,P.source_group_id,o)))return!0}}return!1});tl(x,g),i.pcb_group.update(p.pcb_group_id,{center:s})}};function K7t(n){switch(n.shape){case"rect":case"rotated_rect":case"pill":case"rotated_pill":return{width:n.width,height:n.height};case"circle":return{width:n.radius*2,height:n.radius*2};case"polygon":if(!n.points||n.points.length===0)return null;let e=n.points.map(a=>a.x),t=n.points.map(a=>a.y),i=Math.min(...e),r=Math.max(...e),s=Math.min(...t),o=Math.max(...t);return{width:r-i,height:o-s};default:return null}}function J7t(n){switch(n.shape){case"circular_hole_with_rect_pad":case"pill_hole_with_rect_pad":case"rotated_pill_hole_with_rect_pad":return{width:n.rect_pad_width,height:n.rect_pad_height};case"circle":return{width:n.outer_diameter,height:n.outer_diameter};case"oval":return{width:n.outer_width,height:n.outer_height};case"pill":return{width:n.outer_width,height:n.outer_height};case"hole_with_polygon_pad":if(!("pad_outline"in n)||!n.pad_outline||n.pad_outline.length===0)return null;let e=n.pad_outline.map(a=>a.x),t=n.pad_outline.map(a=>a.y),i=Math.min(...e),r=Math.max(...e),s=Math.min(...t),o=Math.max(...t);return{width:r-i,height:o-s};default:return null}}var Q7t="1mm",snt=(0,Ynt.default)("Group_doInitialPcbLayoutPack"),tFt=n=>{let{db:e}=n.root,{_parsedProps:t}=n,{packOrderStrategy:i,packPlacementStrategy:r,gap:s,pcbGap:o,pcbPackGap:a}=t,c=a??o??s,l=D.parse(c??Q7t),u={},p=new Set,d=k=>{if(k?.pcb_component_id&&k?._parsedProps){let N=k._parsedProps,E=D.parse(N.pcbMarginLeft??N.pcbMarginX??0),C=D.parse(N.pcbMarginRight??N.pcbMarginX??0),M=D.parse(N.pcbMarginTop??N.pcbMarginY??0),A=D.parse(N.pcbMarginBottom??N.pcbMarginY??0);(E||C||M||A)&&(u[k.pcb_component_id]={left:E,right:C,top:M,bottom:A})}k?.children&&k.children.forEach(d)};d(n);let _=new Set;for(let k of n.children){let N=k;N._isNormalComponent&&N.isRelativelyPositioned?.()&&(N.pcb_component_id&&p.add(N.pcb_component_id),N.pcb_group_id&&_.add(N.pcb_group_id))}let g=e.toArray().filter(k=>k.type==="pcb_component"?!p.has(k.pcb_component_id):k.type==="pcb_group"?!_.has(k.pcb_group_id):!0),x=[];for(let k of p){let N=e.toArray().find(R=>R.type==="pcb_component"&&R.pcb_component_id===k);if(!N)continue;let E=N.center.x,C=N.center.y,M=e.toArray().filter(R=>R.type==="pcb_smtpad"&&R.pcb_component_id===k);for(let R of M){let B=K7t(R);if(!B||B.width===0||B.height===0)continue;let j,U;if(R.shape==="polygon"){let X=R.points.map(et=>et.x),W=R.points.map(et=>et.y);j=E+(Math.min(...X)+Math.max(...X))/2,U=C+(Math.min(...W)+Math.max(...W))/2}else j=E+R.x,U=C+R.y;x.push({obstacleId:R.pcb_smtpad_id,absoluteCenter:{x:j,y:U},width:B.width,height:B.height})}let A=e.toArray().filter(R=>R.type==="pcb_plated_hole"&&R.pcb_component_id===k);for(let R of A){let B=J7t(R);if(!B||B.width===0||B.height===0)continue;let j=E+R.x,U=C+R.y;x.push({obstacleId:R.pcb_plated_hole_id,absoluteCenter:{x:j,y:U},width:B.width,height:B.height})}}let v;if(t.width!==void 0&&t.height!==void 0){let k=D.parse(t.width),N=D.parse(t.height);v={minX:-k/2,maxX:k/2,minY:-N/2,maxY:N/2}}let S={...CQ(MQ(g,{source_group_id:n.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:u})),orderStrategy:i??"largest_to_smallest",placementStrategy:r??"minimum_sum_squared_distance_to_network",minGap:l,obstacles:x,bounds:v},P=q7t(n,S);snt.enabled&&(n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${n.name}`,content:JSON.stringify(e.toArray())}),n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${n.name}`,content:S}));let T=$S(S);if(snt.enabled&&global?.debugGraphics){let k=vA(T);k.title=`packOutput-${n.name}`,global.debugGraphics?.push(k)}Z7t(n,T,P)},eFt=n=>{let{db:e}=n.root,{_parsedProps:t}=n,i=n.children.filter(N=>N.pcb_component_id||N.pcb_group_id);if(i.some(N=>{let E=N._parsedProps;return E?.pcbX!==void 0||E?.pcbY!==void 0}))return;let s=t.pcbJustifyContent??t.justifyContent,o=t.pcbAlignItems??t.alignItems,a=t.pcbFlexGap??t.pcbGap??t.gap,c=t.pcbFlexDirection??"row",l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[s??"space-between"],u={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[o??"center"];if(!l)throw new Error(`Invalid justifyContent value: "${s}"`);if(!u)throw new Error(`Invalid alignItems value: "${o}"`);let p=0,d=0;typeof a=="object"?(p=a.y??0,d=a.x??0):typeof a=="number"?(p=a,d=a):typeof a=="string"&&(p=D.parse(a),d=D.parse(a));let _,g=t.width??t.pcbWidth??void 0,x=t.height??t.pcbHeight??void 0;(g===void 0||x===void 0)&&(_=$w(i.map(N=>N._getMinimumFlexContainerSize()).filter(N=>N!==null),{alignItems:u,justifyContent:l,direction:c,rowGap:p,columnGap:d}),g=_.width,x=_.height);let S=new jS(g,x,{alignItems:u,justifyContent:l,direction:c,rowGap:p,columnGap:d});for(let N of i){let E=N._getMinimumFlexContainerSize();S.addChild({metadata:N,width:E?.width??0,height:E?.height??0,flexBasis:E?c==="row"?E.width:E.height:void 0})}S.build();let P={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let N of S.children)P.minX=Math.min(P.minX,N.position.x),P.minY=Math.min(P.minY,N.position.y),P.maxX=Math.max(P.maxX,N.position.x+N.size.width),P.maxY=Math.max(P.maxY,N.position.y+N.size.height);P.width=P.maxX-P.minX,P.height=P.maxY-P.minY;let T=n._getGlobalPcbPositionBeforeLayout(),k={x:T.x-(P.maxX+P.minX)/2,y:T.y-(P.maxY+P.minY)/2};for(let N of S.children)N.metadata._repositionOnPcb({x:N.position.x+N.size.width/2+k.x,y:N.position.y+N.size.height/2+k.y});e.pcb_group.update(n.pcb_group_id,{width:P.width,height:P.height,center:T})};function nFt(n){let{db:e}=n.root,t=new Map,i=new Map,r=new Set,o=n.selectAll("trace").filter(R=>R._parsedProps?.schDisplayLabel),a=n.selectAll("group"),c=[n.schematic_group_id,...a.map(R=>R.schematic_group_id)],l=e.schematic_component.list().filter(R=>c.includes(R.schematic_group_id)),u=[],p=new Map,d=new Map;for(let R of l){let B=R.schematic_component_id,j=[],U=e.source_component.getWhere({source_component_id:R.source_component_id}),X=e.schematic_port.list({schematic_component_id:R.schematic_component_id});for(let W of X){let et=`${U?.name??R.schematic_component_id}.${W.pin_number}`;p.set(et,W.schematic_port_id),d.set(W.schematic_port_id,et)}for(let W of X){let et=d.get(W.schematic_port_id);j.push({pinId:et,x:W.center.x,y:W.center.y})}u.push({chipId:B,center:R.center,width:R.size.width,height:R.size.height,pins:j})}let _=new Set,g=new Map,x=new Map,v=new Map;for(let R of l){let B=e.schematic_port.list({schematic_component_id:R.schematic_component_id});for(let j of B)_.add(j.schematic_port_id),j.source_port_id&&(g.set(j.schematic_port_id,j.source_port_id),x.set(j.source_port_id,j.schematic_port_id))}let S=new Set;n.subcircuit_id&&S.add(n.subcircuit_id);for(let R of a)R.subcircuit_id&&S.add(R.subcircuit_id);let T=e.source_trace.list().filter(R=>{if(R.subcircuit_id===n.subcircuit_id)return!0;for(let B of R.connected_source_port_ids)if(x.has(B))return!0;return!1}).flatMap(R=>R.connected_source_net_ids);for(let R of T){let B=e.source_net.get(R);B?.subcircuit_id&&S.add(B.subcircuit_id)}let k=[],N=new Map;for(let R of e.source_trace.list()){if(R.subcircuit_id&&!S.has(R.subcircuit_id))continue;let B=(R.connected_source_port_ids??[]).map(j=>x.get(j)).filter(j=>!!j&&_.has(j));if(B.length>=2){let[j,U]=B.slice(0,2),X=[j,U].sort().join("::");if(!N.has(X)){N.set(X,R.source_trace_id);let W=R.display_name??R.source_trace_id;R.subcircuit_connectivity_map_key&&(r.add(R.subcircuit_connectivity_map_key),v.set(W,R.subcircuit_connectivity_map_key),i.set(R.subcircuit_connectivity_map_key,W)),k.push({pinIds:[j,U].map(et=>d.get(et)),netId:W})}}}let E=[];for(let R of e.source_net.list().filter(B=>!B.subcircuit_id||S.has(B.subcircuit_id)))R.subcircuit_connectivity_map_key&&(r.add(R.subcircuit_connectivity_map_key),t.set(R.subcircuit_connectivity_map_key,R));let C=new Map;for(let[R,B]of g){let j=e.source_port.get(B);if(!j?.subcircuit_connectivity_map_key)continue;let U=j.subcircuit_connectivity_map_key;r.add(U),C.has(U)||C.set(U,[]),C.get(U).push(R)}for(let[R,B]of C){let j=t.get(R);if(j&&B.length>=2){let U=String(j.name||j.source_net_id||R);v.set(U,R),i.set(R,U);let W=.1*(.18/.18),et=Number((String(U).length*W).toFixed(2));E.push({netId:U,pinIds:B.map(nt=>d.get(nt)),netLabelWidth:et})}}let M=(()=>{let R={},B=new Set(E.map(j=>j.netId));for(let j of e.source_net.list().filter(U=>!U.subcircuit_id||S.has(U.subcircuit_id)))j.name&&B.has(j.name)&&(j.is_ground||j.name.toLowerCase().startsWith("gnd")?R[j.name]=["y-"]:j.is_power||j.name.toLowerCase().startsWith("v")?R[j.name]=["y+"]:R[j.name]=["x-","x+"]);return R})();return{inputProblem:{chips:u,directConnections:k,netConnections:E,availableNetLabelOrientations:M,maxMspPairDistance:n._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:p,pairKeyToSourceTraceId:N,sckToSourceNet:t,sckToUserNetId:i,userNetIdToSck:v,allSourceAndSchematicPortIdsInScope:_,schPortIdToSourcePortId:g,displayLabelTraces:o,allScks:r}}var gr=1e-6;function ont(n){let e=Math.abs(n.to.x-n.from.x),t=Math.abs(n.to.y-n.from.y);return e>=t}function uP(n,e){return Math.hypot(e.x-n.x,e.y-n.y)}function ant(n,e,t){return{x:n.x+(e.x-n.x)*t,y:n.y+(e.y-n.y)*t}}function cnt(n,e,t){let i=uP(n,e);if(i<gr)return 0;let r=((t.x-n.x)*(e.x-n.x)+(t.y-n.y)*(e.y-n.y))/((e.x-n.x)*(e.x-n.x)+(e.y-n.y)*(e.y-n.y));return Math.max(0,Math.min(1,r))*i}function nP(n,e,t,i){return n*i-e*t}function iFt(n,e,t,i){let r={x:e.x-n.x,y:e.y-n.y},s={x:i.x-t.x,y:i.y-t.y},o=nP(r.x,r.y,s.x,s.y),a={x:t.x-n.x,y:t.y-n.y},c=nP(a.x,a.y,r.x,r.y);if(Math.abs(o)<gr&&Math.abs(c)<gr||Math.abs(o)<gr&&Math.abs(c)>=gr)return null;let l=nP(a.x,a.y,s.x,s.y)/o,u=nP(a.x,a.y,r.x,r.y)/o;return l<-gr||l>1+gr||u<-gr||u>1+gr?null:{x:n.x+l*r.x,y:n.y+l*r.y}}function rFt(n,e=gr){if(n.length===0)return n;n.sort((r,s)=>r.start-s.start);let t=[],i={...n[0]};for(let r=1;r<n.length;r++){let s=n[r];s.start<=i.end+e?i.end=Math.max(i.end,s.end):(t.push(i),i={...s})}return t.push(i),t}function sFt(n,e,t){let i=uP(n.from,n.to);if(i<gr||e.length===0)return[n];let r=t/2,s=e.map(p=>({start:Math.max(0,p-r),end:Math.min(i,p+r)})).filter(p=>p.end-p.start>gr),o=rFt(s),a=[],c=0,l={x:n.to.x-n.from.x,y:n.to.y-n.from.y},u=(p,d,_)=>{if(d-p<=gr)return;let g=p/i,x=d/i;a.push({from:ant(n.from,n.to,g),to:ant(n.from,n.to,x),..._?{is_crossing:!0}:{}})};for(let p of o)p.start-c>gr&&u(c,p.start,!1),u(p.start,p.end,!0),c=p.end;return i-c>gr&&u(c,i,!1),a.length>0?a:[n]}function oFt(n,e={}){let t=e.crossSegmentLength??.075,i=e.tolerance??gr,r=new Map,s=c=>`${c.traceIdx}:${c.edgeIdx}`,o=c=>n[c.traceIdx].edges[c.edgeIdx];for(let c=0;c<n.length;c++){let l=n[c];for(let u=0;u<l.edges.length;u++){let p=l.edges[u];for(let d=c;d<n.length;d++){let _=n[d];for(let g=d===c?u+1:0;g<_.edges.length;g++){let x=_.edges[g],v=iFt(p.from,p.to,x.from,x.to);if(!v)continue;let S=uP(p.from,p.to),P=uP(x.from,x.to);if(S<i||P<i)continue;let T=cnt(p.from,p.to,v),k=cnt(x.from,x.to,v),N=T<=i||Math.abs(S-T)<=i||Number.isNaN(T),E=k<=i||Math.abs(P-k)<=i||Number.isNaN(k);if(!N&&!E){let C=ont(p),M=ont(x),A;if(C!==M)A=C;else{let j=Math.abs(p.to.x-p.from.x),U=Math.abs(p.to.y-p.from.y),X=Math.abs(x.to.x-x.from.x),W=Math.abs(x.to.y-x.from.y),et=j-U,nt=X-W;A=et===nt?!0:et>nt}let R=s({traceIdx:A?c:d,edgeIdx:A?u:g}),B=r.get(R)??[];B.push(A?T:k),r.set(R,B)}}}}}let a=n.map(c=>({source_trace_id:c.source_trace_id,edges:[]}));for(let c=0;c<n.length;c++){let l=n[c];for(let u=0;u<l.edges.length;u++){let p=s({traceIdx:c,edgeIdx:u}),d=r.get(p)??[];if(d.length===0){a[c].edges.push(l.edges[u]);continue}let _=Array.from(new Set(d.map(x=>Number(x.toFixed(6))))).sort((x,v)=>x-v),g=sFt(l.edges[u],_,t);a[c].edges.push(...g)}}return a}var Ko=1e-6;function pP(n,e,t=Ko){return Math.abs(n-e)<=t}function K_(n,e,t=Ko){return pP(n.x,e.x,t)&&pP(n.y,e.y,t)}function lnt(n,e,t,i=Ko){let r=Math.min(e.x,t.x)-i,s=Math.max(e.x,t.x)+i,o=Math.min(e.y,t.y)-i,a=Math.max(e.y,t.y)+i;return n.x<r||n.x>s||n.y<o||n.y>a?!1:Math.abs((t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x))<=i}function unt(n,e=Ko){let t=new Map;for(let i of n){let r=`${i.x.toFixed(6)},${i.y.toFixed(6)}`;t.has(r)||t.set(r,i)}return Array.from(t.values())}function pnt(n){return{x:n.to.x-n.from.x,y:n.to.y-n.from.y}}function d9(n,e,t=Ko){let i=pnt(n),r=pnt(e),s=Math.hypot(i.x,i.y),o=Math.hypot(r.x,r.y);if(s<t||o<t)return!0;let a=i.x*r.y-i.y*r.x;return Math.abs(a)<=t*s*o}function V1(n,e,t=Ko){return n.edges.filter(i=>K_(i.from,e,t)||K_(i.to,e,t))}function hnt(n,e,t=Ko){for(let i of n.edges){if(K_(i.from,e,t))return i.from;if(K_(i.to,e,t))return i.to}return null}function aFt(n,e,t=Ko){let i=K_(n.from,e,t)||pP(n.from.x,e.x,t)&&pP(n.from.y,e.y,t)?n.to:n.from,r=i.x-e.x,s=i.y-e.y;return Math.abs(r)<t&&Math.abs(s)<t?null:Math.abs(r)>=Math.abs(s)?r>=0?"right":"left":s>=0?"up":"down"}function V_(n,e,t=Ko){let i=V1(n,e,t);if(i.length<2)return null;let r=i.map(p=>aFt(p,e,t)),s=r.includes("up"),o=r.includes("down"),a=r.includes("left"),c=r.includes("right"),l=s?"up":o?"down":null,u=c?"right":a?"left":null;return l&&u?`${l}-${u}`:null}function cFt(n,e={}){let t=e.tolerance??Ko,i={};for(let s of n)i[s.source_trace_id]=[];let r=n.map(s=>{let o=[];for(let a of s.edges)o.push(a.from,a.to);return unt(o,t)});for(let s=0;s<n.length;s++){let o=n[s],a=r[s];for(let c=s+1;c<n.length;c++){let l=n[c],u=r[c];for(let p of a)for(let d of u)if(K_(p,d,t)){let _=V1(o,p,t),g=V1(l,d,t),x=_.some(T=>g.some(k=>!d9(T,k,t))),v=V_(o,p,t),S=V_(l,d,t);x&&!(v!==null&&S!==null&&v===S)&&(i[o.source_trace_id].push(p),o.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(d))}for(let p of a)for(let d of l.edges)if(lnt(p,d.from,d.to,t)){let g=V1(o,p,t).some(T=>!d9(T,d,t)),x=V_(o,p,t),v=hnt(l,p,t*1e3),S=v?V_(l,v,t):null;g&&!(x!==null&&S!==null&&x===S)&&(i[o.source_trace_id].push(p),o.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(p))}for(let p of u)for(let d of o.edges)if(lnt(p,d.from,d.to,t)){let g=V1(l,p,t).some(T=>!d9(d,T,t)),x=V_(l,p,t),v=hnt(o,p,t*1e3),S=v?V_(o,v,t):null;g&&!(S!==null&&x!==null&&S===x)&&(i[l.source_trace_id].push(p),o.source_trace_id!==l.source_trace_id&&i[o.source_trace_id].push(p))}}}for(let s of Object.keys(i))i[s]=unt(i[s],t);return i}var f9=(0,Unt.default)("Group_doInitialSchematicTraceRender");function lFt(n){let{group:e,solver:t,pinIdToSchematicPortId:i,userNetIdToSck:r}=n,{db:s}=e.root,o=t.traceCleanupSolver?.getOutput().traces??t.traceLabelOverlapAvoidanceSolver?.getOutput().traces??t.schematicTraceLinesSolver?.solvedTracePaths,a=[];f9(`Traces inside SchematicTraceSolver output: ${(o??[]).length}`);for(let u of o??[]){let p=u?.tracePath;if(!Array.isArray(p)||p.length<2){f9(`Skipping trace ${u?.pinIds.join(",")} because it has less than 2 points`);continue}let d=[];for(let x=0;x<p.length-1;x++)d.push({from:{x:p[x].x,y:p[x].y},to:{x:p[x+1].x,y:p[x+1].y}});let _=null,g;if(Array.isArray(u?.pins)&&u.pins.length===2){let x=i.get(u.pins[0]?.pinId),v=i.get(u.pins[1]?.pinId);if(x&&v){for(let S of[x,v])s.schematic_port.get(S)&&s.schematic_port.update(S,{is_connected:!0});g=r.get(String(u.userNetId))}}_||(_=`solver_${u?.mspPairId}`,g=r.get(String(u.userNetId))),a.push({source_trace_id:_,edges:d,subcircuit_connectivity_map_key:g})}f9(`Applying ${a.length} traces from SchematicTraceSolver output`);let c=oFt(a.map(u=>({source_trace_id:u.source_trace_id,edges:u.edges}))),l=cFt(c);for(let u of c)s.schematic_trace.insert({source_trace_id:u.source_trace_id,edges:u.edges,junctions:l[u.source_trace_id]??[],subcircuit_connectivity_map_key:a.find(p=>p.source_trace_id===u.source_trace_id)?.subcircuit_connectivity_map_key})}var uFt=n=>{switch(n){case"x+":return"left";case"x-":return"right";case"y+":return"bottom";case"y-":return"top";case"left":return"right";case"top":return"bottom";case"right":return"left";case"bottom":return"top"}},pFt=n=>{for(let t of n){let i=t._getDirectlyConnectedTraces();for(let r of i){let s=r._parsedProps.schDisplayLabel;if(s)return{name:s,wasAssignedDisplayLabel:!0}}}return{name:n.map(t=>t._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},m9=(0,Vnt.default)("Group_doInitialSchematicTraceRender");function hFt(n){let{group:e,solver:t,sckToSourceNet:i,allScks:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,userNetIdToSck:a,pinIdToSchematicPortId:c,schematicPortIdsWithPreExistingNetLabels:l,schematicPortIdsWithRoutedTraces:u}=n,{db:p}=e.root,d=t.netLabelPlacementSolver?.netLabelPlacements??t.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],_=t.mspConnectionPairSolver.globalConnMap;for(let g of d){m9(`processing placement: ${g.netId}`);let x=_.getIdsConnectedToNet(g.globalConnNetId).find(R=>a.get(R)),v=a.get(x),S=g.anchorPoint,P=g.orientation,T=uFt(P),k=v?i.get(v):void 0,N=g.pinIds.map(R=>c.get(R));if(N.some(R=>l.has(R))){m9(`skipping net label placement for "${g.netId}" REASON:schematic port has pre-existing net label`);continue}if(k){let R=k.name,B=wl({anchor_position:S,anchor_side:T,text:R});p.schematic_net_label.insert({text:R,anchor_position:S,center:B,anchor_side:T,...k?.source_net_id?{source_net_id:k.source_net_id}:{}});continue}let E=e.selectAll("port").filter(R=>R._getSubcircuitConnectivityKey()===v),{name:C,wasAssignedDisplayLabel:M}=pFt(E);if(!M&&N.some(R=>u.has(R))){m9(`skipping net label placement for "${g.netId}" REASON:schematic port has routed traces and no display label`);continue}let A=wl({anchor_position:S,anchor_side:T,text:C});p.schematic_net_label.insert({text:C,anchor_position:S,center:A,anchor_side:T})}}var dFt=({allSourceAndSchematicPortIdsInScope:n,group:e,schPortIdToSourcePortId:t,sckToSourceNet:i,pinIdToSchematicPortId:r,schematicPortIdsWithPreExistingNetLabels:s})=>{let{db:o}=e.root;for(let a of Array.from(n)){let c=o.schematic_port.get(a);if(!c||c.is_connected)continue;let l=t.get(a);if(!l)continue;let p=o.source_port.get(l)?.subcircuit_connectivity_map_key;if(!p)continue;let d=i.get(p);if(!d||o.schematic_net_label.list().some(S=>Math.abs(S.anchor_position.x-c.center.x)<.1&&Math.abs(S.anchor_position.y-c.center.y)<.1?d.source_net_id&&S.source_net_id?S.source_net_id===d.source_net_id:S.text===(d.name||p):!1))continue;let g=d.name||d.source_net_id||p,x=q1(c.facing_direction||"right")||"right",v=wl({anchor_position:c.center,anchor_side:x,text:g});o.schematic_net_label.insert({text:g,anchor_position:c.center,center:v,anchor_side:x,...d.source_net_id?{source_net_id:d.source_net_id}:{}})}},fFt=n=>{let e=new Set,t=n.selectAll("netlabel");for(let i of t){let r=i._getConnectedPorts();for(let s of r)s.schematic_port_id&&e.add(s.schematic_port_id)}return e},mFt=({solver:n,pinIdToSchematicPortId:e})=>{let t=n.schematicTraceLinesSolver.solvedTracePaths,i=new Set;for(let r of t)for(let s of r.pinIds){let o=e.get(s);o&&i.add(o)}return i},_Ft=(0,Xnt.default)("Group_doInitialSchematicTraceRender"),yFt=n=>{if(!n.root?._featureMspSchematicTraceRouting||!n.isSubcircuit||n.root?.schematicDisabled)return;let{inputProblem:e,pinIdToSchematicPortId:t,pairKeyToSourceTraceId:i,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,displayLabelTraces:a,allScks:c,userNetIdToSck:l}=nFt(n),u=fFt(n);_Ft.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(e,null,2)});let p=new rtt(e);p.solve();let d=mFt({solver:p,pinIdToSchematicPortId:t});lFt({group:n,solver:p,pinIdToSchematicPortId:t,userNetIdToSck:l}),hFt({group:n,solver:p,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,pinIdToSchematicPortId:t,allScks:c,userNetIdToSck:l,schematicPortIdsWithPreExistingNetLabels:u,schematicPortIdsWithRoutedTraces:d}),dFt({group:n,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,sckToSourceNet:r,pinIdToSchematicPortId:t,schematicPortIdsWithPreExistingNetLabels:u})},gFt=()=>({async simulate(n){let e="spice-experiment-1",{circuit:t,tran:i}=ctt(n);return{simulationResultCircuitJson:ltt(i,t,e)}}}),dnt=["rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)"],sP=new Map,oP=0;function xFt(n){if(sP.has(n))return sP.get(n);let e=dnt[oP];return oP=(oP+1)%dnt.length,sP.set(n,e),e}function bFt(){sP.clear(),oP=0}var Va=(0,Gnt.default)("tscircuit:core:Group_doInitialSimulationSpiceEngineRender");function vFt(n){if(!n.isSubcircuit)return;let{root:e}=n;if(!e)return;let t=n.selectAll("analogsimulation");if(t.length===0)return;let i=n.selectAll("voltageprobe");bFt();let r={...e.platform?.spiceEngineMap};r.spicey||(r.spicey=gFt());let s=e.db.toArray(),o,a;try{a=ott(s),o=a.toSpiceString(),Va(`Generated SPICE string:
252
- ${o}`)}catch(c){Va(`Failed to convert circuit JSON to SPICE: ${c}`);return}for(let c of t){let l=c._parsedProps.spiceEngine??"spicey",u=r[l];if(!u)throw new Error(`SPICE engine "${l}" not found in platform config. Available engines: ${JSON.stringify(Object.keys(r).filter(d=>d!=="spicey"))}`);let p=`spice-simulation-${l}-${c.source_component_id}`;Va(`Queueing simulation for spice engine: ${l} (id: ${p})`),n._queueAsyncEffect(p,async()=>{try{Va(`Running simulation with engine: ${l}`);let d=await u.simulate(o);Va(`Simulation completed, received ${d.simulationResultCircuitJson.length} elements`);let _=e.db.simulation_experiment.list()[0];if(!_){Va("No simulation experiment found, skipping result insertion");return}for(let g of d.simulationResultCircuitJson){if(g.type==="simulation_transient_voltage_graph"){g.simulation_experiment_id=_.simulation_experiment_id;let v=i.find(S=>S.finalProbeName===g.name);v&&(g.color=v.color)}let x=g.type;x&&e.db[x]?(e.db[x].insert(g),Va(`Inserted ${x} into database`)):(Va(`Warning: Unknown element type ${x}, adding to raw db`),e.db._addElement(g))}n._markDirty("SimulationSpiceEngineRender")}catch(d){Va(`Simulation failed for engine ${l}: ${d}`);let _=e.db.simulation_experiment.list()[0];e.db.simulation_unknown_experiment_error.insert({simulation_experiment_id:_?.simulation_experiment_id,error_type:"simulation_unknown_experiment_error",message:d instanceof Error?d.message:String(d)})}})}}function wFt(n){if(n.root?.pcbDisabled||!n.pcb_group_id)return;let e=n._parsedProps?.pcbPositionAnchor;if(!e)return;let t=n._getGlobalPcbPositionBeforeLayout(),{pcbX:i,pcbY:r}=n._parsedProps;if(i===void 0&&r===void 0)return;let{db:s}=n.root,o=s.pcb_group.get(n.pcb_group_id);if(!o)return;let a=o.width,c=o.height,{center:l}=o;if(o.outline&&o.outline.length>0){let x=co(o.outline);x&&(a=x.maxX-x.minX,c=x.maxY-x.minY)}if(!a||!c)return;let u={left:l.x-a/2,right:l.x+a/2,top:l.y+c/2,bottom:l.y-c/2},p={...l},d=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(e))switch(e){case"center":d=p;break;case"top_left":d={x:u.left,y:u.top};break;case"top_center":d={x:p.x,y:u.top};break;case"top_right":d={x:u.right,y:u.top};break;case"center_left":d={x:u.left,y:p.y};break;case"center_right":d={x:u.right,y:p.y};break;case"bottom_left":d={x:u.left,y:u.bottom};break;case"bottom_center":d={x:p.x,y:u.bottom};break;case"bottom_right":d={x:u.right,y:u.bottom};break}if(!d)return;let g={...p};t.x!==void 0&&(g.x+=t.x-d.x),t.y!==void 0&&(g.y+=t.y-d.y),(Math.abs(g.x-p.x)>1e-6||Math.abs(g.y-p.y)>1e-6)&&(n._repositionOnPcb(g),s.pcb_group.update(n.pcb_group_id,{center:g})),s.pcb_group.update(n.pcb_group_id,{anchor_position:t,anchor_alignment:e})}var Sl=class extends Bn{constructor(){super(...arguments);f(this,"pcb_group_id",null);f(this,"schematic_group_id",null);f(this,"subcircuit_id",null);f(this,"_hasStartedAsyncAutorouting",!1);f(this,"_asyncAutoroutingResult",null);f(this,"unnamedElementCounter",{})}get config(){return{zodProps:HW,componentName:"Group"}}doInitialSourceGroupRender(){let{db:e}=this.root,t=typeof this._parsedProps.name=="string"&&this._parsedProps.name.length>0,i=e.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit,was_automatically_named:!t});this.source_group_id=i.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${i.source_group_id}`,e.source_group.update(i.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:e}=this.root;for(let t of this.children)e.source_component.update(t.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:e}=this.root,t=this.parent?.getGroup?.();if(t?.source_group_id&&e.source_group.update(this.source_group_id,{parent_source_group_id:t.source_group_id}),!this.isSubcircuit)return;let i=this.parent?.getSubcircuit?.()?.subcircuit_id;i&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:i})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=t,r=i.outline&&i.outline.length>0,s=r?i.outline.map(a=>({x:V.parse(a.x),y:V.parse(a.y)})):void 0,o=e.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,center:this._getGlobalPcbPositionBeforeLayout(),...r?{outline:s}:{width:0,height:0},pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:t.autorouter?{trace_clearance:t.autorouter.traceClearance}:void 0});this.pcb_group_id=o.pcb_group_id;for(let a of this.children)e.pcb_component.update(a.pcb_component_id,{pcb_group_id:o.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps,i=t.outline&&t.outline.length>0;if(this.pcb_group_id){let r=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0;if(i){let p=t.outline.map(v=>({x:V.parse(v.x),y:V.parse(v.y)})),d=co(p);if(!d)return;let _=(d.minX+d.maxX)/2,g=(d.minY+d.maxY)/2,x=r?e.pcb_group.get(this.pcb_group_id)?.center??{x:_,y:g}:{x:_,y:g};e.pcb_group.update(this.pcb_group_id,{center:x});return}let s=mP(this.children),o=s.width,a=s.height,c=(s.minX+s.maxX)/2,l=(s.minY+s.maxY)/2;if(this.isSubcircuit){let{padLeft:p,padRight:d,padTop:_,padBottom:g}=this._resolvePcbPadding();o+=p+d,a+=_+g,c+=(d-p)/2,l+=(_-g)/2}let u=r?e.pcb_group.get(this.pcb_group_id)?.center??{x:c,y:l}:{x:c,y:l};e.pcb_group.update(this.pcb_group_id,{width:Number(t.width??o),height:Number(t.height??a),center:u})}}getNextAvailableName(e){var t,i;return(t=this.unnamedElementCounter)[i=e.lowercaseComponentName]??(t[i]=1),`unnamed_${e.lowercaseComponentName}${this.unnamedElementCounter[e.lowercaseComponentName]++}`}_resolvePcbPadding(){let e=this._parsedProps,t=e.pcbLayout,i=p=>{let d=t?.[p],_=e[p];if(typeof d=="number")return d;if(typeof _=="number")return _},r=i("padding")??0,s=i("paddingX"),o=i("paddingY"),a=i("paddingLeft")??s??r,c=i("paddingRight")??s??r,l=i("paddingTop")??o??r,u=i("paddingBottom")??o??r;return{padLeft:a,padRight:c,padTop:l,padBottom:u}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:e}=this,{db:t}=this.root,i=e;if(!this.isSubcircuit)return;let r=i.manualEdits?.manual_trace_hints;if(r)for(let s of r)this.add(new R9({for:s.pcb_port_selector,offsets:s.offsets}))}doInitialSourceAddConnectivityMapKey(){L7t(this)}_areChildSubcircuitsRouted(){let e=this.selectAll("group").filter(t=>t.isSubcircuit);for(let t of e)if(t._shouldRouteAsync()&&!t._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let e=this._getAutorouterConfig();return e.groupMode==="sequential-trace"?!1:!!(e.local&&e.groupMode==="subcircuit"||!e.local)}_hasTracesToRoute(){let e=(0,G_.default)("tscircuit:core:_hasTracesToRoute"),t=this.selectAll("trace");return e(`[${this.getString()}] has ${t.length} traces to route`),t.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:e}=this.root,t=(0,G_.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),i=this._parsedProps,r=this._getAutorouterConfig(),s=r.serverUrl,o=r.serverMode,a=(u,p)=>(t("fetching",u),p.headers&&(p.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(u,p)),c=this.root.db.toArray().filter(u=>u.type.startsWith("source_")||u.type.startsWith("pcb_"));if(o==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:p}=await a(`${s}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:P9({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(d=>d.json());this._asyncAutoroutingResult=p,this._markDirty("PcbTraceRender");return}let{autorouting_result:u}=await a(`${s}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:c,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(p=>p.json());this._asyncAutoroutingResult=u,this._markDirty("PcbTraceRender");return}let{autorouting_job:l}=await a(`${s}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:c,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:r.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(u=>u.json());for(;;){let{autorouting_job:u}=await a(`${s}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(p=>p.json());if(u.is_finished){let{autorouting_job_output:p}=await a(`${s}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(d=>d.json());this._asyncAutoroutingResult={output_pcb_traces:p.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(u.has_error){let p=new X1(`Autorouting job failed: ${JSON.stringify(u.error)}`);throw e.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,error_type:"pcb_autorouting_error",message:p.message}),p}await new Promise(p=>setTimeout(p,100))}}async _runLocalAutorouting(){let{db:e}=this.root,t=this._parsedProps,i=(0,G_.default)("tscircuit:core:_runLocalAutorouting");i(`[${this.getString()}] starting local autorouting`);let r=this._getAutorouterConfig(),s=this._isLaserPrefabAutorouter(r),{simpleRouteJson:o}=P9({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(i.enabled&&global.debugOutputArray?.push({name:`simpleroutejson-${this.props.name}.json`,obj:o}),i.enabled){let l=Kg(o);l.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(l)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:o});let a;r.algorithmFn?a=await r.algorithmFn(o):a=new T7t(o,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity,useAssignableViaSolver:s});let c=new Promise((l,u)=>{a.on("complete",p=>{i(`[${this.getString()}] local autorouting complete`),l(p.traces)}),a.on("error",p=>{i(`[${this.getString()}] local autorouting error: ${p.error.message}`),u(p.error)})});a.on("progress",l=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...l})}),a.start();try{let l=await c;this._asyncAutoroutingResult={output_pcb_traces:l},this._markDirty("PcbTraceRender")}catch(l){let{db:u}=this.root;throw u.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:l instanceof Error?l.message:String(l)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:l instanceof Error?l.message:String(l)},simpleRouteJson:o}),l}finally{a.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let e=(0,G_.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){e(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}e(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){yFt(this)}updatePcbTraceRender(){let e=(0,G_.default)("tscircuit:core:updatePcbTraceRender");if(e(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(e(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:t}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){e(`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){e(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:e}=this.root,{traces:t}=this._asyncAutoroutingResult.output_simple_route_json;if(t)for(let i of t){let r=e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;let{db:t}=this.root,i=this.getInheritedMergedProperty("pcbStyle"),{holeDiameter:r,padDiameter:s}=A9(i);for(let o of e)if(o.type==="pcb_trace"){if(o.subcircuit_id=this.subcircuit_id,o.connection_name){let a=o.connection_name;o.source_trace_id=a}t.pcb_trace.insert(o)}for(let o of e)if(o.type!=="pcb_via"&&o.type==="pcb_trace")for(let a of o.route)a.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:o.pcb_trace_id,x:a.x,y:a.y,hole_diameter:r,outer_diameter:s,layers:[a.from_layer,a.to_layer],from_layer:a.from_layer,to_layer:a.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=e.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=i.schematic_group_id;for(let r of this.children)r.schematic_component_id&&e.schematic_component.update(r.schematic_component_id,{schematic_group_id:i.schematic_group_id})}_getSchematicLayoutMode(){let e=this._parsedProps;if(e.schLayout?.layoutMode==="none"||e.schLayout?.layoutMode==="relative")return"relative";if(e.schLayout?.matchAdapt)return"match-adapt";if(e.schLayout?.flex)return"flex";if(e.schLayout?.grid)return"grid";if(e.schMatchAdapt)return"match-adapt";if(e.schFlex)return"flex";if(e.schGrid)return"grid";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";if(e.relative||e.schRelative)return"relative";let t=this.children.some(r=>{let s=r._parsedProps;return s?.schX!==void 0||s?.schY!==void 0}),i=(e.manualEdits?.schematic_placements?.length??0)>0;return!t&&!i?"match-adapt":"relative"}doInitialSchematicLayout(){let e=this._getSchematicLayoutMode();e==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),e==="grid"&&this._doInitialSchematicLayoutGrid(),e==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){A7t(this)}_doInitialSchematicLayoutMatchpack(){O7t(this)}_doInitialSchematicLayoutGrid(){F7t(this)}_doInitialSchematicLayoutFlex(){$7t(this)}_getPcbLayoutMode(){let e=this._parsedProps;if(e.pcbRelative)return"none";if(e.pcbLayout?.matchAdapt)return"match-adapt";if(e.pcbLayout?.flex)return"flex";if(e.pcbLayout?.grid)return"grid";if(e.pcbLayout?.pack)return"pack";if(e.pcbFlex)return"flex";if(e.pcbGrid)return"grid";if(e.pcbPack||e.pack)return"pack";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";let t=e.pcbX!==void 0||e.pcbY!==void 0,i=(e.manualEdits?.pcb_placements?.length??0)>0,r=this.children.reduce((s,o)=>{if(!o.pcb_component_id&&!o.pcb_group_id)return s;let a=o._parsedProps,c=a?.pcbX!==void 0||a?.pcbY!==void 0;return s+(c?0:1)},0);return!t&&!i&&r>1?"pack":"none"}doInitialPcbLayout(){let e=this._getPcbLayoutMode();e==="grid"?this._doInitialPcbLayoutGrid():e==="pack"?this._doInitialPcbLayoutPack():e==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){z7t(this)}_doInitialPcbLayoutPack(){tFt(this)}_doInitialPcbLayoutFlex(){eFt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!t.border)return;let i=typeof t.schWidth=="number"?t.schWidth:void 0,r=typeof t.schHeight=="number"?t.schHeight:void 0,s=typeof t.schPadding=="number"?t.schPadding:0,o=typeof t.schPaddingLeft=="number"?t.schPaddingLeft:s,a=typeof t.schPaddingRight=="number"?t.schPaddingRight:s,c=typeof t.schPaddingTop=="number"?t.schPaddingTop:s,l=typeof t.schPaddingBottom=="number"?t.schPaddingBottom:s,u=this.schematic_group_id?e.schematic_group.get(this.schematic_group_id):null;if(u&&(i===void 0&&typeof u.width=="number"&&(i=u.width),r===void 0&&typeof u.height=="number"&&(r=u.height)),i===void 0||r===void 0)return;let p=u?.center??this._getGlobalSchematicPositionBeforeLayout(),d=p.x-i/2-o,_=p.y-r/2-l,g=i+o+a,x=r+c+l;e.schematic_box.insert({width:g,height:x,x:d,y:_,is_dashed:t.border?.dashed??!1})}_determineSideFromPosition(e,t){if(!e.center||!t.center)return"left";let i=e.center.x-t.center.x,r=e.center.y-t.center.y;return Math.abs(i)>Math.abs(r)?i>0?"right":"left":r>0?"bottom":"top"}_calculateSchematicBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let a of e)t=Math.min(t,a.centerX),i=Math.max(i,a.centerX),r=Math.min(r,a.centerY),s=Math.max(s,a.centerY);let o=2;return{minX:t-o,maxX:i+o,minY:r-o,maxY:s+o}}_getAutorouterConfig(){let e=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return H7t(e)}_isLaserPrefabAutorouter(e=this._getAutorouterConfig()){let t=this.props.autorouter,i=r=>r?.replace(/-/g,"_")??r;return e.preset==="laser_prefab"?!0:typeof t=="string"?i(t)==="laser_prefab":typeof t=="object"&&t?i(t.preset)==="laser_prefab":!1}_getSubcircuitLayerCount(){let e=this.getInheritedProperty("layers");return typeof e=="number"?e:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(this.isSubcircuit){let t=new Map;for(let i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){let r=t.get(i._parsedProps.name)||[];r.push(i),t.set(i._parsedProps.name,r)}for(let[i,r]of t.entries())r.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:r.map(s=>s.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:e}=this.root,t=e;for(let i of t.schematic_net_label.list()){let r=t.source_net.get(i.source_net_id),s=i.text||r?.name||"";if(i.anchor_side==="top"&&/^gnd/i.test(s)){t.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_down"});continue}i.anchor_side==="bottom"&&/^v/i.test(s)&&t.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_up"})}}doInitialSimulationSpiceEngineRender(){vFt(this)}doInitialPcbComponentAnchorAlignment(){wFt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(e){return super._repositionOnPcb(e)}};function SFt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e;if(i.lowercaseComponentName==="board"||i.parent?.lowercaseComponentName==="board")return;let s=t.pcb_board.list(),o=s.length>0?s[0]:null,a={name:n.title||"inflated_board"};o&&(o.width&&(a.width=o.width),o.height&&(a.height=o.height),o.center&&(a.pcbX=o.center.x,a.pcbY=o.center.y),o.outline&&(a.outline=o.outline),o.thickness&&(a.thickness=o.thickness),o.material&&(a.material=o.material));let c=new gP(a);return c.source_board_id=n.source_board_id,n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(c):i.add(c),c}var PFt=new Proxy({},{get:(n,e)=>e}),Ha=PFt,_P="rgba(132, 0, 0)",yP=.12,L9=class extends Bn{constructor(){super(...arguments);f(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:oH,sourceFtype:Ha.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let e=this.props.capacitance,t=typeof e=="string"?e:`${xi(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${t}/${xi(this._parsedProps.maxVoltageRating)}V`:t}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new zs({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new zs({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,capacitance:t.capacitance,max_voltage_rating:t.maxVoltageRating,max_decoupling_trace_length:t.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!t.polarized});this.source_component_id=i.source_component_id}},J_=(n,e)=>{let{injectionDb:t,normalComponent:i}=e;if(!i)return;let r=n.center||{x:0,y:0},s=n.rotation||0,o=$3(ii(kn(r.x,r.y),Oo(s*Math.PI/180))),a=t.toArray().filter(u=>"pcb_component_id"in u&&u.pcb_component_id===n.pcb_component_id),c=structuredClone(a);tl(c,o);let l=q_({componentName:i.name,componentRotation:"0deg"},c);i.addAll(l)};function kFt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new L9({name:n.name,capacitance:n.capacitance,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&J_(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var Z1=class extends Bn{constructor(e){super(e);f(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:o_,shouldRenderAsSchematicBox:!0}}initPorts(e={}){super.initPorts(e);let{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp();if(t.externallyConnectedPins){let s=new Set;for(let[o,a]of t.externallyConnectedPins)s.add(o),s.add(a);for(let o of s)if(!this.children.find(c=>c instanceof Wi&&c.isMatchingAnyOf([o]))){let c=o.match(/^pin(\d+)$/);if(c){let l=parseInt(c[1]);this.add(new Wi({pinNumber:l,aliases:[o]}))}else this.add(new Wi({name:o,aliases:[o]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:e}=this;e?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=t.layer??"top";if(s!=="top"&&s!=="bottom"){let a=this.getSubcircuit(),c=zm.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${s}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:s,subcircuit_id:a.subcircuit_id??void 0});e.pcb_component_invalid_layer_error.insert(c)}let o=e.pcb_component.insert({center:{x:i,y:r},width:2,height:3,layer:s==="top"||s==="bottom"?s:"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=o.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:e}=this;if(e.externallyConnectedPins)for(let[t,i]of e.externallyConnectedPins)this.add(new zs({from:`${this.getSubcircuitSelector()} > port.${t}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:e}=this.root,{pinAttributes:t}=this.props;if(!t)return;let i=null,r=null,s,o=this.selectAll("port");for(let p of o)for(let d of p.getNameAndAliases())if(t[d]){let _=t[d];_.providesPower&&(i=p,s=_.providesVoltage),_.providesGround&&(r=p)}if(!i||!r||s===void 0)return;let a=e.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=e.source_port.get(r.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=e.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=e.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||e.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:r.source_port_id,negative_source_net_id:u.source_net_id,voltage:s})}},TFt=(n,e)=>{if(!n||n.length===0)return;let{injectionDb:t}=e,i=n.map(r=>r.map(s=>{let o=t.source_port.get(s);return o?o.pin_number!==void 0&&o.pin_number!==null?`pin${o.pin_number}`:o.name:null}).filter(s=>s!==null)).filter(r=>r.length>0);return i.length>0?i:void 0},EFt=(n,e)=>{let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.schematic_component.getWhere({source_component_id:n.source_component_id}),a=t.cad_component.getWhere({source_component_id:n.source_component_id}),c=TFt(n.internally_connected_source_port_ids,e),l=new Z1({name:n.name,manufacturerPartNumber:n.manufacturer_part_number,supplierPartNumbers:n.supplier_part_numbers??void 0,pinLabels:o?.port_labels??void 0,schWidth:o?.size?.width,schHeight:o?.size?.height,schPinSpacing:o?.pin_spacing,schX:o?.center?.x,schY:o?.center?.y,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds,internallyConnectedPins:c}),u=a?.footprinter_string??null;u&&(Object.assign(l.props,{footprint:u}),Object.assign(l._parsedProps,{footprint:u}),a||l._addChildrenFromStringFootprint?.()),s&&J_(s,{...e,normalComponent:l}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(l):i.add(l)},F9=class extends Bn{constructor(){super(...arguments);f(this,"pos",this.portMap.pin1);f(this,"anode",this.portMap.pin1);f(this,"neg",this.portMap.pin2);f(this,"cathode",this.portMap.pin2)}get config(){let e={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},t=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:t?e[t]:this.props.symbolName??"diode",componentName:"Diode",zodProps:SH,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}};function MFt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new F9({name:n.name,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&J_(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}function CFt(n,e){let{subcircuit:t,groupsMap:i}=e,r=new Sl({name:n.name??`inflated_group_${n.source_group_id}`});return r.source_group_id=n.source_group_id,i&&i.set(n.source_group_id,r),n.parent_source_group_id&&i?.has(n.parent_source_group_id)?i.get(n.parent_source_group_id).add(r):t.add(r),r}var $9=class extends Bn{constructor(){super(...arguments);f(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:wH,sourceFtype:Ha.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${xi(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({name:this.name,ftype:Ha.simple_inductor,inductance:t.inductance,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function IFt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new $9({name:n.name,inductance:n.inductance,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&J_(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}function NFt(n,e){let{injectionDb:t,subcircuit:i}=e;if(n.source_component_id!==null)return;let r=t.pcb_port.getWhere({source_port_id:n.source_port_id}),s=new Wi({name:n.name,pinNumber:n.pin_number});i.add(s),s.source_port_id=n.source_port_id;let o=i.root;if(o&&r){let{db:a}=o,c=a.pcb_port.insert({pcb_component_id:void 0,layers:r.layers,subcircuit_id:i.subcircuit_id??void 0,pcb_group_id:i.getGroup()?.pcb_group_id??void 0,x:r.x,y:r.y,source_port_id:n.source_port_id,is_board_pinout:!1});s.pcb_port_id=c.pcb_port_id}}var z9=class extends Bn{constructor(){super(...arguments);f(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:eH,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${xi(this._parsedProps.resistance)}\u03A9`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,this.props.pulldownFor,this.props.pulldownTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new zs({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new zs({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new zs({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new zs({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,resistance:t.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function AFt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new z9({name:n.name,resistance:n.resistance,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&J_(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var RFt=(n,e)=>{let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=[],o=n.source_group_id;for(;o&&o!==i.source_group_id;){let a=t.source_group.get(o),c=r?.get(o);if(!a||!c)break;let l=c.props.name??c.fallbackUnassignedName;s.unshift(`.${l}`),o=a.parent_source_group_id}return s.push(`.${n.name}`),s.join(" > ")};function OFt(n,e){let{injectionDb:t,subcircuit:i}=e,r=[];for(let o of n.connected_source_port_ids){let a=t.source_port.get(o);if(!a)continue;let c;if(a.source_component_id){let l=t.source_component.get(a.source_component_id);l&&(c=`${RFt({name:l.name,source_group_id:l.source_group_id},e)} > .${a.name}`)}else c=`.${a.name}`;c&&r.push(c)}for(let o of n.connected_source_net_ids){let a=t.source_net.get(o);a&&r.push(`net.${a.name}`)}if(r.length<2)return;let s=new zs({path:r});s.source_trace_id=n.source_trace_id,i.add(s)}var D9=class extends Bn{constructor(){super(...arguments);f(this,"emitter",this.portMap.pin1);f(this,"collector",this.portMap.pin2);f(this,"base",this.portMap.pin3)}get config(){let e=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??e,zodProps:bH,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let e={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:e})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:t.type});this.source_component_id=i.source_component_id}};function LFt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new D9({name:n.name,type:n.transistor_type,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&J_(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var Wnt=(n,e,t)=>{if(!e)return;let i=Ke(e);if(e&&t?.length>0)throw new Error("Component cannot have both circuitJson and children");let s={injectionDb:i,subcircuit:n,groupsMap:new Map},o=i.source_group.list();for(let p of o)CFt(p,s);let a=i.source_board.list();for(let p of a)SFt(p,s);let c=i.source_component.list();for(let p of c)switch(p.ftype){case"simple_resistor":AFt(p,s);break;case"simple_capacitor":kFt(p,s);break;case"simple_inductor":IFt(p,s);break;case"simple_diode":MFt(p,s);break;case"simple_chip":EFt(p,s);break;case"simple_transistor":LFt(p,s);break;default:throw new Error(`No inflator implemented for source component ftype: "${p.ftype}"`)}let l=i.source_port.list();for(let p of l)NFt(p,s);let u=i.source_trace.list();for(let p of u)OFt(p,s)},FFt=.01,fnt=(n,e,t)=>{let i=n/2,r=e/2,s=Math.min(t,i,r);if(s<FFt)return[{x:-i,y:-r},{x:i,y:-r},{x:i,y:r},{x:-i,y:r}];let a=Math.max(1,Math.ceil(Math.PI/2*s/.1)),c=Math.PI/2/a,l=[];l.push({x:-i+s,y:-r}),l.push({x:i-s,y:-r});for(let u=1;u<=a;u++){let p=-Math.PI/2+u*c;l.push({x:i-s+s*Math.cos(p),y:-r+s+s*Math.sin(p)})}l.push({x:i,y:r-s});for(let u=1;u<=a;u++){let p=0+u*c;l.push({x:i-s+s*Math.cos(p),y:r-s+s*Math.sin(p)})}l.push({x:-i+s,y:r});for(let u=1;u<=a;u++){let p=Math.PI/2+u*c;l.push({x:-i+s+s*Math.cos(p),y:r-s+s*Math.sin(p)})}l.push({x:-i,y:-r+s});for(let u=1;u<=a;u++){let p=Math.PI+u*c;l.push({x:-i+s+s*Math.cos(p),y:-r+s+s*Math.sin(p)})}return l},gP=class extends Sl{constructor(){super(...arguments);f(this,"pcb_board_id",null);f(this,"source_board_id",null);f(this,"_drcChecksComplete",!1);f(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:T4}}get boardThickness(){let{_parsedProps:e}=this,t=this._resolvePcbCoordinate(e.pcbX,"pcbX",{allowBoardVariables:!1}),i=this._resolvePcbCoordinate(e.pcbY,"pcbY",{allowBoardVariables:!1});return e.thickness??1.4}get allLayers(){return(this._parsedProps.layers??2)===4?["top","bottom","inner1","inner2"]:["top","bottom"]}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}_getBoardCalcVariables(){let{_parsedProps:e}=this;if((e.width==null||e.height==null)&&!e.outline)return{};let i=this.pcb_board_id?this.root?.db.pcb_board.get(this.pcb_board_id):null,r=i?.width??e.width,s=i?.height??e.height;if((r==null||s==null)&&e.outline?.length){let p=co(e.outline);p&&(r??(r=p.maxX-p.minX),s??(s=p.maxY-p.minY))}let{pcbX:o,pcbY:a}=this.getResolvedPcbPositionProp(),c=i?.center??{x:o+(e.outlineOffsetX??0),y:a+(e.outlineOffsetY??0)},l=r??0,u=s??0;return{"board.minx":c.x-l/2,"board.maxx":c.x+l/2,"board.miny":c.y-u/2,"board.maxy":c.y+u/2}}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._resolvePcbCoordinate(t.pcbX,"pcbX",{allowBoardVariables:!1}),r=this._resolvePcbCoordinate(t.pcbY,"pcbY",{allowBoardVariables:!1}),s=e.pcb_board.get(this.pcb_board_id);if(s?.width&&s?.height||s?.outline&&s.outline.length>0)return;let o=1/0,a=1/0,c=-1/0,l=-1/0,u=Dnt(e,this.subcircuit_id),p=new Set([this.subcircuit_id,...u]),d=e.pcb_component.list().filter(M=>M.subcircuit_id&&p.has(M.subcircuit_id)),_=e.pcb_group.list().filter(M=>M.subcircuit_id&&p.has(M.subcircuit_id)),g=!1,x=(M,A,R)=>{A===0||R===0||(g=!0,o=Math.min(o,M.x-A/2),a=Math.min(a,M.y-R/2),c=Math.max(c,M.x+A/2),l=Math.max(l,M.y+R/2))};for(let M of d)x(M.center,M.width,M.height);for(let M of _){let A=M.width??0,R=M.height??0;if(M.outline&&M.outline.length>0){let B=co(M.outline);B&&(A=B.maxX-B.minX,R=B.maxY-B.minY)}x(M.center,A,R)}if(t.boardAnchorPosition){let{x:M,y:A}=t.boardAnchorPosition;o=Math.min(o,M),a=Math.min(a,A),c=Math.max(c,M),l=Math.max(l,A)}let v=2,S=g?c-o+v*2:0,P=g?l-a+v*2:0,T={x:g?(o+c)/2+(t.outlineOffsetX??0):(t.outlineOffsetX??0)+i,y:g?(a+l)/2+(t.outlineOffsetY??0):(t.outlineOffsetY??0)+r},k=t.width??S,N=t.height??P,E=t.outline;!E&&t.borderRadius!=null&&k>0&&N>0&&(E=fnt(k,N,t.borderRadius));let C={width:k,height:N,center:T};E&&(C.outline=E.map(M=>({x:M.x+(t.outlineOffsetX??0),y:M.y+(t.outlineOffsetY??0)}))),e.pcb_board.update(this.pcb_board_id,C)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let e=this.root?.platform;if(!e?.printBoardInformationToSilkscreen)return;let t=this.root.db.pcb_board.get(this.pcb_board_id);if(!t)return;let i=[];if(e.projectName&&i.push(e.projectName),e.version&&i.push(`v${e.version}`),e.url&&i.push(e.url),i.length===0)return;let r=i.join(`
253
- `),a={x:t.center.x+t.width/2-.25,y:t.center.y-t.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:r,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialSourceRender(){super.doInitialSourceRender();let{db:e}=this.root,t=e.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=t.source_board_id}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:e,children:t}=this._parsedProps;Wnt(this,e,t)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,r=t.circuitJson?.find(g=>g.type==="pcb_board"),s=t.width??r?.width??0,o=t.height??r?.height??0,{pcbX:a,pcbY:c}=this.getResolvedPcbPositionProp(),l={x:a+(t.outlineOffsetX??0),y:c+(t.outlineOffsetY??0)},{boardAnchorPosition:u,boardAnchorAlignment:p}=t;if(u&&(l=k7t({boardAnchorPosition:u,boardAnchorAlignment:p??"center",width:s,height:o})),t.outline){let g=t.outline.map(k=>k.x),x=t.outline.map(k=>k.y),v=Math.min(...g),S=Math.max(...g),P=Math.min(...x),T=Math.max(...x);s=S-v,o=T-P,l={x:(v+S)/2+(t.outlineOffsetX??0),y:(P+T)/2+(t.outlineOffsetY??0)}}let d=t.outline;!d&&t.borderRadius!=null&&s>0&&o>0&&(d=fnt(s,o,t.borderRadius));let _=e.pcb_board.insert({center:l,thickness:this.boardThickness,num_layers:this.allLayers.length,width:s,height:o,outline:d?.map(g=>({x:g.x+(t.outlineOffsetX??0),y:g.y+(t.outlineOffsetY??0)})),material:t.material});this.pcb_board_id=_.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:e}=this.root;this.pcb_board_id&&(e.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let t=dtt(e.toArray());for(let u of t)e.pcb_trace_error.insert(u);let i=htt(e.toArray());for(let u of i)e.pcb_port_not_connected_error.insert(u);let r=_tt(e.toArray());for(let u of r)e.pcb_component_outside_board_error.insert(u);let s=xtt(e.toArray());for(let u of s)e.pcb_trace_error.insert(u);let o=gtt(e.toArray());for(let u of o)e.pcb_via_clearance_error.insert(u);let a=ytt(e.toArray());for(let u of a)e.pcb_via_clearance_error.insert(u);let c=btt(e.toArray());for(let u of c)e.pcb_footprint_overlap_error.insert(u);let l=vtt(e.toArray());for(let u of l)e.source_pin_must_be_connected_error.insert(u)}_emitRenderLifecycleEvent(e,t){super._emitRenderLifecycleEvent(e,t),t==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e})}},mnt=5,$Ft=5,_nt=2;function zFt(n,e){let t=n.center.x-n.width/2,i=n.center.x+n.width/2,r=n.center.y-n.height/2,s=n.center.y+n.height/2,o=e.center.x-e.width/2,a=e.center.x+e.width/2,c=e.center.y-e.height/2,l=e.center.y+e.height/2;return!(i<=o||t>=a||s<=c||r>=l)}function DFt(n,e,t){let i=t.center.x-t.width/2,r=t.center.x+t.width/2,s=t.center.y-t.height/2,o=t.center.y+t.height/2,a=Math.max(i,Math.min(n.x,r)),c=Math.max(s,Math.min(n.y,o)),l=n.x-a,u=n.y-c;return l*l+u*u<=e*e}function jFt({board:n,edge:e,otherBoards:t,options:i}){let r=[];if(!n.width||!n.height)return r;let s=n.center.x-n.width/2,o=n.center.x+n.width/2,a=n.center.y-n.height/2,c=n.center.y+n.height/2,l,u,p;e==="top"||e==="bottom"?(l=n.width,u=!0,p=e==="top"?c:a):(l=n.height,u=!1,p=e==="right"?o:s);let d=i.tabLength,_=i.boardGap;if(i.mouseBites){let P=i.tabWidth*.45,T=P*.1,k=Math.max(2,Math.ceil(i.tabLength/2));_=(k*P+(k-1)*T)*1.1}let g=Math.floor((l-_)/(d+_));if(g<1&&l>=d&&(g=1),g===0)return r;let x=_,v=-l/2,S=l/2;for(let P=0;P<g;P++){let T=v+x+P*(d+x)+d/2,k=P===0,N=P===g-1,E=k||N,C=T-d/2,M=T+d/2;if(E&&(k&&(C=v),N&&(M=S)),C=Math.max(C,v),M=Math.min(M,S),E&&(k&&(C-=i.tabWidth),N&&(M+=i.tabWidth)),M<=C)continue;let A=(C+M)/2,R=M-C,B=e==="top"||e==="right"?i.tabWidth/2:-i.tabWidth/2,j=u?{x:n.center.x+A,y:p+B}:{x:p+B,y:n.center.y+A},U=u?R:i.tabWidth,X=u?i.tabWidth:R,W={center:j,width:U,height:X,boardId:`${n.center.x}_${n.center.y}`},et=!1;for(let nt of t){if(!nt.width||!nt.height)continue;let mt={center:nt.center,width:nt.width,height:nt.height};if(zFt(W,mt)){et=!0;break}}et&&!E||r.push(W)}return r}function BFt({board:n,edge:e,edgeTabs:t,allBoards:i,options:r}){let s=[];if(t.length===0||!n.width||!n.height)return s;let o=n.center.x-n.width/2,a=n.center.x+n.width/2,c=n.center.y-n.height/2,l=n.center.y+n.height/2,u=e==="top"||e==="bottom",p=r.tabWidth*.45,d=p*.1,_=Math.max(2,Math.ceil(r.tabLength/2)),g,x=p/2;e==="top"?g=l:e==="bottom"?g=c:e==="right"?g=a:g=o;let v=[...t].sort((S,P)=>u?S.center.x-P.center.x:S.center.y-P.center.y);for(let S=0;S<v.length-1;S++){let P=v[S],T=v[S+1],k,N;u?(k=P.center.x+P.width/2,N=T.center.x-T.width/2):(k=P.center.y+P.height/2,N=T.center.y-T.height/2);let E=N-k,C=_*p,M=(_-1)*d;if(E<C+M)continue;let A=(k+N)/2;for(let R=0;R<_;R++){let B=(R-(_-1)/2)*(p+d),j=u?{x:A+B,y:g}:{x:g,y:A+B},U=p/2,X=!1;for(let W of i){if(!W.width||!W.height)continue;let et={center:W.center,width:W.width,height:W.height};if(DFt(j,U,et)){X=!0;break}}X||s.push(j)}}return s}function YFt(n,e){let t=[],i=[];for(let a=0;a<n.length;a++){let c=n[a],l=n.filter((u,p)=>p!==a);for(let u of["top","bottom","left","right"]){let p=jFt({board:c,edge:u,otherBoards:l,options:e});if(t.push(...p),e.mouseBites){let d=BFt({board:c,edge:u,edgeTabs:p,allBoards:l,options:e});i.push(...d)}}}let r=t.map((a,c)=>{let l=Math.min(a.width,a.height);return{type:"pcb_cutout",pcb_cutout_id:`panel_tab_${c}`,shape:"rect",center:a.center,width:a.width,height:a.height,corner_radius:l/2}}),s=e.tabWidth*.45,o=i.map((a,c)=>({type:"pcb_hole",pcb_hole_id:`panel_mouse_bite_${c}`,hole_shape:"circle",hole_diameter:s,x:a.x,y:a.y}));return{tabCutouts:r,mouseBiteHoles:o}}var Hnt=class extends Sl{constructor(){super(...arguments);f(this,"pcb_panel_id",null);f(this,"_tabsAndMouseBitesGenerated",!1)}get config(){return{componentName:"Panel",zodProps:qW}}get isGroup(){return!0}get isSubcircuit(){return!0}add(e){if(e.lowercaseComponentName!=="board")throw new Error("<panel> can only contain <board> elements");super.add(e)}doInitialPanelLayout(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.children.filter(a=>a instanceof gP),i=t.some(a=>a.props.pcbX!==void 0||a.props.pcbY!==void 0),r=t.filter(a=>a.props.pcbX===void 0&&a.props.pcbY===void 0);if(r.length>0&&!i){let a=this._parsedProps.tabWidth??_nt,c=this._parsedProps.boardGap??a,l=Math.ceil(Math.sqrt(r.length)),u=Math.ceil(r.length/l),p=Array(l).fill(0),d=Array(u).fill(0);r.forEach((A,R)=>{let B=R%l,j=Math.floor(R/l),U=e.pcb_board.get(A.pcb_board_id);!U||U.width===void 0||U.height===void 0||(p[B]=Math.max(p[B],U.width),d[j]=Math.max(d[j],U.height))});let _=p.reduce((A,R)=>A+R,0)+(l>1?(l-1)*c:0),g=d.reduce((A,R)=>A+R,0)+(u>1?(u-1)*c:0),x=-_/2,S=[-g/2];for(let A=0;A<u-1;A++)S.push(S[A]+d[A]+c);let P=[x];for(let A=0;A<l-1;A++)P.push(P[A]+p[A]+c);r.forEach((A,R)=>{let B=R%l,j=Math.floor(R/l),U=e.pcb_board.get(A.pcb_board_id);if(!U||!U.width||!U.height)return;let X=P[B]+p[B]/2,W=S[j]+d[j]/2;A._repositionOnPcb({x:X,y:W}),e.pcb_board.update(A.pcb_board_id,{center:{x:X,y:W}})});let T=t.map(A=>A.pcb_board_id).filter(A=>!!A),k=e.pcb_board.list().filter(A=>T.includes(A.pcb_board_id)),N=1/0,E=1/0,C=-1/0,M=-1/0;for(let A of k){if(A.width===void 0||A.height===void 0||!isFinite(A.width)||!isFinite(A.height))continue;let R=A.center.x-A.width/2,B=A.center.x+A.width/2,j=A.center.y-A.height/2,U=A.center.y+A.height/2;N=Math.min(N,R),C=Math.max(C,B),E=Math.min(E,j),M=Math.max(M,U)}if(isFinite(N)){let A=C-N,R=M-E,B=A+2*mnt,j=R+2*mnt;e.pcb_panel.update(this.pcb_panel_id,{width:B,height:j})}}if(this._tabsAndMouseBitesGenerated)return;let s=this._parsedProps;if((s.panelizationMethod??"tab-routing")!=="none"){let a=t.map(_=>_.pcb_board_id).filter(_=>!!_),c=e.pcb_board.list().filter(_=>a.includes(_.pcb_board_id));if(c.length===0)return;let l=s.tabWidth??_nt,u=s.boardGap??l,{tabCutouts:p,mouseBiteHoles:d}=YFt(c,{boardGap:u,tabWidth:l,tabLength:s.tabLength??$Ft,mouseBites:s.mouseBites??!0});for(let _ of p)e.pcb_cutout.insert(_);for(let _ of d)e.pcb_hole.insert(_)}this._tabsAndMouseBitesGenerated=!0}runRenderCycle(){if(!this.children.some(e=>e.componentName==="Board"))throw new Error("<panel> must contain at least one <board>");super.runRenderCycle()}doInitialPcbComponentRender(){if(super.doInitialPcbComponentRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps,i=e.pcb_panel.insert({width:V.parse(t.width),height:V.parse(t.height),center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(t.noSolderMask??!1)});this.pcb_panel_id=i.pcb_panel_id}updatePcbComponentRender(){if(this.root?.pcbDisabled||!this.pcb_panel_id)return;let{db:e}=this.root,t=this._parsedProps;e.pcb_panel.update(this.pcb_panel_id,{width:V.parse(t.width),height:V.parse(t.height),center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(t.noSolderMask??!1)})}removePcbComponentRender(){this.pcb_panel_id&&(this.root?.db.pcb_panel.delete(this.pcb_panel_id),this.pcb_panel_id=null)}},qnt=class extends Z1{constructor(n){super(n)}get config(){return{...super.config,componentName:"Pinout",zodProps:ZW}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:e.manufacturerPartNumber,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=t.source_component_id}},Znt=class extends Bn{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:QW,sourceFtype:Ha.simple_fuse}}_getSchematicSymbolDisplayValue(){let n=this._parsedProps.currentRating,e=this._parsedProps.voltageRating,t=typeof n=="string"?parseFloat(n):n,i=typeof e=="string"?parseFloat(e):e;return`${xi(t)}A / ${xi(i)}V`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=typeof e.currentRating=="string"?parseFloat(e.currentRating):e.currentRating,i=typeof e.voltageRating=="string"?parseFloat(e.voltageRating):e.voltageRating,r=n.source_component.insert({name:this.name,ftype:Ha.simple_fuse,current_rating_amps:t,voltage_rating_volts:i,display_current_rating:`${xi(t)}A`,display_voltage_rating:`${xi(i)}V`});this.source_component_id=r.source_component_id}},Knt=class extends Bn{constructor(){super(...arguments);f(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:E4,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let t=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?t:0,rightSize:i==="right"?t:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.pcb_component.insert({center:{x:i,y:r},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let o=0;o<t.length;o++){let a=t[o],c=e.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(p=>/^(pin)?\d+$/.test(p));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),s=o=>{if(o&&typeof o=="string"&&o.startsWith("{PIN")){let a=o.replace("{PIN","").replace("}","");return i[a]||o}return o};for(let o of r)if(o.route)for(let a of o.route)a.route_type==="wire"&&(a.start_pcb_port_id=s(a.start_pcb_port_id),a.end_pcb_port_id=s(a.end_pcb_port_id))}},XFt={"0603":"0603","0805":"0805",1206:"1206"},Jnt=class extends Bn{get config(){return{componentName:"Interconnect",zodProps:JW,shouldRenderAsSchematicBox:!0,sourceFtype:"interconnect"}}_getImpliedFootprintString(){let{standard:n}=this._parsedProps;return n?XFt[n]??null:null}doInitialSourceRender(){let{db:n}=this.root,e=n.source_component.insert({ftype:"interconnect",name:this.name,are_pins_interchangeable:!0});this.source_component_id=e.source_component_id}},Qnt=class extends Bn{constructor(){super(...arguments);f(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(e){return this.selectOne(`port.${e}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let e=this.children.filter(t=>t.componentName==="Port").map(t=>t.name);return e.length>0?[e]:[]}return this._parsedProps.bridgedPins??[]}get config(){let e=this._parsedProps??this.props,t=e.pinCount;if(e.pinCount==null&&!e.footprint&&(t=2),e.pinCount==null){let s=(e.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),o=s.length>0?Math.max(...s):0,a=e.pinLabels?Object.keys(e.pinLabels).length:0,c=Math.max(o,a);(c===2||c===3)&&(t=c),t==null&&e.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(t=this.getPortsFromFootprint().length)}let i="";t?i+=`solderjumper${t}`:i="solderjumper";let r=[];return Array.isArray(e.bridgedPins)&&e.bridgedPins.length>0?r=Array.from(new Set(e.bridgedPins.flat().map(s=>this._getPinNumberFromBridgedPinName(s)).filter(s=>s!==null))).sort((s,o)=>s-o):e.bridged&&t&&(r=Array.from({length:t},(s,o)=>o+1)),r.length>0&&(i+=`_bridged${r.join("")}`),{schematicSymbolName:e.symbolName??i,componentName:"SolderJumper",zodProps:KW,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let t=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);t==null&&!this._parsedProps.footprint&&(t=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?t:0,rightSize:i==="right"?t:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.pcb_component.insert({center:{x:i,y:r},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let o=0;o<t.length;o++){let a=t[o],c=e.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(p=>/^(pin)?\d+$/.test(p));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),s=o=>{if(o&&typeof o=="string"&&o.startsWith("{PIN")){let a=o.replace("{PIN","").replace("}","");return i[a]||o}return o};for(let o of r)if(o.route)for(let a of o.route)a.route_type==="wire"&&(a.start_pcb_port_id=s(a.start_pcb_port_id),a.end_pcb_port_id=s(a.end_pcb_port_id))}},tit=class extends Bn{constructor(){super(...arguments);f(this,"pos",this.portMap.pin1);f(this,"anode",this.portMap.pin1);f(this,"neg",this.portMap.pin2);f(this,"cathode",this.portMap.pin2)}get config(){let e={laser:"laser_diode"},t=this.props.laser?"laser":null;return{schematicSymbolName:t?e[t]:this.props.symbolName??"led",componentName:"Led",zodProps:kH,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}getFootprinterString(){let e=super.getFootprinterString();return e&&this.props.color?`${e}_color(${this.props.color})`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_led",name:this.name,wave_length:t.wavelength,color:t.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},eit=class extends Bn{constructor(){super(...arguments);f(this,"pos",this.portMap.pin1);f(this,"positive",this.portMap.pin1);f(this,"neg",this.portMap.pin2);f(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:DH,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Wi({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Wi({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:t.voltage,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},nit=class extends Bn{constructor(){super(...arguments);f(this,"terminal1",this.portMap.terminal1);f(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:jH,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(e){if(!e.startsWith("Pcb"))for(let t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:t.voltage,frequency:t.frequency,peak_to_peak_voltage:t.peakToPeakVoltage,wave_shape:t.waveShape,phase:t.phase,duty_cycle:t.dutyCycle,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=this.portMap.terminal1,r=this.portMap.terminal2;e.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:r.source_port_id,voltage:t.voltage,frequency:t.frequency,peak_to_peak_voltage:t.peakToPeakVoltage,wave_shape:t.waveShape,phase:t.phase,duty_cycle:t.dutyCycle})}},UFt=["leftedge","rightedge","topedge","bottomedge","center"],iit=class extends Me{get config(){return{componentName:"Constraint",zodProps:cH}}constructor(n){if(super(n),("xdist"in n||"ydist"in n)&&!("edgeToEdge"in n)&&!("centerToCenter"in n))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in n&&n.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let n=[],e=this.getPrimitiveContainer();function t(i){let r=i.split(" ").pop(),s=UFt.includes(r)?r:void 0,o=s?i.replace(` ${s}`,""):i,a=e.selectOne(o,{pcbPrimitive:!0});a&&n.push({selector:i,component:a,componentSelector:o,edge:s})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&t(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)t(i);return{componentsWithSelectors:n}}},rit=class extends Me{constructor(){super(...arguments);f(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:CH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),o=s(t.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for FabricationNoteRect. Must be "top" or "bottom".`);let a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=this.getSubcircuit(),l=t.hasStroke??(t.strokeWidth!==void 0&&t.strokeWidth!==null),u=e.pcb_fabrication_note_rect.insert({pcb_component_id:a,layer:o,color:t.color,center:{x:i,y:r},width:t.width,height:t.height,stroke_width:t.strokeWidth??1,is_filled:t.isFilled??!1,has_stroke:l,is_stroke_dashed:t.isStrokeDashed??!1,subcircuit_id:c?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,corner_radius:t.cornerRadius??void 0});this.fabrication_note_rect_id=u.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},sit=class extends Me{constructor(){super(...arguments);f(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:IH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.getSubcircuit(),{_parsedProps:i}=this,r=i.layer??"top";if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let s=this._computePcbGlobalTransformBeforeLayout(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=e.pcb_fabrication_note_path.insert({pcb_component_id:o,layer:r,color:i.color,route:i.route.map(c=>{let l=De(s,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:t?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},oit=class extends Me{get config(){return{componentName:"FabricationNoteText",zodProps:MH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:n}=this.root,{_parsedProps:e}=this,{pcbX:t,pcbY:i}=this.getResolvedPcbPositionProp(),r=this.getPrimitiveContainer(),s=this.getSubcircuit();n.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:t,y:i},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:dP(e.text??""),pcb_component_id:r.pcb_component_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},ait=class extends Me{constructor(){super(...arguments);f(this,"fabrication_note_dimension_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:NH}}_resolvePoint(e,t){if(typeof e=="string"){let s=this.getSubcircuit().selectOne(e);return s?s._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${e}"`),De(t,{x:0,y:0}))}let i=typeof e.x=="string"?parseFloat(e.x):e.x,r=typeof e.y=="string"?parseFloat(e.y):e.y;return De(t,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(t.from,i),s=this._resolvePoint(t.to,i),o=this.getSubcircuit(),a=this.getGroup(),{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),l=c(t.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for FabricationNoteDimension. Must be "top" or "bottom".`);let u=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,p=t.text??this._formatDistanceText({from:r,to:s,units:t.units??"mm"}),d=e.pcb_fabrication_note_dimension.insert({pcb_component_id:u,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,layer:l,from:r,to:s,text:p,offset:t.offset,font:t.font??"tscircuit2024",font_size:t.fontSize??1,color:t.color,arrow_size:t.arrowSize??1});this.fabrication_note_dimension_id=d.pcb_fabrication_note_dimension_id}getPcbSize(){let e=this._computePcbGlobalTransformBeforeLayout(),t=this._resolvePoint(this._parsedProps.from,e),i=this._resolvePoint(this._parsedProps.to,e);return{width:Math.abs(i.x-t.x),height:Math.abs(i.y-t.y)}}_formatDistanceText({from:e,to:t,units:i}){let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s),a=i==="in"?o/25.4:o,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},cit=class extends Me{constructor(){super(...arguments);f(this,"pcb_note_line_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:oq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=this.getGroup(),s=this._computePcbGlobalTransformBeforeLayout(),o=De(s,{x:t.x1,y:t.y1}),a=De(s,{x:t.x2,y:t.y2}),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=e.pcb_note_line.insert({pcb_component_id:c,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,x1:o.x,y1:o.y,x2:a.x,y2:a.y,stroke_width:t.strokeWidth??.1,color:t.color,is_dashed:t.isDashed});this.pcb_note_line_id=l.pcb_note_line_id}getPcbSize(){let{_parsedProps:e}=this;return{width:Math.abs(e.x2-e.x1),height:Math.abs(e.y2-e.y1)}}},lit=class extends Me{constructor(){super(...arguments);f(this,"pcb_note_rect_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:rq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=De(i,{x:0,y:0}),s=this.getSubcircuit(),o=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=e.pcb_note_rect.insert({pcb_component_id:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,center:r,width:t.width,height:t.height,stroke_width:t.strokeWidth??.1,is_filled:t.isFilled??!1,has_stroke:t.hasStroke??!0,is_stroke_dashed:t.isStrokeDashed??!1,color:t.color,corner_radius:t.cornerRadius??void 0});this.pcb_note_rect_id=c.pcb_note_rect_id}getPcbSize(){let{_parsedProps:e}=this,t=typeof e.width=="string"?parseFloat(e.width):e.width,i=typeof e.height=="string"?parseFloat(e.height):e.height;return{width:t,height:i}}},uit=class extends Me{constructor(){super(...arguments);f(this,"pcb_note_text_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:iq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=De(i,{x:0,y:0}),s=this.getSubcircuit(),o=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=e.pcb_note_text.insert({pcb_component_id:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,font:t.font??"tscircuit2024",font_size:t.fontSize??1,text:dP(t.text),anchor_position:r,anchor_alignment:t.anchorAlignment??"center",color:t.color});this.pcb_note_text_id=c.pcb_note_text_id}getPcbSize(){let{_parsedProps:e}=this,t=typeof e.fontSize=="string"?parseFloat(e.fontSize):e.fontSize??1,i=t*.6;return{width:e.text.length*i,height:t}}},pit=class extends Me{constructor(){super(...arguments);f(this,"pcb_note_path_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:sq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this.getSubcircuit(),s=this.getGroup(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=t.route.map(l=>{let{x:u,y:p,...d}=l,_=typeof u=="string"?parseFloat(u):u,g=typeof p=="string"?parseFloat(p):p,x=De(i,{x:_,y:g});return{...d,x:x.x,y:x.y}}),c=e.pcb_note_path.insert({pcb_component_id:o,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,route:a,stroke_width:t.strokeWidth??.1,color:t.color});this.pcb_note_path_id=c.pcb_note_path_id}getPcbSize(){let{_parsedProps:e}=this;if(e.route.length===0)return{width:0,height:0};let t=e.route.map(c=>typeof c.x=="string"?parseFloat(c.x):c.x),i=e.route.map(c=>typeof c.y=="string"?parseFloat(c.y):c.y),r=Math.min(...t),s=Math.max(...t),o=Math.min(...i),a=Math.max(...i);return{width:s-r,height:a-o}}},hit=class extends Me{constructor(){super(...arguments);f(this,"pcb_note_dimension_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:aq}}_resolvePoint(e,t){if(typeof e=="string"){let s=this.getSubcircuit().selectOne(`.${e}`);return s?s._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${e}"`),De(t,{x:0,y:0}))}let i=typeof e.x=="string"?parseFloat(e.x):e.x,r=typeof e.y=="string"?parseFloat(e.y):e.y;return De(t,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(t.from,i),s=this._resolvePoint(t.to,i),o=this.getSubcircuit(),a=this.getGroup(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.text??this._formatDistanceText({from:r,to:s,units:t.units??"mm"}),u=e.pcb_note_dimension.insert({pcb_component_id:c,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,from:r,to:s,text:l,font:t.font??"tscircuit2024",font_size:t.fontSize??1,color:t.color,arrow_size:t.arrowSize??1});this.pcb_note_dimension_id=u.pcb_note_dimension_id}getPcbSize(){let e=this._computePcbGlobalTransformBeforeLayout(),t=this._resolvePoint(this._parsedProps.from,e),i=this._resolvePoint(this._parsedProps.to,e);return{width:Math.abs(i.x-t.x),height:Math.abs(i.y-t.y)}}_formatDistanceText({from:e,to:t,units:i}){let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s),a=i==="in"?o/25.4:o,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},dit=class extends Sl{constructor(n){super({...n,subcircuit:!0})}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:n,children:e}=this._parsedProps;Wnt(this,n,e)}},fit=class extends Sl{constructor(n){super({...n,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:n}=this.root,e=this._parsedProps;if(!this.pcb_group_id)return;let t=n.pcb_group.get(this.pcb_group_id),i=e.paddingLeft??e.padding??0,r=e.paddingRight??e.padding??0,s=e.paddingTop??e.padding??0,o=e.paddingBottom??e.padding??0;n.pcb_group.update(this.pcb_group_id,{width:(t.width??0)+i+r,height:(t.height??0)+s+o,center:{x:t.center.x+(r-i)/2,y:t.center.y+(s-o)/2}})}},mit=class extends Me{constructor(){super(...arguments);f(this,"pcb_breakout_point_id",null);f(this,"matchedPort",null);f(this,"matchedNet",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:OH}}_matchConnection(){let{connection:e}=this._parsedProps,t=this.getSubcircuit();t&&(this.matchedPort=t.selectOne(e,{type:"port"}),this.matchedPort||(this.matchedNet=t.selectOne(e,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${e}"`))}_getSourceTraceIdForPort(e){let{db:t}=this.root;return t.source_trace.list().find(r=>r.connected_source_port_ids.includes(e.source_port_id))?.source_trace_id}_getSourceNetIdForPort(e){let{db:t}=this.root;return t.source_trace.list().find(r=>r.connected_source_port_ids.includes(e.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;this._matchConnection();let{pcbX:t,pcbY:i}=this.getResolvedPcbPositionProp(),r=this.parent?.getGroup(),s=this.getSubcircuit();if(!r||!r.pcb_group_id)return;let o=e.pcb_breakout_point.insert({pcb_group_id:r.pcb_group_id,subcircuit_id:s?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:t,y:i});this.pcb_breakout_point_id=o.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:e,pcbY:t}=this.getResolvedPcbPositionProp();return{center:{x:e,y:t},bounds:{left:e,top:t,right:e,bottom:t},width:0,height:0}}_setPositionFromLayout(e){let{db:t}=this.root;this.pcb_breakout_point_id&&t.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:e.x,y:e.y})}getPcbSize(){return{width:0,height:0}}},_it=class extends Me{constructor(){super(...arguments);f(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:yH}}_getAnchorSide(){let{_parsedProps:e}=this;if(e.anchorSide)return e.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getConnectedPorts();if(r.length===0)return"right";let s=r[0]._getGlobalSchematicPositionBeforeLayout(),o=s.x-i.x,a=s.y-i.y;if(Math.abs(o)>Math.abs(a)){if(o>0)return"right";if(o<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let e=this._resolveConnectsTo();if(!e)return[];let t=[];for(let i of e){let r=this.getSubcircuit().selectOne(i);r&&t.push(r)}return t}computeSchematicPropsTransform(){let{_parsedProps:e}=this;if(e.schX===void 0&&e.schY===void 0){let t=this._getConnectedPorts();if(t.length>0){let i=t[0]._getGlobalSchematicPositionBeforeLayout(),r=De(this.parent?.computeSchematicGlobalTransform?.()??Pr(),{x:0,y:0});return kn(i.x-r.x,i.y-r.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),s=t.anchorSide??"right",o=wl({anchor_position:i,anchor_side:s,text:t.net}),a=e.schematic_net_label.insert({text:t.net,source_net_id:r.source_net_id,anchor_position:i,center:o,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:e}=this,t=e.connectsTo??e.connection;if(Array.isArray(t))return t;if(typeof t=="string")return[t]}_getNetName(){let{_parsedProps:e}=this;return e.net}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;e.net&&hP(this,[`net.${e.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let e=this._resolveConnectsTo();if(e)for(let t of e)this.add(new zs({from:t,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:e}=this.root,t=this._resolveConnectsTo();if(!t||t.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getAnchorSide(),o={left:"x-",right:"x+",top:"y+",bottom:"y-"}[r],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of t){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let S=e.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id??""));if(S&&(u=e.schematic_trace.list().some(P=>P.source_trace_id===S.source_trace_id)),u)continue}let p=l._getGlobalSchematicPositionAfterLayout(),d=x9(l.facingDirection??"right")??"x+",_=Qc({x:p.x,y:p.y,facingDirection:d},{x:i.x,y:i.y,facingDirection:o});if(!Array.isArray(_)||_.length<2)continue;let g=[];for(let S=0;S<_.length-1;S++)g.push({from:{x:_[S].x,y:_[S].y},to:{x:_[S+1].x,y:_[S+1].y}});let x,v;if(a?.source_net_id&&l.source_port_id){let S=e.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id));x=S?.source_trace_id,v=S?.subcircuit_connectivity_map_key||e.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}e.schematic_trace.insert({source_trace_id:x,edges:g,junctions:[],subcircuit_connectivity_map_key:v}),e.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},yit=class extends Me{constructor(){super(...arguments);f(this,"pcb_silkscreen_circle_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:eq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),o=s(t.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenCircle. Must be "top" or "bottom".`);let a=this._computePcbGlobalTransformBeforeLayout(),c=this.getSubcircuit(),l=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,u=e.pcb_silkscreen_circle.insert({pcb_component_id:l,layer:o,center:{x:i,y:r},radius:t.radius,subcircuit_id:c?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_circle_id=u.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:e}=this,t=e.radius*2;return{width:t,height:t}}},git=class extends Me{constructor(){super(...arguments);f(this,"pcb_silkscreen_rect_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:tq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenRect. Must be "top" or "bottom".`);let s=this.getSubcircuit(),{pcbX:o,pcbY:a}=this.getResolvedPcbPositionProp(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,l=e.pcb_silkscreen_rect.insert({pcb_component_id:c,layer:r,center:{x:o,y:a},width:t.width,height:t.height,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:t.strokeWidth??.1,is_filled:t.filled??!1,corner_radius:t.cornerRadius??void 0});this.pcb_silkscreen_rect_id=l.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},xit=class extends Me{constructor(){super(...arguments);f(this,"pcb_silkscreen_line_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:QH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenLine. Must be "top" or "bottom".`);let s=this.getSubcircuit(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=e.pcb_silkscreen_line.insert({pcb_component_id:o,layer:r,x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,stroke_width:t.strokeWidth??.1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:s?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:e}=this,t=Math.abs(e.x2-e.x1),i=Math.abs(e.y2-e.y1);return{width:t,height:i}}},bit=class extends Me{constructor(e){super(e);f(this,"pcb_via_id",null);f(this,"matchedPort",null);f(this,"isPcbPrimitive",!0);f(this,"source_manually_placed_via_id",null);f(this,"subcircuit_connectivity_map_key",null);let t=this._getLayers();this._parsedProps.layers=t,this.initPorts()}get config(){return{componentName:"Via",zodProps:AH}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}_getResolvedViaDiameters(e){return o7t({holeDiameter:this._parsedProps.holeDiameter,padDiameter:this._parsedProps.outerDiameter},e)}getPcbSize(){let e=this.getInheritedMergedProperty("pcbStyle"),{padDiameter:t}=this._getResolvedViaDiameters(e);return{width:t,height:t}}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-i.width/2,top:t.y-i.height/2,right:t.x+i.width/2,bottom:t.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}_getLayers(){let{fromLayer:e="top",toLayer:t="bottom"}=this._parsedProps;return e===t?[e]:[e,t]}initPorts(){let e=this._parsedProps.layers;for(let i of e){let r=new Wi({name:i,layer:i});r.registerMatch(this),this.add(r)}let t=new Wi({name:"pin1"});t.registerMatch(this),this.add(t)}_getConnectedNetOrTrace(){let e=this._parsedProps.connectsTo;if(!e)return null;let t=this.getSubcircuit(),i=Array.isArray(e)?e:[e];for(let r of i)if(r.startsWith("net.")){let s=t.selectOne(r,{type:"net"});if(s)return s}return null}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.getInheritedMergedProperty("pcbStyle"),{padDiameter:i}=this._getResolvedViaDiameters(t),r=this._getGlobalPcbPositionBeforeLayout(),s=this.getSubcircuit(),o=e.pcb_component.insert({center:r,width:i,height:i,layer:this._parsedProps.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:s?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=o.pcb_component_id}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=this.getGroup(),r=this.getSubcircuit(),s=e.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:t.net??"",subcircuit_id:r?.subcircuit_id??void 0});this.source_component_id=s.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.getInheritedMergedProperty("pcbStyle"),{holeDiameter:i,padDiameter:r}=this._getResolvedViaDiameters(t),s=this._getGlobalPcbPositionBeforeLayout(),o=this.getSubcircuit(),a=e.pcb_via.insert({x:s.x,y:s.y,hole_diameter:i,outer_diameter:r,layers:["bottom","top"],from_layer:this._parsedProps.fromLayer||"bottom",to_layer:this._parsedProps.toLayer||"top",subcircuit_id:o?.subcircuit_id??void 0,subcircuit_connectivity_map_key:this.subcircuit_connectivity_map_key??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,net_is_assignable:this._parsedProps.netIsAssignable??void 0});this.pcb_via_id=a.pcb_via_id}},vit=class extends Me{constructor(){super(...arguments);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:FH}}getPcbSize(){return{width:0,height:0}}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;hP(this,[e.connectsTo])}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit().selectOne(t.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${t.connectsTo}" not found for copper pour`);return}let r=this.getSubcircuit(),s=e.toArray().filter(p=>p.type==="source_net"&&p.name===i.name)[0]||"",o=t.clearance??.2,a=Ptt(e.toArray(),{layer:t.layer,pour_connectivity_key:s.subcircuit_connectivity_map_key||"",pad_margin:t.padMargin??o,trace_margin:t.traceMargin??o,board_edge_margin:t.boardEdgeMargin??o,cutout_margin:t.cutoutMargin??o}),c=new Stt(a),{brep_shapes:l}=c.getOutput(),u=t.coveredWithSolderMask??!1;for(let p of l)e.pcb_copper_pour.insert({shape:"brep",layer:t.layer,brep_shape:p,source_net_id:i.source_net_id,subcircuit_id:r?.subcircuit_id??void 0,covered_with_solder_mask:u})})}},wit=class extends Bn{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:mH,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=t.source_component_id}},Sit=class extends Bn{_getPcbRotationBeforeLayout(){let n=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+n}get config(){return{componentName:"PinHeader",zodProps:_H,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),e=this._parsedProps.holeDiameter,t=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,r=this._parsedProps.showSilkscreenPinLabels,s=this._parsedProps.doubleRow?2:1;if(n>0){let o;if(i)!e&&!t?o=`pinrow${n}_p${i}`:o=`pinrow${n}_p${i}_id${e}_od${t}`;else if(!e&&!t)o=`pinrow${n}`;else return null;return r!==!0&&(o+="_nopinlabels"),s>1&&(o+=`_rows${s}`),o}return null}initPorts(){let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let e=1;e<=n;e++){let t=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[e-1]:this._parsedProps.pinLabels?.[`pin${e}`];if(t){let i=Array.isArray(t)?t[0]:t,r=Array.isArray(t)?t.slice(1):[];this.add(new Wi({pinNumber:e,name:i,aliases:[`pin${e}`,...r]}))}else this.add(new Wi({pinNumber:e,name:`pin${e}`}))}}_getSchematicPortArrangement(){let n=this._parsedProps.pinCount??1,e=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",t=this._parsedProps.schPinArrangement;return e==="left"?{leftSide:{direction:t?.leftSide?.direction??"top-to-bottom",pins:t?.leftSide?.pins??Array.from({length:n},(i,r)=>`pin${r+1}`)}}:{rightSide:{direction:t?.rightSide?.direction??"top-to-bottom",pins:t?.rightSide?.pins??Array.from({length:n},(i,r)=>`pin${r+1}`)}}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:e.supplierPartNumbers,pin_count:e.pinCount,gender:e.gender,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}};function VFt(n){switch(n){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var Pit=class extends Bn{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??VFt(this.props.pinVariant),zodProps:sH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"no_ground",i=n.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:t,are_pins_interchangeable:t==="no_ground"||t==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let n=`${xi(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${xi(this._parsedProps.loadCapacitance)}F`:n}};function GFt(n){switch(n){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var kit=class extends Bn{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??GFt(this.props.pinVariant),zodProps:iH,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${xi(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"two_pin",i=n.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:e.maxResistance,pin_variant:t,are_pins_interchangeable:t==="two_pin"});this.source_component_id=i.source_component_id}},Tit=class extends Bn{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:gH,sourceFtype:Ha.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let n=yi[this._getSchematicSymbolNameOrThrow()],e=n.ports.find(l=>l.labels.includes("1")),t=n.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),r=i.find(l=>l.props.pinNumber===1),s=i.find(l=>l.props.pinNumber===2),o=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;r.schematicSymbolPortDef=e,(!c||c.length===0)&&(s.schematicSymbolPortDef=t);for(let[l,u]of[[2,s],[3,o],[4,a]]){let p=c?.find(([_,g])=>_===`pin${l}`||g===`pin${l}`);if(!p){u.schematicSymbolPortDef=t;break}(p?.[0]===`pin${l}`?p[1]:p?.[0])!=="pin1"&&(u.schematicSymbolPortDef=t)}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:Ha.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}},Eit=class extends Bn{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:rH,sourceFtype:"simple_crystal"}}initPorts(){let n=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:n})}_getSchematicSymbolDisplayValue(){let n=`${xi(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${xi(this._parsedProps.loadCapacitance)}F`:n}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:e.frequency,load_capacitance:e.loadCapacitance,pin_variant:e.pinVariant||"two_pin",are_pins_interchangeable:(e.pinVariant||"two_pin")==="two_pin"});this.source_component_id=t.source_component_id}},Mit=class extends Bn{get config(){let n=this.props.mosfetMode==="depletion"?"d":"e",t=`${this.props.channelType}_channel_${n}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??t,zodProps:vH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=t.source_component_id}};function WFt(n){return n.simSwitchFrequency!==void 0||n.simCloseAt!==void 0||n.simOpenAt!==void 0||n.simStartClosed!==void 0||n.simStartOpen!==void 0}var Cit=class extends Bn{_getSwitchType(){let n=this._parsedProps;return n?n.dpdt?"dpdt":n.spst?"spst":n.spdt?"spdt":n.dpst?"dpst":n.type??"spst":"spst"}get config(){let n=this._getSwitchType(),e=this._parsedProps?.isNormallyClosed??!1,t={spst:e?"spst_normally_closed_switch":"spst_switch",spdt:e?"spdt_normally_closed_switch":"spdt_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??t[n],zodProps:EH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,e=this._parsedProps??{},t=n.source_component.insert({ftype:"simple_switch",name:this.name,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=t.source_component_id}doInitialSimulationRender(){let{_parsedProps:n}=this;if(!WFt(n))return;let{db:e}=this.root,t={type:"simulation_switch",source_component_id:this.source_component_id||""};n.simSwitchFrequency!==void 0&&(t.switching_frequency=zr.parse(n.simSwitchFrequency)),n.simCloseAt!==void 0&&(t.closes_at=hr.parse(n.simCloseAt)),n.simOpenAt!==void 0&&(t.opens_at=hr.parse(n.simOpenAt)),n.simStartOpen!==void 0&&(t.starts_closed=!n.simStartOpen),n.simStartClosed!==void 0&&(t.starts_closed=n.simStartClosed),e.simulation_switch.insert(t)}},_9={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},Iit=class extends Bn{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:RH,sourceFtype:Ha.simple_test_point}}_getPropsWithDefaults(){let{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}=this._parsedProps;return!t&&e&&(t="through_hole"),t??(t="through_hole"),n??(n="circle"),t==="pad"?n==="circle"?i??(i=_9.SMT_CIRCLE_DIAMETER):n==="rect"&&(r??(r=_9.SMT_RECT_SIZE),s??(s=r)):t==="through_hole"&&(e??(e=_9.HOLE_DIAMETER)),{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}}_getImpliedFootprintString(){let{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}=this._getPropsWithDefaults();if(t==="through_hole")return`platedhole_d${e}`;if(t==="pad"){if(n==="circle")return`smtpad_circle_d${i}`;if(n==="rect")return`smtpad_rect_w${r}_h${s}`}throw new Error(`Footprint variant "${t}" with pad shape "${n}" not implemented`)}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,{padShape:t,holeDiameter:i,footprintVariant:r,padDiameter:s,width:o,height:a}=this._getPropsWithDefaults(),c=n.source_component.insert({ftype:Ha.simple_test_point,name:this.name,supplier_part_numbers:e.supplierPartNumbers,footprint_variant:r,pad_shape:t,pad_diameter:s,hole_diameter:i,width:o,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},Nit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:WH}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout();e.schematic_text.insert({anchor:t.anchor??"center",text:dP(t.text),font_size:t.fontSize,color:t.color||"#000000",position:{x:i.x,y:i.y},rotation:t.schRotation??0})}},Ait=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:GH}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_line.insert({schematic_component_id:r,x1:t.x1+i.x,y1:t.y1+i.y,x2:t.x2+i.x,y2:t.y2+i.y,stroke_width:t.strokeWidth??yP,color:t.color??_P,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=s.schematic_line_id}},Rit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:VH}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_rect.insert({center:{x:i.x,y:i.y},width:t.width,height:t.height,stroke_width:t.strokeWidth??yP,color:t.color??_P,is_filled:t.isFilled,schematic_component_id:r,is_dashed:t.isDashed,rotation:t.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=s.schematic_rect_id}},Oit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:YH}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_arc.insert({schematic_component_id:r,center:{x:t.center.x+i.x,y:t.center.y+i.y},radius:t.radius,start_angle_degrees:t.startAngleDegrees,end_angle_degrees:t.endAngleDegrees,direction:t.direction,stroke_width:t.strokeWidth??yP,color:t.color??_P,is_dashed:t.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=s.schematic_arc_id}},Lit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:UH}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_circle.insert({schematic_component_id:r,center:{x:t.center.x+i.x,y:t.center.y+i.y},radius:t.radius,stroke_width:t.strokeWidth??yP,color:t.color??_P,is_filled:t.isFilled,fill_color:t.fillColor,is_dashed:t.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=s.schematic_circle_id}};function HFt({anchor:n,x:e,y:t,width:i,height:r,isInside:s}){switch(n){case"top_left":return{x:e,y:t+r,textAnchor:s?"top_left":"bottom_left"};case"top_center":return{x:e+i/2,y:t+r,textAnchor:s?"top_center":"bottom_center"};case"top_right":return{x:e+i,y:t+r,textAnchor:s?"top_right":"bottom_right"};case"center_left":return{x:e,y:t+r/2,textAnchor:s?"center_left":"center_right"};case"center":return{x:e+i/2,y:t+r/2,textAnchor:"center"};case"center_right":return{x:e+i,y:t+r/2,textAnchor:s?"center_right":"center_left"};case"bottom_left":return{x:e,y:t,textAnchor:s?"bottom_left":"top_left"};case"bottom_center":return{x:e+i/2,y:t,textAnchor:s?"bottom_center":"top_center"};case"bottom_right":return{x:e+i,y:t,textAnchor:s?"bottom_right":"top_right"};default:return{x:e+i/2,y:t+r,textAnchor:"center"}}}var Fit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:XH,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=.6,r=typeof t.padding=="number"?t.padding:0,s=typeof t.paddingTop=="number"?t.paddingTop:r,o=typeof t.paddingBottom=="number"?t.paddingBottom:r,a=typeof t.paddingLeft=="number"?t.paddingLeft:r,c=typeof t.paddingRight=="number"?t.paddingRight:r,l=t.overlay&&t.overlay.length>0,u=typeof t.width=="number"&&typeof t.height=="number",p,d,_,g,x,v;if(l){let P=t.overlay.map(J=>({selector:J,port:this.getSubcircuit().selectOne(J,{type:"port"})})).filter(({port:J})=>J!=null).map(({port:J})=>({position:J._getGlobalSchematicPositionAfterLayout()}));if(P.length===0)return;let T=P.map(J=>J.position.x),k=P.map(J=>J.position.y),N=Math.min(...T),E=Math.max(...T),C=Math.min(...k),M=Math.max(...k),A=E-N,R=M-C,B=A===0?i:0,j=R===0?i:0,U=a+B/2,X=c+B/2,W=s+j/2,et=o+j/2,nt=N-U,mt=E+X,G=C-et,tt=M+W;p=mt-nt,d=tt-G,_=nt+(t.schX??0),g=G+(t.schY??0),x=_+p/2,v=g+d/2}else if(u){p=t.width,d=t.height;let S=this._getGlobalSchematicPositionBeforeLayout();x=S.x,v=S.y,_=x-p/2,g=v-d/2}else return;if(e.schematic_box.insert({height:d,width:p,x:_,y:g,is_dashed:t.strokeStyle==="dashed"}),t.title){let S=t.titleInside,P=.1,T=t.titleAlignment,k=HFt({anchor:T,x:_,y:g,width:p,height:d,isInside:S}),N,E,C=k.textAnchor;S?(N=T.includes("top")?-P:T.includes("bottom")?P:0,E=T.includes("left")?P:T.includes("right")?-P:0):(N=T.includes("top")?P:T.includes("bottom")?-P:0,E=T.includes("center_left")?-P:T.includes("center_right")?P:0);let M=k.x+E,A=k.y+N;e.schematic_text.insert({anchor:C,text:t.title,font_size:t.titleFontSize??.18,color:t.titleColor??"#000000",position:{x:M,y:A},rotation:0})}}},$it=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:HH}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.children.filter(d=>d.componentName==="SchematicRow");if(i.length===0)return;let r=[],s=0;for(let d of i){let _=d.children.filter(g=>g.componentName==="SchematicCell");s=Math.max(s,_.length)}for(let d=0;d<i.length;d++)r[d]=[];for(let d=0;d<i.length;d++){let g=i[d].children.filter(v=>v.componentName==="SchematicCell"),x=0;for(let v=0;v<g.length;v++){for(;r[d][x];)x++;let S=g[v],P=S._parsedProps.colSpan??1,T=S._parsedProps.rowSpan??1;for(let k=0;k<T;k++)for(let N=0;N<P;N++)r[d+k]||(r[d+k]=[]),r[d+k][x+N]=S;x+=P}}s=Math.max(0,...r.map(d=>d.length));let o=i.map((d,_)=>d._parsedProps.height??1),a=Array.from({length:s},(d,_)=>{let g=0;for(let x=0;x<i.length;x++){let v=r[x]?.[_];if(v){let S=v._parsedProps.text??v._parsedProps.children,P=v._parsedProps.width??(S?.length??2)*.5;P>g&&(g=P)}}return g||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=e.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:o,cell_padding:t.cellPadding,border_width:t.borderWidth,anchor:t.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=l.schematic_table_id;let u=new Set,p=0;for(let d=0;d<i.length;d++){let _=0;for(let g=0;g<s;g++){let x=r[d]?.[g];if(x&&!u.has(x)){u.add(x);let v=x._parsedProps,S=v.rowSpan??1,P=v.colSpan??1,T=0;for(let N=0;N<P;N++)T+=a[g+N];let k=0;for(let N=0;N<S;N++)k+=o[d+N];e.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:d,end_row_index:d+S-1,start_column_index:g,end_column_index:g+P-1,text:v.text??v.children,center:{x:c.x+_+T/2,y:c.y-p-k/2},width:T,height:k,horizontal_align:v.horizontalAlign,vertical_align:v.verticalAlign,font_size:v.fontSize??t.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[g]&&(_+=a[g])}p+=o[d]}}},zit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:qH}}},Dit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:ZH}}},jit=class extends Me{constructor(){super(...arguments);f(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:fH}}},Bit=class extends Me{get config(){return{componentName:"AnalogSimulation",zodProps:xH}}doInitialSimulationRender(){let{db:n}=this.root,{duration:e,timePerStep:t}=this._parsedProps,i=e||10,r=t||.01;n.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:i,time_per_step:r})}},Yit=class extends Me{constructor(){super(...arguments);f(this,"simulation_voltage_probe_id",null);f(this,"schematic_voltage_probe_id",null);f(this,"finalProbeName",null);f(this,"color",null)}get config(){return{componentName:"VoltageProbe",zodProps:BH}}doInitialSimulationRender(){let{db:e}=this.root,{connectsTo:t,name:i,referenceTo:r,color:s}=this._parsedProps,o=this.getSubcircuit();if(!o){this.renderError("VoltageProbe must be inside a subcircuit");return}let a=Array.isArray(t)?t:[t];if(a.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let c=a[0],l=o.selectOne(c,{type:"port"}),u=l?null:o.selectOne(c,{type:"net"});if(u&&u.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${c}" resolved to a non-net component "${u.componentName}".`);return}if(!l&&!u){this.renderError(`VoltageProbe could not find connection target "${c}"`);return}let p=l?.source_port_id??u?.source_net_id;if(!p){this.renderError("Could not identify connected source for VoltageProbe");return}let d=null,_=null;if(r){let v=Array.isArray(r)?r:[r];if(v.length!==1){this.renderError("VoltageProbe must reference exactly one port or net");return}let S=v[0];if(d=o.selectOne(S,{type:"port"}),_=d?null:o.selectOne(S,{type:"net"}),_&&_.componentName!=="Net"){this.renderError(`VoltageProbe reference target "${S}" resolved to a non-net component "${_.componentName}".`);return}if(!d&&!_){this.renderError(`VoltageProbe could not find reference target "${S}"`);return}}this.color=s??xFt(p);let g=i;g||(g=a[0].split(" > ").map(v=>v.replace(/^\./,"")).join(".")),this.finalProbeName=g??null;let{simulation_voltage_probe_id:x}=e.simulation_voltage_probe.insert({name:g,signal_input_source_port_id:l?.source_port_id??void 0,signal_input_source_net_id:u?.source_net_id??void 0,reference_input_source_port_id:d?.source_port_id??void 0,reference_input_source_net_id:_?.source_net_id??void 0,subcircuit_id:o.subcircuit_id||void 0,color:this.color});this.simulation_voltage_probe_id=x}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{connectsTo:t,name:i}=this._parsedProps,r=this.getSubcircuit();if(!r)return;let s=Array.isArray(t)?t:[t];if(s.length!==1)return;let o=s[0],a=r.selectOne(o,{type:"port"});if(!a||!a.schematic_port_id)return;let c=a._getGlobalSchematicPositionAfterLayout(),l=null;for(let d of e.schematic_trace.list()){for(let _ of d.edges)if(Math.abs(_.from.x-c.x)<1e-6&&Math.abs(_.from.y-c.y)<1e-6||Math.abs(_.to.x-c.x)<1e-6&&Math.abs(_.to.y-c.y)<1e-6){l=d.schematic_trace_id;break}if(l)break}if(!l)return;let u=this.finalProbeName,p=e.schematic_voltage_probe.insert({name:u,position:c,schematic_trace_id:l,subcircuit_id:r.subcircuit_id||void 0,color:this.color??void 0});this.schematic_voltage_probe_id=p.schematic_voltage_probe_id}},qFt={name:"@tscircuit/core",type:"module",version:"0.0.897",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"',"generate-test-plan":"bun run scripts/generate-test-plan.ts"},devDependencies:{"@biomejs/biome":"^1.8.3","@resvg/resvg-js":"^2.6.2","@tscircuit/capacity-autorouter":"^0.0.140","@tscircuit/checks":"^0.0.87","@tscircuit/circuit-json-util":"^0.0.72","@tscircuit/common":"^0.0.20","@tscircuit/copper-pour-solver":"^0.0.14","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.29","@tscircuit/miniflex":"^0.0.4","@tscircuit/ngspice-spice-engine":"^0.0.4","@tscircuit/props":"^0.0.423","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^v0.0.45","@tscircuit/solver-utils":"^0.0.3","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.325","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-gltf":"^0.0.31","circuit-json-to-simple-3d":"^0.0.9","circuit-json-to-spice":"^0.0.27","circuit-to-svg":"^0.0.280",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6","eecircuit-engine":"^1.5.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",poppygl:"^0.0.16",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202",spicey:"^0.0.14","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.62","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},Q_=class{constructor({platform:n,projectUrl:e}={}){f(this,"firstChild",null);f(this,"children");f(this,"db");f(this,"root",null);f(this,"isRoot",!0);f(this,"_schematicDisabledOverride");f(this,"pcbDisabled",!1);f(this,"pcbRoutingDisabled",!1);f(this,"_featureMspSchematicTraceRouting",!0);f(this,"name");f(this,"platform");f(this,"projectUrl");f(this,"_hasRenderedAtleastOnce",!1);f(this,"_eventListeners",{});this.children=[],this.db=Ce([]),this.root=this,this.platform=n,this.projectUrl=e,this.pcbDisabled=n?.pcbDisabled??!1}get schematicDisabled(){return this._schematicDisabledOverride!==void 0?this._schematicDisabledOverride:this._getBoard()?._parsedProps?.schematicDisabled??!1}set schematicDisabled(n){this._schematicDisabledOverride=n}add(n){let e;(0,Xit.isValidElement)(n)?e=Snt(n):e=n,this.children.push(e)}setPlatform(n){this.platform={...this.platform,...n}}_getBoard(){let n=this.children.find(e=>e.componentName==="Board");if(n)return n}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");let n=this.children.filter(t=>t.lowercaseComponentName==="panel");if(n.length>1)throw new Error("Only one <panel> is allowed per circuit");if(n.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=n[0];return}if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let e=new Sl({subcircuit:!0});e.parent=this,e.addAll(this.children),this.children=[e],this.firstChild=e}render(){this.firstChild||this._guessRootComponent();let{firstChild:n,db:e}=this;if(!n)throw new Error("RootCircuit has no root component");n.parent=this,n.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(e=>setTimeout(e,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(n=>n._hasIncompleteAsyncEffects())}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(n){let e=await Promise.resolve().then(()=>(zet(),$et)).catch(t=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
252
+ ${o}`)}catch(c){Va(`Failed to convert circuit JSON to SPICE: ${c}`);return}for(let c of t){let l=c._parsedProps.spiceEngine??"spicey",u=r[l];if(!u)throw new Error(`SPICE engine "${l}" not found in platform config. Available engines: ${JSON.stringify(Object.keys(r).filter(d=>d!=="spicey"))}`);let p=`spice-simulation-${l}-${c.source_component_id}`;Va(`Queueing simulation for spice engine: ${l} (id: ${p})`),n._queueAsyncEffect(p,async()=>{try{Va(`Running simulation with engine: ${l}`);let d=await u.simulate(o);Va(`Simulation completed, received ${d.simulationResultCircuitJson.length} elements`);let _=e.db.simulation_experiment.list()[0];if(!_){Va("No simulation experiment found, skipping result insertion");return}for(let g of d.simulationResultCircuitJson){if(g.type==="simulation_transient_voltage_graph"){g.simulation_experiment_id=_.simulation_experiment_id;let v=i.find(S=>S.finalProbeName===g.name);v&&(g.color=v.color)}let x=g.type;x&&e.db[x]?(e.db[x].insert(g),Va(`Inserted ${x} into database`)):(Va(`Warning: Unknown element type ${x}, adding to raw db`),e.db._addElement(g))}n._markDirty("SimulationSpiceEngineRender")}catch(d){Va(`Simulation failed for engine ${l}: ${d}`);let _=e.db.simulation_experiment.list()[0];e.db.simulation_unknown_experiment_error.insert({simulation_experiment_id:_?.simulation_experiment_id,error_type:"simulation_unknown_experiment_error",message:d instanceof Error?d.message:String(d)})}})}}function wFt(n){if(n.root?.pcbDisabled||!n.pcb_group_id)return;let e=n._parsedProps?.pcbPositionAnchor;if(!e)return;let t=n._getGlobalPcbPositionBeforeLayout(),{pcbX:i,pcbY:r}=n._parsedProps;if(i===void 0&&r===void 0)return;let{db:s}=n.root,o=s.pcb_group.get(n.pcb_group_id);if(!o)return;let a=o.width,c=o.height,{center:l}=o;if(o.outline&&o.outline.length>0){let x=co(o.outline);x&&(a=x.maxX-x.minX,c=x.maxY-x.minY)}if(!a||!c)return;let u={left:l.x-a/2,right:l.x+a/2,top:l.y+c/2,bottom:l.y-c/2},p={...l},d=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(e))switch(e){case"center":d=p;break;case"top_left":d={x:u.left,y:u.top};break;case"top_center":d={x:p.x,y:u.top};break;case"top_right":d={x:u.right,y:u.top};break;case"center_left":d={x:u.left,y:p.y};break;case"center_right":d={x:u.right,y:p.y};break;case"bottom_left":d={x:u.left,y:u.bottom};break;case"bottom_center":d={x:p.x,y:u.bottom};break;case"bottom_right":d={x:u.right,y:u.bottom};break}if(!d)return;let g={...p};t.x!==void 0&&(g.x+=t.x-d.x),t.y!==void 0&&(g.y+=t.y-d.y),(Math.abs(g.x-p.x)>1e-6||Math.abs(g.y-p.y)>1e-6)&&(n._repositionOnPcb(g),s.pcb_group.update(n.pcb_group_id,{center:g})),s.pcb_group.update(n.pcb_group_id,{anchor_position:t,anchor_alignment:e})}var Sl=class extends Bn{constructor(){super(...arguments);f(this,"pcb_group_id",null);f(this,"schematic_group_id",null);f(this,"subcircuit_id",null);f(this,"_hasStartedAsyncAutorouting",!1);f(this,"_asyncAutoroutingResult",null);f(this,"unnamedElementCounter",{})}get config(){return{zodProps:HW,componentName:"Group"}}doInitialSourceGroupRender(){let{db:e}=this.root,t=typeof this._parsedProps.name=="string"&&this._parsedProps.name.length>0,i=e.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit,was_automatically_named:!t});this.source_group_id=i.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${i.source_group_id}`,e.source_group.update(i.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:e}=this.root;for(let t of this.children)e.source_component.update(t.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:e}=this.root,t=this.parent?.getGroup?.();if(t?.source_group_id&&e.source_group.update(this.source_group_id,{parent_source_group_id:t.source_group_id}),!this.isSubcircuit)return;let i=this.parent?.getSubcircuit?.()?.subcircuit_id;i&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:i})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=t,r=i.outline&&i.outline.length>0,s=r?i.outline.map(a=>({x:V.parse(a.x),y:V.parse(a.y)})):void 0,o=e.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,center:this._getGlobalPcbPositionBeforeLayout(),...r?{outline:s}:{width:0,height:0},pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:t.autorouter?{trace_clearance:t.autorouter.traceClearance}:void 0});this.pcb_group_id=o.pcb_group_id;for(let a of this.children)e.pcb_component.update(a.pcb_component_id,{pcb_group_id:o.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps,i=t.outline&&t.outline.length>0;if(this.pcb_group_id){let r=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0;if(i){let p=t.outline.map(v=>({x:V.parse(v.x),y:V.parse(v.y)})),d=co(p);if(!d)return;let _=(d.minX+d.maxX)/2,g=(d.minY+d.maxY)/2,x=r?e.pcb_group.get(this.pcb_group_id)?.center??{x:_,y:g}:{x:_,y:g};e.pcb_group.update(this.pcb_group_id,{center:x});return}let s=mP(this.children),o=s.width,a=s.height,c=(s.minX+s.maxX)/2,l=(s.minY+s.maxY)/2;if(this.isSubcircuit){let{padLeft:p,padRight:d,padTop:_,padBottom:g}=this._resolvePcbPadding();o+=p+d,a+=_+g,c+=(d-p)/2,l+=(_-g)/2}let u=r?e.pcb_group.get(this.pcb_group_id)?.center??{x:c,y:l}:{x:c,y:l};e.pcb_group.update(this.pcb_group_id,{width:Number(t.width??o),height:Number(t.height??a),center:u})}}getNextAvailableName(e){var t,i;return(t=this.unnamedElementCounter)[i=e.lowercaseComponentName]??(t[i]=1),`unnamed_${e.lowercaseComponentName}${this.unnamedElementCounter[e.lowercaseComponentName]++}`}_resolvePcbPadding(){let e=this._parsedProps,t=e.pcbLayout,i=p=>{let d=t?.[p],_=e[p];if(typeof d=="number")return d;if(typeof _=="number")return _},r=i("padding")??0,s=i("paddingX"),o=i("paddingY"),a=i("paddingLeft")??s??r,c=i("paddingRight")??s??r,l=i("paddingTop")??o??r,u=i("paddingBottom")??o??r;return{padLeft:a,padRight:c,padTop:l,padBottom:u}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:e}=this,{db:t}=this.root,i=e;if(!this.isSubcircuit)return;let r=i.manualEdits?.manual_trace_hints;if(r)for(let s of r)this.add(new R9({for:s.pcb_port_selector,offsets:s.offsets}))}doInitialSourceAddConnectivityMapKey(){L7t(this)}_areChildSubcircuitsRouted(){let e=this.selectAll("group").filter(t=>t.isSubcircuit);for(let t of e)if(t._shouldRouteAsync()&&!t._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let e=this._getAutorouterConfig();return e.groupMode==="sequential-trace"?!1:!!(e.local&&e.groupMode==="subcircuit"||!e.local)}_hasTracesToRoute(){let e=(0,G_.default)("tscircuit:core:_hasTracesToRoute"),t=this.selectAll("trace");return e(`[${this.getString()}] has ${t.length} traces to route`),t.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:e}=this.root,t=(0,G_.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),i=this._parsedProps,r=this._getAutorouterConfig(),s=r.serverUrl,o=r.serverMode,a=(u,p)=>(t("fetching",u),p.headers&&(p.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(u,p)),c=this.root.db.toArray().filter(u=>u.type.startsWith("source_")||u.type.startsWith("pcb_"));if(o==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:p}=await a(`${s}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:P9({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(d=>d.json());this._asyncAutoroutingResult=p,this._markDirty("PcbTraceRender");return}let{autorouting_result:u}=await a(`${s}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:c,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(p=>p.json());this._asyncAutoroutingResult=u,this._markDirty("PcbTraceRender");return}let{autorouting_job:l}=await a(`${s}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:c,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:r.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(u=>u.json());for(;;){let{autorouting_job:u}=await a(`${s}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(p=>p.json());if(u.is_finished){let{autorouting_job_output:p}=await a(`${s}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(d=>d.json());this._asyncAutoroutingResult={output_pcb_traces:p.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(u.has_error){let p=new X1(`Autorouting job failed: ${JSON.stringify(u.error)}`);throw e.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,error_type:"pcb_autorouting_error",message:p.message}),p}await new Promise(p=>setTimeout(p,100))}}async _runLocalAutorouting(){let{db:e}=this.root,t=this._parsedProps,i=(0,G_.default)("tscircuit:core:_runLocalAutorouting");i(`[${this.getString()}] starting local autorouting`);let r=this._getAutorouterConfig(),s=this._isLaserPrefabAutorouter(r),{simpleRouteJson:o}=P9({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(i.enabled&&global.debugOutputArray?.push({name:`simpleroutejson-${this.props.name}.json`,obj:o}),i.enabled){let l=Kg(o);l.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(l)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:o});let a;r.algorithmFn?a=await r.algorithmFn(o):a=new T7t(o,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity,useAssignableViaSolver:s});let c=new Promise((l,u)=>{a.on("complete",p=>{i(`[${this.getString()}] local autorouting complete`),l(p.traces)}),a.on("error",p=>{i(`[${this.getString()}] local autorouting error: ${p.error.message}`),u(p.error)})});a.on("progress",l=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...l})}),a.start();try{let l=await c;this._asyncAutoroutingResult={output_pcb_traces:l},this._markDirty("PcbTraceRender")}catch(l){let{db:u}=this.root;throw u.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:l instanceof Error?l.message:String(l)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:l instanceof Error?l.message:String(l)},simpleRouteJson:o}),l}finally{a.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let e=(0,G_.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){e(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}e(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){yFt(this)}updatePcbTraceRender(){let e=(0,G_.default)("tscircuit:core:updatePcbTraceRender");if(e(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(e(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:t}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){e(`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){e(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:e}=this.root,{traces:t}=this._asyncAutoroutingResult.output_simple_route_json;if(t)for(let i of t){let r=e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;let{db:t}=this.root,i=this.getInheritedMergedProperty("pcbStyle"),{holeDiameter:r,padDiameter:s}=A9(i);for(let o of e)if(o.type==="pcb_trace"){if(o.subcircuit_id=this.subcircuit_id,o.connection_name){let a=o.connection_name;o.source_trace_id=a}t.pcb_trace.insert(o)}for(let o of e)if(o.type!=="pcb_via"&&o.type==="pcb_trace")for(let a of o.route)a.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:o.pcb_trace_id,x:a.x,y:a.y,hole_diameter:r,outer_diameter:s,layers:[a.from_layer,a.to_layer],from_layer:a.from_layer,to_layer:a.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=e.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=i.schematic_group_id;for(let r of this.children)r.schematic_component_id&&e.schematic_component.update(r.schematic_component_id,{schematic_group_id:i.schematic_group_id})}_getSchematicLayoutMode(){let e=this._parsedProps;if(e.schLayout?.layoutMode==="none"||e.schLayout?.layoutMode==="relative")return"relative";if(e.schLayout?.matchAdapt)return"match-adapt";if(e.schLayout?.flex)return"flex";if(e.schLayout?.grid)return"grid";if(e.schMatchAdapt)return"match-adapt";if(e.schFlex)return"flex";if(e.schGrid)return"grid";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";if(e.relative||e.schRelative)return"relative";let t=this.children.some(r=>{let s=r._parsedProps;return s?.schX!==void 0||s?.schY!==void 0}),i=(e.manualEdits?.schematic_placements?.length??0)>0;return!t&&!i?"match-adapt":"relative"}doInitialSchematicLayout(){let e=this._getSchematicLayoutMode();e==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),e==="grid"&&this._doInitialSchematicLayoutGrid(),e==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){A7t(this)}_doInitialSchematicLayoutMatchpack(){O7t(this)}_doInitialSchematicLayoutGrid(){F7t(this)}_doInitialSchematicLayoutFlex(){$7t(this)}_getPcbLayoutMode(){let e=this._parsedProps;if(e.pcbRelative)return"none";if(e.pcbLayout?.matchAdapt)return"match-adapt";if(e.pcbLayout?.flex)return"flex";if(e.pcbLayout?.grid)return"grid";if(e.pcbLayout?.pack)return"pack";if(e.pcbFlex)return"flex";if(e.pcbGrid)return"grid";if(e.pcbPack||e.pack)return"pack";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";let t=e.pcbX!==void 0||e.pcbY!==void 0,i=(e.manualEdits?.pcb_placements?.length??0)>0,r=this.children.reduce((s,o)=>{if(!o.pcb_component_id&&!o.pcb_group_id)return s;let a=o._parsedProps,c=a?.pcbX!==void 0||a?.pcbY!==void 0;return s+(c?0:1)},0);return!t&&!i&&r>1?"pack":"none"}doInitialPcbLayout(){let e=this._getPcbLayoutMode();e==="grid"?this._doInitialPcbLayoutGrid():e==="pack"?this._doInitialPcbLayoutPack():e==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){z7t(this)}_doInitialPcbLayoutPack(){tFt(this)}_doInitialPcbLayoutFlex(){eFt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!t.border)return;let i=typeof t.schWidth=="number"?t.schWidth:void 0,r=typeof t.schHeight=="number"?t.schHeight:void 0,s=typeof t.schPadding=="number"?t.schPadding:0,o=typeof t.schPaddingLeft=="number"?t.schPaddingLeft:s,a=typeof t.schPaddingRight=="number"?t.schPaddingRight:s,c=typeof t.schPaddingTop=="number"?t.schPaddingTop:s,l=typeof t.schPaddingBottom=="number"?t.schPaddingBottom:s,u=this.schematic_group_id?e.schematic_group.get(this.schematic_group_id):null;if(u&&(i===void 0&&typeof u.width=="number"&&(i=u.width),r===void 0&&typeof u.height=="number"&&(r=u.height)),i===void 0||r===void 0)return;let p=u?.center??this._getGlobalSchematicPositionBeforeLayout(),d=p.x-i/2-o,_=p.y-r/2-l,g=i+o+a,x=r+c+l;e.schematic_box.insert({width:g,height:x,x:d,y:_,is_dashed:t.border?.dashed??!1})}_determineSideFromPosition(e,t){if(!e.center||!t.center)return"left";let i=e.center.x-t.center.x,r=e.center.y-t.center.y;return Math.abs(i)>Math.abs(r)?i>0?"right":"left":r>0?"bottom":"top"}_calculateSchematicBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let a of e)t=Math.min(t,a.centerX),i=Math.max(i,a.centerX),r=Math.min(r,a.centerY),s=Math.max(s,a.centerY);let o=2;return{minX:t-o,maxX:i+o,minY:r-o,maxY:s+o}}_getAutorouterConfig(){let e=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return H7t(e)}_isLaserPrefabAutorouter(e=this._getAutorouterConfig()){let t=this.props.autorouter,i=r=>r?.replace(/-/g,"_")??r;return e.preset==="laser_prefab"?!0:typeof t=="string"?i(t)==="laser_prefab":typeof t=="object"&&t?i(t.preset)==="laser_prefab":!1}_getSubcircuitLayerCount(){let e=this.getInheritedProperty("layers");return typeof e=="number"?e:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(this.isSubcircuit){let t=new Map;for(let i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){let r=t.get(i._parsedProps.name)||[];r.push(i),t.set(i._parsedProps.name,r)}for(let[i,r]of t.entries())r.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:r.map(s=>s.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:e}=this.root,t=e;for(let i of t.schematic_net_label.list()){let r=t.source_net.get(i.source_net_id),s=i.text||r?.name||"";if(i.anchor_side==="top"&&/^gnd/i.test(s)){t.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_down"});continue}i.anchor_side==="bottom"&&/^v/i.test(s)&&t.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_up"})}}doInitialSimulationSpiceEngineRender(){vFt(this)}doInitialPcbComponentAnchorAlignment(){wFt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(e){return super._repositionOnPcb(e)}};function SFt(n,e){let{subcircuit:t}=e;if(t.lowercaseComponentName==="board"||t.parent?.lowercaseComponentName==="board")return;let i={name:"inflated_board"};n.width&&(i.width=n.width),n.height&&(i.height=n.height),n.center&&(i.pcbX=n.center.x,i.pcbY=n.center.y),n.outline&&(i.outline=n.outline),n.thickness&&(i.thickness=n.thickness),n.material&&(i.material=n.material);let r=new gP(i);return r.pcb_board_id=n.pcb_board_id,t.add(r),r}var PFt=new Proxy({},{get:(n,e)=>e}),Ha=PFt,_P="rgba(132, 0, 0)",yP=.12,L9=class extends Bn{constructor(){super(...arguments);f(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:oH,sourceFtype:Ha.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let e=this.props.capacitance,t=typeof e=="string"?e:`${xi(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${t}/${xi(this._parsedProps.maxVoltageRating)}V`:t}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new zs({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new zs({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,capacitance:t.capacitance,max_voltage_rating:t.maxVoltageRating,max_decoupling_trace_length:t.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!t.polarized});this.source_component_id=i.source_component_id}},J_=(n,e)=>{let{injectionDb:t,normalComponent:i}=e;if(!i)return;let r=n.center||{x:0,y:0},s=n.rotation||0,o=$3(ii(kn(r.x,r.y),Oo(s*Math.PI/180))),a=t.toArray().filter(u=>"pcb_component_id"in u&&u.pcb_component_id===n.pcb_component_id),c=structuredClone(a);tl(c,o);let l=q_({componentName:i.name,componentRotation:"0deg"},c);i.addAll(l)};function kFt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new L9({name:n.name,capacitance:n.capacitance,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&J_(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var Z1=class extends Bn{constructor(e){super(e);f(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:o_,shouldRenderAsSchematicBox:!0}}initPorts(e={}){super.initPorts(e);let{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp();if(t.externallyConnectedPins){let s=new Set;for(let[o,a]of t.externallyConnectedPins)s.add(o),s.add(a);for(let o of s)if(!this.children.find(c=>c instanceof Wi&&c.isMatchingAnyOf([o]))){let c=o.match(/^pin(\d+)$/);if(c){let l=parseInt(c[1]);this.add(new Wi({pinNumber:l,aliases:[o]}))}else this.add(new Wi({name:o,aliases:[o]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:e}=this;e?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=t.layer??"top";if(s!=="top"&&s!=="bottom"){let a=this.getSubcircuit(),c=zm.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${s}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:s,subcircuit_id:a.subcircuit_id??void 0});e.pcb_component_invalid_layer_error.insert(c)}let o=e.pcb_component.insert({center:{x:i,y:r},width:2,height:3,layer:s==="top"||s==="bottom"?s:"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=o.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:e}=this;if(e.externallyConnectedPins)for(let[t,i]of e.externallyConnectedPins)this.add(new zs({from:`${this.getSubcircuitSelector()} > port.${t}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:e}=this.root,{pinAttributes:t}=this.props;if(!t)return;let i=null,r=null,s,o=this.selectAll("port");for(let p of o)for(let d of p.getNameAndAliases())if(t[d]){let _=t[d];_.providesPower&&(i=p,s=_.providesVoltage),_.providesGround&&(r=p)}if(!i||!r||s===void 0)return;let a=e.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=e.source_port.get(r.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=e.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=e.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||e.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:r.source_port_id,negative_source_net_id:u.source_net_id,voltage:s})}},TFt=(n,e)=>{if(!n||n.length===0)return;let{injectionDb:t}=e,i=n.map(r=>r.map(s=>{let o=t.source_port.get(s);return o?o.pin_number!==void 0&&o.pin_number!==null?`pin${o.pin_number}`:o.name:null}).filter(s=>s!==null)).filter(r=>r.length>0);return i.length>0?i:void 0},EFt=(n,e)=>{let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.schematic_component.getWhere({source_component_id:n.source_component_id}),a=t.cad_component.getWhere({source_component_id:n.source_component_id}),c=TFt(n.internally_connected_source_port_ids,e),l=new Z1({name:n.name,manufacturerPartNumber:n.manufacturer_part_number,supplierPartNumbers:n.supplier_part_numbers??void 0,pinLabels:o?.port_labels??void 0,schWidth:o?.size?.width,schHeight:o?.size?.height,schPinSpacing:o?.pin_spacing,schX:o?.center?.x,schY:o?.center?.y,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds,internallyConnectedPins:c}),u=a?.footprinter_string??null;u&&(Object.assign(l.props,{footprint:u}),Object.assign(l._parsedProps,{footprint:u}),a||l._addChildrenFromStringFootprint?.()),s&&J_(s,{...e,normalComponent:l}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(l):i.add(l)},F9=class extends Bn{constructor(){super(...arguments);f(this,"pos",this.portMap.pin1);f(this,"anode",this.portMap.pin1);f(this,"neg",this.portMap.pin2);f(this,"cathode",this.portMap.pin2)}get config(){let e={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},t=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:t?e[t]:this.props.symbolName??"diode",componentName:"Diode",zodProps:SH,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}};function MFt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new F9({name:n.name,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&J_(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}function CFt(n,e){let{subcircuit:t,groupsMap:i}=e,r=new Sl({name:n.name??`inflated_group_${n.source_group_id}`});return r.source_group_id=n.source_group_id,i&&i.set(n.source_group_id,r),n.parent_source_group_id&&i?.has(n.parent_source_group_id)?i.get(n.parent_source_group_id).add(r):t.add(r),r}var $9=class extends Bn{constructor(){super(...arguments);f(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:wH,sourceFtype:Ha.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${xi(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({name:this.name,ftype:Ha.simple_inductor,inductance:t.inductance,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function IFt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new $9({name:n.name,inductance:n.inductance,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&J_(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}function NFt(n,e){let{injectionDb:t,subcircuit:i}=e;if(n.source_component_id!==null)return;let r=t.pcb_port.getWhere({source_port_id:n.source_port_id}),s=new Wi({name:n.name,pinNumber:n.pin_number});i.add(s),s.source_port_id=n.source_port_id;let o=i.root;if(o&&r){let{db:a}=o,c=a.pcb_port.insert({pcb_component_id:void 0,layers:r.layers,subcircuit_id:i.subcircuit_id??void 0,pcb_group_id:i.getGroup()?.pcb_group_id??void 0,x:r.x,y:r.y,source_port_id:n.source_port_id,is_board_pinout:!1});s.pcb_port_id=c.pcb_port_id}}var z9=class extends Bn{constructor(){super(...arguments);f(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:eH,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${xi(this._parsedProps.resistance)}\u03A9`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,this.props.pulldownFor,this.props.pulldownTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new zs({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new zs({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new zs({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new zs({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,resistance:t.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function AFt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new z9({name:n.name,resistance:n.resistance,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&J_(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var RFt=(n,e)=>{let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=[],o=n.source_group_id;for(;o&&o!==i.source_group_id;){let a=t.source_group.get(o),c=r?.get(o);if(!a||!c)break;let l=c.props.name??c.fallbackUnassignedName;s.unshift(`.${l}`),o=a.parent_source_group_id}return s.push(`.${n.name}`),s.join(" > ")};function OFt(n,e){let{injectionDb:t,subcircuit:i}=e,r=[];for(let o of n.connected_source_port_ids){let a=t.source_port.get(o);if(!a)continue;let c;if(a.source_component_id){let l=t.source_component.get(a.source_component_id);l&&(c=`${RFt({name:l.name,source_group_id:l.source_group_id},e)} > .${a.name}`)}else c=`.${a.name}`;c&&r.push(c)}for(let o of n.connected_source_net_ids){let a=t.source_net.get(o);a&&r.push(`net.${a.name}`)}if(r.length<2)return;let s=new zs({path:r});s.source_trace_id=n.source_trace_id,i.add(s)}var D9=class extends Bn{constructor(){super(...arguments);f(this,"emitter",this.portMap.pin1);f(this,"collector",this.portMap.pin2);f(this,"base",this.portMap.pin3)}get config(){let e=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??e,zodProps:bH,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let e={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:e})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:t.type});this.source_component_id=i.source_component_id}};function LFt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new D9({name:n.name,type:n.transistor_type,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds});s&&J_(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var Wnt=(n,e,t)=>{if(!e)return;let i=Ke(e);if(e&&t?.length>0)throw new Error("Component cannot have both circuitJson and children");let s={injectionDb:i,subcircuit:n,groupsMap:new Map},o=i.source_group.list();for(let p of o)CFt(p,s);let a=i.pcb_board.list();for(let p of a)SFt(p,s);let c=i.source_component.list();for(let p of c)switch(p.ftype){case"simple_resistor":AFt(p,s);break;case"simple_capacitor":kFt(p,s);break;case"simple_inductor":IFt(p,s);break;case"simple_diode":MFt(p,s);break;case"simple_chip":EFt(p,s);break;case"simple_transistor":LFt(p,s);break;default:throw new Error(`No inflator implemented for source component ftype: "${p.ftype}"`)}let l=i.source_port.list();for(let p of l)NFt(p,s);let u=i.source_trace.list();for(let p of u)OFt(p,s)},FFt=.01,fnt=(n,e,t)=>{let i=n/2,r=e/2,s=Math.min(t,i,r);if(s<FFt)return[{x:-i,y:-r},{x:i,y:-r},{x:i,y:r},{x:-i,y:r}];let a=Math.max(1,Math.ceil(Math.PI/2*s/.1)),c=Math.PI/2/a,l=[];l.push({x:-i+s,y:-r}),l.push({x:i-s,y:-r});for(let u=1;u<=a;u++){let p=-Math.PI/2+u*c;l.push({x:i-s+s*Math.cos(p),y:-r+s+s*Math.sin(p)})}l.push({x:i,y:r-s});for(let u=1;u<=a;u++){let p=0+u*c;l.push({x:i-s+s*Math.cos(p),y:r-s+s*Math.sin(p)})}l.push({x:-i+s,y:r});for(let u=1;u<=a;u++){let p=Math.PI/2+u*c;l.push({x:-i+s+s*Math.cos(p),y:r-s+s*Math.sin(p)})}l.push({x:-i,y:-r+s});for(let u=1;u<=a;u++){let p=Math.PI+u*c;l.push({x:-i+s+s*Math.cos(p),y:-r+s+s*Math.sin(p)})}return l},gP=class extends Sl{constructor(){super(...arguments);f(this,"pcb_board_id",null);f(this,"source_board_id",null);f(this,"_drcChecksComplete",!1);f(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:T4}}get boardThickness(){let{_parsedProps:e}=this,t=this._resolvePcbCoordinate(e.pcbX,"pcbX",{allowBoardVariables:!1}),i=this._resolvePcbCoordinate(e.pcbY,"pcbY",{allowBoardVariables:!1});return e.thickness??1.4}get allLayers(){return(this._parsedProps.layers??2)===4?["top","bottom","inner1","inner2"]:["top","bottom"]}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}_getBoardCalcVariables(){let{_parsedProps:e}=this;if((e.width==null||e.height==null)&&!e.outline)return{};let i=this.pcb_board_id?this.root?.db.pcb_board.get(this.pcb_board_id):null,r=i?.width??e.width,s=i?.height??e.height;if((r==null||s==null)&&e.outline?.length){let p=co(e.outline);p&&(r??(r=p.maxX-p.minX),s??(s=p.maxY-p.minY))}let{pcbX:o,pcbY:a}=this.getResolvedPcbPositionProp(),c=i?.center??{x:o+(e.outlineOffsetX??0),y:a+(e.outlineOffsetY??0)},l=r??0,u=s??0;return{"board.minx":c.x-l/2,"board.maxx":c.x+l/2,"board.miny":c.y-u/2,"board.maxy":c.y+u/2}}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._resolvePcbCoordinate(t.pcbX,"pcbX",{allowBoardVariables:!1}),r=this._resolvePcbCoordinate(t.pcbY,"pcbY",{allowBoardVariables:!1}),s=e.pcb_board.get(this.pcb_board_id);if(s?.width&&s?.height||s?.outline&&s.outline.length>0)return;let o=1/0,a=1/0,c=-1/0,l=-1/0,u=Dnt(e,this.subcircuit_id),p=new Set([this.subcircuit_id,...u]),d=e.pcb_component.list().filter(M=>M.subcircuit_id&&p.has(M.subcircuit_id)),_=e.pcb_group.list().filter(M=>M.subcircuit_id&&p.has(M.subcircuit_id)),g=!1,x=(M,A,R)=>{A===0||R===0||(g=!0,o=Math.min(o,M.x-A/2),a=Math.min(a,M.y-R/2),c=Math.max(c,M.x+A/2),l=Math.max(l,M.y+R/2))};for(let M of d)x(M.center,M.width,M.height);for(let M of _){let A=M.width??0,R=M.height??0;if(M.outline&&M.outline.length>0){let B=co(M.outline);B&&(A=B.maxX-B.minX,R=B.maxY-B.minY)}x(M.center,A,R)}if(t.boardAnchorPosition){let{x:M,y:A}=t.boardAnchorPosition;o=Math.min(o,M),a=Math.min(a,A),c=Math.max(c,M),l=Math.max(l,A)}let v=2,S=g?c-o+v*2:0,P=g?l-a+v*2:0,T={x:g?(o+c)/2+(t.outlineOffsetX??0):(t.outlineOffsetX??0)+i,y:g?(a+l)/2+(t.outlineOffsetY??0):(t.outlineOffsetY??0)+r},k=t.width??S,N=t.height??P,E=t.outline;!E&&t.borderRadius!=null&&k>0&&N>0&&(E=fnt(k,N,t.borderRadius));let C={width:k,height:N,center:T};E&&(C.outline=E.map(M=>({x:M.x+(t.outlineOffsetX??0),y:M.y+(t.outlineOffsetY??0)}))),e.pcb_board.update(this.pcb_board_id,C)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let e=this.root?.platform;if(!e?.printBoardInformationToSilkscreen)return;let t=this.root.db.pcb_board.get(this.pcb_board_id);if(!t)return;let i=[];if(e.projectName&&i.push(e.projectName),e.version&&i.push(`v${e.version}`),e.url&&i.push(e.url),i.length===0)return;let r=i.join(`
253
+ `),a={x:t.center.x+t.width/2-.25,y:t.center.y-t.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:r,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialSourceRender(){super.doInitialSourceRender();let{db:e}=this.root,t=e.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=t.source_board_id}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:e,children:t}=this._parsedProps;Wnt(this,e,t)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,r=t.circuitJson?.find(g=>g.type==="pcb_board"),s=t.width??r?.width??0,o=t.height??r?.height??0,{pcbX:a,pcbY:c}=this.getResolvedPcbPositionProp(),l={x:a+(t.outlineOffsetX??0),y:c+(t.outlineOffsetY??0)},{boardAnchorPosition:u,boardAnchorAlignment:p}=t;if(u&&(l=k7t({boardAnchorPosition:u,boardAnchorAlignment:p??"center",width:s,height:o})),t.outline){let g=t.outline.map(k=>k.x),x=t.outline.map(k=>k.y),v=Math.min(...g),S=Math.max(...g),P=Math.min(...x),T=Math.max(...x);s=S-v,o=T-P,l={x:(v+S)/2+(t.outlineOffsetX??0),y:(P+T)/2+(t.outlineOffsetY??0)}}let d=t.outline;!d&&t.borderRadius!=null&&s>0&&o>0&&(d=fnt(s,o,t.borderRadius));let _=e.pcb_board.insert({center:l,thickness:this.boardThickness,num_layers:this.allLayers.length,width:s,height:o,outline:d?.map(g=>({x:g.x+(t.outlineOffsetX??0),y:g.y+(t.outlineOffsetY??0)})),material:t.material});this.pcb_board_id=_.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:e}=this.root;this.pcb_board_id&&(e.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let t=dtt(e.toArray());for(let u of t)e.pcb_trace_error.insert(u);let i=htt(e.toArray());for(let u of i)e.pcb_port_not_connected_error.insert(u);let r=_tt(e.toArray());for(let u of r)e.pcb_component_outside_board_error.insert(u);let s=xtt(e.toArray());for(let u of s)e.pcb_trace_error.insert(u);let o=gtt(e.toArray());for(let u of o)e.pcb_via_clearance_error.insert(u);let a=ytt(e.toArray());for(let u of a)e.pcb_via_clearance_error.insert(u);let c=btt(e.toArray());for(let u of c)e.pcb_footprint_overlap_error.insert(u);let l=vtt(e.toArray());for(let u of l)e.source_pin_must_be_connected_error.insert(u)}_emitRenderLifecycleEvent(e,t){super._emitRenderLifecycleEvent(e,t),t==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e})}},mnt=5,$Ft=5,_nt=2;function zFt(n,e){let t=n.center.x-n.width/2,i=n.center.x+n.width/2,r=n.center.y-n.height/2,s=n.center.y+n.height/2,o=e.center.x-e.width/2,a=e.center.x+e.width/2,c=e.center.y-e.height/2,l=e.center.y+e.height/2;return!(i<=o||t>=a||s<=c||r>=l)}function DFt(n,e,t){let i=t.center.x-t.width/2,r=t.center.x+t.width/2,s=t.center.y-t.height/2,o=t.center.y+t.height/2,a=Math.max(i,Math.min(n.x,r)),c=Math.max(s,Math.min(n.y,o)),l=n.x-a,u=n.y-c;return l*l+u*u<=e*e}function jFt({board:n,edge:e,otherBoards:t,options:i}){let r=[];if(!n.width||!n.height)return r;let s=n.center.x-n.width/2,o=n.center.x+n.width/2,a=n.center.y-n.height/2,c=n.center.y+n.height/2,l,u,p;e==="top"||e==="bottom"?(l=n.width,u=!0,p=e==="top"?c:a):(l=n.height,u=!1,p=e==="right"?o:s);let d=i.tabLength,_=i.boardGap;if(i.mouseBites){let P=i.tabWidth*.45,T=P*.1,k=Math.max(2,Math.ceil(i.tabLength/2));_=(k*P+(k-1)*T)*1.1}let g=Math.floor((l-_)/(d+_));if(g<1&&l>=d&&(g=1),g===0)return r;let x=_,v=-l/2,S=l/2;for(let P=0;P<g;P++){let T=v+x+P*(d+x)+d/2,k=P===0,N=P===g-1,E=k||N,C=T-d/2,M=T+d/2;if(E&&(k&&(C=v),N&&(M=S)),C=Math.max(C,v),M=Math.min(M,S),E&&(k&&(C-=i.tabWidth),N&&(M+=i.tabWidth)),M<=C)continue;let A=(C+M)/2,R=M-C,B=e==="top"||e==="right"?i.tabWidth/2:-i.tabWidth/2,j=u?{x:n.center.x+A,y:p+B}:{x:p+B,y:n.center.y+A},U=u?R:i.tabWidth,X=u?i.tabWidth:R,W={center:j,width:U,height:X,boardId:`${n.center.x}_${n.center.y}`},et=!1;for(let nt of t){if(!nt.width||!nt.height)continue;let mt={center:nt.center,width:nt.width,height:nt.height};if(zFt(W,mt)){et=!0;break}}et&&!E||r.push(W)}return r}function BFt({board:n,edge:e,edgeTabs:t,allBoards:i,options:r}){let s=[];if(t.length===0||!n.width||!n.height)return s;let o=n.center.x-n.width/2,a=n.center.x+n.width/2,c=n.center.y-n.height/2,l=n.center.y+n.height/2,u=e==="top"||e==="bottom",p=r.tabWidth*.45,d=p*.1,_=Math.max(2,Math.ceil(r.tabLength/2)),g,x=p/2;e==="top"?g=l:e==="bottom"?g=c:e==="right"?g=a:g=o;let v=[...t].sort((S,P)=>u?S.center.x-P.center.x:S.center.y-P.center.y);for(let S=0;S<v.length-1;S++){let P=v[S],T=v[S+1],k,N;u?(k=P.center.x+P.width/2,N=T.center.x-T.width/2):(k=P.center.y+P.height/2,N=T.center.y-T.height/2);let E=N-k,C=_*p,M=(_-1)*d;if(E<C+M)continue;let A=(k+N)/2;for(let R=0;R<_;R++){let B=(R-(_-1)/2)*(p+d),j=u?{x:A+B,y:g}:{x:g,y:A+B},U=p/2,X=!1;for(let W of i){if(!W.width||!W.height)continue;let et={center:W.center,width:W.width,height:W.height};if(DFt(j,U,et)){X=!0;break}}X||s.push(j)}}return s}function YFt(n,e){let t=[],i=[];for(let a=0;a<n.length;a++){let c=n[a],l=n.filter((u,p)=>p!==a);for(let u of["top","bottom","left","right"]){let p=jFt({board:c,edge:u,otherBoards:l,options:e});if(t.push(...p),e.mouseBites){let d=BFt({board:c,edge:u,edgeTabs:p,allBoards:l,options:e});i.push(...d)}}}let r=t.map((a,c)=>{let l=Math.min(a.width,a.height);return{type:"pcb_cutout",pcb_cutout_id:`panel_tab_${c}`,shape:"rect",center:a.center,width:a.width,height:a.height,corner_radius:l/2}}),s=e.tabWidth*.45,o=i.map((a,c)=>({type:"pcb_hole",pcb_hole_id:`panel_mouse_bite_${c}`,hole_shape:"circle",hole_diameter:s,x:a.x,y:a.y}));return{tabCutouts:r,mouseBiteHoles:o}}var Hnt=class extends Sl{constructor(){super(...arguments);f(this,"pcb_panel_id",null);f(this,"_tabsAndMouseBitesGenerated",!1)}get config(){return{componentName:"Panel",zodProps:qW}}get isGroup(){return!0}get isSubcircuit(){return!0}add(e){if(e.lowercaseComponentName!=="board")throw new Error("<panel> can only contain <board> elements");super.add(e)}doInitialPanelLayout(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.children.filter(a=>a instanceof gP),i=t.some(a=>a.props.pcbX!==void 0||a.props.pcbY!==void 0),r=t.filter(a=>a.props.pcbX===void 0&&a.props.pcbY===void 0);if(r.length>0&&!i){let a=this._parsedProps.tabWidth??_nt,c=this._parsedProps.boardGap??a,l=Math.ceil(Math.sqrt(r.length)),u=Math.ceil(r.length/l),p=Array(l).fill(0),d=Array(u).fill(0);r.forEach((A,R)=>{let B=R%l,j=Math.floor(R/l),U=e.pcb_board.get(A.pcb_board_id);!U||U.width===void 0||U.height===void 0||(p[B]=Math.max(p[B],U.width),d[j]=Math.max(d[j],U.height))});let _=p.reduce((A,R)=>A+R,0)+(l>1?(l-1)*c:0),g=d.reduce((A,R)=>A+R,0)+(u>1?(u-1)*c:0),x=-_/2,S=[-g/2];for(let A=0;A<u-1;A++)S.push(S[A]+d[A]+c);let P=[x];for(let A=0;A<l-1;A++)P.push(P[A]+p[A]+c);r.forEach((A,R)=>{let B=R%l,j=Math.floor(R/l),U=e.pcb_board.get(A.pcb_board_id);if(!U||!U.width||!U.height)return;let X=P[B]+p[B]/2,W=S[j]+d[j]/2;A._repositionOnPcb({x:X,y:W}),e.pcb_board.update(A.pcb_board_id,{center:{x:X,y:W}})});let T=t.map(A=>A.pcb_board_id).filter(A=>!!A),k=e.pcb_board.list().filter(A=>T.includes(A.pcb_board_id)),N=1/0,E=1/0,C=-1/0,M=-1/0;for(let A of k){if(A.width===void 0||A.height===void 0||!isFinite(A.width)||!isFinite(A.height))continue;let R=A.center.x-A.width/2,B=A.center.x+A.width/2,j=A.center.y-A.height/2,U=A.center.y+A.height/2;N=Math.min(N,R),C=Math.max(C,B),E=Math.min(E,j),M=Math.max(M,U)}if(isFinite(N)){let A=C-N,R=M-E,B=A+2*mnt,j=R+2*mnt;e.pcb_panel.update(this.pcb_panel_id,{width:B,height:j})}}if(this._tabsAndMouseBitesGenerated)return;let s=this._parsedProps;if((s.panelizationMethod??"tab-routing")!=="none"){let a=t.map(_=>_.pcb_board_id).filter(_=>!!_),c=e.pcb_board.list().filter(_=>a.includes(_.pcb_board_id));if(c.length===0)return;let l=s.tabWidth??_nt,u=s.boardGap??l,{tabCutouts:p,mouseBiteHoles:d}=YFt(c,{boardGap:u,tabWidth:l,tabLength:s.tabLength??$Ft,mouseBites:s.mouseBites??!0});for(let _ of p)e.pcb_cutout.insert(_);for(let _ of d)e.pcb_hole.insert(_)}this._tabsAndMouseBitesGenerated=!0}runRenderCycle(){if(!this.children.some(e=>e.componentName==="Board"))throw new Error("<panel> must contain at least one <board>");super.runRenderCycle()}doInitialPcbComponentRender(){if(super.doInitialPcbComponentRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps,i=e.pcb_panel.insert({width:V.parse(t.width),height:V.parse(t.height),center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(t.noSolderMask??!1)});this.pcb_panel_id=i.pcb_panel_id}updatePcbComponentRender(){if(this.root?.pcbDisabled||!this.pcb_panel_id)return;let{db:e}=this.root,t=this._parsedProps;e.pcb_panel.update(this.pcb_panel_id,{width:V.parse(t.width),height:V.parse(t.height),center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(t.noSolderMask??!1)})}removePcbComponentRender(){this.pcb_panel_id&&(this.root?.db.pcb_panel.delete(this.pcb_panel_id),this.pcb_panel_id=null)}},qnt=class extends Z1{constructor(n){super(n)}get config(){return{...super.config,componentName:"Pinout",zodProps:ZW}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:e.manufacturerPartNumber,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=t.source_component_id}},Znt=class extends Bn{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:QW,sourceFtype:Ha.simple_fuse}}_getSchematicSymbolDisplayValue(){let n=this._parsedProps.currentRating,e=this._parsedProps.voltageRating,t=typeof n=="string"?parseFloat(n):n,i=typeof e=="string"?parseFloat(e):e;return`${xi(t)}A / ${xi(i)}V`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=typeof e.currentRating=="string"?parseFloat(e.currentRating):e.currentRating,i=typeof e.voltageRating=="string"?parseFloat(e.voltageRating):e.voltageRating,r=n.source_component.insert({name:this.name,ftype:Ha.simple_fuse,current_rating_amps:t,voltage_rating_volts:i,display_current_rating:`${xi(t)}A`,display_voltage_rating:`${xi(i)}V`});this.source_component_id=r.source_component_id}},Knt=class extends Bn{constructor(){super(...arguments);f(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:E4,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let t=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?t:0,rightSize:i==="right"?t:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.pcb_component.insert({center:{x:i,y:r},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let o=0;o<t.length;o++){let a=t[o],c=e.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(p=>/^(pin)?\d+$/.test(p));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),s=o=>{if(o&&typeof o=="string"&&o.startsWith("{PIN")){let a=o.replace("{PIN","").replace("}","");return i[a]||o}return o};for(let o of r)if(o.route)for(let a of o.route)a.route_type==="wire"&&(a.start_pcb_port_id=s(a.start_pcb_port_id),a.end_pcb_port_id=s(a.end_pcb_port_id))}},XFt={"0603":"0603","0805":"0805",1206:"1206"},Jnt=class extends Bn{get config(){return{componentName:"Interconnect",zodProps:JW,shouldRenderAsSchematicBox:!0,sourceFtype:"interconnect"}}_getImpliedFootprintString(){let{standard:n}=this._parsedProps;return n?XFt[n]??null:null}doInitialSourceRender(){let{db:n}=this.root,e=n.source_component.insert({ftype:"interconnect",name:this.name,are_pins_interchangeable:!0});this.source_component_id=e.source_component_id}},Qnt=class extends Bn{constructor(){super(...arguments);f(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(e){return this.selectOne(`port.${e}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let e=this.children.filter(t=>t.componentName==="Port").map(t=>t.name);return e.length>0?[e]:[]}return this._parsedProps.bridgedPins??[]}get config(){let e=this._parsedProps??this.props,t=e.pinCount;if(e.pinCount==null&&!e.footprint&&(t=2),e.pinCount==null){let s=(e.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),o=s.length>0?Math.max(...s):0,a=e.pinLabels?Object.keys(e.pinLabels).length:0,c=Math.max(o,a);(c===2||c===3)&&(t=c),t==null&&e.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(t=this.getPortsFromFootprint().length)}let i="";t?i+=`solderjumper${t}`:i="solderjumper";let r=[];return Array.isArray(e.bridgedPins)&&e.bridgedPins.length>0?r=Array.from(new Set(e.bridgedPins.flat().map(s=>this._getPinNumberFromBridgedPinName(s)).filter(s=>s!==null))).sort((s,o)=>s-o):e.bridged&&t&&(r=Array.from({length:t},(s,o)=>o+1)),r.length>0&&(i+=`_bridged${r.join("")}`),{schematicSymbolName:e.symbolName??i,componentName:"SolderJumper",zodProps:KW,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let t=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);t==null&&!this._parsedProps.footprint&&(t=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?t:0,rightSize:i==="right"?t:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),s=e.pcb_component.insert({center:{x:i,y:r},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let o=0;o<t.length;o++){let a=t[o],c=e.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(p=>/^(pin)?\d+$/.test(p));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),s=o=>{if(o&&typeof o=="string"&&o.startsWith("{PIN")){let a=o.replace("{PIN","").replace("}","");return i[a]||o}return o};for(let o of r)if(o.route)for(let a of o.route)a.route_type==="wire"&&(a.start_pcb_port_id=s(a.start_pcb_port_id),a.end_pcb_port_id=s(a.end_pcb_port_id))}},tit=class extends Bn{constructor(){super(...arguments);f(this,"pos",this.portMap.pin1);f(this,"anode",this.portMap.pin1);f(this,"neg",this.portMap.pin2);f(this,"cathode",this.portMap.pin2)}get config(){let e={laser:"laser_diode"},t=this.props.laser?"laser":null;return{schematicSymbolName:t?e[t]:this.props.symbolName??"led",componentName:"Led",zodProps:kH,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}getFootprinterString(){let e=super.getFootprinterString();return e&&this.props.color?`${e}_color(${this.props.color})`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_led",name:this.name,wave_length:t.wavelength,color:t.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},eit=class extends Bn{constructor(){super(...arguments);f(this,"pos",this.portMap.pin1);f(this,"positive",this.portMap.pin1);f(this,"neg",this.portMap.pin2);f(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:DH,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Wi({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Wi({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:t.voltage,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},nit=class extends Bn{constructor(){super(...arguments);f(this,"terminal1",this.portMap.terminal1);f(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:jH,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(e){if(!e.startsWith("Pcb"))for(let t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:t.voltage,frequency:t.frequency,peak_to_peak_voltage:t.peakToPeakVoltage,wave_shape:t.waveShape,phase:t.phase,duty_cycle:t.dutyCycle,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=this.portMap.terminal1,r=this.portMap.terminal2;e.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:r.source_port_id,voltage:t.voltage,frequency:t.frequency,peak_to_peak_voltage:t.peakToPeakVoltage,wave_shape:t.waveShape,phase:t.phase,duty_cycle:t.dutyCycle})}},UFt=["leftedge","rightedge","topedge","bottomedge","center"],iit=class extends Me{get config(){return{componentName:"Constraint",zodProps:cH}}constructor(n){if(super(n),("xdist"in n||"ydist"in n)&&!("edgeToEdge"in n)&&!("centerToCenter"in n))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in n&&n.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let n=[],e=this.getPrimitiveContainer();function t(i){let r=i.split(" ").pop(),s=UFt.includes(r)?r:void 0,o=s?i.replace(` ${s}`,""):i,a=e.selectOne(o,{pcbPrimitive:!0});a&&n.push({selector:i,component:a,componentSelector:o,edge:s})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&t(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)t(i);return{componentsWithSelectors:n}}},rit=class extends Me{constructor(){super(...arguments);f(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:CH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),o=s(t.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for FabricationNoteRect. Must be "top" or "bottom".`);let a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=this.getSubcircuit(),l=t.hasStroke??(t.strokeWidth!==void 0&&t.strokeWidth!==null),u=e.pcb_fabrication_note_rect.insert({pcb_component_id:a,layer:o,color:t.color,center:{x:i,y:r},width:t.width,height:t.height,stroke_width:t.strokeWidth??1,is_filled:t.isFilled??!1,has_stroke:l,is_stroke_dashed:t.isStrokeDashed??!1,subcircuit_id:c?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,corner_radius:t.cornerRadius??void 0});this.fabrication_note_rect_id=u.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},sit=class extends Me{constructor(){super(...arguments);f(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:IH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.getSubcircuit(),{_parsedProps:i}=this,r=i.layer??"top";if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let s=this._computePcbGlobalTransformBeforeLayout(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=e.pcb_fabrication_note_path.insert({pcb_component_id:o,layer:r,color:i.color,route:i.route.map(c=>{let l=De(s,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:t?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},oit=class extends Me{get config(){return{componentName:"FabricationNoteText",zodProps:MH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:n}=this.root,{_parsedProps:e}=this,{pcbX:t,pcbY:i}=this.getResolvedPcbPositionProp(),r=this.getPrimitiveContainer(),s=this.getSubcircuit();n.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:t,y:i},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:dP(e.text??""),pcb_component_id:r.pcb_component_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},ait=class extends Me{constructor(){super(...arguments);f(this,"fabrication_note_dimension_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:NH}}_resolvePoint(e,t){if(typeof e=="string"){let s=this.getSubcircuit().selectOne(e);return s?s._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${e}"`),De(t,{x:0,y:0}))}let i=typeof e.x=="string"?parseFloat(e.x):e.x,r=typeof e.y=="string"?parseFloat(e.y):e.y;return De(t,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(t.from,i),s=this._resolvePoint(t.to,i),o=this.getSubcircuit(),a=this.getGroup(),{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),l=c(t.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for FabricationNoteDimension. Must be "top" or "bottom".`);let u=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,p=t.text??this._formatDistanceText({from:r,to:s,units:t.units??"mm"}),d=e.pcb_fabrication_note_dimension.insert({pcb_component_id:u,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,layer:l,from:r,to:s,text:p,offset:t.offset,font:t.font??"tscircuit2024",font_size:t.fontSize??1,color:t.color,arrow_size:t.arrowSize??1});this.fabrication_note_dimension_id=d.pcb_fabrication_note_dimension_id}getPcbSize(){let e=this._computePcbGlobalTransformBeforeLayout(),t=this._resolvePoint(this._parsedProps.from,e),i=this._resolvePoint(this._parsedProps.to,e);return{width:Math.abs(i.x-t.x),height:Math.abs(i.y-t.y)}}_formatDistanceText({from:e,to:t,units:i}){let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s),a=i==="in"?o/25.4:o,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},cit=class extends Me{constructor(){super(...arguments);f(this,"pcb_note_line_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:oq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=this.getGroup(),s=this._computePcbGlobalTransformBeforeLayout(),o=De(s,{x:t.x1,y:t.y1}),a=De(s,{x:t.x2,y:t.y2}),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=e.pcb_note_line.insert({pcb_component_id:c,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,x1:o.x,y1:o.y,x2:a.x,y2:a.y,stroke_width:t.strokeWidth??.1,color:t.color,is_dashed:t.isDashed});this.pcb_note_line_id=l.pcb_note_line_id}getPcbSize(){let{_parsedProps:e}=this;return{width:Math.abs(e.x2-e.x1),height:Math.abs(e.y2-e.y1)}}},lit=class extends Me{constructor(){super(...arguments);f(this,"pcb_note_rect_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:rq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=De(i,{x:0,y:0}),s=this.getSubcircuit(),o=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=e.pcb_note_rect.insert({pcb_component_id:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,center:r,width:t.width,height:t.height,stroke_width:t.strokeWidth??.1,is_filled:t.isFilled??!1,has_stroke:t.hasStroke??!0,is_stroke_dashed:t.isStrokeDashed??!1,color:t.color,corner_radius:t.cornerRadius??void 0});this.pcb_note_rect_id=c.pcb_note_rect_id}getPcbSize(){let{_parsedProps:e}=this,t=typeof e.width=="string"?parseFloat(e.width):e.width,i=typeof e.height=="string"?parseFloat(e.height):e.height;return{width:t,height:i}}},uit=class extends Me{constructor(){super(...arguments);f(this,"pcb_note_text_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:iq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=De(i,{x:0,y:0}),s=this.getSubcircuit(),o=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=e.pcb_note_text.insert({pcb_component_id:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,font:t.font??"tscircuit2024",font_size:t.fontSize??1,text:dP(t.text),anchor_position:r,anchor_alignment:t.anchorAlignment??"center",color:t.color});this.pcb_note_text_id=c.pcb_note_text_id}getPcbSize(){let{_parsedProps:e}=this,t=typeof e.fontSize=="string"?parseFloat(e.fontSize):e.fontSize??1,i=t*.6;return{width:e.text.length*i,height:t}}},pit=class extends Me{constructor(){super(...arguments);f(this,"pcb_note_path_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:sq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this.getSubcircuit(),s=this.getGroup(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=t.route.map(l=>{let{x:u,y:p,...d}=l,_=typeof u=="string"?parseFloat(u):u,g=typeof p=="string"?parseFloat(p):p,x=De(i,{x:_,y:g});return{...d,x:x.x,y:x.y}}),c=e.pcb_note_path.insert({pcb_component_id:o,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,route:a,stroke_width:t.strokeWidth??.1,color:t.color});this.pcb_note_path_id=c.pcb_note_path_id}getPcbSize(){let{_parsedProps:e}=this;if(e.route.length===0)return{width:0,height:0};let t=e.route.map(c=>typeof c.x=="string"?parseFloat(c.x):c.x),i=e.route.map(c=>typeof c.y=="string"?parseFloat(c.y):c.y),r=Math.min(...t),s=Math.max(...t),o=Math.min(...i),a=Math.max(...i);return{width:s-r,height:a-o}}},hit=class extends Me{constructor(){super(...arguments);f(this,"pcb_note_dimension_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:aq}}_resolvePoint(e,t){if(typeof e=="string"){let s=this.getSubcircuit().selectOne(`.${e}`);return s?s._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${e}"`),De(t,{x:0,y:0}))}let i=typeof e.x=="string"?parseFloat(e.x):e.x,r=typeof e.y=="string"?parseFloat(e.y):e.y;return De(t,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(t.from,i),s=this._resolvePoint(t.to,i),o=this.getSubcircuit(),a=this.getGroup(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.text??this._formatDistanceText({from:r,to:s,units:t.units??"mm"}),u=e.pcb_note_dimension.insert({pcb_component_id:c,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,from:r,to:s,text:l,font:t.font??"tscircuit2024",font_size:t.fontSize??1,color:t.color,arrow_size:t.arrowSize??1});this.pcb_note_dimension_id=u.pcb_note_dimension_id}getPcbSize(){let e=this._computePcbGlobalTransformBeforeLayout(),t=this._resolvePoint(this._parsedProps.from,e),i=this._resolvePoint(this._parsedProps.to,e);return{width:Math.abs(i.x-t.x),height:Math.abs(i.y-t.y)}}_formatDistanceText({from:e,to:t,units:i}){let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s),a=i==="in"?o/25.4:o,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},dit=class extends Sl{constructor(n){super({...n,subcircuit:!0})}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:n,children:e}=this._parsedProps;Wnt(this,n,e)}},fit=class extends Sl{constructor(n){super({...n,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:n}=this.root,e=this._parsedProps;if(!this.pcb_group_id)return;let t=n.pcb_group.get(this.pcb_group_id),i=e.paddingLeft??e.padding??0,r=e.paddingRight??e.padding??0,s=e.paddingTop??e.padding??0,o=e.paddingBottom??e.padding??0;n.pcb_group.update(this.pcb_group_id,{width:(t.width??0)+i+r,height:(t.height??0)+s+o,center:{x:t.center.x+(r-i)/2,y:t.center.y+(s-o)/2}})}},mit=class extends Me{constructor(){super(...arguments);f(this,"pcb_breakout_point_id",null);f(this,"matchedPort",null);f(this,"matchedNet",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:OH}}_matchConnection(){let{connection:e}=this._parsedProps,t=this.getSubcircuit();t&&(this.matchedPort=t.selectOne(e,{type:"port"}),this.matchedPort||(this.matchedNet=t.selectOne(e,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${e}"`))}_getSourceTraceIdForPort(e){let{db:t}=this.root;return t.source_trace.list().find(r=>r.connected_source_port_ids.includes(e.source_port_id))?.source_trace_id}_getSourceNetIdForPort(e){let{db:t}=this.root;return t.source_trace.list().find(r=>r.connected_source_port_ids.includes(e.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;this._matchConnection();let{pcbX:t,pcbY:i}=this.getResolvedPcbPositionProp(),r=this.parent?.getGroup(),s=this.getSubcircuit();if(!r||!r.pcb_group_id)return;let o=e.pcb_breakout_point.insert({pcb_group_id:r.pcb_group_id,subcircuit_id:s?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:t,y:i});this.pcb_breakout_point_id=o.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:e,pcbY:t}=this.getResolvedPcbPositionProp();return{center:{x:e,y:t},bounds:{left:e,top:t,right:e,bottom:t},width:0,height:0}}_setPositionFromLayout(e){let{db:t}=this.root;this.pcb_breakout_point_id&&t.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:e.x,y:e.y})}getPcbSize(){return{width:0,height:0}}},_it=class extends Me{constructor(){super(...arguments);f(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:yH}}_getAnchorSide(){let{_parsedProps:e}=this;if(e.anchorSide)return e.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getConnectedPorts();if(r.length===0)return"right";let s=r[0]._getGlobalSchematicPositionBeforeLayout(),o=s.x-i.x,a=s.y-i.y;if(Math.abs(o)>Math.abs(a)){if(o>0)return"right";if(o<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let e=this._resolveConnectsTo();if(!e)return[];let t=[];for(let i of e){let r=this.getSubcircuit().selectOne(i);r&&t.push(r)}return t}computeSchematicPropsTransform(){let{_parsedProps:e}=this;if(e.schX===void 0&&e.schY===void 0){let t=this._getConnectedPorts();if(t.length>0){let i=t[0]._getGlobalSchematicPositionBeforeLayout(),r=De(this.parent?.computeSchematicGlobalTransform?.()??Pr(),{x:0,y:0});return kn(i.x-r.x,i.y-r.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),s=t.anchorSide??"right",o=wl({anchor_position:i,anchor_side:s,text:t.net}),a=e.schematic_net_label.insert({text:t.net,source_net_id:r.source_net_id,anchor_position:i,center:o,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:e}=this,t=e.connectsTo??e.connection;if(Array.isArray(t))return t;if(typeof t=="string")return[t]}_getNetName(){let{_parsedProps:e}=this;return e.net}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;e.net&&hP(this,[`net.${e.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let e=this._resolveConnectsTo();if(e)for(let t of e)this.add(new zs({from:t,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:e}=this.root,t=this._resolveConnectsTo();if(!t||t.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getAnchorSide(),o={left:"x-",right:"x+",top:"y+",bottom:"y-"}[r],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of t){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let S=e.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id??""));if(S&&(u=e.schematic_trace.list().some(P=>P.source_trace_id===S.source_trace_id)),u)continue}let p=l._getGlobalSchematicPositionAfterLayout(),d=x9(l.facingDirection??"right")??"x+",_=Qc({x:p.x,y:p.y,facingDirection:d},{x:i.x,y:i.y,facingDirection:o});if(!Array.isArray(_)||_.length<2)continue;let g=[];for(let S=0;S<_.length-1;S++)g.push({from:{x:_[S].x,y:_[S].y},to:{x:_[S+1].x,y:_[S+1].y}});let x,v;if(a?.source_net_id&&l.source_port_id){let S=e.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id));x=S?.source_trace_id,v=S?.subcircuit_connectivity_map_key||e.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}e.schematic_trace.insert({source_trace_id:x,edges:g,junctions:[],subcircuit_connectivity_map_key:v}),e.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},yit=class extends Me{constructor(){super(...arguments);f(this,"pcb_silkscreen_circle_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:eq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{pcbX:i,pcbY:r}=this.getResolvedPcbPositionProp(),{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),o=s(t.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenCircle. Must be "top" or "bottom".`);let a=this._computePcbGlobalTransformBeforeLayout(),c=this.getSubcircuit(),l=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,u=e.pcb_silkscreen_circle.insert({pcb_component_id:l,layer:o,center:{x:i,y:r},radius:t.radius,subcircuit_id:c?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_circle_id=u.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:e}=this,t=e.radius*2;return{width:t,height:t}}},git=class extends Me{constructor(){super(...arguments);f(this,"pcb_silkscreen_rect_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:tq}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenRect. Must be "top" or "bottom".`);let s=this.getSubcircuit(),{pcbX:o,pcbY:a}=this.getResolvedPcbPositionProp(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,l=e.pcb_silkscreen_rect.insert({pcb_component_id:c,layer:r,center:{x:o,y:a},width:t.width,height:t.height,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:t.strokeWidth??.1,is_filled:t.filled??!1,corner_radius:t.cornerRadius??void 0});this.pcb_silkscreen_rect_id=l.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},xit=class extends Me{constructor(){super(...arguments);f(this,"pcb_silkscreen_line_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:QH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenLine. Must be "top" or "bottom".`);let s=this.getSubcircuit(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=e.pcb_silkscreen_line.insert({pcb_component_id:o,layer:r,x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,stroke_width:t.strokeWidth??.1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:s?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:e}=this,t=Math.abs(e.x2-e.x1),i=Math.abs(e.y2-e.y1);return{width:t,height:i}}},bit=class extends Me{constructor(e){super(e);f(this,"pcb_via_id",null);f(this,"matchedPort",null);f(this,"isPcbPrimitive",!0);f(this,"source_manually_placed_via_id",null);f(this,"subcircuit_connectivity_map_key",null);let t=this._getLayers();this._parsedProps.layers=t,this.initPorts()}get config(){return{componentName:"Via",zodProps:AH}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}_getResolvedViaDiameters(e){return o7t({holeDiameter:this._parsedProps.holeDiameter,padDiameter:this._parsedProps.outerDiameter},e)}getPcbSize(){let e=this.getInheritedMergedProperty("pcbStyle"),{padDiameter:t}=this._getResolvedViaDiameters(e);return{width:t,height:t}}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-i.width/2,top:t.y-i.height/2,right:t.x+i.width/2,bottom:t.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}_getLayers(){let{fromLayer:e="top",toLayer:t="bottom"}=this._parsedProps;return e===t?[e]:[e,t]}initPorts(){let e=this._parsedProps.layers;for(let i of e){let r=new Wi({name:i,layer:i});r.registerMatch(this),this.add(r)}let t=new Wi({name:"pin1"});t.registerMatch(this),this.add(t)}_getConnectedNetOrTrace(){let e=this._parsedProps.connectsTo;if(!e)return null;let t=this.getSubcircuit(),i=Array.isArray(e)?e:[e];for(let r of i)if(r.startsWith("net.")){let s=t.selectOne(r,{type:"net"});if(s)return s}return null}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.getInheritedMergedProperty("pcbStyle"),{padDiameter:i}=this._getResolvedViaDiameters(t),r=this._getGlobalPcbPositionBeforeLayout(),s=this.getSubcircuit(),o=e.pcb_component.insert({center:r,width:i,height:i,layer:this._parsedProps.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:s?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=o.pcb_component_id}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=this.getGroup(),r=this.getSubcircuit(),s=e.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:t.net??"",subcircuit_id:r?.subcircuit_id??void 0});this.source_component_id=s.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.getInheritedMergedProperty("pcbStyle"),{holeDiameter:i,padDiameter:r}=this._getResolvedViaDiameters(t),s=this._getGlobalPcbPositionBeforeLayout(),o=this.getSubcircuit(),a=e.pcb_via.insert({x:s.x,y:s.y,hole_diameter:i,outer_diameter:r,layers:["bottom","top"],from_layer:this._parsedProps.fromLayer||"bottom",to_layer:this._parsedProps.toLayer||"top",subcircuit_id:o?.subcircuit_id??void 0,subcircuit_connectivity_map_key:this.subcircuit_connectivity_map_key??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,net_is_assignable:this._parsedProps.netIsAssignable??void 0});this.pcb_via_id=a.pcb_via_id}},vit=class extends Me{constructor(){super(...arguments);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:FH}}getPcbSize(){return{width:0,height:0}}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;hP(this,[e.connectsTo])}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit().selectOne(t.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${t.connectsTo}" not found for copper pour`);return}let r=this.getSubcircuit(),s=e.toArray().filter(p=>p.type==="source_net"&&p.name===i.name)[0]||"",o=t.clearance??.2,a=Ptt(e.toArray(),{layer:t.layer,pour_connectivity_key:s.subcircuit_connectivity_map_key||"",pad_margin:t.padMargin??o,trace_margin:t.traceMargin??o,board_edge_margin:t.boardEdgeMargin??o,cutout_margin:t.cutoutMargin??o}),c=new Stt(a),{brep_shapes:l}=c.getOutput(),u=t.coveredWithSolderMask??!1;for(let p of l)e.pcb_copper_pour.insert({shape:"brep",layer:t.layer,brep_shape:p,source_net_id:i.source_net_id,subcircuit_id:r?.subcircuit_id??void 0,covered_with_solder_mask:u})})}},wit=class extends Bn{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:mH,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=t.source_component_id}},Sit=class extends Bn{_getPcbRotationBeforeLayout(){let n=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+n}get config(){return{componentName:"PinHeader",zodProps:_H,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),e=this._parsedProps.holeDiameter,t=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,r=this._parsedProps.showSilkscreenPinLabels,s=this._parsedProps.doubleRow?2:1;if(n>0){let o;if(i)!e&&!t?o=`pinrow${n}_p${i}`:o=`pinrow${n}_p${i}_id${e}_od${t}`;else if(!e&&!t)o=`pinrow${n}`;else return null;return r!==!0&&(o+="_nopinlabels"),s>1&&(o+=`_rows${s}`),o}return null}initPorts(){let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let e=1;e<=n;e++){let t=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[e-1]:this._parsedProps.pinLabels?.[`pin${e}`];if(t){let i=Array.isArray(t)?t[0]:t,r=Array.isArray(t)?t.slice(1):[];this.add(new Wi({pinNumber:e,name:i,aliases:[`pin${e}`,...r]}))}else this.add(new Wi({pinNumber:e,name:`pin${e}`}))}}_getSchematicPortArrangement(){let n=this._parsedProps.pinCount??1,e=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",t=this._parsedProps.schPinArrangement;return e==="left"?{leftSide:{direction:t?.leftSide?.direction??"top-to-bottom",pins:t?.leftSide?.pins??Array.from({length:n},(i,r)=>`pin${r+1}`)}}:{rightSide:{direction:t?.rightSide?.direction??"top-to-bottom",pins:t?.rightSide?.pins??Array.from({length:n},(i,r)=>`pin${r+1}`)}}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:e.supplierPartNumbers,pin_count:e.pinCount,gender:e.gender,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}};function VFt(n){switch(n){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var Pit=class extends Bn{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??VFt(this.props.pinVariant),zodProps:sH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"no_ground",i=n.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:t,are_pins_interchangeable:t==="no_ground"||t==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let n=`${xi(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${xi(this._parsedProps.loadCapacitance)}F`:n}};function GFt(n){switch(n){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var kit=class extends Bn{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??GFt(this.props.pinVariant),zodProps:iH,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${xi(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"two_pin",i=n.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:e.maxResistance,pin_variant:t,are_pins_interchangeable:t==="two_pin"});this.source_component_id=i.source_component_id}},Tit=class extends Bn{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:gH,sourceFtype:Ha.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let n=yi[this._getSchematicSymbolNameOrThrow()],e=n.ports.find(l=>l.labels.includes("1")),t=n.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),r=i.find(l=>l.props.pinNumber===1),s=i.find(l=>l.props.pinNumber===2),o=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;r.schematicSymbolPortDef=e,(!c||c.length===0)&&(s.schematicSymbolPortDef=t);for(let[l,u]of[[2,s],[3,o],[4,a]]){let p=c?.find(([_,g])=>_===`pin${l}`||g===`pin${l}`);if(!p){u.schematicSymbolPortDef=t;break}(p?.[0]===`pin${l}`?p[1]:p?.[0])!=="pin1"&&(u.schematicSymbolPortDef=t)}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:Ha.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}},Eit=class extends Bn{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:rH,sourceFtype:"simple_crystal"}}initPorts(){let n=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:n})}_getSchematicSymbolDisplayValue(){let n=`${xi(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${xi(this._parsedProps.loadCapacitance)}F`:n}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:e.frequency,load_capacitance:e.loadCapacitance,pin_variant:e.pinVariant||"two_pin",are_pins_interchangeable:(e.pinVariant||"two_pin")==="two_pin"});this.source_component_id=t.source_component_id}},Mit=class extends Bn{get config(){let n=this.props.mosfetMode==="depletion"?"d":"e",t=`${this.props.channelType}_channel_${n}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??t,zodProps:vH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=t.source_component_id}};function WFt(n){return n.simSwitchFrequency!==void 0||n.simCloseAt!==void 0||n.simOpenAt!==void 0||n.simStartClosed!==void 0||n.simStartOpen!==void 0}var Cit=class extends Bn{_getSwitchType(){let n=this._parsedProps;return n?n.dpdt?"dpdt":n.spst?"spst":n.spdt?"spdt":n.dpst?"dpst":n.type??"spst":"spst"}get config(){let n=this._getSwitchType(),e=this._parsedProps?.isNormallyClosed??!1,t={spst:e?"spst_normally_closed_switch":"spst_switch",spdt:e?"spdt_normally_closed_switch":"spdt_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??t[n],zodProps:EH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,e=this._parsedProps??{},t=n.source_component.insert({ftype:"simple_switch",name:this.name,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=t.source_component_id}doInitialSimulationRender(){let{_parsedProps:n}=this;if(!WFt(n))return;let{db:e}=this.root,t={type:"simulation_switch",source_component_id:this.source_component_id||""};n.simSwitchFrequency!==void 0&&(t.switching_frequency=zr.parse(n.simSwitchFrequency)),n.simCloseAt!==void 0&&(t.closes_at=hr.parse(n.simCloseAt)),n.simOpenAt!==void 0&&(t.opens_at=hr.parse(n.simOpenAt)),n.simStartOpen!==void 0&&(t.starts_closed=!n.simStartOpen),n.simStartClosed!==void 0&&(t.starts_closed=n.simStartClosed),e.simulation_switch.insert(t)}},_9={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},Iit=class extends Bn{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:RH,sourceFtype:Ha.simple_test_point}}_getPropsWithDefaults(){let{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}=this._parsedProps;return!t&&e&&(t="through_hole"),t??(t="through_hole"),n??(n="circle"),t==="pad"?n==="circle"?i??(i=_9.SMT_CIRCLE_DIAMETER):n==="rect"&&(r??(r=_9.SMT_RECT_SIZE),s??(s=r)):t==="through_hole"&&(e??(e=_9.HOLE_DIAMETER)),{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}}_getImpliedFootprintString(){let{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}=this._getPropsWithDefaults();if(t==="through_hole")return`platedhole_d${e}`;if(t==="pad"){if(n==="circle")return`smtpad_circle_d${i}`;if(n==="rect")return`smtpad_rect_w${r}_h${s}`}throw new Error(`Footprint variant "${t}" with pad shape "${n}" not implemented`)}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,{padShape:t,holeDiameter:i,footprintVariant:r,padDiameter:s,width:o,height:a}=this._getPropsWithDefaults(),c=n.source_component.insert({ftype:Ha.simple_test_point,name:this.name,supplier_part_numbers:e.supplierPartNumbers,footprint_variant:r,pad_shape:t,pad_diameter:s,hole_diameter:i,width:o,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},Nit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:WH}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout();e.schematic_text.insert({anchor:t.anchor??"center",text:dP(t.text),font_size:t.fontSize,color:t.color||"#000000",position:{x:i.x,y:i.y},rotation:t.schRotation??0})}},Ait=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:GH}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_line.insert({schematic_component_id:r,x1:t.x1+i.x,y1:t.y1+i.y,x2:t.x2+i.x,y2:t.y2+i.y,stroke_width:t.strokeWidth??yP,color:t.color??_P,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=s.schematic_line_id}},Rit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:VH}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_rect.insert({center:{x:i.x,y:i.y},width:t.width,height:t.height,stroke_width:t.strokeWidth??yP,color:t.color??_P,is_filled:t.isFilled,schematic_component_id:r,is_dashed:t.isDashed,rotation:t.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=s.schematic_rect_id}},Oit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:YH}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_arc.insert({schematic_component_id:r,center:{x:t.center.x+i.x,y:t.center.y+i.y},radius:t.radius,start_angle_degrees:t.startAngleDegrees,end_angle_degrees:t.endAngleDegrees,direction:t.direction,stroke_width:t.strokeWidth??yP,color:t.color??_P,is_dashed:t.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=s.schematic_arc_id}},Lit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:UH}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_circle.insert({schematic_component_id:r,center:{x:t.center.x+i.x,y:t.center.y+i.y},radius:t.radius,stroke_width:t.strokeWidth??yP,color:t.color??_P,is_filled:t.isFilled,fill_color:t.fillColor,is_dashed:t.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=s.schematic_circle_id}};function HFt({anchor:n,x:e,y:t,width:i,height:r,isInside:s}){switch(n){case"top_left":return{x:e,y:t+r,textAnchor:s?"top_left":"bottom_left"};case"top_center":return{x:e+i/2,y:t+r,textAnchor:s?"top_center":"bottom_center"};case"top_right":return{x:e+i,y:t+r,textAnchor:s?"top_right":"bottom_right"};case"center_left":return{x:e,y:t+r/2,textAnchor:s?"center_left":"center_right"};case"center":return{x:e+i/2,y:t+r/2,textAnchor:"center"};case"center_right":return{x:e+i,y:t+r/2,textAnchor:s?"center_right":"center_left"};case"bottom_left":return{x:e,y:t,textAnchor:s?"bottom_left":"top_left"};case"bottom_center":return{x:e+i/2,y:t,textAnchor:s?"bottom_center":"top_center"};case"bottom_right":return{x:e+i,y:t,textAnchor:s?"bottom_right":"top_right"};default:return{x:e+i/2,y:t+r,textAnchor:"center"}}}var Fit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:XH,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=.6,r=typeof t.padding=="number"?t.padding:0,s=typeof t.paddingTop=="number"?t.paddingTop:r,o=typeof t.paddingBottom=="number"?t.paddingBottom:r,a=typeof t.paddingLeft=="number"?t.paddingLeft:r,c=typeof t.paddingRight=="number"?t.paddingRight:r,l=t.overlay&&t.overlay.length>0,u=typeof t.width=="number"&&typeof t.height=="number",p,d,_,g,x,v;if(l){let P=t.overlay.map(J=>({selector:J,port:this.getSubcircuit().selectOne(J,{type:"port"})})).filter(({port:J})=>J!=null).map(({port:J})=>({position:J._getGlobalSchematicPositionAfterLayout()}));if(P.length===0)return;let T=P.map(J=>J.position.x),k=P.map(J=>J.position.y),N=Math.min(...T),E=Math.max(...T),C=Math.min(...k),M=Math.max(...k),A=E-N,R=M-C,B=A===0?i:0,j=R===0?i:0,U=a+B/2,X=c+B/2,W=s+j/2,et=o+j/2,nt=N-U,mt=E+X,G=C-et,tt=M+W;p=mt-nt,d=tt-G,_=nt+(t.schX??0),g=G+(t.schY??0),x=_+p/2,v=g+d/2}else if(u){p=t.width,d=t.height;let S=this._getGlobalSchematicPositionBeforeLayout();x=S.x,v=S.y,_=x-p/2,g=v-d/2}else return;if(e.schematic_box.insert({height:d,width:p,x:_,y:g,is_dashed:t.strokeStyle==="dashed"}),t.title){let S=t.titleInside,P=.1,T=t.titleAlignment,k=HFt({anchor:T,x:_,y:g,width:p,height:d,isInside:S}),N,E,C=k.textAnchor;S?(N=T.includes("top")?-P:T.includes("bottom")?P:0,E=T.includes("left")?P:T.includes("right")?-P:0):(N=T.includes("top")?P:T.includes("bottom")?-P:0,E=T.includes("center_left")?-P:T.includes("center_right")?P:0);let M=k.x+E,A=k.y+N;e.schematic_text.insert({anchor:C,text:t.title,font_size:t.titleFontSize??.18,color:t.titleColor??"#000000",position:{x:M,y:A},rotation:0})}}},$it=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:HH}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.children.filter(d=>d.componentName==="SchematicRow");if(i.length===0)return;let r=[],s=0;for(let d of i){let _=d.children.filter(g=>g.componentName==="SchematicCell");s=Math.max(s,_.length)}for(let d=0;d<i.length;d++)r[d]=[];for(let d=0;d<i.length;d++){let g=i[d].children.filter(v=>v.componentName==="SchematicCell"),x=0;for(let v=0;v<g.length;v++){for(;r[d][x];)x++;let S=g[v],P=S._parsedProps.colSpan??1,T=S._parsedProps.rowSpan??1;for(let k=0;k<T;k++)for(let N=0;N<P;N++)r[d+k]||(r[d+k]=[]),r[d+k][x+N]=S;x+=P}}s=Math.max(0,...r.map(d=>d.length));let o=i.map((d,_)=>d._parsedProps.height??1),a=Array.from({length:s},(d,_)=>{let g=0;for(let x=0;x<i.length;x++){let v=r[x]?.[_];if(v){let S=v._parsedProps.text??v._parsedProps.children,P=v._parsedProps.width??(S?.length??2)*.5;P>g&&(g=P)}}return g||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=e.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:o,cell_padding:t.cellPadding,border_width:t.borderWidth,anchor:t.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=l.schematic_table_id;let u=new Set,p=0;for(let d=0;d<i.length;d++){let _=0;for(let g=0;g<s;g++){let x=r[d]?.[g];if(x&&!u.has(x)){u.add(x);let v=x._parsedProps,S=v.rowSpan??1,P=v.colSpan??1,T=0;for(let N=0;N<P;N++)T+=a[g+N];let k=0;for(let N=0;N<S;N++)k+=o[d+N];e.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:d,end_row_index:d+S-1,start_column_index:g,end_column_index:g+P-1,text:v.text??v.children,center:{x:c.x+_+T/2,y:c.y-p-k/2},width:T,height:k,horizontal_align:v.horizontalAlign,vertical_align:v.verticalAlign,font_size:v.fontSize??t.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[g]&&(_+=a[g])}p+=o[d]}}},zit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:qH}}},Dit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:ZH}}},jit=class extends Me{constructor(){super(...arguments);f(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:fH}}},Bit=class extends Me{get config(){return{componentName:"AnalogSimulation",zodProps:xH}}doInitialSimulationRender(){let{db:n}=this.root,{duration:e,timePerStep:t}=this._parsedProps,i=e||10,r=t||.01;n.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:i,time_per_step:r})}},Yit=class extends Me{constructor(){super(...arguments);f(this,"simulation_voltage_probe_id",null);f(this,"schematic_voltage_probe_id",null);f(this,"finalProbeName",null);f(this,"color",null)}get config(){return{componentName:"VoltageProbe",zodProps:BH}}doInitialSimulationRender(){let{db:e}=this.root,{connectsTo:t,name:i,referenceTo:r,color:s}=this._parsedProps,o=this.getSubcircuit();if(!o){this.renderError("VoltageProbe must be inside a subcircuit");return}let a=Array.isArray(t)?t:[t];if(a.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let c=a[0],l=o.selectOne(c,{type:"port"}),u=l?null:o.selectOne(c,{type:"net"});if(u&&u.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${c}" resolved to a non-net component "${u.componentName}".`);return}if(!l&&!u){this.renderError(`VoltageProbe could not find connection target "${c}"`);return}let p=l?.source_port_id??u?.source_net_id;if(!p){this.renderError("Could not identify connected source for VoltageProbe");return}let d=null,_=null;if(r){let v=Array.isArray(r)?r:[r];if(v.length!==1){this.renderError("VoltageProbe must reference exactly one port or net");return}let S=v[0];if(d=o.selectOne(S,{type:"port"}),_=d?null:o.selectOne(S,{type:"net"}),_&&_.componentName!=="Net"){this.renderError(`VoltageProbe reference target "${S}" resolved to a non-net component "${_.componentName}".`);return}if(!d&&!_){this.renderError(`VoltageProbe could not find reference target "${S}"`);return}}this.color=s??xFt(p);let g=i;g||(g=a[0].split(" > ").map(v=>v.replace(/^\./,"")).join(".")),this.finalProbeName=g??null;let{simulation_voltage_probe_id:x}=e.simulation_voltage_probe.insert({name:g,signal_input_source_port_id:l?.source_port_id??void 0,signal_input_source_net_id:u?.source_net_id??void 0,reference_input_source_port_id:d?.source_port_id??void 0,reference_input_source_net_id:_?.source_net_id??void 0,subcircuit_id:o.subcircuit_id||void 0,color:this.color});this.simulation_voltage_probe_id=x}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{connectsTo:t,name:i}=this._parsedProps,r=this.getSubcircuit();if(!r)return;let s=Array.isArray(t)?t:[t];if(s.length!==1)return;let o=s[0],a=r.selectOne(o,{type:"port"});if(!a||!a.schematic_port_id)return;let c=a._getGlobalSchematicPositionAfterLayout(),l=null;for(let d of e.schematic_trace.list()){for(let _ of d.edges)if(Math.abs(_.from.x-c.x)<1e-6&&Math.abs(_.from.y-c.y)<1e-6||Math.abs(_.to.x-c.x)<1e-6&&Math.abs(_.to.y-c.y)<1e-6){l=d.schematic_trace_id;break}if(l)break}if(!l)return;let u=this.finalProbeName,p=e.schematic_voltage_probe.insert({name:u,position:c,schematic_trace_id:l,subcircuit_id:r.subcircuit_id||void 0,color:this.color??void 0});this.schematic_voltage_probe_id=p.schematic_voltage_probe_id}},qFt={name:"@tscircuit/core",type:"module",version:"0.0.898",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"',"generate-test-plan":"bun run scripts/generate-test-plan.ts"},devDependencies:{"@biomejs/biome":"^1.8.3","@resvg/resvg-js":"^2.6.2","@tscircuit/capacity-autorouter":"^0.0.140","@tscircuit/checks":"^0.0.87","@tscircuit/circuit-json-util":"^0.0.72","@tscircuit/common":"^0.0.20","@tscircuit/copper-pour-solver":"^0.0.14","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.29","@tscircuit/miniflex":"^0.0.4","@tscircuit/ngspice-spice-engine":"^0.0.4","@tscircuit/props":"^0.0.423","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^v0.0.45","@tscircuit/solver-utils":"^0.0.3","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.325","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-gltf":"^0.0.31","circuit-json-to-simple-3d":"^0.0.9","circuit-json-to-spice":"^0.0.27","circuit-to-svg":"^0.0.280",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6","eecircuit-engine":"^1.5.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",poppygl:"^0.0.16",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202",spicey:"^0.0.14","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.62","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},Q_=class{constructor({platform:n,projectUrl:e}={}){f(this,"firstChild",null);f(this,"children");f(this,"db");f(this,"root",null);f(this,"isRoot",!0);f(this,"_schematicDisabledOverride");f(this,"pcbDisabled",!1);f(this,"pcbRoutingDisabled",!1);f(this,"_featureMspSchematicTraceRouting",!0);f(this,"name");f(this,"platform");f(this,"projectUrl");f(this,"_hasRenderedAtleastOnce",!1);f(this,"_eventListeners",{});this.children=[],this.db=Ce([]),this.root=this,this.platform=n,this.projectUrl=e,this.pcbDisabled=n?.pcbDisabled??!1}get schematicDisabled(){return this._schematicDisabledOverride!==void 0?this._schematicDisabledOverride:this._getBoard()?._parsedProps?.schematicDisabled??!1}set schematicDisabled(n){this._schematicDisabledOverride=n}add(n){let e;(0,Xit.isValidElement)(n)?e=Snt(n):e=n,this.children.push(e)}setPlatform(n){this.platform={...this.platform,...n}}_getBoard(){let n=this.children.find(e=>e.componentName==="Board");if(n)return n}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");let n=this.children.filter(t=>t.lowercaseComponentName==="panel");if(n.length>1)throw new Error("Only one <panel> is allowed per circuit");if(n.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=n[0];return}if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let e=new Sl({subcircuit:!0});e.parent=this,e.addAll(this.children),this.children=[e],this.firstChild=e}render(){this.firstChild||this._guessRootComponent();let{firstChild:n,db:e}=this;if(!n)throw new Error("RootCircuit has no root component");n.parent=this,n.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(e=>setTimeout(e,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(n=>n._hasIncompleteAsyncEffects())}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(n){let e=await Promise.resolve().then(()=>(zet(),$et)).catch(t=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
254
254
 
255
255
  "${t.message}"`)});if(n.view==="pcb")return e.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(n.view==="schematic")return e.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${n.view}`)}getCoreVersion(){let[n,e,t]=qFt.version.split(".").map(Number);return`${n}.${e}.${t+1}`}async preview(n){let e=typeof n=="object"?n:{previewName:n};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return Pr()}_computePcbGlobalTransformBeforeLayout(){return Pr()}selectAll(n){return this._guessRootComponent(),this.firstChild?.selectAll(n)??[]}selectOne(n,e){return this._guessRootComponent(),this.firstChild?.selectOne(n,e)??null}emit(n,...e){if(this._eventListeners[n])for(let t of this._eventListeners[n])t(...e)}on(n,e){this._eventListeners[n]||(this._eventListeners[n]=[]),this._eventListeners[n].push(e)}removeListener(n,e){this._eventListeners[n]&&(this._eventListeners[n]=this._eventListeners[n].filter(t=>t!==e))}enableDebug(n){typeof n=="string"?k9.default.enable(n):(n===null||n===!1)&&k9.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},ZFt=Q_,KFt=Q_,JFt=n=>{let[e,t]=W_.default.useState(!0),[i,r]=W_.default.useState(null),[s,o]=W_.default.useState(),[a,c]=W_.default.useState();return W_.default.useEffect(()=>{t(!0),r(null),n&&setTimeout(()=>{try{let l=new Q_;l.add(n),o(l),c(l.toJson())}catch(l){r(l)}t(!1)},1)},[n]),{isLoading:e,error:i,circuit:s,circuitJson:a}},ty=(n,e)=>(t,i)=>{let r=[];Array.isArray(e)?r.push(...e.flat()):typeof e=="object"&&r.push(...Object.values(e).flat(),...Object.keys(e));let s=o=>{if(o?.name&&o.name!==t)throw new Error(`Component name mismatch. Hook name: ${t}, Component prop name: ${o.name}`);let a={...i,...o,name:t},c=[];for(let l of r)if(a[l]){let u=`.${t} > .${l}`,p=a[l];c.push({from:u,to:p}),delete a[l]}return(0,Fd.jsxs)(Fd.Fragment,{children:[(0,Fd.jsx)(n,{...a}),c.map((l,u)=>(0,Fd.jsx)("trace",{...l},u))]})};for(let o of r)s[o]=`.${t} > .${o}`;return s},QFt=ty(n=>(0,Uit.jsx)("capacitor",{...n}),aH),t$t=n=>ty(e=>(0,Vit.jsx)("chip",{pinLabels:n,...e}),n),e$t=ty(n=>(0,Git.jsx)("diode",{...n}),PH),n$t=ty(n=>(0,Wit.jsx)("led",{...n}),TH),i$t=ty(n=>(0,Hit.jsx)("resistor",{...n}),nH),r$t=new Proxy(n=>new Proxy({},{get:(e,t)=>`.${n} > .${t}`}),{get:(n,e)=>{let t=(...i)=>{let r=i[0];return new Proxy({},{get:(s,o)=>`.${e} > .${o}`})};return new Proxy(t,{get:(i,r)=>e==="net"?`net.${r}`:e==="subcircuit"?new Proxy({},{get:(s,o)=>new Proxy({},{get:(a,c)=>`subcircuit.${r} > .${o} > .${c}`})}):`.${e} > .${r}`,apply:(i,r,s)=>e==="net"?new Proxy({},{get:(o,a)=>`net.${a}`}):new Proxy({},{get:(o,a)=>{let c=`.${e} > .${a}`;return["U","J","CN"].some(u=>e.startsWith(u))?c:new Proxy(new String(c),{get:(u,p)=>typeof p=="symbol"||p==="toString"?()=>c:`.${e} > .${a} > .${p}`})}})})}});wnt(ynt);wnt({Bug:Z1});var Yrt=Vt(Js(),1),L$t=Vt(_l(),1);var Zit=n=>{let e=n.match(/:[RC]_(\d{4})_/);if(e||(e=n.match(/:(SOIC-\d+|SOT-\d+|SOD-\d+|SSOP-\d+|TSSOP-\d+|QFP-\d+|QFN-\d+)/),e))return e[1]};var j9=n=>n.includes("cap")?n.replace(/cap/g,""):n;var Kit=n=>{if(n){if(n.startsWith("kicad:")){let e=Zit(n);return e?j9(e):n}return j9(n)}};var B9=new Map,Er=async(n,e)=>{let t=new URLSearchParams({...e,json:"true"}).toString();if(B9.has(t))return B9.get(t);let r=await(await fetch(`https://jlcsearch.tscircuit.com/${n}/list?${t}`)).json();return B9.set(t,r),r},Mr=n=>n?[...n].sort((e,t)=>Number(t.is_basic??!1)-Number(e.is_basic??!1)):[],Jit={findPart:async({sourceComponent:n,footprinterString:e})=>{let t=Kit(e);if(n.type==="source_component"&&n.ftype==="simple_resistor"){let{resistors:i}=await Er("resistors",{resistance:n.resistance,package:t});return{jlcpcb:Mr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_capacitor"){let{capacitors:i}=await Er("capacitors",{capacitance:n.capacitance,package:t});return{jlcpcb:Mr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_pin_header"){let i;e?.includes("_p")&&(i=Number(e.split("_p")[1]));let{headers:r}=await Er("headers",i?{pitch:i,num_pins:n.pin_count,gender:n.gender}:{num_pins:n.pin_count,gender:n.gender});return{jlcpcb:Mr(r).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_potentiometer"){let{potentiometers:i}=await Er("potentiometers",{resistance:n.max_resistance,package:t});return{jlcpcb:Mr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_diode"){let{diodes:i}=await Er("diodes",{package:t});return{jlcpcb:Mr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_chip"){let{chips:i}=await Er("chips",{package:t});return{jlcpcb:Mr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_transistor"){let{transistors:i}=await Er("transistors",{package:t,transistor_type:n.transistor_type});return{jlcpcb:Mr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_power_source"){let{power_sources:i}=await Er("power_sources",{voltage:n.voltage,package:t});return{jlcpcb:Mr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_inductor"){let{inductors:i}=await Er("inductors",{inductance:n.inductance,package:t});return{jlcpcb:Mr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_crystal"){let{crystals:i}=await Er("crystals",{frequency:n.frequency,load_capacitance:n.load_capacitance,package:t});return{jlcpcb:Mr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_mosfet"){let{mosfets:i}=await Er("mosfets",{package:t,mosfet_mode:n.mosfet_mode,channel_type:n.channel_type});return{jlcpcb:Mr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_resonator"){let{resonators:i}=await Er("resonators",{frequency:n.frequency,package:t});return{jlcpcb:Mr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_switch"){let{switches:i}=await Er("switches",{switch_type:n.type,package:t});return{jlcpcb:Mr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_led"){let{leds:i}=await Er("leds",{package:t});return{jlcpcb:Mr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_fuse"){let{fuses:i}=await Er("fuses",{package:t});return{jlcpcb:Mr(i).map(r=>`C${r.lcsc}`).slice(0,3)}}return{}}};var irt=Vt(Qit(),1);Q();var crt=Vt(In(),1),lrt=Vt(In(),1),bi=h.tuple([h.coerce.number(),h.coerce.number()]),f$t=h.tuple([h.number(),h.number(),h.number()]),PP=h.union([bi,f$t]),m$t=h.object({kind:h.literal("arc"),start:bi,mid:bi,end:bi}),_$t=h.union([bi,m$t]),rrt=h.object({at:PP,size:bi,layer:h.string(),layers:h.array(h.string()),roundrect_rratio:h.number(),uuid:h.string()}).partial(),y$t=h.object({key:h.string(),val:h.string(),attributes:rrt}),vP=h.object({oval:h.boolean().default(!1),width:h.number().optional(),height:h.number().optional(),offset:bi.optional()}),srt=h.object({name:h.string(),pad_type:h.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:h.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:PP,drill:h.union([h.number(),h.array(h.any()),vP]).transform(n=>typeof n=="number"?{oval:!1,width:n,height:n}:"oval"in n?n:n.length===2?{oval:!1,width:Number.parseFloat(n[0]),height:Number.parseFloat(n[0]),offset:bi.parse(n[1].slice(1))}:n.length===3||n.length===4?{oval:n[0]==="oval",width:Number.parseFloat(n[1]),height:Number.parseFloat(n[2]),offset:n[3]?bi.parse(n[3].slice(1)):void 0}:n).pipe(vP),size:h.union([h.array(h.number()).length(2).transform(([n,e])=>({width:n,height:e})),h.object({width:h.number(),height:h.number()})]),layers:h.array(h.string()).optional(),roundrect_rratio:h.number().optional(),uuid:h.string().optional()}),ort=h.object({name:h.string(),pad_type:h.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:h.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:PP,size:bi,drill:h.union([h.number(),h.array(h.any()),vP]).transform(n=>typeof n=="number"?{oval:!1,width:n,height:n}:"oval"in n?n:n.length===2?{oval:!1,width:Number.parseFloat(n[0]),height:Number.parseFloat(n[0]),offset:bi.parse(n[1].slice(1))}:n.length===3||n.length===4?{oval:n[0]==="oval",width:Number.parseFloat(n[1]),height:Number.parseFloat(n[2]),offset:n[3]?bi.parse(n[3].slice(1)):void 0}:n).pipe(vP).optional(),layers:h.array(h.string()).optional(),roundrect_rratio:h.number().optional(),chamfer_ratio:h.number().optional(),solder_paste_margin:h.number().optional(),solder_paste_margin_ratio:h.number().optional(),clearance:h.number().optional(),zone_connection:h.union([h.literal(0).describe("Pad is not connect to zone"),h.literal(1).describe("Pad is connected to zone using thermal relief"),h.literal(2).describe("Pad is connected to zone using solid fill")]).optional(),thermal_width:h.number().optional(),thermal_gap:h.number().optional(),uuid:h.string().optional()}),art=h.object({font:h.object({size:bi,thickness:h.number().optional()})}).partial(),g$t=h.object({fp_text_type:h.literal("user"),text:h.string(),at:PP,layer:h.string(),uuid:h.string().optional(),effects:art.partial()}),x$t=h.object({start:bi,mid:bi,end:bi,stroke:h.object({width:h.number(),type:h.string()}),layer:h.string(),uuid:h.string().optional()}),b$t=h.object({center:bi,end:bi,stroke:h.object({width:h.number(),type:h.string()}),fill:h.string().optional(),layer:h.string(),uuid:h.string().optional()}),v$t=h.object({pts:h.array(_$t),stroke:h.object({width:h.number(),type:h.string()}).optional(),width:h.number().optional(),layer:h.string(),uuid:h.string().optional(),fill:h.string().optional()}).transform(n=>({...n,width:void 0,stroke:n.stroke??{width:n.width}})),w$t=h.object({start:bi,end:bi,stroke:h.object({width:h.number(),type:h.string()}).optional(),width:h.number().optional(),layer:h.string(),uuid:h.string().optional()}).transform(n=>({...n,width:void 0,stroke:n.stroke??{width:n.width}})),trt=h.object({footprint_name:h.string(),version:h.string().optional(),generator:h.string().optional(),generator_version:h.string().optional(),layer:h.string(),descr:h.string().default(""),tags:h.array(h.string()).optional(),properties:h.array(y$t),fp_lines:h.array(w$t),fp_texts:h.array(g$t),fp_arcs:h.array(x$t),fp_circles:h.array(b$t).optional(),fp_polys:h.array(v$t).optional(),pads:h.array(ort),holes:h.array(srt).optional()}),wP=(n,e)=>{if(e==="effects"&&Array.isArray(n)){let t={};for(let i of n)if(i[0]==="font"){let r={};for(let s of i.slice(1))s.length===2?r[s[0].valueOf()]=Number.parseFloat(s[1].valueOf()):r[s[0].valueOf()]=s.slice(1).map(o=>Number.parseFloat(o.valueOf()));t.font=r}return art.parse(t)}if(e==="pts")return n.map(t=>{let i=t[0]?.valueOf?.()??t[0];if(i==="xy")return t.slice(1).map(r=>Number.parseFloat(r.valueOf()));if(i==="arc"){let r={kind:"arc"};for(let s of t.slice(1)){let o=s[0].valueOf();r[o]=s.slice(1).map(a=>Number.parseFloat(a.valueOf()))}return r}return t});if(e==="stroke"){let t={};for(let i of n){let r=i[0].valueOf();t[r]=wP(i.slice(1),r)}return t}return e==="at"||e==="size"||e==="start"||e==="mid"||e==="end"?(Array.isArray(n)?n:[n]).map(i=>i?.valueOf?.()??i).filter(i=>typeof i=="number"||typeof i=="string"&&/^[-+]?\d*\.?\d+(e[-+]?\d+)?$/i.test(i)).map(i=>typeof i=="number"?i:Number.parseFloat(i)):e==="tags"?n.map(t=>t.valueOf()):e==="generator_version"||e==="version"?n[0].valueOf():n.length===2?n.valueOf():e==="uuid"?Array.isArray(n)?n[0].valueOf():n.valueOf():/^[\d\.]+$/.test(n)&&!Number.isNaN(Number.parseFloat(n))?Number.parseFloat(n):Array.isArray(n)&&n.length===1?n[0].valueOf():Array.isArray(n)?n.map(t=>t.valueOf()):n},Ye=(n,e)=>{for(let t of n)if(Array.isArray(t)&&t[0]===e)return wP(t.slice(1),e)},Y9=(0,crt.default)("kicad-mod-converter"),S$t=n=>{let e=(0,irt.default)(n),t=e[1].valueOf(),i={},r=Object.entries(trt.shape).filter(([T,k])=>k._def.typeName==="ZodString"||T==="tags").map(([T])=>T);for(let T of e.slice(2)){if(!r.includes(T[0]))continue;let k=T[0].valueOf(),N=wP(T.slice(1),k);i[k]=N}let s=e.slice(2).filter(T=>T[0]==="property").map(T=>{let k=T[1].valueOf(),N=T[2].valueOf(),E=rrt.parse(T.slice(3).reduce((C,M)=>{let A=M[0].valueOf();return C[A]=wP(M.slice(1),A),C},{}));return{key:k,val:N,attributes:E}}),o=e.slice(2).filter(T=>T[0]==="pad"),a=[];for(let T of o){let k=Ye(T,"at"),N=Ye(T,"size"),E=Ye(T,"drill"),C=Ye(T,"layers");if(Array.isArray(C)?C=C.map(B=>B.valueOf()):typeof C=="string"?C=[C]:C||(C=[]),!C.includes("F.Cu")){Y9(`Skipping pad without F.Cu layer: layers=${C.join(", ")}`);continue}let M=Ye(T,"roundrect_rratio"),A=Ye(T,"uuid"),R={name:T[1].valueOf(),pad_type:T[2].valueOf(),pad_shape:T[3].valueOf(),at:k,drill:E,size:N,layers:C,roundrect_rratio:M,uuid:A};Y9(`attempting to parse pad: ${JSON.stringify(R,null," ")}`),a.push(ort.parse(R))}let c=e.slice(2).filter(T=>T[0]==="fp_text"),l=[];for(let T of c){let k=T[2].valueOf(),N=Ye(T,"at"),E=Ye(T,"layer"),C=Ye(T,"uuid"),M=Ye(T,"effects");l.push({fp_text_type:"user",text:k,at:N,layer:E,uuid:C,effects:M})}let u=[],p=e.slice(2).filter(T=>T[0]==="fp_line");for(let T of p){let k=Ye(T,"start"),N=Ye(T,"end"),E=Ye(T,"stroke"),C=Ye(T,"layer"),M=Ye(T,"uuid");u.push({start:k,end:N,stroke:E,layer:C,uuid:M})}let d=[],_=e.slice(2).filter(T=>T[0]==="fp_arc");for(let T of _){let k=Ye(T,"start"),N=Ye(T,"mid"),E=Ye(T,"end"),C=Ye(T,"stroke"),M=Ye(T,"layer"),A=Ye(T,"uuid");!k||!E||!N||!C||!M||d.push({start:k,mid:N,end:E,stroke:C,layer:M,uuid:A})}let g=[],x=e.slice(2).filter(T=>T[0]==="fp_circle");for(let T of x){let k=Ye(T,"center"),N=Ye(T,"end"),E=Ye(T,"stroke"),C=Ye(T,"fill"),M=Ye(T,"layer"),A=Ye(T,"uuid");!k||!N||!E||!M||g.push({center:k,end:N,stroke:E,fill:C,layer:M,uuid:A})}let v=[],S=e.slice(2).filter(T=>T[0]==="fp_poly");for(let T of S){let k=Ye(T,"pts"),N=Ye(T,"stroke"),E=Ye(T,"width"),C=Ye(T,"layer"),M=Ye(T,"uuid"),A=Ye(T,"fill"),R=N;!R&&typeof E=="number"?R={width:E,type:"solid"}:R&&typeof R=="object"&&typeof E=="number"&&R.width===void 0&&(R={...R,width:E}),v.push({pts:k,stroke:R,layer:C,uuid:M,fill:A})}let P=[];for(let T of e.slice(2)){if(T[0]!=="pad"||T[2]?.valueOf?.()!=="thru_hole")continue;let k=T[1]?.valueOf?.(),N=T[2]?.valueOf?.(),E=T[3]?.valueOf?.(),C=Ye(T,"at"),M=Ye(T,"drill"),A=Ye(T,"size");Array.isArray(A)&&(A[0]==="size"&&(A=A.slice(1)),A={width:Number(A[0]),height:Number(A[1])});let R=Ye(T,"uuid"),B=Ye(T,"roundrect_rratio"),j=Ye(T,"layers");Array.isArray(j)?j=j.map(X=>X.valueOf()):typeof j=="string"?j=[j]:j||(j=[]);let U={name:k,pad_type:N,pad_shape:E,at:C,drill:M,size:A,layers:j,roundrect_rratio:B,uuid:R};Y9(`attempting to parse holes: ${JSON.stringify(U,null,2)}`),P.push(srt.parse(U))}return trt.parse({footprint_name:t,...i,properties:s,fp_lines:u,fp_texts:l,fp_arcs:d,fp_circles:g,pads:a,holes:P,fp_polys:v})},K1=Math.PI*2,ert=n=>{let e=n%K1;return e<0&&(e+=K1),e},SP=(n,e)=>{let t=ert(n),r=ert(e)-t;return r<0&&(r+=K1),r};function urt(n,e,t){let i={x:(n.x+e.x)/2,y:(n.y+e.y)/2},r={x:(e.x+t.x)/2,y:(e.y+t.y)/2},s=-(n.x-e.x)/(n.y-e.y),o=-(e.x-t.x)/(e.y-t.y),a=(i.y-r.y+o*r.x-s*i.x)/(o-s),c=i.y+s*(a-i.x);return{x:a,y:c}}function prt(n,e){return Math.sqrt((n.x-e.x)**2+(n.y-e.y)**2)}function ny(n,e){return Math.atan2(e.y-n.y,e.x-n.x)}var G9=(n,e,t)=>{let i=urt(n,e,t),r=prt(i,n),s=ny(i,n),o=ny(i,e),a=ny(i,t),c=SP(s,o),l=SP(s,a),u=l;return c>l&&(u=l-K1),Math.abs(r*u)};function W9(n,e,t,i){let r=urt(n,e,t),s=prt(r,n),o=ny(r,n),a=ny(r,e),c=ny(r,t),l=SP(o,a),u=SP(o,c),p=u;l>u&&(p=u-K1);let d=[];for(let _=0;_<=i;_++){let g=o+_/i*p,x=r.x+s*Math.cos(g),v=r.y+s*Math.sin(g);d.push({x,y:v})}return d}var Pl=n=>Array.isArray(n)?{x:n[0],y:n[1]}:n,X9=(n,e,t=1e-4)=>Math.abs(n.x-e.x)<t&&Math.abs(n.y-e.y)<t,P$t=n=>{let e=[],t=new Set;for(let i=0;i<n.length;i++){if(t.has(i))continue;let r=[n[i]];t.add(i);let s=n[i].end,o=!0;for(;o;){if(o=!1,r.length>1&&X9(s,r[0].start)){e.push(r);break}for(let a=0;a<n.length;a++)if(!t.has(a)){if(X9(s,n[a].start)){r.push(n[a]),t.add(a),s=n[a].end,o=!0;break}else if(X9(s,n[a].end)){n[a].type==="arc"?r.push({...n[a],reversed:!0}):r.push({...n[a],start:n[a].end,end:n[a].start}),t.add(a),s=n[a].start,o=!0;break}}if(!o){for(let a=r.length-1;a>=0;a--){let c=n.indexOf(r[a]);c!==-1&&t.delete(c)}break}}}return e},k$t=n=>{let e=[];for(let t of n)if(t.type==="line")e.push(t.start);else if(t.type==="arc"&&t.mid){let i=G9(t.start,t.mid,t.end),r=Math.max(3,Math.ceil(i)),s=W9(t.start,t.mid,t.end,r);t.reversed&&(s=s.reverse()),e.push(...s.slice(0,-1))}return e};function T$t(n){if(!Array.isArray(n))return null;let e=n.find(o=>o.layer?.toLowerCase()==="f.silks"&&(o.text?.includes("${REFERENCE}")||o.fp_text_type?.toLowerCase()==="reference"||o.text?.match(/^R\d+|C\d+|U\d+/))),t=e||n.find(o=>o.layer?.toLowerCase()==="f.fab"&&(o.text?.includes("${REFERENCE}")||o.fp_text_type?.toLowerCase()==="reference")),i=e||t;if(!i?.effects?.font?.size)return null;let[r,s]=i.effects.font.size;return s??r??1}var E$t=n=>n*Math.PI/180,U9=(n,e,t)=>{let i=E$t(t),r=Math.cos(i),s=Math.sin(i);return{x:n*r-e*s,y:n*s+e*r}},M$t=n=>{let e=[...new Map(n.map(u=>[`${u.x},${u.y}`,u])).values()];if(e.length!==4)return null;let t=e.map(u=>u.x),i=e.map(u=>u.y),r=[...new Set(t)],s=[...new Set(i)];if(r.length!==2||s.length!==2)return null;let[o,a]=r.sort((u,p)=>u-p),[c,l]=s.sort((u,p)=>u-p);return o===void 0||a===void 0||c===void 0||l===void 0?null:{x:(o+a)/2,y:(c+l)/2,width:a-o,height:l-c}},C$t=n=>{if(!n)return!1;let e=n.toLowerCase();return e!=="no"&&e!=="none"&&e!=="outline"},V9=n=>n&&Array.isArray(n)&&n.length>=3&&typeof n[2]=="number"?n[2]:0,Gr=n=>{let e=(n%360+360)%360;return e===90||e===270},$d=n=>{if(n!=null)return`${n}`},nrt=n=>{let e=$d(n),t=e!==void 0?Number(e):NaN;return Number.isFinite(t)?t:void 0},ey=(0,lrt.default)("kicad-mod-converter"),Ds=n=>{switch(n.toLowerCase()){case"f.cu":case"f.fab":case"f.silks":case"edge.cuts":return"top";case"b.cu":case"b.fab":case"b.silks":return"bottom"}},I$t=async n=>{let{fp_lines:e,fp_texts:t,fp_arcs:i,fp_circles:r,pads:s,properties:o,holes:a,fp_polys:c}=n,l=[];l.push({type:"source_component",source_component_id:"source_component_0",supplier_part_numbers:{}}),l.push({type:"schematic_component",schematic_component_id:"schematic_component_0",source_component_id:"source_component_0",center:{x:0,y:0},rotation:0,size:{width:0,height:0}});let u=new Set,p=new Map;for(let G of s){let tt=$d(G.name);if(tt){u.add(tt);let J=nrt(G.name);J!==void 0&&p.set(tt,J)}}if(a)for(let G of a){let tt=$d(G.name);if(tt){u.add(tt);let J=nrt(G.name);J!==void 0&&p.set(tt,J)}}let d=0,_=new Map;for(let G of u){let tt=`source_port_${d++}`;_.set(G,tt);let J=p.get(G);l.push({type:"source_port",source_port_id:tt,source_component_id:"source_component_0",name:G,port_hints:[G],pin_number:J,pin_label:J!==void 0?`pin${J}`:void 0}),l.push({type:"schematic_port",schematic_port_id:`schematic_port_${d++}`,source_port_id:tt,schematic_component_id:"schematic_component_0",center:{x:0,y:0}})}let g=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY,v=Number.POSITIVE_INFINITY,S=Number.NEGATIVE_INFINITY;for(let G of s){let tt=G.at[0],J=-G.at[1],ht=G.size[0],pt=G.size[1];g=Math.min(g,tt-ht/2),x=Math.max(x,tt+ht/2),v=Math.min(v,J-pt/2),S=Math.max(S,J+pt/2)}let P="pcb_component_0";l.push({type:"pcb_component",source_component_id:"source_component_0",pcb_component_id:P,layer:"top",center:{x:0,y:0},rotation:0,width:Number.isFinite(g)?x-g:0,height:Number.isFinite(v)?S-v:0});let T=0,k=new Map;for(let G of u){let tt=`pcb_port_${T++}`,J=_.get(G);k.set(G,tt);let ht=0,pt=0,St=["top","bottom"],Mt=s.find(ot=>$d(ot.name)===G);if(Mt)ht=Mt.at[0],pt=-Mt.at[1],St=Mt.layers?Mt.layers.map(ot=>Ds(ot)).filter(Boolean):["top","bottom"];else if(a){let ot=a.find(Y=>$d(Y.name)===G);ot&&(ht=ot.at[0],pt=-ot.at[1],St=ot.layers?ot.layers.map(Y=>Ds(Y)).filter(Boolean):["top","bottom"])}l.push({type:"pcb_port",pcb_port_id:tt,source_port_id:J,pcb_component_id:P,x:ht,y:pt,layers:St})}let N=0,E=0,C=0;for(let G of s){let tt=$d(G.name),J=tt?p.get(tt):void 0;if(G.pad_type==="smd"){let ht=V9(G.at),pt=Gr(ht)?G.size[1]:G.size[0],St=Gr(ht)?G.size[0]:G.size[1],Mt=tt?k.get(tt):void 0,ot=J!==void 0?`pin${J}`:void 0;l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${N++}`,shape:"rect",x:G.at[0],y:-G.at[1],width:pt,height:St,layer:Ds(G.layers?.[0]??"F.Cu"),pcb_component_id:P,port_hints:ot?[ot]:tt?[tt]:[],pcb_port_id:Mt,pin_number:J,pin_label:ot})}else if(G.pad_type==="thru_hole"){if(G.pad_shape==="rect"){let ht=V9(G.at),pt=Gr(ht)?G.size[1]:G.size[0],St=Gr(ht)?G.size[0]:G.size[1],Mt=G.drill?.offset?.[0]??0,ot=G.drill?.offset?.[1]??0,Y=U9(Mt,ot,ht),H=tt?k.get(tt):void 0,it=J!==void 0?`pin${J}`:void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:G.at[0],y:-G.at[1],hole_offset_x:-Y.x,hole_offset_y:-Y.y,hole_diameter:G.drill?.width,rect_pad_width:pt,rect_pad_height:St,layers:["top","bottom"],pcb_component_id:P,port_hints:it?[it]:tt?[tt]:[],pcb_port_id:H,pin_number:J,pin_label:it})}else if(G.pad_shape==="circle"){let ht=tt?k.get(tt):void 0,pt=J!==void 0?`pin${J}`:void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circle",x:G.at[0],y:-G.at[1],outer_diameter:G.size[0],hole_diameter:G.drill?.width,layers:["top","bottom"],pcb_component_id:P,port_hints:pt?[pt]:tt?[tt]:[],pcb_port_id:ht,pin_number:J,pin_label:pt})}else if(G.pad_shape==="oval"){let ht=tt?k.get(tt):void 0,pt=J!==void 0?`pin${J}`:void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"pill",x:G.at[0],y:-G.at[1],outer_width:G.size[0],outer_height:G.size[1],hole_width:G.drill?.width,hole_height:G.drill?.height,layers:["top","bottom"],pcb_component_id:P,port_hints:pt?[pt]:tt?[tt]:[],pcb_port_id:ht,pin_number:J,pin_label:pt})}}else G.pad_type==="np_thru_hole"&&l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${C++}`,x:G.at[0],y:-G.at[1],hole_diameter:G.drill?.width,pcb_component_id:P})}if(a)for(let G of a){let tt=$d(G.name),J=tt?p.get(tt):void 0,ht=G.layers?.some(at=>at.endsWith(".Cu")||at==="*.Cu"),pt=V9(G.at),St=G.drill?.offset?.[0]??0,Mt=G.drill?.offset?.[1]??0,ot=U9(St,Mt,pt),Y=G.at[0]+ot.x,H=-(G.at[1]+ot.y),it=G.drill?.width??0,ut=G.size?.width??it,yt=G.roundrect_rratio??0,Z=yt>0?Math.min(Gr(pt)?G.size?.height??ut:G.size?.width??ut,Gr(pt)?G.size?.width??ut:G.size?.height??ut)/2*yt:0;if(ht)if(G.pad_shape==="rect"){let at=tt?k.get(tt):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:G.at[0],y:-G.at[1],hole_offset_x:-ot.x,hole_offset_y:-ot.y,hole_diameter:it,rect_pad_width:Gr(pt)?G.size?.height??ut:G.size?.width??ut,rect_pad_height:Gr(pt)?G.size?.width??ut:G.size?.height??ut,rect_border_radius:Z,port_hints:J!==void 0?[`pin${J}`]:tt?[tt]:[],layers:["top","bottom"],pcb_component_id:P,pcb_port_id:at,pin_number:J,pin_label:J!==void 0?`pin${J}`:void 0})}else if(G.pad_shape==="oval"){let at=tt?k.get(tt):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"pill",x:Y,y:H,outer_width:Gr(pt)?G.size?.height??ut:G.size?.width??ut,outer_height:Gr(pt)?G.size?.width??ut:G.size?.height??ut,hole_width:Gr(pt)?G.drill?.height??it:G.drill?.width??it,hole_height:Gr(pt)?G.drill?.width??it:G.drill?.height??it,port_hints:J!==void 0?[`pin${J}`]:tt?[tt]:[],layers:["top","bottom"],pcb_component_id:P,pcb_port_id:at,pin_number:J,pin_label:J!==void 0?`pin${J}`:void 0})}else if(G.pad_shape==="roundrect"){let at=tt?k.get(tt):void 0,Et=G.drill?.offset?.[0]??0,Ft=G.drill?.offset?.[1]??0,Ot=U9(Et,Ft,pt),Ie=Gr(pt)?G.size?.height??ut:G.size?.width??ut,Se=Gr(pt)?G.size?.width??ut:G.size?.height??ut;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:Y,y:H,hole_offset_x:-Ot.x,hole_offset_y:Ot.y,hole_diameter:it,rect_pad_width:Ie,rect_pad_height:Se,rect_border_radius:Z,port_hints:J!==void 0?[`pin${J}`]:tt?[tt]:[],layers:["top","bottom"],pcb_component_id:P,pcb_port_id:at,pin_number:J,pin_label:J!==void 0?`pin${J}`:void 0})}else{let at=tt?k.get(tt):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circle",x:Y,y:H,outer_diameter:ut,hole_diameter:it,port_hints:J!==void 0?[`pin${J}`]:tt?[tt]:[],layers:["top","bottom"],pcb_component_id:P,pcb_port_id:at,pin_number:J,pin_label:J!==void 0?`pin${J}`:void 0})}else l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${C++}`,x:Y,y:H,hole_diameter:ut,hole_shape:"circle",pcb_component_id:P})}let M=[];for(let G of e)G.layer.toLowerCase()==="edge.cuts"&&M.push({type:"line",start:{x:G.start[0],y:G.start[1]},end:{x:G.end[0],y:G.end[1]},strokeWidth:G.stroke.width});for(let G of i)G.layer.toLowerCase()==="edge.cuts"&&M.push({type:"arc",start:{x:G.start[0],y:G.start[1]},mid:{x:G.mid[0],y:G.mid[1]},end:{x:G.end[0],y:G.end[1]},strokeWidth:G.stroke.width});let A=P$t(M),R=0;for(let G of A){let tt=k$t(G);tt.length>=3&&l.push({type:"pcb_cutout",pcb_cutout_id:`pcb_cutout_${R++}`,shape:"polygon",points:tt.map(J=>({x:J.x,y:-J.y})),pcb_component_id:P})}let B=0,j=0,U=0,X=0;for(let G of e){let tt=[{x:G.start[0],y:-G.start[1]},{x:G.end[0],y:-G.end[1]}],J=G.layer.toLowerCase();J==="f.cu"?l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${B++}`,pcb_component_id:P,layer:Ds(G.layer),route:tt,thickness:G.stroke.width}):J==="f.silks"?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${j++}`,pcb_component_id:P,layer:"top",route:tt,stroke_width:G.stroke.width}):J==="edge.cuts"?ey("Skipping Edge.Cuts fp_line (converted to pcb_cutout)",G.layer):J==="f.fab"?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${U++}`,pcb_component_id:P,layer:"top",route:tt,stroke_width:G.stroke.width,port_hints:[]}):J.startsWith("user.")?l.push({type:"pcb_note_line",pcb_note_line_id:`pcb_note_line_${X++}`,pcb_component_id:P,x1:G.start[0],y1:-G.start[1],x2:G.end[0],y2:-G.end[1],stroke_width:G.stroke.width}):ey("Unhandled layer for fp_line",G.layer)}if(c)for(let G of c){let tt=[],J=ot=>{!Number.isFinite(ot.x)||!Number.isFinite(ot.y)||tt.push(ot)};for(let ot of G.pts){if(Array.isArray(ot)){J({x:ot[0],y:-ot[1]});continue}if(ot&&typeof ot=="object"&&"kind"in ot){if(ot.kind==="arc"){let Y=Pl(ot.start),H=Pl(ot.mid),it=Pl(ot.end),ut=G9(Y,H,it),yt=Math.max(8,Math.ceil(ut)),Z=Math.max(2,Math.ceil(ut/.1)),at=W9(Y,H,it,Z).map(Et=>({x:Et.x,y:-Et.y}));for(let Et of at)J(Et)}continue}}let ht=tt,St=ht.length>2&&ht[0].x===ht[ht.length-1].x&&ht[0].y===ht[ht.length-1].y?ht.slice(0,-1):ht;if(ht.length===0)continue;let Mt=G.stroke?.width??0;if(G.layer.endsWith(".Cu")){let ot=M$t(St);ot?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${N++}`,shape:"rect",x:ot.x,y:ot.y,width:ot.width,height:ot.height,layer:Ds(G.layer),pcb_component_id:P}):C$t(G.fill)?St.length>=3?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${N++}`,shape:"polygon",points:St,layer:Ds(G.layer),pcb_component_id:P}):St.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${B++}`,pcb_component_id:P,layer:Ds(G.layer),route:St,thickness:Mt}):St.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${B++}`,pcb_component_id:P,layer:Ds(G.layer),route:St,thickness:Mt})}else G.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${j++}`,pcb_component_id:P,layer:Ds(G.layer),route:ht,stroke_width:Mt}):G.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${U++}`,pcb_component_id:P,layer:Ds(G.layer),route:St,stroke_width:Mt,port_hints:[]}):ey("Unhandled layer for fp_poly",G.layer)}let W=0;for(let G of i){let tt=G.layer.toLowerCase();if(tt==="edge.cuts"){ey("Skipping Edge.Cuts fp_arc (converted to pcb_cutout)",G.layer);continue}let J=Pl(G.start),ht=Pl(G.mid),pt=Pl(G.end),St=G9(J,ht,pt),Mt=W9(J,ht,pt,Math.ceil(St));if(tt.startsWith("user.")){l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${W++}`,pcb_component_id:P,route:Mt.map(Y=>({x:Y.x,y:-Y.y})),stroke_width:G.stroke.width});continue}let ot=Ds(G.layer);if(!ot){ey("Unable to convert layer for fp_arc",G.layer);continue}l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${j++}`,layer:ot,pcb_component_id:P,route:Mt.map(Y=>({x:Y.x,y:-Y.y})),stroke_width:G.stroke.width})}if(r)for(let G of r){let tt=G.layer.toLowerCase(),J=Pl(G.center),ht=Pl(G.end),pt=Math.sqrt((ht.x-J.x)**2+(ht.y-J.y)**2),St=Math.max(16,Math.ceil(2*Math.PI*pt)),Mt=[];for(let ot=0;ot<=St;ot++){let Y=ot/St*2*Math.PI;Mt.push({x:J.x+pt*Math.cos(Y),y:J.y+pt*Math.sin(Y)})}tt.startsWith("user.")&&l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${W++}`,pcb_component_id:P,route:Mt.map(ot=>({x:ot.x,y:-ot.y})),stroke_width:G.stroke.width})}for(let G of t){let tt=Ds(G.layer);G.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_text",layer:tt,font:"tscircuit2024",font_size:G.effects?.font?.size[0]??1,pcb_component_id:P,anchor_position:{x:G.at[0],y:-G.at[1]},anchor_alignment:"center",text:G.text}):G.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_text",layer:tt,font:"tscircuit2024",font_size:G.effects?.font?.size[0]??1,pcb_component_id:P,anchor_position:{x:G.at[0],y:-G.at[1]},anchor_alignment:"center",text:G.text}):ey("Unhandled layer for fp_text",G.layer)}let et=o.find(G=>G.key==="Reference"),nt=o.find(G=>G.key==="Value"),mt=[et,nt].filter(G=>G&&!!G.val);for(let G of mt){let tt=G.attributes.at;if(!tt)continue;let ht=G.attributes.layer?.toLowerCase()?.endsWith(".fab"),pt=T$t(t);l.push({type:ht?"pcb_fabrication_note_text":"pcb_silkscreen_text",layer:"top",font:"tscircuit2024",font_size:pt,pcb_component_id:P,anchor_position:{x:tt[0],y:-tt[1]},anchor_alignment:"center",text:G.val})}return l},hrt=async n=>{let e=S$t(n);return await I$t(e)};var drt=async n=>{try{return(await import(n)).default}catch{console.log(`Failed to load ${n} locally, trying CDN fallback...`);try{let t=await fetch(`https://cdn.jsdelivr.net/npm/${n}/+esm`);if(!t.ok)throw new Error(`Failed to fetch ${n} from CDN: ${t.statusText}`);let i=await t.text(),r=new Blob([i],{type:"application/javascript"}),s=URL.createObjectURL(r);try{let{default:o}=await import(s);return o}finally{URL.revokeObjectURL(s)}}catch(t){throw console.error(`CDN fallback for ${n} also failed:`,t),t}}};var N$t="https://kicad-mod-cache.tscircuit.com",kP=null,frt=()=>({partsEngine:Jit,spiceEngineMap:{ngspice:{simulate:async n=>{if(!kP){let e=await drt("@tscircuit/ngspice-spice-engine").catch(t=>{throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.",{cause:t})});e&&(kP=await e())}if(!kP)throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.");return kP.simulate(n)}}},footprintLibraryMap:{kicad:async n=>{let e=`${N$t}/${n}`,t=`${e}.circuit.json`,r=await(await fetch(t)).json(),s=Array.isArray(r)?r.filter(a=>a?.type==="pcb_silkscreen_text"?a?.text==="REF**":!0):r,o=`${e}.wrl`;return{footprintCircuitJson:s,cadModel:{wrlUrl:o,modelUnitToMmScale:2.54}}}},footprintFileParserMap:{kicad_mod:{loadFromUrl:async n=>{let e=await fetch(n).then(i=>i.text()),t=await hrt(e);return{footprintCircuitJson:Array.isArray(t)?t:[t]}}}}});var K9={};$c(K9,{__addDisposableResource:()=>Drt,__assign:()=>TP,__asyncDelegator:()=>Nrt,__asyncGenerator:()=>Irt,__asyncValues:()=>Art,__await:()=>iy,__awaiter:()=>Prt,__classPrivateFieldGet:()=>Frt,__classPrivateFieldIn:()=>zrt,__classPrivateFieldSet:()=>$rt,__createBinding:()=>MP,__decorate:()=>yrt,__disposeResources:()=>jrt,__esDecorate:()=>xrt,__exportStar:()=>Trt,__extends:()=>mrt,__generator:()=>krt,__importDefault:()=>Lrt,__importStar:()=>Ort,__makeTemplateObject:()=>Rrt,__metadata:()=>Srt,__param:()=>grt,__propKey:()=>vrt,__read:()=>Z9,__rest:()=>_rt,__rewriteRelativeImportExtension:()=>Brt,__runInitializers:()=>brt,__setFunctionName:()=>wrt,__spread:()=>Ert,__spreadArray:()=>Crt,__spreadArrays:()=>Mrt,__values:()=>EP,default:()=>O$t});var H9=function(n,e){return H9=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,i){t.__proto__=i}||function(t,i){for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(t[r]=i[r])},H9(n,e)};function mrt(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");H9(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var TP=function(){return TP=Object.assign||function(e){for(var t,i=1,r=arguments.length;i<r;i++){t=arguments[i];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s])}return e},TP.apply(this,arguments)};function _rt(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(n);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(n,i[r])&&(t[i[r]]=n[i[r]]);return t}function yrt(n,e,t,i){var r=arguments.length,s=r<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,i);else for(var a=n.length-1;a>=0;a--)(o=n[a])&&(s=(r<3?o(s):r>3?o(e,t,s):o(e,t))||s);return r>3&&s&&Object.defineProperty(e,t,s),s}function grt(n,e){return function(t,i){e(t,i,n)}}function xrt(n,e,t,i,r,s){function o(S){if(S!==void 0&&typeof S!="function")throw new TypeError("Function expected");return S}for(var a=i.kind,c=a==="getter"?"get":a==="setter"?"set":"value",l=!e&&n?i.static?n:n.prototype:null,u=e||(l?Object.getOwnPropertyDescriptor(l,i.name):{}),p,d=!1,_=t.length-1;_>=0;_--){var g={};for(var x in i)g[x]=x==="access"?{}:i[x];for(var x in i.access)g.access[x]=i.access[x];g.addInitializer=function(S){if(d)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(S||null))};var v=(0,t[_])(a==="accessor"?{get:u.get,set:u.set}:u[c],g);if(a==="accessor"){if(v===void 0)continue;if(v===null||typeof v!="object")throw new TypeError("Object expected");(p=o(v.get))&&(u.get=p),(p=o(v.set))&&(u.set=p),(p=o(v.init))&&r.unshift(p)}else(p=o(v))&&(a==="field"?r.unshift(p):u[c]=p)}l&&Object.defineProperty(l,i.name,u),d=!0}function brt(n,e,t){for(var i=arguments.length>2,r=0;r<e.length;r++)t=i?e[r].call(n,t):e[r].call(n);return i?t:void 0}function vrt(n){return typeof n=="symbol"?n:"".concat(n)}function wrt(n,e,t){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(n,"name",{configurable:!0,value:t?"".concat(t," ",e):e})}function Srt(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}function Prt(n,e,t,i){function r(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(i.next(u))}catch(p){o(p)}}function c(u){try{l(i.throw(u))}catch(p){o(p)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((i=i.apply(n,e||[])).next())})}function krt(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,r,s,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(t=0)),t;)try{if(i=1,r&&(s=l[0]&2?r.return:l[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,l[1])).done)return s;switch(r=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,r=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(n,t)}catch(u){l=[6,u],r=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}var MP=Object.create?(function(n,e,t,i){i===void 0&&(i=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,i,r)}):(function(n,e,t,i){i===void 0&&(i=t),n[i]=e[t]});function Trt(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&MP(e,n,t)}function EP(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Z9(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var i=t.call(n),r,s=[],o;try{for(;(e===void 0||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(o)throw o.error}}return s}function Ert(){for(var n=[],e=0;e<arguments.length;e++)n=n.concat(Z9(arguments[e]));return n}function Mrt(){for(var n=0,e=0,t=arguments.length;e<t;e++)n+=arguments[e].length;for(var i=Array(n),r=0,e=0;e<t;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,r++)i[r]=s[o];return i}function Crt(n,e,t){if(t||arguments.length===2)for(var i=0,r=e.length,s;i<r;i++)(s||!(i in e))&&(s||(s=Array.prototype.slice.call(e,0,i)),s[i]=e[i]);return n.concat(s||Array.prototype.slice.call(e))}function iy(n){return this instanceof iy?(this.v=n,this):new iy(n)}function Irt(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),r,s=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),r[Symbol.asyncIterator]=function(){return this},r;function o(_){return function(g){return Promise.resolve(g).then(_,p)}}function a(_,g){i[_]&&(r[_]=function(x){return new Promise(function(v,S){s.push([_,x,v,S])>1||c(_,x)})},g&&(r[_]=g(r[_])))}function c(_,g){try{l(i[_](g))}catch(x){d(s[0][3],x)}}function l(_){_.value instanceof iy?Promise.resolve(_.value.v).then(u,p):d(s[0][2],_)}function u(_){c("next",_)}function p(_){c("throw",_)}function d(_,g){_(g),s.shift(),s.length&&c(s[0][0],s[0][1])}}function Nrt(n){var e,t;return e={},i("next"),i("throw",function(r){throw r}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(r,s){e[r]=n[r]?function(o){return(t=!t)?{value:iy(n[r](o)),done:!1}:s?s(o):o}:s}}function Art(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof EP=="function"?EP(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=n[s]&&function(o){return new Promise(function(a,c){o=n[s](o),r(a,c,o.done,o.value)})}}function r(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function Rrt(n,e){return Object.defineProperty?Object.defineProperty(n,"raw",{value:e}):n.raw=e,n}var A$t=Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e},q9=function(n){return q9=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},q9(n)};function Ort(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t=q9(n),i=0;i<t.length;i++)t[i]!=="default"&&MP(e,n,t[i]);return A$t(e,n),e}function Lrt(n){return n&&n.__esModule?n:{default:n}}function Frt(n,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!i:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(n):i?i.value:e.get(n)}function $rt(n,e,t,i,r){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?r.call(n,t):r?r.value=t:e.set(n,t),t}function zrt(n,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof n=="function"?e===n:n.has(e)}function Drt(n,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,r;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(r=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");r&&(i=function(){try{r.call(this)}catch(s){return Promise.reject(s)}}),n.stack.push({value:e,dispose:i,async:t})}else t&&n.stack.push({async:!0});return e}var R$t=typeof SuppressedError=="function"?SuppressedError:function(n,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=n,i.suppressed=e,i};function jrt(n){function e(s){n.error=n.hasError?new R$t(s,n.error,"An error was suppressed during disposal."):s,n.hasError=!0}var t,i=0;function r(){for(;t=n.stack.pop();)try{if(!t.async&&i===1)return i=0,n.stack.push(t),Promise.resolve().then(r);if(t.dispose){var s=t.dispose.call(t.value);if(t.async)return i|=2,Promise.resolve(s).then(r,function(o){return e(o),r()})}else i|=1}catch(o){e(o)}if(i===1)return n.hasError?Promise.reject(n.error):Promise.resolve();if(n.hasError)throw n.error}return r()}function Brt(n,e){return typeof n=="string"&&/^\.\.?\//.test(n)?n.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(t,i,r,s,o){return i?e?".jsx":".js":r&&(!s||!o)?t:r+s+"."+o.toLowerCase()+"js"}):n}var O$t={__extends:mrt,__assign:TP,__rest:_rt,__decorate:yrt,__param:grt,__esDecorate:xrt,__runInitializers:brt,__propKey:vrt,__setFunctionName:wrt,__metadata:Srt,__awaiter:Prt,__generator:krt,__createBinding:MP,__exportStar:Trt,__values:EP,__read:Z9,__spread:Ert,__spreadArrays:Mrt,__spreadArray:Crt,__await:iy,__asyncGenerator:Irt,__asyncDelegator:Nrt,__asyncValues:Art,__makeTemplateObject:Rrt,__importStar:Ort,__importDefault:Lrt,__classPrivateFieldGet:Frt,__classPrivateFieldSet:$rt,__classPrivateFieldIn:zrt,__addDisposableResource:Drt,__disposeResources:jrt,__rewriteRelativeImportExtension:Brt};var J9=Vt(In(),1),Vbe=(0,J9.default)("tsci:eval:execution-context");function J1(n,e={}){globalThis.React=Yrt;let t=e.platform||frt(),i=e.projectConfig?{...t,...e.projectConfig}:t;i.partsEngineDisabled&&(i.partsEngine=void 0);let r=new Q_({platform:i});e.name&&(r.name=e.name),e.debugNamespace&&r.enableDebug(e.debugNamespace);let s=[];return{fsMap:{},entrypoint:"",logger:{info:o=>{s.push({msg:o})},getLogs:()=>s,stringifyLogs:()=>s.map(o=>o.msg).join(`
256
256
  `)},preSuppliedImports:{"@tscircuit/core":xP,tscircuit:xP,"@tscircuit/math-utils":R4,react:Yrt,"react/jsx-runtime":L$t,debug:J9.default,tslib:K9,"@tscircuit/props":{}},circuit:r,tsConfig:null,importStack:[],currentlyImporting:new Set,...n}}function kl(n){let e=n;return e=e.replace(/\\/g,"/"),e=e.trim(),e.startsWith("./")&&(e=e.slice(2)),e.startsWith("/")&&(e=e.slice(1)),e}function Xrt(n){let e={};for(let[t,i]of Object.entries(n))e[kl(t)]=i;return e}function js(n){if(!n)return".";let t=n.replace(/\\/g,"/").replace(/\/+$/,"");return t.indexOf("/")===-1?".":t.substring(0,t.lastIndexOf("/"))||"/"}function CP(n,e){if(n.startsWith("../")){let t=js(e);return CP(n.slice(3),t)}return n.startsWith("./")?CP(n.slice(2),e):n.startsWith("/")?n.slice(1):`${e}/${n}`}function Q1(n){if(Array.isArray(n))return null;let e=n["tsconfig.json"];if(!e)return null;try{let t=e.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,"");return JSON.parse(t)}catch(t){throw new Error(`Failed to parse tsconfig.json: ${t.message}`)}}function Urt(n){let{importPath:e,normalizedFilePathMap:t,extensions:i,tsConfig:r,tsconfigDir:s}=n,o=r?.compilerOptions?.paths;if(!o)return null;let a=r?.compilerOptions?.baseUrl||".",c=u=>{let p=kl(u);if(t.has(p))return t.get(p);for(let d of i){let _=`${p}.${d}`;if(t.has(_))return t.get(_)}return null};for(let[u,p]of Object.entries(o))if(u.includes("*")){let[_,g]=u.split("*");if(!e.startsWith(_)||!e.endsWith(g||""))continue;let x=e.slice(_.length,e.length-(g?g.length:0));for(let v of p){let S=v.replace("*",x),P=a&&!S.startsWith("./")&&!S.startsWith("/")?`${a}/${S}`:S,T=c(P);if(T)return T}}else{if(e!==u)continue;for(let _ of p){let g=a&&!_.startsWith("./")&&!_.startsWith("/")?`${a}/${_}`:_,x=c(g);if(x)return x}}let l=Q9({importPath:e,normalizedFilePathMap:t,extensions:i,tsConfig:r,tsconfigDir:s});return l||null}function Q9(n){let{importPath:e,normalizedFilePathMap:t,extensions:i,tsConfig:r,tsconfigDir:s}=n,o=r?.compilerOptions?.baseUrl;if(!o)return null;let c=`${s||"."}/${o}/${e}`;c=c.replace(/\/+/g,"/"),c=c.replace(/\/\.\//g,"/");let l=kl(c);if(t.has(l))return t.get(l);for(let u of i){let p=`${l}.${u}`;if(t.has(p))return t.get(p)}return null}function Vrt(n,e){let t=e?.compilerOptions?.paths;if(!t)return!1;for(let[i]of Object.entries(t))if(i.includes("*")){let[s,o]=i.split("*");if(n.startsWith(s)&&n.endsWith(o||""))return!0}else if(n===i)return!0;return!1}var IP=["tsx","ts","json","js","jsx","obj","gltf","glb","stl","step","stp"],t0=(n,e,t,i={})=>{let r=i.tsConfig??null,s=n.startsWith("./")||n.startsWith("../"),o=!!r?.compilerOptions?.baseUrl,a=t&&(s||!o)?CP(n,t):n,c=new Set(Array.isArray(e)?e:Object.keys(e));if(c.has(a))return a;let l=new Map;for(let p of c)l.set(kl(p),p);let u=kl(a);if(s||!o){if(l.has(u))return l.get(u);for(let p of IP){let d=`${u}.${p}`;if(l.has(d))return l.get(d)}}if(!s){let p=Urt({importPath:n,normalizedFilePathMap:l,extensions:IP,tsConfig:r,tsconfigDir:i.tsconfigDir});if(p)return p;let d=Q9({importPath:n,normalizedFilePathMap:l,extensions:IP,tsConfig:r,tsconfigDir:i.tsconfigDir});if(d)return d}if(!s&&!o){let p=kl(n);if(l.has(p))return l.get(p);for(let d of IP){let _=`${p}.${d}`;if(l.has(_))return l.get(_)}}return null},NP=(n,e,t,i={})=>{let r=t0(n,e,t,i);if(!r)throw new Error(`File not found "${n}", available paths: