@tscircuit/eval 0.0.495 → 0.0.496

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 Kpt=Object.create;var Mx=Object.defineProperty;var Jpt=Object.getOwnProperty
5
5
  `);for(O=N=0;N<xt.length&&!xt[N].includes("DetermineComponentFrameRoot");)N++;for(;O<It.length&&!It[O].includes("DetermineComponentFrameRoot");)O++;if(N===xt.length||O===It.length)for(N=xt.length-1,O=It.length-1;1<=N&&0<=O&&xt[N]!==It[O];)O--;for(;1<=N&&0<=O;N--,O--)if(xt[N]!==It[O]){if(N!==1||O!==1)do if(N--,O--,0>O||xt[N]!==It[O]){var $t=`
6
6
  `+xt[N].replace(" at new "," at ");return m.displayName&&$t.includes("<anonymous>")&&($t=$t.replace("<anonymous>",m.displayName)),$t}while(1<=N&&0<=O);break}}}finally{f3=!1,Error.prepareStackTrace=S}return(S=m?m.displayName||m.name:"")?U(S):""}function H(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 V(m.type,!1);case 11:return V(m.type.render,!1);case 1:return V(m.type,!0);case 31:return U("Activity");default:return""}}function et(m){try{var y="";do y+=H(m),m=m.return;while(m);return y}catch(S){return`
7
7
  Error generating stack: `+S.message+`
8
- `+S.stack}}function tt(m,y){if(typeof m=="object"&&m!==null){var S=n$.get(m);return S!==void 0?S:(y={value:m,source:y,stack:et(y)},n$.set(m,y),y)}return{value:m,source:y,stack:et(y)}}function mt(m,y){em[nm++]=ux,em[nm++]=lx,lx=m,ux=y}function G(m,y,S){_s[ys++]=ha,_s[ys++]=da,_s[ys++]=fh,fh=m;var N=ha;m=da;var O=32-ts(N)-1;N&=~(1<<O),S+=1;var $=32-ts(y)+O;if(30<$){var K=O-O%5;$=(N&(1<<K)-1).toString(32),N>>=K,O-=K,ha=1<<32-ts(y)+O|S<<O|N,da=$+m}else ha=1<<$|S<<O|N,da=m}function Q(m){m.return!==null&&(mt(m,1),G(m,1,0))}function nt(m){for(;m===lx;)lx=em[--nm],em[nm]=null,ux=em[--nm],em[nm]=null;for(;m===fh;)fh=_s[--ys],_s[ys]=null,da=_s[--ys],_s[ys]=null,ha=_s[--ys],_s[ys]=null}function pt(m,y){_(kc,y),_(Yy,m),_(qi,null),m=but(y),d(qi),_(qi,m)}function ht(){d(qi),d(Yy),d(kc)}function wt(m){m.memoizedState!==null&&_(px,m);var y=qi.current,S=vut(y,m.type);y!==S&&(_(Yy,m),_(qi,S))}function Et(m){Yy.current===m&&(d(qi),d(Yy)),px.current===m&&(d(px),ua?dh._currentValue=Kf:dh._currentValue2=Kf)}function ot(m){var y=Error(i(418,""));throw Z(tt(y,m)),m3}function X(m,y){if(!ms)throw Error(i(175));gpt(m.stateNode,m.type,m.memoizedProps,y,m)||ot(m)}function W(m){for(vr=m.return;vr;)switch(vr.tag){case 5:case 13:To=!1;return;case 27:case 3:To=!0;return;default:vr=vr.return}}function rt(m){if(!ms||m!==vr)return!1;if(!mn)return W(m),mn=!0,!1;var y=m.tag;if(bi?y!==3&&y!==27&&(y!==5||Xz(m.type)&&!sx(m.type,m.memoizedProps))&&vi&&ot(m):y!==3&&(y!==5||Xz(m.type)&&!sx(m.type,m.memoizedProps))&&vi&&ot(m),W(m),y===13){if(!ms)throw Error(i(316));if(m=m.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(i(317));vi=vpt(m)}else vi=bi&&y===27?upt(m.type,vi):vr?Yz(m.stateNode):null;return!0}function ut(){ms&&(vi=vr=null,mn=!1)}function yt(){var m=mh;return m!==null&&(Rr===null?Rr=m:Rr.push.apply(Rr,m),mh=null),m}function Z(m){mh===null?mh=[m]:mh.push(m)}function at(m,y){return m===y&&(m!==0||1/m===1/y)||m!==m&&y!==y}function Mt(m,y,S){ua?(_(hx,y._currentValue),y._currentValue=S):(_(hx,y._currentValue2),y._currentValue2=S)}function Ft(m){var y=hx.current;ua?m._currentValue=y:m._currentValue2=y,d(hx)}function Ot(m,y,S){for(;m!==null;){var N=m.alternate;if((m.childLanes&y)!==y?(m.childLanes|=y,N!==null&&(N.childLanes|=y)):N!==null&&(N.childLanes&y)!==y&&(N.childLanes|=y),m===S)break;m=m.return}}function Ce(m,y,S,N){var O=m.child;for(O!==null&&(O.return=m);O!==null;){var $=O.dependencies;if($!==null){var K=O.child;$=$.firstContext;t:for(;$!==null;){var ct=$;$=O;for(var xt=0;xt<y.length;xt++)if(ct.context===y[xt]){$.lanes|=S,ct=$.alternate,ct!==null&&(ct.lanes|=S),Ot($.return,S,m),N||(K=null);break t}$=ct.next}}else if(O.tag===18){if(K=O.return,K===null)throw Error(i(341));K.lanes|=S,$=K.alternate,$!==null&&($.lanes|=S),Ot(K,S,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,S,N){m=null;for(var O=y,$=!1;O!==null;){if(!$){if((O.flags&524288)!==0)$=!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;ns(O.pendingProps.value,K.value)||(m!==null?m.push(ct):m=[ct])}}else if(O===px.current){if(K=O.alternate,K===null)throw Error(i(387));K.memoizedState.memoizedState!==O.memoizedState.memoizedState&&(m!==null?m.push(dh):m=[dh])}O=O.return}m!==null&&Ce(y,m,S,N),y.flags|=262144}function Kt(m){for(m=m.firstContext;m!==null;){var y=m.context;if(!ns(ua?y._currentValue:y._currentValue2,m.memoizedValue))return!0;m=m.next}return!1}function le(m){_h=m,fa=null,m=m.dependencies,m!==null&&(m.firstContext=null)}function Jt(m){return Ci(_h,m)}function Wn(m,y){return _h===null&&le(m),Ci(m,y)}function Ci(m,y){var S=ua?y._currentValue:y._currentValue2;if(y={context:y,memoizedValue:S,next:null},fa===null){if(m===null)throw Error(i(308));fa=y,m.dependencies={lanes:0,firstContext:y},m.flags|=524288}else fa=fa.next=y;return S}function Cr(){return{controller:new Ypt,data:new Map,refCount:0}}function Us(m){m.refCount--,m.refCount===0&&Xpt(Upt,function(){m.controller.abort()})}function Ir(m){m!==im&&m.next===null&&(im===null?dx=im=m:im=im.next=m),fx=!0,_3||(_3=!0,xy())}function So(m,y){if(!y3&&fx){y3=!0;do for(var S=!1,N=dx;N!==null;){if(!y)if(m!==0){var O=N.pendingLanes;if(O===0)var $=0;else{var K=N.suspendedLanes,ct=N.pingedLanes;$=(1<<31-ts(42|m)+1)-1,$&=O&~(K&~ct),$=$&201326741?$&201326741|1:$?$|2:0}$!==0&&(S=!0,Af(N,$))}else $=tn,$=v(N,N===Nn?$:0,N.cancelPendingCommit!==null||N.timeoutHandle!==hh),($&3)===0||P(N,$)||(S=!0,Af(N,$));N=N.next}while(S);y3=!1}}function Ef(){Cf()}function Cf(){fx=_3=!1;var m=0;rm!==0&&(Iut()&&(m=rm),rm=0);for(var y=Ws(),S=null,N=dx;N!==null;){var O=N.next,$=If(N,y);$===0?(N.next=null,S===null?dx=O:S.next=O,O===null&&(im=S)):(S=N,(m!==0||($&3)!==0)&&(fx=!0)),N=O}So(m,!1)}function If(m,y){for(var S=m.suspendedLanes,N=m.pingedLanes,O=m.expirationTimes,$=m.pendingLanes&-62914561;0<$;){var K=31-ts($),ct=1<<K,xt=O[K];xt===-1?((ct&S)===0||(ct&N)!==0)&&(O[K]=w(ct,y)):xt<=y&&(m.expiredLanes|=ct),$&=~ct}if(y=Nn,S=tn,S=v(m,m===y?S:0,m.cancelPendingCommit!==null||m.timeoutHandle!==hh),N=m.callbackNode,S===0||m===y&&(xn===2||xn===9)||m.cancelPendingCommit!==null)return N!==null&&N!==null&&p3(N),m.callbackNode=null,m.callbackPriority=0;if((S&3)===0||P(m,S)){if(y=S&-S,y===m.callbackPriority)return y;switch(N!==null&&p3(N),B(S)){case 2:case 8:S=$pt;break;case 32:S=h3;break;case 268435456:S=Dpt;break;default:S=h3}return N=Nf.bind(null,m),S=cx(S,N),m.callbackPriority=y,m.callbackNode=S,y}return N!==null&&N!==null&&p3(N),m.callbackPriority=2,m.callbackNode=null,2}function Nf(m,y){if(Zi!==0&&Zi!==5)return m.callbackNode=null,m.callbackPriority=0,null;var S=m.callbackNode;if(zy(!0)&&m.callbackNode!==S)return null;var N=tn;return N=v(m,m===Nn?N:0,m.cancelPendingCommit!==null||m.timeoutHandle!==hh),N===0?null:(rz(m,N,y),If(m,Ws()),m.callbackNode!=null&&m.callbackNode===S?Nf.bind(null,m):null)}function Af(m,y){if(zy())return null;rz(m,y,!0)}function xy(){Fut?zut(function(){(Je&6)!==0?cx(t$,Ef):Cf()}):cx(t$,Ef)}function Kp(){return rm===0&&(rm=T()),rm}function by(m,y){if(Xy===null){var S=Xy=[];g3=0,sm=Kp(),om={status:"pending",value:void 0,then:function(N){S.push(N)}}}return g3++,y.then(Rf,Rf),y}function Rf(){if(--g3===0&&Xy!==null){om!==null&&(om.status="fulfilled");var m=Xy;Xy=null,sm=0,om=null;for(var y=0;y<m.length;y++)(0,m[y])()}}function vy(m,y){var S=[],N={status:"pending",value:null,reason:null,then:function(O){S.push(O)}};return m.then(function(){N.status="fulfilled",N.value=y;for(var O=0;O<S.length;O++)(0,S[O])(y)},function(O){for(N.status="rejected",N.reason=O,O=0;O<S.length;O++)(0,S[O])(void 0)}),N}function Jp(){var m=yh.current;return m!==null?m:Nn.pooledCache}function uc(m,y){y===null?_(yh,yh.current):_(yh,y.pool)}function Of(){var m=Jp();return m===null?null:{parent:ua?ti._currentValue:ti._currentValue2,pool:m}}function pc(m,y){if(ns(m,y))return!0;if(typeof m!="object"||m===null||typeof y!="object"||y===null)return!1;var S=Object.keys(m),N=Object.keys(y);if(S.length!==N.length)return!1;for(N=0;N<S.length;N++){var O=S[N];if(!Vpt.call(y,O)||!ns(m[O],y[O]))return!1}return!0}function Lf(m){return m=m.status,m==="fulfilled"||m==="rejected"}function hc(){}function Ff(m,y,S){switch(S=m[S],S===void 0?m.push(y):S!==y&&(y.then(hc,hc),y=S),y.status){case"fulfilled":return y.value;case"rejected":throw m=y.reason,$f(m),m;default:if(typeof y.status=="string")y.then(hc,hc);else{if(m=Nn,m!==null&&100<m.shellSuspendCounter)throw Error(i(482));m=y,m.status="pending",m.then(function(N){if(y.status==="pending"){var O=y;O.status="fulfilled",O.value=N}},function(N){if(y.status==="pending"){var O=y;O.status="rejected",O.reason=N}})}switch(y.status){case"fulfilled":return y.value;case"rejected":throw m=y.reason,$f(m),m}throw am=y,Uy}}function zf(){if(am===null)throw Error(i(459));var m=am;return am=null,m}function $f(m){if(m===Uy||m===mx)throw Error(i(483))}function dc(){for(var m=cm,y=b3=cm=0;y<m;){var S=gs[y];gs[y++]=null;var N=gs[y];gs[y++]=null;var O=gs[y];gs[y++]=null;var $=gs[y];if(gs[y++]=null,N!==null&&O!==null){var K=N.pending;K===null?O.next=O:(O.next=K.next,K.next=O),N.pending=O}$!==0&&Df(S,O,$)}}function fc(m,y,S,N){gs[cm++]=m,gs[cm++]=y,gs[cm++]=S,gs[cm++]=N,b3|=N,m.lanes|=N,m=m.alternate,m!==null&&(m.lanes|=N)}function Qp(m,y,S,N){return fc(m,y,S,N),mc(m)}function wo(m,y){return fc(m,null,null,y),mc(m)}function Df(m,y,S){m.lanes|=S;var N=m.alternate;N!==null&&(N.lanes|=S);for(var O=!1,$=m.return;$!==null;)$.childLanes|=S,N=$.alternate,N!==null&&(N.childLanes|=S),$.tag===22&&(m=$.stateNode,m===null||m._visibility&1||(O=!0)),m=$,$=$.return;return m.tag===3?($=m.stateNode,O&&y!==null&&(O=31-ts(S),m=$.hiddenUpdates,N=m[O],N===null?m[O]=[y]:N.push(y),y.lane=S|536870912),$):null}function mc(m){if(50<Zy)throw Zy=0,N3=null,Error(i(185));for(var y=m.return;y!==null;)m=y,y=m.return;return m.tag===3?m.stateNode:null}function th(m){m.updateQueue={baseState:m.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function eh(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 ds(m){return{lane:m,tag:0,payload:null,callback:null,next:null}}function fs(m,y,S){var N=m.updateQueue;if(N===null)return null;if(N=N.shared,(Je&2)!==0){var O=N.pending;return O===null?y.next=y:(y.next=O.next,O.next=y),N.pending=y,y=mc(m),Df(m,null,S),y}return fc(m,N,y,S),mc(m)}function ra(m,y,S){if(y=y.updateQueue,y!==null&&(y=y.shared,(S&4194048)!==0)){var N=y.lanes;N&=m.pendingLanes,S|=N,y.lanes=S,A(m,S)}}function nh(m,y){var S=m.updateQueue,N=m.alternate;if(N!==null&&(N=N.updateQueue,S===N)){var O=null,$=null;if(S=S.firstBaseUpdate,S!==null){do{var K={lane:S.lane,tag:S.tag,payload:S.payload,callback:null,next:null};$===null?O=$=K:$=$.next=K,S=S.next}while(S!==null);$===null?O=$=y:$=$.next=y}else O=$=y;S={baseState:N.baseState,firstBaseUpdate:O,lastBaseUpdate:$,shared:N.shared,callbacks:N.callbacks},m.updateQueue=S;return}m=S.lastBaseUpdate,m===null?S.firstBaseUpdate=y:m.next=y,S.lastBaseUpdate=y}function sa(){if(v3){var m=om;if(m!==null)throw m}}function oa(m,y,S,N){v3=!1;var O=m.updateQueue;Tc=!1;var $=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?$=It:K.next=It,K=xt;var $t=m.alternate;$t!==null&&($t=$t.updateQueue,ct=$t.lastBaseUpdate,ct!==K&&(ct===null?$t.firstBaseUpdate=It:ct.next=It,$t.lastBaseUpdate=xt))}if($!==null){var Xt=O.baseState;K=0,$t=It=xt=null,ct=$;do{var Wt=ct.lane&-536870913,Le=Wt!==ct.lane;if(Le?(tn&Wt)===Wt:(N&Wt)===Wt){Wt!==0&&Wt===sm&&(v3=!0),$t!==null&&($t=$t.next={lane:0,tag:ct.tag,payload:ct.payload,callback:null,next:null});t:{var vs=m,Ky=ct;Wt=y;var bh=S;switch(Ky.tag){case 1:if(vs=Ky.payload,typeof vs=="function"){Xt=vs.call(bh,Xt,Wt);break t}Xt=vs;break t;case 3:vs.flags=vs.flags&-65537|128;case 0:if(vs=Ky.payload,Wt=typeof vs=="function"?vs.call(bh,Xt,Wt):vs,Wt==null)break t;Xt=QT({},Xt,Wt);break t;case 2:Tc=!0}}Wt=ct.callback,Wt!==null&&(m.flags|=64,Le&&(m.flags|=8192),Le=O.callbacks,Le===null?O.callbacks=[Wt]:Le.push(Wt))}else Le={lane:Wt,tag:ct.tag,payload:ct.payload,callback:ct.callback,next:null},$t===null?(It=$t=Le,xt=Xt):$t=$t.next=Le,K|=Wt;if(ct=ct.next,ct===null){if(ct=O.shared.pending,ct===null)break;Le=ct,ct=Le.next,Le.next=null,O.lastBaseUpdate=Le,O.shared.pending=null}}while(!0);$t===null&&(xt=Xt),O.baseState=xt,O.firstBaseUpdate=It,O.lastBaseUpdate=$t,$===null&&(O.shared.lanes=0),Cc|=K,m.lanes=K,m.memoizedState=Xt}}function jf(m,y){if(typeof m!="function")throw Error(i(191,m));m.call(y)}function Bf(m,y){var S=m.callbacks;if(S!==null)for(m.callbacks=null,m=0;m<S.length;m++)jf(S[m],y)}function Yf(m,y){m=_a,_(yx,m),_(lm,y),_a=m|y.baseLanes}function ih(){_(yx,_a),_(lm,lm.current)}function rh(){_a=yx.current,d(lm),d(yx)}function Ln(){throw Error(i(321))}function sh(m,y){if(y===null)return!1;for(var S=0;S<y.length&&S<m.length;S++)if(!ns(m[S],y[S]))return!1;return!0}function oh(m,y,S,N,O,$){return Mc=$,De=y,y.memoizedState=null,y.updateQueue=null,y.lanes=0,_e.H=m===null||m.memoizedState===null?r$:s$,gh=!1,$=S(N,O),gh=!1,um&&($=Y0(y,S,N,O)),B0(m),$}function B0(m){_e.H=bx;var y=wn!==null&&wn.next!==null;if(Mc=0,di=wn=De=null,gx=!1,Vy=0,pm=null,y)throw Error(i(300));m===null||Ni||(m=m.dependencies,m!==null&&Kt(m)&&(Ni=!0))}function Y0(m,y,S,N){De=m;var O=0;do{if(um&&(pm=null),Vy=0,um=!1,25<=O)throw Error(i(301));if(O+=1,di=wn=null,m.updateQueue!=null){var $=m.updateQueue;$.lastEffect=null,$.events=null,$.stores=null,$.memoCache!=null&&($.memoCache.index=0)}_e.H=Hpt,$=y(S,N)}while(um);return $}function mT(){var m=_e.H,y=m.useState()[0];return y=typeof y.then=="function"?ah(y):y,m=m.useState()[0],(wn!==null?wn.memoizedState:null)!==m&&(De.flags|=1024),y}function Sy(){var m=xx!==0;return xx=0,m}function wy(m,y,S){y.updateQueue=m.updateQueue,y.flags&=-2053,m.lanes&=~S}function Py(m){if(gx){for(m=m.memoizedState;m!==null;){var y=m.queue;y!==null&&(y.pending=null),m=m.next}gx=!1}Mc=0,di=wn=De=null,um=!1,Vy=xx=0,pm=null}function or(){var m={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return di===null?De.memoizedState=di=m:di=di.next=m,di}function Qn(){if(wn===null){var m=De.alternate;m=m!==null?m.memoizedState:null}else m=wn.next;var y=di===null?De.memoizedState:di.next;if(y!==null)di=y,wn=m;else{if(m===null)throw De.alternate===null?Error(i(467)):Error(i(310));wn=m,m={memoizedState:wn.memoizedState,baseState:wn.baseState,baseQueue:wn.baseQueue,queue:wn.queue,next:null},di===null?De.memoizedState=di=m:di=di.next=m}return di}function ky(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function ah(m){var y=Vy;return Vy+=1,pm===null&&(pm=[]),m=Ff(pm,m,y),y=De,(di===null?y.memoizedState:di.next)===null&&(y=y.alternate,_e.H=y===null||y.memoizedState===null?r$:s$),m}function Xf(m){if(m!==null&&typeof m=="object"){if(typeof m.then=="function")return ah(m);if(m.$$typeof===Sc)return Jt(m)}throw Error(i(438,String(m)))}function Ty(m){var y=null,S=De.updateQueue;if(S!==null&&(y=S.memoCache),y==null){var N=De.alternate;N!==null&&(N=N.updateQueue,N!==null&&(N=N.memoCache,N!=null&&(y={data:N.data.map(function(O){return O.slice()}),index:0})))}if(y==null&&(y={data:[],index:0}),S===null&&(S=ky(),De.updateQueue=S),S.memoCache=y,S=y.data[y.index],S===void 0)for(S=y.data[y.index]=Array(m),N=0;N<m;N++)S[N]=_ut;return y.index++,S}function Vs(m,y){return typeof y=="function"?y(m):y}function Uf(m){var y=Qn();return My(y,wn,m)}function My(m,y,S){var N=m.queue;if(N===null)throw Error(i(311));N.lastRenderedReducer=S;var O=m.baseQueue,$=N.pending;if($!==null){if(O!==null){var K=O.next;O.next=$.next,$.next=K}y.baseQueue=O=$,N.pending=null}if($=m.baseState,O===null)m.memoizedState=$;else{y=O.next;var ct=K=null,xt=null,It=y,$t=!1;do{var Xt=It.lane&-536870913;if(Xt!==It.lane?(tn&Xt)===Xt:(Mc&Xt)===Xt){var Wt=It.revertLane;if(Wt===0)xt!==null&&(xt=xt.next={lane:0,revertLane:0,action:It.action,hasEagerState:It.hasEagerState,eagerState:It.eagerState,next:null}),Xt===sm&&($t=!0);else if((Mc&Wt)===Wt){It=It.next,Wt===sm&&($t=!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=$):xt=xt.next=Xt,De.lanes|=Wt,Cc|=Wt;Xt=It.action,gh&&S($,Xt),$=It.hasEagerState?It.eagerState:S($,Xt)}else Wt={lane:Xt,revertLane:It.revertLane,action:It.action,hasEagerState:It.hasEagerState,eagerState:It.eagerState,next:null},xt===null?(ct=xt=Wt,K=$):xt=xt.next=Wt,De.lanes|=Xt,Cc|=Xt;It=It.next}while(It!==null&&It!==y);if(xt===null?K=$:xt.next=ct,!ns($,m.memoizedState)&&(Ni=!0,$t&&(S=om,S!==null)))throw S;m.memoizedState=$,m.baseState=K,m.baseQueue=xt,N.lastRenderedState=$}return O===null&&(N.lanes=0),[m.memoizedState,N.dispatch]}function Ey(m){var y=Qn(),S=y.queue;if(S===null)throw Error(i(311));S.lastRenderedReducer=m;var N=S.dispatch,O=S.pending,$=y.memoizedState;if(O!==null){S.pending=null;var K=O=O.next;do $=m($,K.action),K=K.next;while(K!==O);ns($,y.memoizedState)||(Ni=!0),y.memoizedState=$,y.baseQueue===null&&(y.baseState=$),S.lastRenderedState=$}return[$,N]}function F7(m,y,S){var N=De,O=Qn(),$=mn;if($){if(S===void 0)throw Error(i(407));S=S()}else S=y();var K=!ns((wn||O).memoizedState,S);K&&(O.memoizedState=S,Ni=!0),O=O.queue;var ct=D7.bind(null,N,O,m);if(Cy(2048,8,ct,[m]),O.getSnapshot!==y||K||di!==null&&di.memoizedState.tag&1){if(N.flags|=2048,Vf(9,X0(),$7.bind(null,N,O,S,y),null),Nn===null)throw Error(i(349));$||(Mc&124)!==0||z7(N,y,S)}return S}function z7(m,y,S){m.flags|=16384,m={getSnapshot:y,value:S},y=De.updateQueue,y===null?(y=ky(),De.updateQueue=y,y.stores=[m]):(S=y.stores,S===null?y.stores=[m]:S.push(m))}function $7(m,y,S,N){y.value=S,y.getSnapshot=N,j7(y)&&B7(m)}function D7(m,y,S){return S(function(){j7(y)&&B7(m)})}function j7(m){var y=m.getSnapshot;m=m.value;try{var S=y();return!ns(m,S)}catch{return!0}}function B7(m){var y=wo(m,2);y!==null&&Jr(y,m,2)}function _T(m){var y=or();if(typeof m=="function"){var S=m;if(m=S(),gh){j(!0);try{S()}finally{j(!1)}}}return y.memoizedState=y.baseState=m,y.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Vs,lastRenderedState:m},y}function Y7(m,y,S,N){return m.baseState=S,My(m,wn,typeof N=="function"?N:Vs)}function Hlt(m,y,S,N,O){if(V0(m))throw Error(i(485));if(m=y.action,m!==null){var $={payload:O,action:m,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(K){$.listeners.push(K)}};_e.T!==null?S(!0):$.isTransition=!1,N($),S=y.pending,S===null?($.next=y.pending=$,X7(y,$)):($.next=S.next,y.pending=S.next=$)}}function X7(m,y){var S=y.action,N=y.payload,O=m.state;if(y.isTransition){var $=_e.T,K={};_e.T=K;try{var ct=S(O,N),xt=_e.S;xt!==null&&xt(K,ct),U7(m,y,ct)}catch(It){yT(m,y,It)}finally{_e.T=$}}else try{$=S(O,N),U7(m,y,$)}catch(It){yT(m,y,It)}}function U7(m,y,S){S!==null&&typeof S=="object"&&typeof S.then=="function"?S.then(function(N){V7(m,y,N)},function(N){return yT(m,y,N)}):V7(m,y,S)}function V7(m,y,S){y.status="fulfilled",y.value=S,G7(y),m.state=S,y=m.pending,y!==null&&(S=y.next,S===y?m.pending=null:(S=S.next,y.next=S,X7(m,S)))}function yT(m,y,S){var N=m.pending;if(m.pending=null,N!==null){N=N.next;do y.status="rejected",y.reason=S,G7(y),y=y.next;while(y!==N)}m.action=null}function G7(m){m=m.listeners;for(var y=0;y<m.length;y++)(0,m[y])()}function H7(m,y){return y}function W7(m,y){if(mn){var S=Nn.formState;if(S!==null){t:{var N=De;if(mn){if(vi){var O=cpt(vi,To);if(O){vi=Yz(O),N=lpt(O);break t}}ot(N)}N=!1}N&&(y=S[0])}}S=or(),S.memoizedState=S.baseState=y,N={pending:null,lanes:0,dispatch:null,lastRenderedReducer:H7,lastRenderedState:y},S.queue=N,S=hF.bind(null,De,N),N.dispatch=S,N=_T(!1);var $=vT.bind(null,De,!1,N.queue);return N=or(),O={state:y,dispatch:null,action:m,pending:null},N.queue=O,S=Hlt.bind(null,De,O,$,S),O.dispatch=S,N.memoizedState=m,[y,S,!1]}function q7(m){var y=Qn();return Z7(y,wn,m)}function Z7(m,y,S){if(y=My(m,y,H7)[0],m=Uf(Vs)[0],typeof y=="object"&&y!==null&&typeof y.then=="function")try{var N=ah(y)}catch(K){throw K===Uy?mx:K}else N=y;y=Qn();var O=y.queue,$=O.dispatch;return S!==y.memoizedState&&(De.flags|=2048,Vf(9,X0(),Wlt.bind(null,O,S),null)),[N,$,m]}function Wlt(m,y){m.action=y}function K7(m){var y=Qn(),S=wn;if(S!==null)return Z7(y,S,m);Qn(),y=y.memoizedState,S=Qn();var N=S.queue.dispatch;return S.memoizedState=m,[y,N,!1]}function Vf(m,y,S,N){return m={tag:m,create:S,deps:N,inst:y,next:null},y=De.updateQueue,y===null&&(y=ky(),De.updateQueue=y),S=y.lastEffect,S===null?y.lastEffect=m.next=m:(N=S.next,S.next=m,m.next=N,y.lastEffect=m),m}function X0(){return{destroy:void 0,resource:void 0}}function J7(){return Qn().memoizedState}function U0(m,y,S,N){var O=or();N=N===void 0?null:N,De.flags|=m,O.memoizedState=Vf(1|y,X0(),S,N)}function Cy(m,y,S,N){var O=Qn();N=N===void 0?null:N;var $=O.memoizedState.inst;wn!==null&&N!==null&&sh(N,wn.memoizedState.deps)?O.memoizedState=Vf(y,$,S,N):(De.flags|=m,O.memoizedState=Vf(1|y,$,S,N))}function Q7(m,y){U0(8390656,8,m,y)}function tF(m,y){Cy(2048,8,m,y)}function eF(m,y){return Cy(4,2,m,y)}function nF(m,y){return Cy(4,4,m,y)}function iF(m,y){if(typeof y=="function"){m=m();var S=y(m);return function(){typeof S=="function"?S():y(null)}}if(y!=null)return m=m(),y.current=m,function(){y.current=null}}function rF(m,y,S){S=S!=null?S.concat([m]):null,Cy(4,4,iF.bind(null,y,m),S)}function gT(){}function sF(m,y){var S=Qn();y=y===void 0?null:y;var N=S.memoizedState;return y!==null&&sh(y,N[1])?N[0]:(S.memoizedState=[m,y],m)}function oF(m,y){var S=Qn();y=y===void 0?null:y;var N=S.memoizedState;if(y!==null&&sh(y,N[1]))return N[0];if(N=m(),gh){j(!0);try{m()}finally{j(!1)}}return S.memoizedState=[N,y],N}function xT(m,y,S){return S===void 0||(Mc&1073741824)!==0?m.memoizedState=y:(m.memoizedState=S,m=iz(),De.lanes|=m,Cc|=m,S)}function aF(m,y,S,N){return ns(S,y)?S:lm.current!==null?(m=xT(m,S,N),ns(m,y)||(Ni=!0),m):(Mc&42)===0?(Ni=!0,m.memoizedState=S):(m=iz(),De.lanes|=m,Cc|=m,y)}function cF(m,y,S,N,O){var $=pa();Ii($!==0&&8>$?$:8);var K=_e.T,ct={};_e.T=ct,vT(m,!1,y,S);try{var xt=O(),It=_e.S;if(It!==null&&It(ct,xt),xt!==null&&typeof xt=="object"&&typeof xt.then=="function"){var $t=vy(xt,N);Iy(m,y,$t,Kr(m))}else Iy(m,y,N,Kr(m))}catch(Xt){Iy(m,y,{then:function(){},status:"rejected",reason:Xt},Kr())}finally{Ii($),_e.T=K}}function lF(m){var y=m.memoizedState;if(y!==null)return y;y={memoizedState:Kf,baseState:Kf,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Vs,lastRenderedState:Kf},next:null};var S={};return y.next={memoizedState:S,baseState:S,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Vs,lastRenderedState:S},next:null},m.memoizedState=y,m=m.alternate,m!==null&&(m.memoizedState=y),y}function bT(){return Jt(dh)}function uF(){return Qn().memoizedState}function pF(){return Qn().memoizedState}function qlt(m){for(var y=m.return;y!==null;){switch(y.tag){case 24:case 3:var S=Kr();m=ds(S);var N=fs(y,m,S);N!==null&&(Jr(N,y,S),ra(N,y,S)),y={cache:Cr()},m.payload=y;return}y=y.return}}function Zlt(m,y,S){var N=Kr();S={lane:N,revertLane:0,action:S,hasEagerState:!1,eagerState:null,next:null},V0(m)?dF(y,S):(S=Qp(m,y,S,N),S!==null&&(Jr(S,m,N),fF(S,y,N)))}function hF(m,y,S){var N=Kr();Iy(m,y,S,N)}function Iy(m,y,S,N){var O={lane:N,revertLane:0,action:S,hasEagerState:!1,eagerState:null,next:null};if(V0(m))dF(y,O);else{var $=m.alternate;if(m.lanes===0&&($===null||$.lanes===0)&&($=y.lastRenderedReducer,$!==null))try{var K=y.lastRenderedState,ct=$(K,S);if(O.hasEagerState=!0,O.eagerState=ct,ns(ct,K))return fc(m,y,O,0),Nn===null&&dc(),!1}catch{}finally{}if(S=Qp(m,y,O,N),S!==null)return Jr(S,m,N),fF(S,y,N),!0}return!1}function vT(m,y,S,N){if(N={lane:2,revertLane:Kp(),action:N,hasEagerState:!1,eagerState:null,next:null},V0(m)){if(y)throw Error(i(479))}else y=Qp(m,S,N,2),y!==null&&Jr(y,m,2)}function V0(m){var y=m.alternate;return m===De||y!==null&&y===De}function dF(m,y){um=gx=!0;var S=m.pending;S===null?y.next=y:(y.next=S.next,S.next=y),m.pending=y}function fF(m,y,S){if((S&4194048)!==0){var N=y.lanes;N&=m.pendingLanes,S|=N,y.lanes=S,A(m,S)}}function G0(m){var y=Gy;return Gy+=1,hm===null&&(hm=[]),Ff(hm,m,y)}function Ny(m,y){y=y.props.ref,m.ref=y!==void 0?y:null}function H0(m,y){throw y.$$typeof===fut?Error(i(525)):(m=Object.prototype.toString.call(y),Error(i(31,m==="[object Object]"?"object with keys {"+Object.keys(y).join(", ")+"}":m)))}function mF(m){var y=m._init;return y(m._payload)}function _F(m){function y(gt,dt){if(m){var vt=gt.deletions;vt===null?(gt.deletions=[dt],gt.flags|=16):vt.push(dt)}}function S(gt,dt){if(!m)return null;for(;dt!==null;)y(gt,dt),dt=dt.sibling;return null}function N(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=la(gt,dt),gt.index=0,gt.sibling=null,gt}function $(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,zt){return dt===null||dt.tag!==6?(dt=ZT(vt,gt.mode,zt),dt.return=gt,dt):(dt=O(dt,vt),dt.return=gt,dt)}function xt(gt,dt,vt,zt){var ce=vt.type;return ce===Zf?$t(gt,dt,vt.props.children,zt,vt.key):dt!==null&&(dt.elementType===ce||typeof ce=="object"&&ce!==null&&ce.$$typeof===wc&&mF(ce)===dt.type)?(dt=O(dt,vt.props),Ny(dt,vt),dt.return=gt,dt):(dt=nx(vt.type,vt.key,vt.props,null,gt.mode,zt),Ny(dt,vt),dt.return=gt,dt)}function It(gt,dt,vt,zt){return dt===null||dt.tag!==4||dt.stateNode.containerInfo!==vt.containerInfo||dt.stateNode.implementation!==vt.implementation?(dt=KT(vt,gt.mode,zt),dt.return=gt,dt):(dt=O(dt,vt.children||[]),dt.return=gt,dt)}function $t(gt,dt,vt,zt,ce){return dt===null||dt.tag!==7?(dt=ph(vt,gt.mode,zt,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=ZT(""+dt,gt.mode,vt),dt.return=gt,dt;if(typeof dt=="object"&&dt!==null){switch(dt.$$typeof){case ix:return vt=nx(dt.type,dt.key,dt.props,null,gt.mode,vt),Ny(vt,dt),vt.return=gt,vt;case qf:return dt=KT(dt,gt.mode,vt),dt.return=gt,dt;case wc:var zt=dt._init;return dt=zt(dt._payload),Xt(gt,dt,vt)}if(rx(dt)||l(dt))return dt=ph(dt,gt.mode,vt,null),dt.return=gt,dt;if(typeof dt.then=="function")return Xt(gt,G0(dt),vt);if(dt.$$typeof===Sc)return Xt(gt,Wn(gt,dt),vt);H0(gt,dt)}return null}function Wt(gt,dt,vt,zt){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,zt);if(typeof vt=="object"&&vt!==null){switch(vt.$$typeof){case ix:return vt.key===ce?xt(gt,dt,vt,zt):null;case qf:return vt.key===ce?It(gt,dt,vt,zt):null;case wc:return ce=vt._init,vt=ce(vt._payload),Wt(gt,dt,vt,zt)}if(rx(vt)||l(vt))return ce!==null?null:$t(gt,dt,vt,zt,null);if(typeof vt.then=="function")return Wt(gt,dt,G0(vt),zt);if(vt.$$typeof===Sc)return Wt(gt,dt,Wn(gt,vt),zt);H0(gt,vt)}return null}function Le(gt,dt,vt,zt,ce){if(typeof zt=="string"&&zt!==""||typeof zt=="number"||typeof zt=="bigint")return gt=gt.get(vt)||null,ct(dt,gt,""+zt,ce);if(typeof zt=="object"&&zt!==null){switch(zt.$$typeof){case ix:return gt=gt.get(zt.key===null?vt:zt.key)||null,xt(dt,gt,zt,ce);case qf:return gt=gt.get(zt.key===null?vt:zt.key)||null,It(dt,gt,zt,ce);case wc:var Fn=zt._init;return zt=Fn(zt._payload),Le(gt,dt,vt,zt,ce)}if(rx(zt)||l(zt))return gt=gt.get(vt)||null,$t(dt,gt,zt,ce,null);if(typeof zt.then=="function")return Le(gt,dt,vt,G0(zt),ce);if(zt.$$typeof===Sc)return Le(gt,dt,vt,Wn(dt,zt),ce);H0(dt,zt)}return null}function vs(gt,dt,vt,zt){for(var ce=null,Fn=null,ke=dt,sn=dt=0,Ri=null;ke!==null&&sn<vt.length;sn++){ke.index>sn?(Ri=ke,ke=null):Ri=ke.sibling;var on=Wt(gt,ke,vt[sn],zt);if(on===null){ke===null&&(ke=Ri);break}m&&ke&&on.alternate===null&&y(gt,ke),dt=$(on,dt,sn),Fn===null?ce=on:Fn.sibling=on,Fn=on,ke=Ri}if(sn===vt.length)return S(gt,ke),mn&&mt(gt,sn),ce;if(ke===null){for(;sn<vt.length;sn++)ke=Xt(gt,vt[sn],zt),ke!==null&&(dt=$(ke,dt,sn),Fn===null?ce=ke:Fn.sibling=ke,Fn=ke);return mn&&mt(gt,sn),ce}for(ke=N(ke);sn<vt.length;sn++)Ri=Le(ke,gt,sn,vt[sn],zt),Ri!==null&&(m&&Ri.alternate!==null&&ke.delete(Ri.key===null?sn:Ri.key),dt=$(Ri,dt,sn),Fn===null?ce=Ri:Fn.sibling=Ri,Fn=Ri);return m&&ke.forEach(function(Ac){return y(gt,Ac)}),mn&&mt(gt,sn),ce}function Ky(gt,dt,vt,zt){if(vt==null)throw Error(i(151));for(var ce=null,Fn=null,ke=dt,sn=dt=0,Ri=null,on=vt.next();ke!==null&&!on.done;sn++,on=vt.next()){ke.index>sn?(Ri=ke,ke=null):Ri=ke.sibling;var Ac=Wt(gt,ke,on.value,zt);if(Ac===null){ke===null&&(ke=Ri);break}m&&ke&&Ac.alternate===null&&y(gt,ke),dt=$(Ac,dt,sn),Fn===null?ce=Ac:Fn.sibling=Ac,Fn=Ac,ke=Ri}if(on.done)return S(gt,ke),mn&&mt(gt,sn),ce;if(ke===null){for(;!on.done;sn++,on=vt.next())on=Xt(gt,on.value,zt),on!==null&&(dt=$(on,dt,sn),Fn===null?ce=on:Fn.sibling=on,Fn=on);return mn&&mt(gt,sn),ce}for(ke=N(ke);!on.done;sn++,on=vt.next())on=Le(ke,gt,sn,on.value,zt),on!==null&&(m&&on.alternate!==null&&ke.delete(on.key===null?sn:on.key),dt=$(on,dt,sn),Fn===null?ce=on:Fn.sibling=on,Fn=on);return m&&ke.forEach(function(Zpt){return y(gt,Zpt)}),mn&&mt(gt,sn),ce}function bh(gt,dt,vt,zt){if(typeof vt=="object"&&vt!==null&&vt.type===Zf&&vt.key===null&&(vt=vt.props.children),typeof vt=="object"&&vt!==null){switch(vt.$$typeof){case ix:t:{for(var ce=vt.key;dt!==null;){if(dt.key===ce){if(ce=vt.type,ce===Zf){if(dt.tag===7){S(gt,dt.sibling),zt=O(dt,vt.props.children),zt.return=gt,gt=zt;break t}}else if(dt.elementType===ce||typeof ce=="object"&&ce!==null&&ce.$$typeof===wc&&mF(ce)===dt.type){S(gt,dt.sibling),zt=O(dt,vt.props),Ny(zt,vt),zt.return=gt,gt=zt;break t}S(gt,dt);break}else y(gt,dt);dt=dt.sibling}vt.type===Zf?(zt=ph(vt.props.children,gt.mode,zt,vt.key),zt.return=gt,gt=zt):(zt=nx(vt.type,vt.key,vt.props,null,gt.mode,zt),Ny(zt,vt),zt.return=gt,gt=zt)}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){S(gt,dt.sibling),zt=O(dt,vt.children||[]),zt.return=gt,gt=zt;break t}else{S(gt,dt);break}else y(gt,dt);dt=dt.sibling}zt=KT(vt,gt.mode,zt),zt.return=gt,gt=zt}return K(gt);case wc:return ce=vt._init,vt=ce(vt._payload),bh(gt,dt,vt,zt)}if(rx(vt))return vs(gt,dt,vt,zt);if(l(vt)){if(ce=l(vt),typeof ce!="function")throw Error(i(150));return vt=ce.call(vt),Ky(gt,dt,vt,zt)}if(typeof vt.then=="function")return bh(gt,dt,G0(vt),zt);if(vt.$$typeof===Sc)return bh(gt,dt,Wn(gt,vt),zt);H0(gt,vt)}return typeof vt=="string"&&vt!==""||typeof vt=="number"||typeof vt=="bigint"?(vt=""+vt,dt!==null&&dt.tag===6?(S(gt,dt.sibling),zt=O(dt,vt),zt.return=gt,gt=zt):(S(gt,dt),zt=ZT(vt,gt.mode,zt),zt.return=gt,gt=zt),K(gt)):S(gt,dt)}return function(gt,dt,vt,zt){try{Gy=0;var ce=bh(gt,dt,vt,zt);return hm=null,ce}catch(ke){if(ke===Uy||ke===mx)throw ke;var Fn=e(29,ke,null,gt.mode);return Fn.lanes=zt,Fn.return=gt,Fn}finally{}}}function _c(m){var y=m.alternate;_(Si,Si.current&1),_(xs,m),Mo===null&&(y===null||lm.current!==null||y.memoizedState!==null)&&(Mo=m)}function yF(m){if(m.tag===22){if(_(Si,Si.current),_(xs,m),Mo===null){var y=m.alternate;y!==null&&y.memoizedState!==null&&(Mo=m)}}else yc(m)}function yc(){_(Si,Si.current),_(xs,xs.current)}function aa(m){d(xs),Mo===m&&(Mo=null),d(Si)}function W0(m){for(var y=m;y!==null;){if(y.tag===13){var S=y.memoizedState;if(S!==null&&(S=S.dehydrated,S===null||a3(S)||c3(S)))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 ST(m,y,S,N){y=m.memoizedState,S=S(N,y),S=S==null?y:QT({},y,S),m.memoizedState=S,m.lanes===0&&(m.updateQueue.baseState=S)}function gF(m,y,S,N,O,$,K){return m=m.stateNode,typeof m.shouldComponentUpdate=="function"?m.shouldComponentUpdate(N,$,K):y.prototype&&y.prototype.isPureReactComponent?!pc(S,N)||!pc(O,$):!0}function xF(m,y,S,N){m=y.state,typeof y.componentWillReceiveProps=="function"&&y.componentWillReceiveProps(S,N),typeof y.UNSAFE_componentWillReceiveProps=="function"&&y.UNSAFE_componentWillReceiveProps(S,N),y.state!==m&&S3.enqueueReplaceState(y,y.state,null)}function ch(m,y){var S=y;if("ref"in y){S={};for(var N in y)N!=="ref"&&(S[N]=y[N])}if(m=m.defaultProps){S===y&&(S=QT({},S));for(var O in m)S[O]===void 0&&(S[O]=m[O])}return S}function q0(m,y){try{var S=m.onUncaughtError;S(y.value,{componentStack:y.stack})}catch(N){setTimeout(function(){throw N})}}function bF(m,y,S){try{var N=m.onCaughtError;N(S.value,{componentStack:S.stack,errorBoundary:y.tag===1?y.stateNode:null})}catch(O){setTimeout(function(){throw O})}}function wT(m,y,S){return S=ds(S),S.tag=3,S.payload={element:null},S.callback=function(){q0(m,y)},S}function vF(m){return m=ds(m),m.tag=3,m}function SF(m,y,S,N){var O=S.type.getDerivedStateFromError;if(typeof O=="function"){var $=N.value;m.payload=function(){return O($)},m.callback=function(){bF(y,S,N)}}var K=S.stateNode;K!==null&&typeof K.componentDidCatch=="function"&&(m.callback=function(){bF(y,S,N),typeof O!="function"&&(Ic===null?Ic=new Set([this]):Ic.add(this));var ct=N.stack;this.componentDidCatch(N.value,{componentStack:ct!==null?ct:""})})}function Klt(m,y,S,N,O){if(S.flags|=32768,N!==null&&typeof N=="object"&&typeof N.then=="function"){if(y=S.alternate,y!==null&&Se(y,S,O,!0),S=xs.current,S!==null){switch(S.tag){case 13:return Mo===null?GT():S.alternate===null&&ei===0&&(ei=3),S.flags&=-257,S.flags|=65536,S.lanes=O,N===_x?S.flags|=16384:(y=S.updateQueue,y===null?S.updateQueue=new Set([N]):y.add(N),WT(m,N,O)),!1;case 22:return S.flags|=65536,N===_x?S.flags|=16384:(y=S.updateQueue,y===null?(y={transitions:null,markerInstances:null,retryQueue:new Set([N])},S.updateQueue=y):(S=y.retryQueue,S===null?y.retryQueue=new Set([N]):S.add(N)),WT(m,N,O)),!1}throw Error(i(435,S.tag))}return WT(m,N,O),GT(),!1}if(mn)return y=xs.current,y!==null?((y.flags&65536)===0&&(y.flags|=256),y.flags|=65536,y.lanes=O,N!==m3&&(m=Error(i(422),{cause:N}),Z(tt(m,S)))):(N!==m3&&(y=Error(i(423),{cause:N}),Z(tt(y,S))),m=m.current.alternate,m.flags|=65536,O&=-O,m.lanes|=O,N=tt(N,S),O=wT(m.stateNode,N,O),nh(m,O),ei!==4&&(ei=2)),!1;var $=Error(i(520),{cause:N});if($=tt($,S),Wy===null?Wy=[$]:Wy.push($),ei!==4&&(ei=2),y===null)return!0;N=tt(N,S),S=y;do{switch(S.tag){case 3:return S.flags|=65536,m=O&-O,S.lanes|=m,m=wT(S.stateNode,N,m),nh(S,m),!1;case 1:if(y=S.type,$=S.stateNode,(S.flags&128)===0&&(typeof y.getDerivedStateFromError=="function"||$!==null&&typeof $.componentDidCatch=="function"&&(Ic===null||!Ic.has($))))return S.flags|=65536,O&=-O,S.lanes|=O,O=vF(O),SF(O,m,S,N),nh(S,O),!1}S=S.return}while(S!==null);return!1}function Wi(m,y,S,N){y.child=m===null?o$(y,null,S,N):dm(y,m.child,S,N)}function wF(m,y,S,N,O){S=S.render;var $=y.ref;if("ref"in N){var K={};for(var ct in N)ct!=="ref"&&(K[ct]=N[ct])}else K=N;return le(y),N=oh(m,y,S,K,$,O),ct=Sy(),m!==null&&!Ni?(wy(m,y,O),ca(m,y,O)):(mn&&ct&&Q(y),y.flags|=1,Wi(m,y,N,O),y.child)}function PF(m,y,S,N,O){if(m===null){var $=S.type;return typeof $=="function"&&!qT($)&&$.defaultProps===void 0&&S.compare===null?(y.tag=15,y.type=$,kF(m,y,$,N,O)):(m=nx(S.type,null,N,y,y.mode,O),m.ref=y.ref,m.return=y,y.child=m)}if($=m.child,!IT(m,O)){var K=$.memoizedProps;if(S=S.compare,S=S!==null?S:pc,S(K,N)&&m.ref===y.ref)return ca(m,y,O)}return y.flags|=1,m=la($,N),m.ref=y.ref,m.return=y,y.child=m}function kF(m,y,S,N,O){if(m!==null){var $=m.memoizedProps;if(pc($,N)&&m.ref===y.ref)if(Ni=!1,y.pendingProps=N=$,IT(m,O))(m.flags&131072)!==0&&(Ni=!0);else return y.lanes=m.lanes,ca(m,y,O)}return PT(m,y,S,N,O)}function TF(m,y,S){var N=y.pendingProps,O=N.children,$=m!==null?m.memoizedState:null;if(N.mode==="hidden"){if((y.flags&128)!==0){if(N=$!==null?$.baseLanes|S:S,m!==null){for(O=y.child=m.child,$=0;O!==null;)$=$|O.lanes|O.childLanes,O=O.sibling;y.childLanes=$&~N}else y.childLanes=0,y.child=null;return MF(m,y,N,S)}if((S&536870912)!==0)y.memoizedState={baseLanes:0,cachePool:null},m!==null&&uc(y,$!==null?$.cachePool:null),$!==null?Yf(y,$):ih(),yF(y);else return y.lanes=y.childLanes=536870912,MF(m,y,$!==null?$.baseLanes|S:S,S)}else $!==null?(uc(y,$.cachePool),Yf(y,$),yc(y),y.memoizedState=null):(m!==null&&uc(y,null),ih(),yc(y));return Wi(m,y,O,S),y.child}function MF(m,y,S,N){var O=Jp();return O=O===null?null:{parent:ua?ti._currentValue:ti._currentValue2,pool:O},y.memoizedState={baseLanes:S,cachePool:O},m!==null&&uc(y,null),ih(),yF(y),m!==null&&Se(m,y,N,!0),null}function Z0(m,y){var S=y.ref;if(S===null)m!==null&&m.ref!==null&&(y.flags|=4194816);else{if(typeof S!="function"&&typeof S!="object")throw Error(i(284));(m===null||m.ref!==S)&&(y.flags|=4194816)}}function PT(m,y,S,N,O){return le(y),S=oh(m,y,S,N,void 0,O),N=Sy(),m!==null&&!Ni?(wy(m,y,O),ca(m,y,O)):(mn&&N&&Q(y),y.flags|=1,Wi(m,y,S,O),y.child)}function EF(m,y,S,N,O,$){return le(y),y.updateQueue=null,S=Y0(y,N,S,O),B0(m),N=Sy(),m!==null&&!Ni?(wy(m,y,$),ca(m,y,$)):(mn&&N&&Q(y),y.flags|=1,Wi(m,y,S,$),y.child)}function CF(m,y,S,N,O){if(le(y),y.stateNode===null){var $=tm,K=S.contextType;typeof K=="object"&&K!==null&&($=Jt(K)),$=new S(N,$),y.memoizedState=$.state!==null&&$.state!==void 0?$.state:null,$.updater=S3,y.stateNode=$,$._reactInternals=y,$=y.stateNode,$.props=N,$.state=y.memoizedState,$.refs={},th(y),K=S.contextType,$.context=typeof K=="object"&&K!==null?Jt(K):tm,$.state=y.memoizedState,K=S.getDerivedStateFromProps,typeof K=="function"&&(ST(y,S,K,N),$.state=y.memoizedState),typeof S.getDerivedStateFromProps=="function"||typeof $.getSnapshotBeforeUpdate=="function"||typeof $.UNSAFE_componentWillMount!="function"&&typeof $.componentWillMount!="function"||(K=$.state,typeof $.componentWillMount=="function"&&$.componentWillMount(),typeof $.UNSAFE_componentWillMount=="function"&&$.UNSAFE_componentWillMount(),K!==$.state&&S3.enqueueReplaceState($,$.state,null),oa(y,N,$,O),sa(),$.state=y.memoizedState),typeof $.componentDidMount=="function"&&(y.flags|=4194308),N=!0}else if(m===null){$=y.stateNode;var ct=y.memoizedProps,xt=ch(S,ct);$.props=xt;var It=$.context,$t=S.contextType;K=tm,typeof $t=="object"&&$t!==null&&(K=Jt($t));var Xt=S.getDerivedStateFromProps;$t=typeof Xt=="function"||typeof $.getSnapshotBeforeUpdate=="function",ct=y.pendingProps!==ct,$t||typeof $.UNSAFE_componentWillReceiveProps!="function"&&typeof $.componentWillReceiveProps!="function"||(ct||It!==K)&&xF(y,$,N,K),Tc=!1;var Wt=y.memoizedState;$.state=Wt,oa(y,N,$,O),sa(),It=y.memoizedState,ct||Wt!==It||Tc?(typeof Xt=="function"&&(ST(y,S,Xt,N),It=y.memoizedState),(xt=Tc||gF(y,S,xt,N,Wt,It,K))?($t||typeof $.UNSAFE_componentWillMount!="function"&&typeof $.componentWillMount!="function"||(typeof $.componentWillMount=="function"&&$.componentWillMount(),typeof $.UNSAFE_componentWillMount=="function"&&$.UNSAFE_componentWillMount()),typeof $.componentDidMount=="function"&&(y.flags|=4194308)):(typeof $.componentDidMount=="function"&&(y.flags|=4194308),y.memoizedProps=N,y.memoizedState=It),$.props=N,$.state=It,$.context=K,N=xt):(typeof $.componentDidMount=="function"&&(y.flags|=4194308),N=!1)}else{$=y.stateNode,eh(m,y),K=y.memoizedProps,$t=ch(S,K),$.props=$t,Xt=y.pendingProps,Wt=$.context,It=S.contextType,xt=tm,typeof It=="object"&&It!==null&&(xt=Jt(It)),ct=S.getDerivedStateFromProps,(It=typeof ct=="function"||typeof $.getSnapshotBeforeUpdate=="function")||typeof $.UNSAFE_componentWillReceiveProps!="function"&&typeof $.componentWillReceiveProps!="function"||(K!==Xt||Wt!==xt)&&xF(y,$,N,xt),Tc=!1,Wt=y.memoizedState,$.state=Wt,oa(y,N,$,O),sa();var Le=y.memoizedState;K!==Xt||Wt!==Le||Tc||m!==null&&m.dependencies!==null&&Kt(m.dependencies)?(typeof ct=="function"&&(ST(y,S,ct,N),Le=y.memoizedState),($t=Tc||gF(y,S,$t,N,Wt,Le,xt)||m!==null&&m.dependencies!==null&&Kt(m.dependencies))?(It||typeof $.UNSAFE_componentWillUpdate!="function"&&typeof $.componentWillUpdate!="function"||(typeof $.componentWillUpdate=="function"&&$.componentWillUpdate(N,Le,xt),typeof $.UNSAFE_componentWillUpdate=="function"&&$.UNSAFE_componentWillUpdate(N,Le,xt)),typeof $.componentDidUpdate=="function"&&(y.flags|=4),typeof $.getSnapshotBeforeUpdate=="function"&&(y.flags|=1024)):(typeof $.componentDidUpdate!="function"||K===m.memoizedProps&&Wt===m.memoizedState||(y.flags|=4),typeof $.getSnapshotBeforeUpdate!="function"||K===m.memoizedProps&&Wt===m.memoizedState||(y.flags|=1024),y.memoizedProps=N,y.memoizedState=Le),$.props=N,$.state=Le,$.context=xt,N=$t):(typeof $.componentDidUpdate!="function"||K===m.memoizedProps&&Wt===m.memoizedState||(y.flags|=4),typeof $.getSnapshotBeforeUpdate!="function"||K===m.memoizedProps&&Wt===m.memoizedState||(y.flags|=1024),N=!1)}return $=N,Z0(m,y),N=(y.flags&128)!==0,$||N?($=y.stateNode,S=N&&typeof S.getDerivedStateFromError!="function"?null:$.render(),y.flags|=1,m!==null&&N?(y.child=dm(y,m.child,null,O),y.child=dm(y,null,S,O)):Wi(m,y,S,O),y.memoizedState=$.state,m=y.child):m=ca(m,y,O),m}function IF(m,y,S,N){return ut(),y.flags|=256,Wi(m,y,S,N),y.child}function kT(m){return{baseLanes:m,cachePool:Of()}}function TT(m,y,S){return m=m!==null?m.childLanes&~S:0,y&&(m|=bs),m}function NF(m,y,S){var N=y.pendingProps,O=!1,$=(y.flags&128)!==0,K;if((K=$)||(K=m!==null&&m.memoizedState===null?!1:(Si.current&2)!==0),K&&(O=!0,y.flags&=-129),K=(y.flags&32)!==0,y.flags&=-33,m===null){if(mn){if(O?_c(y):yc(y),mn){var ct=vi,xt;(xt=ct)&&(ct=ypt(ct,To),ct!==null?(y.memoizedState={dehydrated:ct,treeContext:fh!==null?{id:ha,overflow:da}:null,retryLane:536870912,hydrationErrors:null},xt=e(18,null,null,0),xt.stateNode=ct,xt.return=y,y.child=xt,vr=y,vi=null,xt=!0):xt=!1),xt||ot(y)}if(ct=y.memoizedState,ct!==null&&(ct=ct.dehydrated,ct!==null))return c3(ct)?y.lanes=32:y.lanes=536870912,null;aa(y)}return ct=N.children,N=N.fallback,O?(yc(y),O=y.mode,ct=K0({mode:"hidden",children:ct},O),N=ph(N,O,S,null),ct.return=y,N.return=y,ct.sibling=N,y.child=ct,O=y.child,O.memoizedState=kT(S),O.childLanes=TT(m,K,S),y.memoizedState=w3,N):(_c(y),MT(y,ct))}if(xt=m.memoizedState,xt!==null&&(ct=xt.dehydrated,ct!==null)){if($)y.flags&256?(_c(y),y.flags&=-257,y=ET(m,y,S)):y.memoizedState!==null?(yc(y),y.child=m.child,y.flags|=128,y=null):(yc(y),O=N.fallback,ct=y.mode,N=K0({mode:"visible",children:N.children},ct),O=ph(O,ct,S,null),O.flags|=2,N.return=y,O.return=y,N.sibling=O,y.child=N,dm(y,m.child,null,S),N=y.child,N.memoizedState=kT(S),N.childLanes=TT(m,K,S),y.memoizedState=w3,y=O);else if(_c(y),c3(ct))K=opt(ct).digest,N=Error(i(419)),N.stack="",N.digest=K,Z({value:N,source:null,stack:null}),y=ET(m,y,S);else if(Ni||Se(m,y,S,!1),K=(S&m.childLanes)!==0,Ni||K){if(K=Nn,K!==null&&(N=S&-S,N=(N&42)!==0?1:R(N),N=(N&(K.suspendedLanes|S))!==0?0:N,N!==0&&N!==xt.retryLane))throw xt.retryLane=N,wo(m,N),Jr(K,m,N),c$;a3(ct)||GT(),y=ET(m,y,S)}else a3(ct)?(y.flags|=192,y.child=m.child,y=null):(m=xt.treeContext,ms&&(vi=dpt(ct),vr=y,mn=!0,mh=null,To=!1,m!==null&&(_s[ys++]=ha,_s[ys++]=da,_s[ys++]=fh,ha=m.id,da=m.overflow,fh=y)),y=MT(y,N.children),y.flags|=4096);return y}return O?(yc(y),O=N.fallback,ct=y.mode,xt=m.child,$=xt.sibling,N=la(xt,{mode:"hidden",children:N.children}),N.subtreeFlags=xt.subtreeFlags&65011712,$!==null?O=la($,O):(O=ph(O,ct,S,null),O.flags|=2),O.return=y,N.return=y,N.sibling=O,y.child=N,N=O,O=y.child,ct=m.child.memoizedState,ct===null?ct=kT(S):(xt=ct.cachePool,xt!==null?($=ua?ti._currentValue:ti._currentValue2,xt=xt.parent!==$?{parent:$,pool:$}:xt):xt=Of(),ct={baseLanes:ct.baseLanes|S,cachePool:xt}),O.memoizedState=ct,O.childLanes=TT(m,K,S),y.memoizedState=w3,N):(_c(y),S=m.child,m=S.sibling,S=la(S,{mode:"visible",children:N.children}),S.return=y,S.sibling=null,m!==null&&(K=y.deletions,K===null?(y.deletions=[m],y.flags|=16):K.push(m)),y.child=S,y.memoizedState=null,S)}function MT(m,y){return y=K0({mode:"visible",children:y},m.mode),y.return=m,m.child=y}function K0(m,y){return m=e(22,m,null,y),m.lanes=0,m.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null},m}function ET(m,y,S){return dm(y,m.child,null,S),m=MT(y,y.pendingProps.children),m.flags|=2,y.memoizedState=null,m}function AF(m,y,S){m.lanes|=y;var N=m.alternate;N!==null&&(N.lanes|=y),Ot(m.return,y,S)}function CT(m,y,S,N,O){var $=m.memoizedState;$===null?m.memoizedState={isBackwards:y,rendering:null,renderingStartTime:0,last:N,tail:S,tailMode:O}:($.isBackwards=y,$.rendering=null,$.renderingStartTime=0,$.last=N,$.tail=S,$.tailMode=O)}function RF(m,y,S){var N=y.pendingProps,O=N.revealOrder,$=N.tail;if(Wi(m,y,N.children,S),N=Si.current,(N&2)!==0)N=N&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&&AF(m,S,y);else if(m.tag===19)AF(m,S,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}N&=1}switch(_(Si,N),O){case"forwards":for(S=y.child,O=null;S!==null;)m=S.alternate,m!==null&&W0(m)===null&&(O=S),S=S.sibling;S=O,S===null?(O=y.child,y.child=null):(O=S.sibling,S.sibling=null),CT(y,!1,O,S,$);break;case"backwards":for(S=null,O=y.child,y.child=null;O!==null;){if(m=O.alternate,m!==null&&W0(m)===null){y.child=O;break}m=O.sibling,O.sibling=S,S=O,O=m}CT(y,!0,S,null,$);break;case"together":CT(y,!1,null,null,void 0);break;default:y.memoizedState=null}return y.child}function ca(m,y,S){if(m!==null&&(y.dependencies=m.dependencies),Cc|=y.lanes,(S&y.childLanes)===0)if(m!==null){if(Se(m,y,S,!1),(S&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,S=la(m,m.pendingProps),y.child=S,S.return=y;m.sibling!==null;)m=m.sibling,S=S.sibling=la(m,m.pendingProps),S.return=y;S.sibling=null}return y.child}function IT(m,y){return(m.lanes&y)!==0?!0:(m=m.dependencies,!!(m!==null&&Kt(m)))}function Jlt(m,y,S){switch(y.tag){case 3:pt(y,y.stateNode.containerInfo),Mt(y,ti,m.memoizedState.cache),ut();break;case 27:case 5:wt(y);break;case 4:pt(y,y.stateNode.containerInfo);break;case 10:Mt(y,y.type,y.memoizedProps.value);break;case 13:var N=y.memoizedState;if(N!==null)return N.dehydrated!==null?(_c(y),y.flags|=128,null):(S&y.child.childLanes)!==0?NF(m,y,S):(_c(y),m=ca(m,y,S),m!==null?m.sibling:null);_c(y);break;case 19:var O=(m.flags&128)!==0;if(N=(S&y.childLanes)!==0,N||(Se(m,y,S,!1),N=(S&y.childLanes)!==0),O){if(N)return RF(m,y,S);y.flags|=128}if(O=y.memoizedState,O!==null&&(O.rendering=null,O.tail=null,O.lastEffect=null),_(Si,Si.current),N)break;return null;case 22:case 23:return y.lanes=0,TF(m,y,S);case 24:Mt(y,ti,m.memoizedState.cache)}return ca(m,y,S)}function OF(m,y,S){if(m!==null)if(m.memoizedProps!==y.pendingProps)Ni=!0;else{if(!IT(m,S)&&(y.flags&128)===0)return Ni=!1,Jlt(m,y,S);Ni=(m.flags&131072)!==0}else Ni=!1,mn&&(y.flags&1048576)!==0&&G(y,ux,y.index);switch(y.lanes=0,y.tag){case 16:t:{m=y.pendingProps;var N=y.elementType,O=N._init;if(N=O(N._payload),y.type=N,typeof N=="function")qT(N)?(m=ch(N,m),y.tag=1,y=CF(null,y,N,m,S)):(y.tag=0,y=PT(null,y,N,m,S));else{if(N!=null){if(O=N.$$typeof,O===e3){y.tag=11,y=wF(null,y,N,m,S);break t}else if(O===r3){y.tag=14,y=PF(null,y,N,m,S);break t}}throw y=u(N)||N,Error(i(306,y,""))}}return y;case 0:return PT(m,y,y.type,y.pendingProps,S);case 1:return N=y.type,O=ch(N,y.pendingProps),CF(m,y,N,O,S);case 3:t:{if(pt(y,y.stateNode.containerInfo),m===null)throw Error(i(387));var $=y.pendingProps;O=y.memoizedState,N=O.element,eh(m,y),oa(y,$,null,S);var K=y.memoizedState;if($=K.cache,Mt(y,ti,$),$!==O.cache&&Ce(y,[ti],S,!0),sa(),$=K.element,ms&&O.isDehydrated)if(O={element:$,isDehydrated:!1,cache:K.cache},y.updateQueue.baseState=O,y.memoizedState=O,y.flags&256){y=IF(m,y,$,S);break t}else if($!==N){N=tt(Error(i(424)),y),Z(N),y=IF(m,y,$,S);break t}else for(ms&&(vi=hpt(y.stateNode.containerInfo),vr=y,mn=!0,mh=null,To=!0),S=o$(y,null,$,S),y.child=S;S;)S.flags=S.flags&-3|4096,S=S.sibling;else{if(ut(),$===N){y=ca(m,y,S);break t}Wi(m,y,$,S)}y=y.child}return y;case 26:if(Hs)return Z0(m,y),m===null?(S=Vz(y.type,null,y.pendingProps,null))?y.memoizedState=S:mn||(y.stateNode=Cpt(y.type,y.pendingProps,kc.current,y)):y.memoizedState=Vz(y.type,m.memoizedProps,y.pendingProps,m.memoizedState),null;case 27:if(bi)return wt(y),m===null&&bi&&mn&&(N=y.stateNode=Kz(y.type,y.pendingProps,kc.current,qi.current,!1),vr=y,To=!0,vi=fpt(y.type,N,vi)),Wi(m,y,y.pendingProps.children,S),Z0(m,y),m===null&&(y.flags|=4194304),y.child;case 5:return m===null&&mn&&(Tpt(y.type,y.pendingProps,qi.current),(O=N=vi)&&(N=mpt(N,y.type,y.pendingProps,To),N!==null?(y.stateNode=N,vr=y,vi=ppt(N),To=!1,O=!0):O=!1),O||ot(y)),wt(y),O=y.type,$=y.pendingProps,K=m!==null?m.memoizedProps:null,N=$.children,sx(O,$)?N=null:K!==null&&sx(O,K)&&(y.flags|=32),y.memoizedState!==null&&(O=oh(m,y,mT,null,null,S),ua?dh._currentValue=O:dh._currentValue2=O),Z0(m,y),Wi(m,y,N,S),y.child;case 6:return m===null&&mn&&(Mpt(y.pendingProps,qi.current),(m=S=vi)&&(S=_pt(S,y.pendingProps,To),S!==null?(y.stateNode=S,vr=y,vi=null,m=!0):m=!1),m||ot(y)),null;case 13:return NF(m,y,S);case 4:return pt(y,y.stateNode.containerInfo),N=y.pendingProps,m===null?y.child=dm(y,null,N,S):Wi(m,y,N,S),y.child;case 11:return wF(m,y,y.type,y.pendingProps,S);case 7:return Wi(m,y,y.pendingProps,S),y.child;case 8:return Wi(m,y,y.pendingProps.children,S),y.child;case 12:return Wi(m,y,y.pendingProps.children,S),y.child;case 10:return N=y.pendingProps,Mt(y,y.type,N.value),Wi(m,y,N.children,S),y.child;case 9:return O=y.type._context,N=y.pendingProps.children,le(y),O=Jt(O),N=N(O),y.flags|=1,Wi(m,y,N,S),y.child;case 14:return PF(m,y,y.type,y.pendingProps,S);case 15:return kF(m,y,y.type,y.pendingProps,S);case 19:return RF(m,y,S);case 31:return N=y.pendingProps,S=y.mode,N={mode:N.mode,children:N.children},m===null?(S=K0(N,S),S.ref=y.ref,y.child=S,S.return=y,y=S):(S=la(m.child,N),S.ref=y.ref,y.child=S,S.return=y,y=S),y;case 22:return TF(m,y,S);case 24:return le(y),N=Jt(ti),m===null?(O=Jp(),O===null&&(O=Nn,$=Cr(),O.pooledCache=$,$.refCount++,$!==null&&(O.pooledCacheLanes|=S),O=$),y.memoizedState={parent:N,cache:O},th(y),Mt(y,ti,O)):((m.lanes&S)!==0&&(eh(m,y),oa(y,null,null,S),sa()),O=m.memoizedState,$=y.memoizedState,O.parent!==N?(O={parent:N,cache:N},y.memoizedState=O,y.lanes===0&&(y.memoizedState=y.updateQueue.baseState=O),Mt(y,ti,N)):(N=$.cache,Mt(y,ti,N),N!==O.cache&&Ce(y,[ti],S,!0))),Wi(m,y,y.pendingProps.children,S),y.child;case 29:throw y.pendingProps}throw Error(i(156,y.tag))}function Zr(m){m.flags|=4}function LF(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 NT(m,y,S,N){if(ar)for(S=y.child;S!==null;){if(S.tag===5||S.tag===6)o3(m,S.stateNode);else if(!(S.tag===4||bi&&S.tag===27)&&S.child!==null){S.child.return=S,S=S.child;continue}if(S===y)break;for(;S.sibling===null;){if(S.return===null||S.return===y)return;S=S.return}S.sibling.return=S.return,S=S.sibling}else if(Pc)for(var O=y.child;O!==null;){if(O.tag===5){var $=O.stateNode;S&&N&&($=jz($,O.type,O.memoizedProps)),o3(m,$)}else if(O.tag===6)$=O.stateNode,S&&N&&($=Bz($,O.memoizedProps)),o3(m,$);else if(O.tag!==4){if(O.tag===22&&O.memoizedState!==null)$=O.child,$!==null&&($.return=O),NT(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 FF(m,y,S,N){var O=!1;if(Pc)for(var $=y.child;$!==null;){if($.tag===5){var K=$.stateNode;S&&N&&(K=jz(K,$.type,$.memoizedProps)),$z(m,K)}else if($.tag===6)K=$.stateNode,S&&N&&(K=Bz(K,$.memoizedProps)),$z(m,K);else if($.tag!==4){if($.tag===22&&$.memoizedState!==null)O=$.child,O!==null&&(O.return=$),FF(m,$,!0,!0),O=!0;else if($.child!==null){$.child.return=$,$=$.child;continue}}if($===y)break;for(;$.sibling===null;){if($.return===null||$.return===y)return O;$=$.return}$.sibling.return=$.return,$=$.sibling}return O}function zF(m,y){if(Pc&&LF(m,y)){m=y.stateNode;var S=m.containerInfo,N=zz();FF(N,y,!1,!1),m.pendingChildren=N,Zr(y),spt(S,N)}}function AT(m,y,S,N){if(ar)m.memoizedProps!==N&&Zr(y);else if(Pc){var O=m.stateNode,$=m.memoizedProps;if((m=LF(m,y))||$!==N){var K=qi.current;$=rpt(O,S,$,N,!m,null),$===O?y.stateNode=O:(Az($,S,N,K)&&Zr(y),y.stateNode=$,m?NT($,y,!1,!1):Zr(y))}else y.stateNode=O}}function RT(m,y,S){if(Aut(y,S)){if(m.flags|=16777216,!Oz(y,S))if(cz())m.flags|=8192;else throw am=_x,x3}else m.flags&=-16777217}function $F(m,y){if(Npt(y)){if(m.flags|=16777216,!Zz(y))if(cz())m.flags|=8192;else throw am=_x,x3}else m.flags&=-16777217}function J0(m,y){y!==null&&(m.flags|=4),m.flags&16384&&(y=m.tag!==22?k():536870912,m.lanes|=y,_m|=y)}function Ay(m,y){if(!mn)switch(m.tailMode){case"hidden":y=m.tail;for(var S=null;y!==null;)y.alternate!==null&&(S=y),y=y.sibling;S===null?m.tail=null:S.sibling=null;break;case"collapsed":S=m.tail;for(var N=null;S!==null;)S.alternate!==null&&(N=S),S=S.sibling;N===null?y||m.tail===null?m.tail=null:m.tail.sibling=null:N.sibling=null}}function qn(m){var y=m.alternate!==null&&m.alternate.child===m.child,S=0,N=0;if(y)for(var O=m.child;O!==null;)S|=O.lanes|O.childLanes,N|=O.subtreeFlags&65011712,N|=O.flags&65011712,O.return=m,O=O.sibling;else for(O=m.child;O!==null;)S|=O.lanes|O.childLanes,N|=O.subtreeFlags,N|=O.flags,O.return=m,O=O.sibling;return m.subtreeFlags|=N,m.childLanes=S,y}function Qlt(m,y,S){var N=y.pendingProps;switch(nt(y),y.tag){case 31:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return qn(y),null;case 1:return qn(y),null;case 3:return S=y.stateNode,N=null,m!==null&&(N=m.memoizedState.cache),y.memoizedState.cache!==N&&(y.flags|=2048),Ft(ti),ht(),S.pendingContext&&(S.context=S.pendingContext,S.pendingContext=null),(m===null||m.child===null)&&(rt(y)?Zr(y):m===null||m.memoizedState.isDehydrated&&(y.flags&256)===0||(y.flags|=1024,yt())),zF(m,y),qn(y),null;case 26:if(Hs){S=y.type;var O=y.memoizedState;return m===null?(Zr(y),O!==null?(qn(y),$F(y,O)):(qn(y),RT(y,S,N))):O?O!==m.memoizedState?(Zr(y),qn(y),$F(y,O)):(qn(y),y.flags&=-16777217):(ar?m.memoizedProps!==N&&Zr(y):AT(m,y,S,N),qn(y),RT(y,S,N)),null}case 27:if(bi){if(Et(y),S=kc.current,O=y.type,m!==null&&y.stateNode!=null)ar?m.memoizedProps!==N&&Zr(y):AT(m,y,O,N);else{if(!N){if(y.stateNode===null)throw Error(i(166));return qn(y),null}m=qi.current,rt(y)?X(y,m):(m=Kz(O,N,S,m,!0),y.stateNode=m,Zr(y))}return qn(y),null}case 5:if(Et(y),S=y.type,m!==null&&y.stateNode!=null)AT(m,y,S,N);else{if(!N){if(y.stateNode===null)throw Error(i(166));return qn(y),null}m=qi.current,rt(y)?X(y,m):(O=Put(S,N,kc.current,m,y),NT(O,y,!1,!1),y.stateNode=O,Az(O,S,N,m)&&Zr(y))}return qn(y),RT(y,y.type,y.pendingProps),null;case 6:if(m&&y.stateNode!=null)S=m.memoizedProps,ar?S!==N&&Zr(y):Pc&&(S!==N?(y.stateNode=Rz(N,kc.current,qi.current,y),Zr(y)):y.stateNode=m.stateNode);else{if(typeof N!="string"&&y.stateNode===null)throw Error(i(166));if(m=kc.current,S=qi.current,rt(y)){if(!ms)throw Error(i(176));if(m=y.stateNode,S=y.memoizedProps,N=null,O=vr,O!==null)switch(O.tag){case 27:case 5:N=O.memoizedProps}xpt(m,S,y,N)||ot(y)}else y.stateNode=Rz(N,m,S,y)}return qn(y),null;case 13:if(N=y.memoizedState,m===null||m.memoizedState!==null&&m.memoizedState.dehydrated!==null){if(O=rt(y),N!==null&&N.dehydrated!==null){if(m===null){if(!O)throw Error(i(318));if(!ms)throw Error(i(344));if(O=y.memoizedState,O=O!==null?O.dehydrated:null,!O)throw Error(i(317));bpt(O,y)}else ut(),(y.flags&128)===0&&(y.memoizedState=null),y.flags|=4;qn(y),O=!1}else O=yt(),m!==null&&m.memoizedState!==null&&(m.memoizedState.hydrationErrors=O),O=!0;if(!O)return y.flags&256?(aa(y),y):(aa(y),null)}if(aa(y),(y.flags&128)!==0)return y.lanes=S,y;if(S=N!==null,m=m!==null&&m.memoizedState!==null,S){N=y.child,O=null,N.alternate!==null&&N.alternate.memoizedState!==null&&N.alternate.memoizedState.cachePool!==null&&(O=N.alternate.memoizedState.cachePool.pool);var $=null;N.memoizedState!==null&&N.memoizedState.cachePool!==null&&($=N.memoizedState.cachePool.pool),$!==O&&(N.flags|=2048)}return S!==m&&S&&(y.child.flags|=8192),J0(y,y.updateQueue),qn(y),null;case 4:return ht(),zF(m,y),m===null&&Eut(y.stateNode.containerInfo),qn(y),null;case 10:return Ft(y.type),qn(y),null;case 19:if(d(Si),O=y.memoizedState,O===null)return qn(y),null;if(N=(y.flags&128)!==0,$=O.rendering,$===null)if(N)Ay(O,!1);else{if(ei!==0||m!==null&&(m.flags&128)!==0)for(m=y.child;m!==null;){if($=W0(m),$!==null){for(y.flags|=128,Ay(O,!1),m=$.updateQueue,y.updateQueue=m,J0(y,m),y.subtreeFlags=0,m=S,S=y.child;S!==null;)Sz(S,m),S=S.sibling;return _(Si,Si.current&1|2),y.child}m=m.sibling}O.tail!==null&&Ws()>qy&&(y.flags|=128,N=!0,Ay(O,!1),y.lanes=4194304)}else{if(!N)if(m=W0($),m!==null){if(y.flags|=128,N=!0,m=m.updateQueue,y.updateQueue=m,J0(y,m),Ay(O,!0),O.tail===null&&O.tailMode==="hidden"&&!$.alternate&&!mn)return qn(y),null}else 2*Ws()-O.renderingStartTime>qy&&S!==536870912&&(y.flags|=128,N=!0,Ay(O,!1),y.lanes=4194304);O.isBackwards?($.sibling=y.child,y.child=$):(m=O.last,m!==null?m.sibling=$:y.child=$,O.last=$)}return O.tail!==null?(y=O.tail,O.rendering=y,O.tail=y.sibling,O.renderingStartTime=Ws(),y.sibling=null,m=Si.current,_(Si,N?m&1|2:m&1),y):(qn(y),null);case 22:case 23:return aa(y),rh(),N=y.memoizedState!==null,m!==null?m.memoizedState!==null!==N&&(y.flags|=8192):N&&(y.flags|=8192),N?(S&536870912)!==0&&(y.flags&128)===0&&(qn(y),y.subtreeFlags&6&&(y.flags|=8192)):qn(y),S=y.updateQueue,S!==null&&J0(y,S.retryQueue),S=null,m!==null&&m.memoizedState!==null&&m.memoizedState.cachePool!==null&&(S=m.memoizedState.cachePool.pool),N=null,y.memoizedState!==null&&y.memoizedState.cachePool!==null&&(N=y.memoizedState.cachePool.pool),N!==S&&(y.flags|=2048),m!==null&&d(yh),null;case 24:return S=null,m!==null&&(S=m.memoizedState.cache),y.memoizedState.cache!==S&&(y.flags|=2048),Ft(ti),qn(y),null;case 25:return null;case 30:return null}throw Error(i(156,y.tag))}function tut(m,y){switch(nt(y),y.tag){case 1:return m=y.flags,m&65536?(y.flags=m&-65537|128,y):null;case 3:return Ft(ti),ht(),m=y.flags,(m&65536)!==0&&(m&128)===0?(y.flags=m&-65537|128,y):null;case 26:case 27:case 5:return Et(y),null;case 13:if(aa(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(Si),null;case 4:return ht(),null;case 10:return Ft(y.type),null;case 22:case 23:return aa(y),rh(),m!==null&&d(yh),m=y.flags,m&65536?(y.flags=m&-65537|128,y):null;case 24:return Ft(ti),null;case 25:return null;default:return null}}function DF(m,y){switch(nt(y),y.tag){case 3:Ft(ti),ht();break;case 26:case 27:case 5:Et(y);break;case 4:ht();break;case 13:aa(y);break;case 19:d(Si);break;case 10:Ft(y.type);break;case 22:case 23:aa(y),rh(),m!==null&&d(yh);break;case 24:Ft(ti)}}function Ry(m,y){try{var S=y.updateQueue,N=S!==null?S.lastEffect:null;if(N!==null){var O=N.next;S=O;do{if((S.tag&m)===m){N=void 0;var $=S.create,K=S.inst;N=$(),K.destroy=N}S=S.next}while(S!==O)}}catch(ct){gn(y,y.return,ct)}}function gc(m,y,S){try{var N=y.updateQueue,O=N!==null?N.lastEffect:null;if(O!==null){var $=O.next;N=$;do{if((N.tag&m)===m){var K=N.inst,ct=K.destroy;if(ct!==void 0){K.destroy=void 0,O=y;var xt=S,It=ct;try{It()}catch($t){gn(O,xt,$t)}}}N=N.next}while(N!==$)}}catch($t){gn(y,y.return,$t)}}function jF(m){var y=m.updateQueue;if(y!==null){var S=m.stateNode;try{Bf(y,S)}catch(N){gn(m,m.return,N)}}}function BF(m,y,S){S.props=ch(m.type,m.memoizedProps),S.state=m.memoizedState;try{S.componentWillUnmount()}catch(N){gn(m,y,N)}}function Oy(m,y){try{var S=m.ref;if(S!==null){switch(m.tag){case 26:case 27:case 5:var N=$y(m.stateNode);break;case 30:N=m.stateNode;break;default:N=m.stateNode}typeof S=="function"?m.refCleanup=S(N):S.current=N}}catch(O){gn(m,y,O)}}function Po(m,y){var S=m.ref,N=m.refCleanup;if(S!==null)if(typeof N=="function")try{N()}catch(O){gn(m,y,O)}finally{m.refCleanup=null,m=m.alternate,m!=null&&(m.refCleanup=null)}else if(typeof S=="function")try{S(null)}catch(O){gn(m,y,O)}else S.current=null}function YF(m){var y=m.type,S=m.memoizedProps,N=m.stateNode;try{Hut(N,y,S,m)}catch(O){gn(m,m.return,O)}}function OT(m,y,S){try{Wut(m.stateNode,m.type,S,y,m)}catch(N){gn(m,m.return,N)}}function XF(m){return m.tag===5||m.tag===3||(Hs?m.tag===26:!1)||(bi?m.tag===27&&Jf(m.type):!1)||m.tag===4}function LT(m){t:for(;;){for(;m.sibling===null;){if(m.return===null||XF(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(bi&&m.tag===27&&Jf(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 FT(m,y,S){var N=m.tag;if(N===5||N===6)m=m.stateNode,y?Zut(S,m,y):Vut(S,m);else if(N!==4&&(bi&&N===27&&Jf(m.type)&&(S=m.stateNode,y=null),m=m.child,m!==null))for(FT(m,y,S),m=m.sibling;m!==null;)FT(m,y,S),m=m.sibling}function Q0(m,y,S){var N=m.tag;if(N===5||N===6)m=m.stateNode,y?qut(S,m,y):Uut(S,m);else if(N!==4&&(bi&&N===27&&Jf(m.type)&&(S=m.stateNode),m=m.child,m!==null))for(Q0(m,y,S),m=m.sibling;m!==null;)Q0(m,y,S),m=m.sibling}function UF(m,y,S){m=m.containerInfo;try{Dz(m,S)}catch(N){gn(y,y.return,N)}}function VF(m){var y=m.stateNode,S=m.memoizedProps;try{Rpt(m.type,S,y,m)}catch(N){gn(m,m.return,N)}}function eut(m,y){for(Sut(m.containerInfo),Ai=y;Ai!==null;)if(m=Ai,y=m.child,(m.subtreeFlags&1024)!==0&&y!==null)y.return=m,Ai=y;else for(;Ai!==null;){m=Ai;var S=m.alternate;switch(y=m.flags,m.tag){case 0:break;case 11:case 15:break;case 1:if((y&1024)!==0&&S!==null){y=void 0;var N=m,O=S.memoizedProps;S=S.memoizedState;var $=N.stateNode;try{var K=ch(N.type,O,N.elementType===N.type);y=$.getSnapshotBeforeUpdate(K,S),$.__reactInternalSnapshotBeforeUpdate=y}catch(ct){gn(N,N.return,ct)}}break;case 3:(y&1024)!==0&&ar&&ipt(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,Ai=y;break}Ai=m.return}}function GF(m,y,S){var N=S.flags;switch(S.tag){case 0:case 11:case 15:xc(m,S),N&4&&Ry(5,S);break;case 1:if(xc(m,S),N&4)if(m=S.stateNode,y===null)try{m.componentDidMount()}catch(K){gn(S,S.return,K)}else{var O=ch(S.type,y.memoizedProps);y=y.memoizedState;try{m.componentDidUpdate(O,y,m.__reactInternalSnapshotBeforeUpdate)}catch(K){gn(S,S.return,K)}}N&64&&jF(S),N&512&&Oy(S,S.return);break;case 3:if(xc(m,S),N&64&&(m=S.updateQueue,m!==null)){if(y=null,S.child!==null)switch(S.child.tag){case 27:case 5:y=$y(S.child.stateNode);break;case 1:y=S.child.stateNode}try{Bf(m,y)}catch(K){gn(S,S.return,K)}}break;case 27:bi&&y===null&&N&4&&VF(S);case 26:case 5:xc(m,S),y===null&&N&4&&YF(S),N&512&&Oy(S,S.return);break;case 12:xc(m,S);break;case 13:xc(m,S),N&4&&WF(m,S),N&64&&(m=S.memoizedState,m!==null&&(m=m.dehydrated,m!==null&&(S=cut.bind(null,S),apt(m,S))));break;case 22:if(N=S.memoizedState!==null||ma,!N){y=y!==null&&y.memoizedState!==null||ui,O=ma;var $=ui;ma=N,(ui=y)&&!$?bc(m,S,(S.subtreeFlags&8772)!==0):xc(m,S),ma=O,ui=$}break;case 30:break;default:xc(m,S)}}function HF(m){var y=m.alternate;y!==null&&(m.alternate=null,HF(y)),m.child=null,m.deletions=null,m.sibling=null,m.tag===5&&(y=m.stateNode,y!==null&&Nut(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 Gs(m,y,S){for(S=S.child;S!==null;)zT(m,y,S),S=S.sibling}function zT(m,y,S){if(es&&typeof es.onCommitFiberUnmount=="function")try{es.onCommitFiberUnmount(By,S)}catch{}switch(S.tag){case 26:if(Hs){ui||Po(S,y),Gs(m,y,S),S.memoizedState?Hz(S.memoizedState):S.stateNode&&qz(S.stateNode);break}case 27:if(bi){ui||Po(S,y);var N=fi,O=Ar;Jf(S.type)&&(fi=S.stateNode,Ar=!1),Gs(m,y,S),Jz(S.stateNode),fi=N,Ar=O;break}case 5:ui||Po(S,y);case 6:if(ar){if(N=fi,O=Ar,fi=null,Gs(m,y,S),fi=N,Ar=O,fi!==null)if(Ar)try{Jut(fi,S.stateNode)}catch($){gn(S,y,$)}else try{Kut(fi,S.stateNode)}catch($){gn(S,y,$)}}else Gs(m,y,S);break;case 18:ar&&fi!==null&&(Ar?kpt(fi,S.stateNode):Ppt(fi,S.stateNode));break;case 4:ar?(N=fi,O=Ar,fi=S.stateNode.containerInfo,Ar=!0,Gs(m,y,S),fi=N,Ar=O):(Pc&&UF(S.stateNode,S,zz()),Gs(m,y,S));break;case 0:case 11:case 14:case 15:ui||gc(2,S,y),ui||gc(4,S,y),Gs(m,y,S);break;case 1:ui||(Po(S,y),N=S.stateNode,typeof N.componentWillUnmount=="function"&&BF(S,y,N)),Gs(m,y,S);break;case 21:Gs(m,y,S);break;case 22:ui=(N=ui)||S.memoizedState!==null,Gs(m,y,S),ui=N;break;default:Gs(m,y,S)}}function WF(m,y){if(ms&&y.memoizedState===null&&(m=y.alternate,m!==null&&(m=m.memoizedState,m!==null&&(m=m.dehydrated,m!==null))))try{wpt(m)}catch(S){gn(y,y.return,S)}}function nut(m){switch(m.tag){case 13:case 19:var y=m.stateNode;return y===null&&(y=m.stateNode=new l$),y;case 22:return m=m.stateNode,y=m._retryCache,y===null&&(y=m._retryCache=new l$),y;default:throw Error(i(435,m.tag))}}function $T(m,y){var S=nut(m);y.forEach(function(N){var O=lut.bind(null,m,N);S.has(N)||(S.add(N),N.then(O,O))})}function br(m,y){var S=y.deletions;if(S!==null)for(var N=0;N<S.length;N++){var O=S[N],$=m,K=y;if(ar){var ct=K;t:for(;ct!==null;){switch(ct.tag){case 27:if(bi){if(Jf(ct.type)){fi=ct.stateNode,Ar=!1;break t}break}case 5:fi=ct.stateNode,Ar=!1;break t;case 3:case 4:fi=ct.stateNode.containerInfo,Ar=!0;break t}ct=ct.return}if(fi===null)throw Error(i(160));zT($,K,O),fi=null,Ar=!1}else zT($,K,O);$=O.alternate,$!==null&&($.return=null),O.return=null}if(y.subtreeFlags&13878)for(y=y.child;y!==null;)qF(y,m),y=y.sibling}function qF(m,y){var S=m.alternate,N=m.flags;switch(m.tag){case 0:case 11:case 14:case 15:br(y,m),Nr(m),N&4&&(gc(3,m,m.return),Ry(3,m),gc(5,m,m.return));break;case 1:br(y,m),Nr(m),N&512&&(ui||S===null||Po(S,S.return)),N&64&&ma&&(m=m.updateQueue,m!==null&&(N=m.callbacks,N!==null&&(S=m.shared.hiddenCallbacks,m.shared.hiddenCallbacks=S===null?N:S.concat(N))));break;case 26:if(Hs){var O=qs;if(br(y,m),Nr(m),N&512&&(ui||S===null||Po(S,S.return)),N&4){N=S!==null?S.memoizedState:null;var $=m.memoizedState;S===null?$===null?m.stateNode===null?m.stateNode=Ept(O,m.type,m.memoizedProps,m):Wz(O,m.type,m.stateNode):m.stateNode=Gz(O,$,m.memoizedProps):N!==$?(N===null?S.stateNode!==null&&qz(S.stateNode):Hz(N),$===null?Wz(O,m.type,m.stateNode):Gz(O,$,m.memoizedProps)):$===null&&m.stateNode!==null&&OT(m,m.memoizedProps,S.memoizedProps)}break}case 27:if(bi){br(y,m),Nr(m),N&512&&(ui||S===null||Po(S,S.return)),S!==null&&N&4&&OT(m,m.memoizedProps,S.memoizedProps);break}case 5:if(br(y,m),Nr(m),N&512&&(ui||S===null||Po(S,S.return)),ar){if(m.flags&32){O=m.stateNode;try{Fz(O)}catch($t){gn(m,m.return,$t)}}N&4&&m.stateNode!=null&&(O=m.memoizedProps,OT(m,O,S!==null?S.memoizedProps:O)),N&1024&&(P3=!0)}break;case 6:if(br(y,m),Nr(m),N&4&&ar){if(m.stateNode===null)throw Error(i(162));N=m.memoizedProps,S=S!==null?S.memoizedProps:N,O=m.stateNode;try{Gut(O,S,N)}catch($t){gn(m,m.return,$t)}}break;case 3:if(Hs?(Ipt(),O=qs,qs=l3(y.containerInfo),br(y,m),qs=O):br(y,m),Nr(m),N&4){if(ar&&ms&&S!==null&&S.memoizedState.isDehydrated)try{Spt(y.containerInfo)}catch($t){gn(m,m.return,$t)}if(Pc){N=y.containerInfo,S=y.pendingChildren;try{Dz(N,S)}catch($t){gn(m,m.return,$t)}}}P3&&(P3=!1,ZF(m));break;case 4:Hs?(S=qs,qs=l3(m.stateNode.containerInfo),br(y,m),Nr(m),qs=S):(br(y,m),Nr(m)),N&4&&Pc&&UF(m.stateNode,m,m.stateNode.pendingChildren);break;case 12:br(y,m),Nr(m);break;case 13:br(y,m),Nr(m),m.child.flags&8192&&m.memoizedState!==null!=(S!==null&&S.memoizedState!==null)&&(E3=Ws()),N&4&&(N=m.updateQueue,N!==null&&(m.updateQueue=null,$T(m,N)));break;case 22:O=m.memoizedState!==null;var K=S!==null&&S.memoizedState!==null,ct=ma,xt=ui;if(ma=ct||O,ui=xt||K,br(y,m),ui=xt,ma=ct,Nr(m),N&8192&&(y=m.stateNode,y._visibility=O?y._visibility&-2:y._visibility|1,O&&(S===null||K||ma||ui||lh(m)),ar)){t:if(S=null,ar)for(y=m;;){if(y.tag===5||Hs&&y.tag===26){if(S===null){K=S=y;try{$=K.stateNode,O?Qut($):ept(K.stateNode,K.memoizedProps)}catch($t){gn(K,K.return,$t)}}}else if(y.tag===6){if(S===null){K=y;try{var It=K.stateNode;O?tpt(It):npt(It,K.memoizedProps)}catch($t){gn(K,K.return,$t)}}}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;S===y&&(S=null),y=y.return}S===y&&(S=null),y.sibling.return=y.return,y=y.sibling}}N&4&&(N=m.updateQueue,N!==null&&(S=N.retryQueue,S!==null&&(N.retryQueue=null,$T(m,S))));break;case 19:br(y,m),Nr(m),N&4&&(N=m.updateQueue,N!==null&&(m.updateQueue=null,$T(m,N)));break;case 30:break;case 21:break;default:br(y,m),Nr(m)}}function Nr(m){var y=m.flags;if(y&2){try{if(ar){for(var S,N=m.return;N!==null;){if(XF(N)){S=N;break}N=N.return}if(S==null)throw Error(i(160));switch(S.tag){case 27:if(bi){var O=S.stateNode,$=LT(m);Q0(m,$,O);break}case 5:var K=S.stateNode;S.flags&32&&(Fz(K),S.flags&=-33);var ct=LT(m);Q0(m,ct,K);break;case 3:case 4:var xt=S.stateNode.containerInfo,It=LT(m);FT(m,It,xt);break;default:throw Error(i(161))}}}catch($t){gn(m,m.return,$t)}m.flags&=-3}y&4096&&(m.flags&=-4097)}function ZF(m){if(m.subtreeFlags&1024)for(m=m.child;m!==null;){var y=m;ZF(y),y.tag===5&&y.flags&1024&&Lut(y.stateNode),m=m.sibling}}function xc(m,y){if(y.subtreeFlags&8772)for(y=y.child;y!==null;)GF(m,y.alternate,y),y=y.sibling}function lh(m){for(m=m.child;m!==null;){var y=m;switch(y.tag){case 0:case 11:case 14:case 15:gc(4,y,y.return),lh(y);break;case 1:Po(y,y.return);var S=y.stateNode;typeof S.componentWillUnmount=="function"&&BF(y,y.return,S),lh(y);break;case 27:bi&&Jz(y.stateNode);case 26:case 5:Po(y,y.return),lh(y);break;case 22:y.memoizedState===null&&lh(y);break;case 30:lh(y);break;default:lh(y)}m=m.sibling}}function bc(m,y,S){for(S=S&&(y.subtreeFlags&8772)!==0,y=y.child;y!==null;){var N=y.alternate,O=m,$=y,K=$.flags;switch($.tag){case 0:case 11:case 15:bc(O,$,S),Ry(4,$);break;case 1:if(bc(O,$,S),N=$,O=N.stateNode,typeof O.componentDidMount=="function")try{O.componentDidMount()}catch(It){gn(N,N.return,It)}if(N=$,O=N.updateQueue,O!==null){var ct=N.stateNode;try{var xt=O.shared.hiddenCallbacks;if(xt!==null)for(O.shared.hiddenCallbacks=null,O=0;O<xt.length;O++)jf(xt[O],ct)}catch(It){gn(N,N.return,It)}}S&&K&64&&jF($),Oy($,$.return);break;case 27:bi&&VF($);case 26:case 5:bc(O,$,S),S&&N===null&&K&4&&YF($),Oy($,$.return);break;case 12:bc(O,$,S);break;case 13:bc(O,$,S),S&&K&4&&WF(O,$);break;case 22:$.memoizedState===null&&bc(O,$,S),Oy($,$.return);break;case 30:break;default:bc(O,$,S)}y=y.sibling}}function DT(m,y){var S=null;m!==null&&m.memoizedState!==null&&m.memoizedState.cachePool!==null&&(S=m.memoizedState.cachePool.pool),m=null,y.memoizedState!==null&&y.memoizedState.cachePool!==null&&(m=y.memoizedState.cachePool.pool),m!==S&&(m!=null&&m.refCount++,S!=null&&Us(S))}function jT(m,y){m=null,y.alternate!==null&&(m=y.alternate.memoizedState.cache),y=y.memoizedState.cache,y!==m&&(y.refCount++,m!=null&&Us(m))}function ko(m,y,S,N){if(y.subtreeFlags&10256)for(y=y.child;y!==null;)KF(m,y,S,N),y=y.sibling}function KF(m,y,S,N){var O=y.flags;switch(y.tag){case 0:case 11:case 15:ko(m,y,S,N),O&2048&&Ry(9,y);break;case 1:ko(m,y,S,N);break;case 3:ko(m,y,S,N),O&2048&&(m=null,y.alternate!==null&&(m=y.alternate.memoizedState.cache),y=y.memoizedState.cache,y!==m&&(y.refCount++,m!=null&&Us(m)));break;case 12:if(O&2048){ko(m,y,S,N),m=y.stateNode;try{var $=y.memoizedProps,K=$.id,ct=$.onPostCommit;typeof ct=="function"&&ct(K,y.alternate===null?"mount":"update",m.passiveEffectDuration,-0)}catch(xt){gn(y,y.return,xt)}}else ko(m,y,S,N);break;case 13:ko(m,y,S,N);break;case 23:break;case 22:$=y.stateNode,K=y.alternate,y.memoizedState!==null?$._visibility&2?ko(m,y,S,N):Ly(m,y):$._visibility&2?ko(m,y,S,N):($._visibility|=2,Gf(m,y,S,N,(y.subtreeFlags&10256)!==0)),O&2048&&DT(K,y);break;case 24:ko(m,y,S,N),O&2048&&jT(y.alternate,y);break;default:ko(m,y,S,N)}}function Gf(m,y,S,N,O){for(O=O&&(y.subtreeFlags&10256)!==0,y=y.child;y!==null;){var $=m,K=y,ct=S,xt=N,It=K.flags;switch(K.tag){case 0:case 11:case 15:Gf($,K,ct,xt,O),Ry(8,K);break;case 23:break;case 22:var $t=K.stateNode;K.memoizedState!==null?$t._visibility&2?Gf($,K,ct,xt,O):Ly($,K):($t._visibility|=2,Gf($,K,ct,xt,O)),O&&It&2048&&DT(K.alternate,K);break;case 24:Gf($,K,ct,xt,O),O&&It&2048&&jT(K.alternate,K);break;default:Gf($,K,ct,xt,O)}y=y.sibling}}function Ly(m,y){if(y.subtreeFlags&10256)for(y=y.child;y!==null;){var S=m,N=y,O=N.flags;switch(N.tag){case 22:Ly(S,N),O&2048&&DT(N.alternate,N);break;case 24:Ly(S,N),O&2048&&jT(N.alternate,N);break;default:Ly(S,N)}y=y.sibling}}function uh(m){if(m.subtreeFlags&fm)for(m=m.child;m!==null;)JF(m),m=m.sibling}function JF(m){switch(m.tag){case 26:uh(m),m.flags&fm&&(m.memoizedState!==null?Apt(qs,m.memoizedState,m.memoizedProps):Lz(m.type,m.memoizedProps));break;case 5:uh(m),m.flags&fm&&Lz(m.type,m.memoizedProps);break;case 3:case 4:if(Hs){var y=qs;qs=l3(m.stateNode.containerInfo),uh(m),qs=y}else uh(m);break;case 22:m.memoizedState===null&&(y=m.alternate,y!==null&&y.memoizedState!==null?(y=fm,fm=16777216,uh(m),fm=y):uh(m));break;default:uh(m)}}function QF(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 Fy(m){var y=m.deletions;if((m.flags&16)!==0){if(y!==null)for(var S=0;S<y.length;S++){var N=y[S];Ai=N,ez(N,m)}QF(m)}if(m.subtreeFlags&10256)for(m=m.child;m!==null;)tz(m),m=m.sibling}function tz(m){switch(m.tag){case 0:case 11:case 15:Fy(m),m.flags&2048&&gc(9,m,m.return);break;case 3:Fy(m);break;case 12:Fy(m);break;case 22:var y=m.stateNode;m.memoizedState!==null&&y._visibility&2&&(m.return===null||m.return.tag!==13)?(y._visibility&=-3,tx(m)):Fy(m);break;default:Fy(m)}}function tx(m){var y=m.deletions;if((m.flags&16)!==0){if(y!==null)for(var S=0;S<y.length;S++){var N=y[S];Ai=N,ez(N,m)}QF(m)}for(m=m.child;m!==null;){switch(y=m,y.tag){case 0:case 11:case 15:gc(8,y,y.return),tx(y);break;case 22:S=y.stateNode,S._visibility&2&&(S._visibility&=-3,tx(y));break;default:tx(y)}m=m.sibling}}function ez(m,y){for(;Ai!==null;){var S=Ai;switch(S.tag){case 0:case 11:case 15:gc(8,S,y);break;case 23:case 22:if(S.memoizedState!==null&&S.memoizedState.cachePool!==null){var N=S.memoizedState.cachePool.pool;N!=null&&N.refCount++}break;case 24:Us(S.memoizedState.cache)}if(N=S.child,N!==null)N.return=S,Ai=N;else t:for(S=m;Ai!==null;){N=Ai;var O=N.sibling,$=N.return;if(HF(N),N===S){Ai=null;break t}if(O!==null){O.return=$,Ai=O;break t}Ai=$}}}function BT(m){var y=Mut(m);if(y!=null){if(typeof y.memoizedProps["data-testname"]!="string")throw Error(i(364));return y}if(m=$ut(m),m===null)throw Error(i(362));return m.stateNode.current}function YT(m,y){var S=m.tag;switch(y.$$typeof){case vx:if(m.type===y.value)return!0;break;case Sx:t:{for(y=y.value,m=[m,0],S=0;S<m.length;){var N=m[S++],O=N.tag,$=m[S++],K=y[$];if(O!==5&&O!==26&&O!==27||!jy(N)){for(;K!=null&&YT(N,K);)$++,K=y[$];if($===y.length){y=!0;break t}else for(N=N.child;N!==null;)m.push(N,$),N=N.sibling}}y=!1}return y;case wx:if((S===5||S===26||S===27)&&But(m.stateNode,y.value))return!0;break;case kx:if((S===5||S===6||S===26||S===27)&&(m=jut(m),m!==null&&0<=m.indexOf(y.value)))return!0;break;case Px:if((S===5||S===26||S===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 XT(m){switch(m.$$typeof){case vx:return"<"+(u(m.value)||"Unknown")+">";case Sx:return":has("+(XT(m)||"")+")";case wx:return'[role="'+m.value+'"]';case kx:return'"'+m.value+'"';case Px:return'[data-testname="'+m.value+'"]';default:throw Error(i(365))}}function nz(m,y){var S=[];m=[m,0];for(var N=0;N<m.length;){var O=m[N++],$=O.tag,K=m[N++],ct=y[K];if($!==5&&$!==26&&$!==27||!jy(O)){for(;ct!=null&&YT(O,ct);)K++,ct=y[K];if(K===y.length)S.push(O);else for(O=O.child;O!==null;)m.push(O,K),O=O.sibling}}return S}function UT(m,y){if(!Dy)throw Error(i(363));m=BT(m),m=nz(m,y),y=[],m=Array.from(m);for(var S=0;S<m.length;){var N=m[S++],O=N.tag;if(O===5||O===26||O===27)jy(N)||y.push(N.stateNode);else for(N=N.child;N!==null;)m.push(N),N=N.sibling}return y}function Kr(){if((Je&2)!==0&&tn!==0)return tn&-tn;if(_e.T!==null){var m=sm;return m!==0?m:Kp()}return Cut()}function iz(){bs===0&&(bs=(tn&536870912)===0||mn?T():536870912);var m=xs.current;return m!==null&&(m.flags|=32),bs}function Jr(m,y,S){(m===Nn&&(xn===2||xn===9)||m.cancelPendingCommit!==null)&&(Hf(m,0),vc(m,tn,bs,!1)),M(m,S),((Je&2)===0||m!==Nn)&&(m===Nn&&((Je&2)===0&&(xh|=S),ei===4&&vc(m,tn,bs,!1)),Ir(m))}function rz(m,y,S){if((Je&6)!==0)throw Error(i(327));var N=!S&&(y&124)===0&&(y&m.expiredLanes)===0||P(m,y),O=N?sut(m,y):HT(m,y,!0),$=N;do{if(O===0){mm&&!N&&vc(m,y,0,!1);break}else{if(S=m.current.alternate,$&&!iut(S)){O=HT(m,y,!1),$=!1;continue}if(O===2){if($=y,m.errorRecoveryDisabledLanes&$)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=Wy;var xt=ms&&ct.current.memoizedState.isDehydrated;if(xt&&(Hf(ct,K).flags|=256),K=HT(ct,K,!1),K!==2){if(k3&&!xt){ct.errorRecoveryDisabledLanes|=$,xh|=$,O=4;break t}$=Rr,Rr=O,$!==null&&(Rr===null?Rr=$:Rr.push.apply(Rr,$))}O=K}if($=!1,O!==2)continue}}if(O===1){Hf(m,0),vc(m,y,0,!0);break}t:{switch(N=m,$=O,$){case 0:case 1:throw Error(i(345));case 4:if((y&4194048)!==y)break;case 6:vc(N,y,bs,!Ec);break t;case 2:Rr=null;break;case 3:case 5:break;default:throw Error(i(329))}if((y&62914560)===y&&(O=E3+300-Ws(),10<O)){if(vc(N,y,bs,!Ec),v(N,0,!0)!==0)break t;N.timeoutHandle=kut(sz.bind(null,N,S,Rr,Tx,M3,y,bs,xh,_m,Ec,$,2,-0,0),O);break t}sz(N,S,Rr,Tx,M3,y,bs,xh,_m,Ec,$,0,-0,0)}}break}while(!0);Ir(m)}function sz(m,y,S,N,O,$,K,ct,xt,It,$t,Xt,Wt,Le){if(m.timeoutHandle=hh,Xt=y.subtreeFlags,(Xt&8192||(Xt&16785408)===16785408)&&(Rut(),JF(y),Xt=Out(),Xt!==null)){m.cancelPendingCommit=Xt(fz.bind(null,m,y,$,S,N,O,K,ct,xt,$t,1,Wt,Le)),vc(m,$,K,!It);return}fz(m,y,$,S,N,O,K,ct,xt)}function iut(m){for(var y=m;;){var S=y.tag;if((S===0||S===11||S===15)&&y.flags&16384&&(S=y.updateQueue,S!==null&&(S=S.stores,S!==null)))for(var N=0;N<S.length;N++){var O=S[N],$=O.getSnapshot;O=O.value;try{if(!ns($(),O))return!1}catch{return!1}}if(S=y.child,y.subtreeFlags&16384&&S!==null)S.return=y,y=S;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 vc(m,y,S,N){y&=~T3,y&=~xh,m.suspendedLanes|=y,m.pingedLanes&=~y,N&&(m.warmLanes|=y),N=m.expirationTimes;for(var O=y;0<O;){var $=31-ts(O),K=1<<$;N[$]=-1,O&=~K}S!==0&&E(m,S,y)}function oz(){return(Je&6)===0?(So(0,!1),!1):!0}function VT(){if(Ue!==null){if(xn===0)var m=Ue.return;else m=Ue,fa=_h=null,Py(m),hm=null,Gy=0,m=Ue;for(;m!==null;)DF(m.alternate,m),m=m.return;Ue=null}}function Hf(m,y){var S=m.timeoutHandle;S!==hh&&(m.timeoutHandle=hh,Tut(S)),S=m.cancelPendingCommit,S!==null&&(m.cancelPendingCommit=null,S()),VT(),Nn=m,Ue=S=la(m.current,null),tn=y,xn=0,is=null,Ec=!1,mm=P(m,y),k3=!1,_m=bs=T3=xh=Cc=ei=0,Rr=Wy=null,M3=!1,(y&8)!==0&&(y|=y&32);var N=m.entangledLanes;if(N!==0)for(m=m.entanglements,N&=y;0<N;){var O=31-ts(N),$=1<<O;y|=m[O],N&=~$}return _a=y,dc(),S}function az(m,y){De=null,_e.H=bx,y===Uy||y===mx?(y=zf(),xn=3):y===x3?(y=zf(),xn=4):xn=y===c$?8:y!==null&&typeof y=="object"&&typeof y.then=="function"?6:1,is=y,Ue===null&&(ei=1,q0(m,tt(y,m.current)))}function cz(){var m=xs.current;return m===null?!0:(tn&4194048)===tn?Mo===null:(tn&62914560)===tn||(tn&536870912)!==0?m===Mo:!1}function lz(){var m=_e.H;return _e.H=bx,m===null?bx:m}function uz(){var m=_e.A;return _e.A=Wpt,m}function GT(){ei=4,Ec||(tn&4194048)!==tn&&xs.current!==null||(mm=!0),(Cc&134217727)===0&&(xh&134217727)===0||Nn===null||vc(Nn,tn,bs,!1)}function HT(m,y,S){var N=Je;Je|=2;var O=lz(),$=uz();(Nn!==m||tn!==y)&&(Tx=null,Hf(m,y)),y=!1;var K=ei;t:do try{if(xn!==0&&Ue!==null){var ct=Ue,xt=is;switch(xn){case 8:VT(),K=6;break t;case 3:case 2:case 9:case 6:xs.current===null&&(y=!0);var It=xn;if(xn=0,is=null,Wf(m,ct,xt,It),S&&mm){K=0;break t}break;default:It=xn,xn=0,is=null,Wf(m,ct,xt,It)}}rut(),K=ei;break}catch($t){az(m,$t)}while(!0);return y&&m.shellSuspendCounter++,fa=_h=null,Je=N,_e.H=O,_e.A=$,Ue===null&&(Nn=null,tn=0,dc()),K}function rut(){for(;Ue!==null;)pz(Ue)}function sut(m,y){var S=Je;Je|=2;var N=lz(),O=uz();Nn!==m||tn!==y?(Tx=null,qy=Ws()+500,Hf(m,y)):mm=P(m,y);t:do try{if(xn!==0&&Ue!==null){y=Ue;var $=is;e:switch(xn){case 1:xn=0,is=null,Wf(m,y,$,1);break;case 2:case 9:if(Lf($)){xn=0,is=null,hz(y);break}y=function(){xn!==2&&xn!==9||Nn!==m||(xn=7),Ir(m)},$.then(y,y);break t;case 3:xn=7;break t;case 4:xn=5;break t;case 7:Lf($)?(xn=0,is=null,hz(y)):(xn=0,is=null,Wf(m,y,$,7));break;case 5:var K=null;switch(Ue.tag){case 26:K=Ue.memoizedState;case 5:case 27:var ct=Ue,xt=ct.type,It=ct.pendingProps;if(K?Zz(K):Oz(xt,It)){xn=0,is=null;var $t=ct.sibling;if($t!==null)Ue=$t;else{var Xt=ct.return;Xt!==null?(Ue=Xt,ex(Xt)):Ue=null}break e}}xn=0,is=null,Wf(m,y,$,5);break;case 6:xn=0,is=null,Wf(m,y,$,6);break;case 8:VT(),ei=6;break t;default:throw Error(i(462))}}out();break}catch(Wt){az(m,Wt)}while(!0);return fa=_h=null,_e.H=N,_e.A=O,Je=S,Ue!==null?0:(Nn=null,tn=0,dc(),ei)}function out(){for(;Ue!==null&&!Fpt();)pz(Ue)}function pz(m){var y=OF(m.alternate,m,_a);m.memoizedProps=m.pendingProps,y===null?ex(m):Ue=y}function hz(m){var y=m,S=y.alternate;switch(y.tag){case 15:case 0:y=EF(S,y,y.pendingProps,y.type,void 0,tn);break;case 11:y=EF(S,y,y.pendingProps,y.type.render,y.ref,tn);break;case 5:Py(y);default:DF(S,y),y=Ue=Sz(y,_a),y=OF(S,y,_a)}m.memoizedProps=m.pendingProps,y===null?ex(m):Ue=y}function Wf(m,y,S,N){fa=_h=null,Py(y),hm=null,Gy=0;var O=y.return;try{if(Klt(m,O,y,S,tn)){ei=1,q0(m,tt(S,m.current)),Ue=null;return}}catch($){if(O!==null)throw Ue=O,$;ei=1,q0(m,tt(S,m.current)),Ue=null;return}y.flags&32768?(mn||N===1?m=!0:mm||(tn&536870912)!==0?m=!1:(Ec=m=!0,(N===2||N===9||N===3||N===6)&&(N=xs.current,N!==null&&N.tag===13&&(N.flags|=16384))),dz(y,m)):ex(y)}function ex(m){var y=m;do{if((y.flags&32768)!==0){dz(y,Ec);return}m=y.return;var S=Qlt(y.alternate,y,_a);if(S!==null){Ue=S;return}if(y=y.sibling,y!==null){Ue=y;return}Ue=y=m}while(y!==null);ei===0&&(ei=5)}function dz(m,y){do{var S=tut(m.alternate,m);if(S!==null){S.flags&=32767,Ue=S;return}if(S=m.return,S!==null&&(S.flags|=32768,S.subtreeFlags=0,S.deletions=null),!y&&(m=m.sibling,m!==null)){Ue=m;return}Ue=m=S}while(m!==null);ei=6,Ue=null}function fz(m,y,S,N,O,$,K,ct,xt){m.cancelPendingCommit=null;do zy();while(Zi!==0);if((Je&6)!==0)throw Error(i(327));if(y!==null){if(y===m.current)throw Error(i(177));if($=y.lanes|y.childLanes,$|=b3,I(m,S,$,K,ct,xt),m===Nn&&(Ue=Nn=null,tn=0),ym=y,Nc=m,gm=S,C3=$,I3=O,u$=N,(y.subtreeFlags&10256)!==0||(y.flags&10256)!==0?(m.callbackNode=null,m.callbackPriority=0,uut(h3,function(){return xz(!0),null})):(m.callbackNode=null,m.callbackPriority=0),N=(y.flags&13878)!==0,(y.subtreeFlags&13878)!==0||N){N=_e.T,_e.T=null,O=pa(),Ii(2),K=Je,Je|=4;try{eut(m,y,S)}finally{Je=K,Ii(O),_e.T=N}}Zi=1,mz(),_z(),yz()}}function mz(){if(Zi===1){Zi=0;var m=Nc,y=ym,S=(y.flags&13878)!==0;if((y.subtreeFlags&13878)!==0||S){S=_e.T,_e.T=null;var N=pa();Ii(2);var O=Je;Je|=4;try{qF(y,m),wut(m.containerInfo)}finally{Je=O,Ii(N),_e.T=S}}m.current=y,Zi=2}}function _z(){if(Zi===2){Zi=0;var m=Nc,y=ym,S=(y.flags&8772)!==0;if((y.subtreeFlags&8772)!==0||S){S=_e.T,_e.T=null;var N=pa();Ii(2);var O=Je;Je|=4;try{GF(m,y.alternate,y)}finally{Je=O,Ii(N),_e.T=S}}Zi=3}}function yz(){if(Zi===4||Zi===3){Zi=0,zpt();var m=Nc,y=ym,S=gm,N=u$;(y.subtreeFlags&10256)!==0||(y.flags&10256)!==0?Zi=5:(Zi=0,ym=Nc=null,gz(m,m.pendingLanes));var O=m.pendingLanes;if(O===0&&(Ic=null),B(S),y=y.stateNode,es&&typeof es.onCommitFiberRoot=="function")try{es.onCommitFiberRoot(By,y,void 0,(y.current.flags&128)===128)}catch{}if(N!==null){y=_e.T,O=pa(),Ii(2),_e.T=null;try{for(var $=m.onRecoverableError,K=0;K<N.length;K++){var ct=N[K];$(ct.value,{componentStack:ct.stack})}}finally{_e.T=y,Ii(O)}}(gm&3)!==0&&zy(),Ir(m),O=m.pendingLanes,(S&4194090)!==0&&(O&42)!==0?m===N3?Zy++:(Zy=0,N3=m):Zy=0,So(0,!1)}}function gz(m,y){(m.pooledCacheLanes&=y)===0&&(y=m.pooledCache,y!=null&&(m.pooledCache=null,Us(y)))}function zy(m){return mz(),_z(),yz(),xz(m)}function xz(){if(Zi!==5)return!1;var m=Nc,y=C3;C3=0;var S=B(gm),N=32>S?32:S;S=_e.T;var O=pa();try{Ii(N),_e.T=null,N=I3,I3=null;var $=Nc,K=gm;if(Zi=0,ym=Nc=null,gm=0,(Je&6)!==0)throw Error(i(331));var ct=Je;if(Je|=4,tz($.current),KF($,$.current,K,N),Je=ct,So(0,!1),es&&typeof es.onPostCommitFiberRoot=="function")try{es.onPostCommitFiberRoot(By,$)}catch{}return!0}finally{Ii(O),_e.T=S,gz(m,y)}}function bz(m,y,S){y=tt(S,y),y=wT(m.stateNode,y,2),m=fs(m,y,2),m!==null&&(M(m,2),Ir(m))}function gn(m,y,S){if(m.tag===3)bz(m,m,S);else for(;y!==null;){if(y.tag===3){bz(y,m,S);break}else if(y.tag===1){var N=y.stateNode;if(typeof y.type.getDerivedStateFromError=="function"||typeof N.componentDidCatch=="function"&&(Ic===null||!Ic.has(N))){m=tt(S,m),S=vF(2),N=fs(y,S,2),N!==null&&(SF(S,N,y,m),M(N,2),Ir(N));break}}y=y.return}}function WT(m,y,S){var N=m.pingCache;if(N===null){N=m.pingCache=new qpt;var O=new Set;N.set(y,O)}else O=N.get(y),O===void 0&&(O=new Set,N.set(y,O));O.has(S)||(k3=!0,O.add(S),m=aut.bind(null,m,y,S),y.then(m,m))}function aut(m,y,S){var N=m.pingCache;N!==null&&N.delete(y),m.pingedLanes|=m.suspendedLanes&S,m.warmLanes&=~S,Nn===m&&(tn&S)===S&&(ei===4||ei===3&&(tn&62914560)===tn&&300>Ws()-E3?(Je&2)===0&&Hf(m,0):T3|=S,_m===tn&&(_m=0)),Ir(m)}function vz(m,y){y===0&&(y=k()),m=wo(m,y),m!==null&&(M(m,y),Ir(m))}function cut(m){var y=m.memoizedState,S=0;y!==null&&(S=y.retryLane),vz(m,S)}function lut(m,y){var S=0;switch(m.tag){case 13:var N=m.stateNode,O=m.memoizedState;O!==null&&(S=O.retryLane);break;case 19:N=m.stateNode;break;case 22:N=m.stateNode._retryCache;break;default:throw Error(i(314))}N!==null&&N.delete(y),vz(m,S)}function uut(m,y){return cx(m,y)}function put(m,y,S,N){this.tag=m,this.key=S,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=N,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function qT(m){return m=m.prototype,!(!m||!m.isReactComponent)}function la(m,y){var S=m.alternate;return S===null?(S=e(m.tag,y,m.key,m.mode),S.elementType=m.elementType,S.type=m.type,S.stateNode=m.stateNode,S.alternate=m,m.alternate=S):(S.pendingProps=y,S.type=m.type,S.flags=0,S.subtreeFlags=0,S.deletions=null),S.flags=m.flags&65011712,S.childLanes=m.childLanes,S.lanes=m.lanes,S.child=m.child,S.memoizedProps=m.memoizedProps,S.memoizedState=m.memoizedState,S.updateQueue=m.updateQueue,y=m.dependencies,S.dependencies=y===null?null:{lanes:y.lanes,firstContext:y.firstContext},S.sibling=m.sibling,S.index=m.index,S.ref=m.ref,S.refCleanup=m.refCleanup,S}function Sz(m,y){m.flags&=65011714;var S=m.alternate;return S===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=S.childLanes,m.lanes=S.lanes,m.child=S.child,m.subtreeFlags=0,m.deletions=null,m.memoizedProps=S.memoizedProps,m.memoizedState=S.memoizedState,m.updateQueue=S.updateQueue,m.type=S.type,y=S.dependencies,m.dependencies=y===null?null:{lanes:y.lanes,firstContext:y.firstContext}),m}function nx(m,y,S,N,O,$){var K=0;if(N=m,typeof m=="function")qT(m)&&(K=1);else if(typeof m=="string")K=Hs&&bi?Uz(m,S,qi.current)?26:Qz(m)?27:5:Hs?Uz(m,S,qi.current)?26:5:bi&&Qz(m)?27:5;else t:switch(m){case s3:return m=e(31,S,y,O),m.elementType=s3,m.lanes=$,m;case Zf:return ph(S.children,O,$,y);case Ez:K=8,O|=24;break;case t3:return m=e(12,S,y,O|2),m.elementType=t3,m.lanes=$,m;case n3:return m=e(13,S,y,O),m.elementType=n3,m.lanes=$,m;case i3:return m=e(19,S,y,O),m.elementType=i3,m.lanes=$,m;default:if(typeof m=="object"&&m!==null)switch(m.$$typeof){case mut:case Sc:K=10;break t;case Cz:K=9;break t;case e3:K=11;break t;case r3:K=14;break t;case wc:K=16,N=null;break t}K=29,S=Error(i(130,m===null?"null":typeof m,"")),N=null}return y=e(K,S,y,O),y.elementType=m,y.type=N,y.lanes=$,y}function ph(m,y,S,N){return m=e(7,m,N,y),m.lanes=S,m}function ZT(m,y,S){return m=e(6,m,null,y),m.lanes=S,m}function KT(m,y,S){return y=e(4,m.children!==null?m.children:[],m.key,y),y.lanes=S,y.stateNode={containerInfo:m.containerInfo,pendingChildren:null,implementation:m.implementation},y}function hut(m,y,S,N,O,$,K,ct){this.tag=1,this.containerInfo=m,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=hh,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=C(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=C(0),this.hiddenUpdates=C(null),this.identifierPrefix=N,this.onUncaughtError=O,this.onCaughtError=$,this.onRecoverableError=K,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=ct,this.incompleteTransitions=new Map}function wz(m,y,S,N,O,$,K,ct,xt,It,$t,Xt){return m=new hut(m,y,S,K,ct,xt,It,Xt),y=1,$===!0&&(y|=24),$=e(3,null,null,y),m.current=$,$.stateNode=m,y=Cr(),y.refCount++,m.pooledCache=y,y.refCount++,$.memoizedState={element:N,isDehydrated:S,cache:y},th($),m}function Pz(m){return m?(m=tm,m):tm}function kz(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:$y(m.stateNode)}function Tz(m,y,S,N,O,$){O=Pz(O),N.context===null?N.context=O:N.pendingContext=O,N=ds(y),N.payload={element:S},$=$===void 0?null:$,$!==null&&(N.callback=$),S=fs(m,N,y),S!==null&&(Jr(S,m,y),ra(S,m,y))}function Mz(m,y){if(m=m.memoizedState,m!==null&&m.dehydrated!==null){var S=m.retryLane;m.retryLane=S!==0&&S<y?S:y}}function JT(m,y){Mz(m,y),(m=m.alternate)&&Mz(m,y)}var Xe={},dut=Zs(),Qr=HB(),QT=Object.assign,fut=Symbol.for("react.element"),ix=Symbol.for("react.transitional.element"),qf=Symbol.for("react.portal"),Zf=Symbol.for("react.fragment"),Ez=Symbol.for("react.strict_mode"),t3=Symbol.for("react.profiler"),mut=Symbol.for("react.provider"),Cz=Symbol.for("react.consumer"),Sc=Symbol.for("react.context"),e3=Symbol.for("react.forward_ref"),n3=Symbol.for("react.suspense"),i3=Symbol.for("react.suspense_list"),r3=Symbol.for("react.memo"),wc=Symbol.for("react.lazy");Symbol.for("react.scope");var s3=Symbol.for("react.activity");Symbol.for("react.legacy_hidden"),Symbol.for("react.tracing_marker");var _ut=Symbol.for("react.memo_cache_sentinel");Symbol.for("react.view_transition");var Iz=Symbol.iterator,yut=Symbol.for("react.client.reference"),rx=Array.isArray,_e=dut.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,gut=n.rendererVersion,xut=n.rendererPackageName,Nz=n.extraDevToolsConfig,$y=n.getPublicInstance,but=n.getRootHostContext,vut=n.getChildHostContext,Sut=n.prepareForCommit,wut=n.resetAfterCommit,Put=n.createInstance;n.cloneMutableInstance;var o3=n.appendInitialChild,Az=n.finalizeInitialChildren,sx=n.shouldSetTextContent,Rz=n.createTextInstance;n.cloneMutableTextInstance;var kut=n.scheduleTimeout,Tut=n.cancelTimeout,hh=n.noTimeout,ua=n.isPrimaryRenderer;n.warnsIfNotActing;var ar=n.supportsMutation,Pc=n.supportsPersistence,ms=n.supportsHydration,Mut=n.getInstanceFromNode;n.beforeActiveInstanceBlur;var Eut=n.preparePortalMount;n.prepareScopeUpdate,n.getInstanceFromScope;var Ii=n.setCurrentUpdatePriority,pa=n.getCurrentUpdatePriority,Cut=n.resolveUpdatePriority;n.trackSchedulerEvent,n.resolveEventType,n.resolveEventTimeStamp;var Iut=n.shouldAttemptEagerTransition,Nut=n.detachDeletedInstance;n.requestPostPaintCallback;var Aut=n.maySuspendCommit,Oz=n.preloadInstance,Rut=n.startSuspendingCommit,Lz=n.suspendInstance;n.suspendOnActiveViewTransition;var Out=n.waitForCommitToBeReady,Kf=n.NotPendingTransition,dh=n.HostTransitionContext,Lut=n.resetFormInstance;n.bindToConsole;var Fut=n.supportsMicrotasks,zut=n.scheduleMicrotask,Dy=n.supportsTestSelectors,$ut=n.findFiberRoot,Dut=n.getBoundingRect,jut=n.getTextContent,jy=n.isHiddenSubtree,But=n.matchAccessibilityRole,Yut=n.setFocusIfFocusable,Xut=n.setupIntersectionObserver,Uut=n.appendChild,Vut=n.appendChildToContainer,Gut=n.commitTextUpdate,Hut=n.commitMount,Wut=n.commitUpdate,qut=n.insertBefore,Zut=n.insertInContainerBefore,Kut=n.removeChild,Jut=n.removeChildFromContainer,Fz=n.resetTextContent,Qut=n.hideInstance,tpt=n.hideTextInstance,ept=n.unhideInstance,npt=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 ipt=n.clearContainer;n.createFragmentInstance,n.updateFragmentInstanceFiber,n.commitNewChildToFragmentInstance,n.deleteChildFromFragmentInstance;var rpt=n.cloneInstance,zz=n.createContainerChildSet,$z=n.appendChildToContainerChildSet,spt=n.finalizeContainerChildren,Dz=n.replaceContainerChildren,jz=n.cloneHiddenInstance,Bz=n.cloneHiddenTextInstance,a3=n.isSuspenseInstancePending,c3=n.isSuspenseInstanceFallback,opt=n.getSuspenseInstanceFallbackErrorDetails,apt=n.registerSuspenseInstanceRetry,cpt=n.canHydrateFormStateMarker,lpt=n.isFormStateMarkerMatching,Yz=n.getNextHydratableSibling,upt=n.getNextHydratableSiblingAfterSingleton,ppt=n.getFirstHydratableChild,hpt=n.getFirstHydratableChildWithinContainer,dpt=n.getFirstHydratableChildWithinSuspenseInstance,fpt=n.getFirstHydratableChildWithinSingleton,mpt=n.canHydrateInstance,_pt=n.canHydrateTextInstance,ypt=n.canHydrateSuspenseInstance,gpt=n.hydrateInstance,xpt=n.hydrateTextInstance,bpt=n.hydrateSuspenseInstance,vpt=n.getNextHydratableInstanceAfterSuspenseInstance,Spt=n.commitHydratedContainer,wpt=n.commitHydratedSuspenseInstance,Ppt=n.clearSuspenseBoundary,kpt=n.clearSuspenseBoundaryFromContainer,Xz=n.shouldDeleteUnhydratedTailInstances;n.diffHydratedPropsForDevWarnings,n.diffHydratedTextForDevWarnings,n.describeHydratableInstanceForDevWarnings;var Tpt=n.validateHydratableInstance,Mpt=n.validateHydratableTextInstance,Hs=n.supportsResources,Uz=n.isHostHoistableType,l3=n.getHoistableRoot,Vz=n.getResource,Gz=n.acquireResource,Hz=n.releaseResource,Ept=n.hydrateHoistable,Wz=n.mountHoistable,qz=n.unmountHoistable,Cpt=n.createHoistableInstance,Ipt=n.prepareToCommitHoistables,Npt=n.mayResourceSuspendCommit,Zz=n.preloadResource,Apt=n.suspendResource,bi=n.supportsSingletons,Kz=n.resolveSingletonInstance,Rpt=n.acquireSingletonInstance,Jz=n.releaseSingletonInstance,Qz=n.isHostSingletonType,Jf=n.isSingletonScope,u3=[],Qf=-1,tm={},ts=Math.clz32?Math.clz32:g,Opt=Math.log,Lpt=Math.LN2,ox=256,ax=4194304,cx=Qr.unstable_scheduleCallback,p3=Qr.unstable_cancelCallback,Fpt=Qr.unstable_shouldYield,zpt=Qr.unstable_requestPaint,Ws=Qr.unstable_now,t$=Qr.unstable_ImmediatePriority,$pt=Qr.unstable_UserBlockingPriority,h3=Qr.unstable_NormalPriority,Dpt=Qr.unstable_IdlePriority,jpt=Qr.log,Bpt=Qr.unstable_setDisableYieldValue,By=null,es=null,d3,e$,f3=!1,n$=new WeakMap,em=[],nm=0,lx=null,ux=0,_s=[],ys=0,fh=null,ha=1,da="",qi=h(null),Yy=h(null),kc=h(null),px=h(null),vr=null,vi=null,mn=!1,mh=null,To=!1,m3=Error(i(519)),ns=typeof Object.is=="function"?Object.is:at,hx=h(null),_h=null,fa=null,Ypt=typeof AbortController<"u"?AbortController:function(){var m=[],y=this.signal={aborted:!1,addEventListener:function(S,N){m.push(N)}};this.abort=function(){y.aborted=!0,m.forEach(function(S){return S()})}},Xpt=Qr.unstable_scheduleCallback,Upt=Qr.unstable_NormalPriority,ti={$$typeof:Sc,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0},dx=null,im=null,_3=!1,fx=!1,y3=!1,rm=0,Xy=null,g3=0,sm=0,om=null,i$=_e.S;_e.S=function(m,y){typeof y=="object"&&y!==null&&typeof y.then=="function"&&by(m,y),i$!==null&&i$(m,y)};var yh=h(null),Vpt=Object.prototype.hasOwnProperty,Uy=Error(i(460)),x3=Error(i(474)),mx=Error(i(542)),_x={then:function(){}},am=null,gs=[],cm=0,b3=0,Tc=!1,v3=!1,lm=h(null),yx=h(0),Mc=0,De=null,wn=null,di=null,gx=!1,um=!1,gh=!1,xx=0,Vy=0,pm=null,Gpt=0,bx={readContext:Jt,use:Xf,useCallback:Ln,useContext:Ln,useEffect:Ln,useImperativeHandle:Ln,useLayoutEffect:Ln,useInsertionEffect:Ln,useMemo:Ln,useReducer:Ln,useRef:Ln,useState:Ln,useDebugValue:Ln,useDeferredValue:Ln,useTransition:Ln,useSyncExternalStore:Ln,useId:Ln,useHostTransitionStatus:Ln,useFormState:Ln,useActionState:Ln,useOptimistic:Ln,useMemoCache:Ln,useCacheRefresh:Ln},r$={readContext:Jt,use:Xf,useCallback:function(m,y){return or().memoizedState=[m,y===void 0?null:y],m},useContext:Jt,useEffect:Q7,useImperativeHandle:function(m,y,S){S=S!=null?S.concat([m]):null,U0(4194308,4,iF.bind(null,y,m),S)},useLayoutEffect:function(m,y){return U0(4194308,4,m,y)},useInsertionEffect:function(m,y){U0(4,2,m,y)},useMemo:function(m,y){var S=or();y=y===void 0?null:y;var N=m();if(gh){j(!0);try{m()}finally{j(!1)}}return S.memoizedState=[N,y],N},useReducer:function(m,y,S){var N=or();if(S!==void 0){var O=S(y);if(gh){j(!0);try{S(y)}finally{j(!1)}}}else O=y;return N.memoizedState=N.baseState=O,m={pending:null,lanes:0,dispatch:null,lastRenderedReducer:m,lastRenderedState:O},N.queue=m,m=m.dispatch=Zlt.bind(null,De,m),[N.memoizedState,m]},useRef:function(m){var y=or();return m={current:m},y.memoizedState=m},useState:function(m){m=_T(m);var y=m.queue,S=hF.bind(null,De,y);return y.dispatch=S,[m.memoizedState,S]},useDebugValue:gT,useDeferredValue:function(m,y){var S=or();return xT(S,m,y)},useTransition:function(){var m=_T(!1);return m=cF.bind(null,De,m.queue,!0,!1),or().memoizedState=m,[!1,m]},useSyncExternalStore:function(m,y,S){var N=De,O=or();if(mn){if(S===void 0)throw Error(i(407));S=S()}else{if(S=y(),Nn===null)throw Error(i(349));(tn&124)!==0||z7(N,y,S)}O.memoizedState=S;var $={value:S,getSnapshot:y};return O.queue=$,Q7(D7.bind(null,N,$,m),[m]),N.flags|=2048,Vf(9,X0(),$7.bind(null,N,$,S,y),null),S},useId:function(){var m=or(),y=Nn.identifierPrefix;if(mn){var S=da,N=ha;S=(N&~(1<<32-ts(N)-1)).toString(32)+S,y="\xAB"+y+"R"+S,S=xx++,0<S&&(y+="H"+S.toString(32)),y+="\xBB"}else S=Gpt++,y="\xAB"+y+"r"+S.toString(32)+"\xBB";return m.memoizedState=y},useHostTransitionStatus:bT,useFormState:W7,useActionState:W7,useOptimistic:function(m){var y=or();y.memoizedState=y.baseState=m;var S={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return y.queue=S,y=vT.bind(null,De,!0,S),S.dispatch=y,[m,y]},useMemoCache:Ty,useCacheRefresh:function(){return or().memoizedState=qlt.bind(null,De)}},s$={readContext:Jt,use:Xf,useCallback:sF,useContext:Jt,useEffect:tF,useImperativeHandle:rF,useInsertionEffect:eF,useLayoutEffect:nF,useMemo:oF,useReducer:Uf,useRef:J7,useState:function(){return Uf(Vs)},useDebugValue:gT,useDeferredValue:function(m,y){var S=Qn();return aF(S,wn.memoizedState,m,y)},useTransition:function(){var m=Uf(Vs)[0],y=Qn().memoizedState;return[typeof m=="boolean"?m:ah(m),y]},useSyncExternalStore:F7,useId:uF,useHostTransitionStatus:bT,useFormState:q7,useActionState:q7,useOptimistic:function(m,y){var S=Qn();return Y7(S,wn,m,y)},useMemoCache:Ty,useCacheRefresh:pF},Hpt={readContext:Jt,use:Xf,useCallback:sF,useContext:Jt,useEffect:tF,useImperativeHandle:rF,useInsertionEffect:eF,useLayoutEffect:nF,useMemo:oF,useReducer:Ey,useRef:J7,useState:function(){return Ey(Vs)},useDebugValue:gT,useDeferredValue:function(m,y){var S=Qn();return wn===null?xT(S,m,y):aF(S,wn.memoizedState,m,y)},useTransition:function(){var m=Ey(Vs)[0],y=Qn().memoizedState;return[typeof m=="boolean"?m:ah(m),y]},useSyncExternalStore:F7,useId:uF,useHostTransitionStatus:bT,useFormState:K7,useActionState:K7,useOptimistic:function(m,y){var S=Qn();return wn!==null?Y7(S,wn,m,y):(S.baseState=m,[m,S.queue.dispatch])},useMemoCache:Ty,useCacheRefresh:pF},hm=null,Gy=0,dm=_F(!0),o$=_F(!1),xs=h(null),Mo=null,Si=h(0),S3={enqueueSetState:function(m,y,S){m=m._reactInternals;var N=Kr(),O=ds(N);O.payload=y,S!=null&&(O.callback=S),y=fs(m,O,N),y!==null&&(Jr(y,m,N),ra(y,m,N))},enqueueReplaceState:function(m,y,S){m=m._reactInternals;var N=Kr(),O=ds(N);O.tag=1,O.payload=y,S!=null&&(O.callback=S),y=fs(m,O,N),y!==null&&(Jr(y,m,N),ra(y,m,N))},enqueueForceUpdate:function(m,y){m=m._reactInternals;var S=Kr(),N=ds(S);N.tag=2,y!=null&&(N.callback=y),y=fs(m,N,S),y!==null&&(Jr(y,m,S),ra(y,m,S))}},a$=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)},c$=Error(i(461)),Ni=!1,w3={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null},ma=!1,ui=!1,P3=!1,l$=typeof WeakSet=="function"?WeakSet:Set,Ai=null,fi=null,Ar=!1,qs=null,fm=8192,Wpt={getCacheForType:function(m){var y=Jt(ti),S=y.data.get(m);return S===void 0&&(S=m(),y.data.set(m,S)),S}},vx=0,Sx=1,wx=2,Px=3,kx=4;if(typeof Symbol=="function"&&Symbol.for){var Hy=Symbol.for;vx=Hy("selector.component"),Sx=Hy("selector.has_pseudo_class"),wx=Hy("selector.role"),Px=Hy("selector.test_id"),kx=Hy("selector.text")}var qpt=typeof WeakMap=="function"?WeakMap:Map,Je=0,Nn=null,Ue=null,tn=0,xn=0,is=null,Ec=!1,mm=!1,k3=!1,_a=0,ei=0,Cc=0,xh=0,T3=0,bs=0,_m=0,Wy=null,Rr=null,M3=!1,E3=0,qy=1/0,Tx=null,Ic=null,Zi=0,Nc=null,ym=null,gm=0,C3=0,I3=null,u$=null,Zy=0,N3=null;return Xe.attemptContinuousHydration=function(m){if(m.tag===13){var y=wo(m,67108864);y!==null&&Jr(y,m,67108864),JT(m,67108864)}},Xe.attemptHydrationAtCurrentPriority=function(m){if(m.tag===13){var y=Kr();y=R(y);var S=wo(m,y);S!==null&&Jr(S,m,y),JT(m,y)}},Xe.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 S=1<<31-ts(y);m.entanglements[1]|=S,y&=~S}Ir(m),(Je&6)===0&&(qy=Ws()+500,So(0,!1))}}break;case 13:y=wo(m,2),y!==null&&Jr(y,m,2),oz(),JT(m,2)}},Xe.batchedUpdates=function(m,y){return m(y)},Xe.createComponentSelector=function(m){return{$$typeof:vx,value:m}},Xe.createContainer=function(m,y,S,N,O,$,K,ct,xt,It){return wz(m,y,!1,null,S,N,$,K,ct,xt,It,null)},Xe.createHasPseudoClassSelector=function(m){return{$$typeof:Sx,value:m}},Xe.createHydrationContainer=function(m,y,S,N,O,$,K,ct,xt,It,$t,Xt,Wt){return m=wz(S,N,!0,m,O,$,ct,xt,It,$t,Xt,Wt),m.context=Pz(null),S=m.current,N=Kr(),N=R(N),O=ds(N),O.callback=y??null,fs(S,O,N),y=N,m.current.lanes=y,M(m,y),Ir(m),m},Xe.createPortal=function(m,y,S){var N=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:qf,key:N==null?null:""+N,children:m,containerInfo:y,implementation:S}},Xe.createRoleSelector=function(m){return{$$typeof:wx,value:m}},Xe.createTestNameSelector=function(m){return{$$typeof:Px,value:m}},Xe.createTextSelector=function(m){return{$$typeof:kx,value:m}},Xe.defaultOnCaughtError=function(m){console.error(m)},Xe.defaultOnRecoverableError=function(m){a$(m)},Xe.defaultOnUncaughtError=function(m){a$(m)},Xe.deferredUpdates=function(m){var y=_e.T,S=pa();try{return Ii(32),_e.T=null,m()}finally{Ii(S),_e.T=y}},Xe.discreteUpdates=function(m,y,S,N,O){var $=_e.T,K=pa();try{return Ii(2),_e.T=null,m(y,S,N,O)}finally{Ii(K),_e.T=$,Je===0&&(qy=Ws()+500)}},Xe.findAllNodes=UT,Xe.findBoundingRects=function(m,y){if(!Dy)throw Error(i(363));y=UT(m,y),m=[];for(var S=0;S<y.length;S++)m.push(Dut(y[S]));for(y=m.length-1;0<y;y--){S=m[y];for(var N=S.x,O=N+S.width,$=S.y,K=$+S.height,ct=y-1;0<=ct;ct--)if(y!==ct){var xt=m[ct],It=xt.x,$t=It+xt.width,Xt=xt.y,Wt=Xt+xt.height;if(N>=It&&$>=Xt&&O<=$t&&K<=Wt){m.splice(y,1);break}else if(N!==It||S.width!==xt.width||Wt<$||Xt>K){if(!($!==Xt||S.height!==xt.height||$t<N||It>O)){It>N&&(xt.width+=It-N,xt.x=N),$t<O&&(xt.width=O-It),m.splice(y,1);break}}else{Xt>$&&(xt.height+=Xt-$,xt.y=$),Wt<K&&(xt.height=K-Xt),m.splice(y,1);break}}}return m},Xe.findHostInstance=kz,Xe.findHostInstanceWithNoPortals=function(m){return m=o(m),m=m!==null?c(m):null,m===null?null:$y(m.stateNode)},Xe.findHostInstanceWithWarning=function(m){return kz(m)},Xe.flushPassiveEffects=zy,Xe.flushSyncFromReconciler=function(m){var y=Je;Je|=1;var S=_e.T,N=pa();try{if(Ii(2),_e.T=null,m)return m()}finally{Ii(N),_e.T=S,Je=y,(Je&6)===0&&So(0,!1)}},Xe.flushSyncWork=oz,Xe.focusWithin=function(m,y){if(!Dy)throw Error(i(363));for(m=BT(m),y=nz(m,y),y=Array.from(y),m=0;m<y.length;){var S=y[m++],N=S.tag;if(!jy(S)){if((N===5||N===26||N===27)&&Yut(S.stateNode))return!0;for(S=S.child;S!==null;)y.push(S),S=S.sibling}}return!1},Xe.getFindAllNodesFailureDescription=function(m,y){if(!Dy)throw Error(i(363));var S=0,N=[];m=[BT(m),0];for(var O=0;O<m.length;){var $=m[O++],K=$.tag,ct=m[O++],xt=y[ct];if((K!==5&&K!==26&&K!==27||!jy($))&&(YT($,xt)&&(N.push(XT(xt)),ct++,ct>S&&(S=ct)),ct<y.length))for($=$.child;$!==null;)m.push($,ct),$=$.sibling}if(S<y.length){for(m=[];S<y.length;S++)m.push(XT(y[S]));return`findAllNodes was able to match part of the selector:
8
+ `+S.stack}}function tt(m,y){if(typeof m=="object"&&m!==null){var S=n$.get(m);return S!==void 0?S:(y={value:m,source:y,stack:et(y)},n$.set(m,y),y)}return{value:m,source:y,stack:et(y)}}function mt(m,y){em[nm++]=ux,em[nm++]=lx,lx=m,ux=y}function G(m,y,S){_s[ys++]=ha,_s[ys++]=da,_s[ys++]=fh,fh=m;var N=ha;m=da;var O=32-ts(N)-1;N&=~(1<<O),S+=1;var $=32-ts(y)+O;if(30<$){var K=O-O%5;$=(N&(1<<K)-1).toString(32),N>>=K,O-=K,ha=1<<32-ts(y)+O|S<<O|N,da=$+m}else ha=1<<$|S<<O|N,da=m}function Q(m){m.return!==null&&(mt(m,1),G(m,1,0))}function nt(m){for(;m===lx;)lx=em[--nm],em[nm]=null,ux=em[--nm],em[nm]=null;for(;m===fh;)fh=_s[--ys],_s[ys]=null,da=_s[--ys],_s[ys]=null,ha=_s[--ys],_s[ys]=null}function pt(m,y){_(kc,y),_(Yy,m),_(qi,null),m=but(y),d(qi),_(qi,m)}function ht(){d(qi),d(Yy),d(kc)}function wt(m){m.memoizedState!==null&&_(px,m);var y=qi.current,S=vut(y,m.type);y!==S&&(_(Yy,m),_(qi,S))}function Et(m){Yy.current===m&&(d(qi),d(Yy)),px.current===m&&(d(px),ua?dh._currentValue=Kf:dh._currentValue2=Kf)}function ot(m){var y=Error(i(418,""));throw Z(tt(y,m)),m3}function X(m,y){if(!ms)throw Error(i(175));gpt(m.stateNode,m.type,m.memoizedProps,y,m)||ot(m)}function W(m){for(vr=m.return;vr;)switch(vr.tag){case 5:case 13:To=!1;return;case 27:case 3:To=!0;return;default:vr=vr.return}}function rt(m){if(!ms||m!==vr)return!1;if(!mn)return W(m),mn=!0,!1;var y=m.tag;if(vi?y!==3&&y!==27&&(y!==5||Xz(m.type)&&!sx(m.type,m.memoizedProps))&&Si&&ot(m):y!==3&&(y!==5||Xz(m.type)&&!sx(m.type,m.memoizedProps))&&Si&&ot(m),W(m),y===13){if(!ms)throw Error(i(316));if(m=m.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(i(317));Si=vpt(m)}else Si=vi&&y===27?upt(m.type,Si):vr?Yz(m.stateNode):null;return!0}function ut(){ms&&(Si=vr=null,mn=!1)}function yt(){var m=mh;return m!==null&&(Rr===null?Rr=m:Rr.push.apply(Rr,m),mh=null),m}function Z(m){mh===null?mh=[m]:mh.push(m)}function at(m,y){return m===y&&(m!==0||1/m===1/y)||m!==m&&y!==y}function Mt(m,y,S){ua?(_(hx,y._currentValue),y._currentValue=S):(_(hx,y._currentValue2),y._currentValue2=S)}function Ft(m){var y=hx.current;ua?m._currentValue=y:m._currentValue2=y,d(hx)}function Ot(m,y,S){for(;m!==null;){var N=m.alternate;if((m.childLanes&y)!==y?(m.childLanes|=y,N!==null&&(N.childLanes|=y)):N!==null&&(N.childLanes&y)!==y&&(N.childLanes|=y),m===S)break;m=m.return}}function Ce(m,y,S,N){var O=m.child;for(O!==null&&(O.return=m);O!==null;){var $=O.dependencies;if($!==null){var K=O.child;$=$.firstContext;t:for(;$!==null;){var ct=$;$=O;for(var xt=0;xt<y.length;xt++)if(ct.context===y[xt]){$.lanes|=S,ct=$.alternate,ct!==null&&(ct.lanes|=S),Ot($.return,S,m),N||(K=null);break t}$=ct.next}}else if(O.tag===18){if(K=O.return,K===null)throw Error(i(341));K.lanes|=S,$=K.alternate,$!==null&&($.lanes|=S),Ot(K,S,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,S,N){m=null;for(var O=y,$=!1;O!==null;){if(!$){if((O.flags&524288)!==0)$=!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;ns(O.pendingProps.value,K.value)||(m!==null?m.push(ct):m=[ct])}}else if(O===px.current){if(K=O.alternate,K===null)throw Error(i(387));K.memoizedState.memoizedState!==O.memoizedState.memoizedState&&(m!==null?m.push(dh):m=[dh])}O=O.return}m!==null&&Ce(y,m,S,N),y.flags|=262144}function Kt(m){for(m=m.firstContext;m!==null;){var y=m.context;if(!ns(ua?y._currentValue:y._currentValue2,m.memoizedValue))return!0;m=m.next}return!1}function le(m){_h=m,fa=null,m=m.dependencies,m!==null&&(m.firstContext=null)}function Jt(m){return Ci(_h,m)}function Wn(m,y){return _h===null&&le(m),Ci(m,y)}function Ci(m,y){var S=ua?y._currentValue:y._currentValue2;if(y={context:y,memoizedValue:S,next:null},fa===null){if(m===null)throw Error(i(308));fa=y,m.dependencies={lanes:0,firstContext:y},m.flags|=524288}else fa=fa.next=y;return S}function Cr(){return{controller:new Ypt,data:new Map,refCount:0}}function Us(m){m.refCount--,m.refCount===0&&Xpt(Upt,function(){m.controller.abort()})}function Ir(m){m!==im&&m.next===null&&(im===null?dx=im=m:im=im.next=m),fx=!0,_3||(_3=!0,xy())}function So(m,y){if(!y3&&fx){y3=!0;do for(var S=!1,N=dx;N!==null;){if(!y)if(m!==0){var O=N.pendingLanes;if(O===0)var $=0;else{var K=N.suspendedLanes,ct=N.pingedLanes;$=(1<<31-ts(42|m)+1)-1,$&=O&~(K&~ct),$=$&201326741?$&201326741|1:$?$|2:0}$!==0&&(S=!0,Af(N,$))}else $=tn,$=v(N,N===Nn?$:0,N.cancelPendingCommit!==null||N.timeoutHandle!==hh),($&3)===0||P(N,$)||(S=!0,Af(N,$));N=N.next}while(S);y3=!1}}function Ef(){Cf()}function Cf(){fx=_3=!1;var m=0;rm!==0&&(Iut()&&(m=rm),rm=0);for(var y=Ws(),S=null,N=dx;N!==null;){var O=N.next,$=If(N,y);$===0?(N.next=null,S===null?dx=O:S.next=O,O===null&&(im=S)):(S=N,(m!==0||($&3)!==0)&&(fx=!0)),N=O}So(m,!1)}function If(m,y){for(var S=m.suspendedLanes,N=m.pingedLanes,O=m.expirationTimes,$=m.pendingLanes&-62914561;0<$;){var K=31-ts($),ct=1<<K,xt=O[K];xt===-1?((ct&S)===0||(ct&N)!==0)&&(O[K]=w(ct,y)):xt<=y&&(m.expiredLanes|=ct),$&=~ct}if(y=Nn,S=tn,S=v(m,m===y?S:0,m.cancelPendingCommit!==null||m.timeoutHandle!==hh),N=m.callbackNode,S===0||m===y&&(xn===2||xn===9)||m.cancelPendingCommit!==null)return N!==null&&N!==null&&p3(N),m.callbackNode=null,m.callbackPriority=0;if((S&3)===0||P(m,S)){if(y=S&-S,y===m.callbackPriority)return y;switch(N!==null&&p3(N),B(S)){case 2:case 8:S=$pt;break;case 32:S=h3;break;case 268435456:S=Dpt;break;default:S=h3}return N=Nf.bind(null,m),S=cx(S,N),m.callbackPriority=y,m.callbackNode=S,y}return N!==null&&N!==null&&p3(N),m.callbackPriority=2,m.callbackNode=null,2}function Nf(m,y){if(Zi!==0&&Zi!==5)return m.callbackNode=null,m.callbackPriority=0,null;var S=m.callbackNode;if(zy(!0)&&m.callbackNode!==S)return null;var N=tn;return N=v(m,m===Nn?N:0,m.cancelPendingCommit!==null||m.timeoutHandle!==hh),N===0?null:(rz(m,N,y),If(m,Ws()),m.callbackNode!=null&&m.callbackNode===S?Nf.bind(null,m):null)}function Af(m,y){if(zy())return null;rz(m,y,!0)}function xy(){Fut?zut(function(){(Je&6)!==0?cx(t$,Ef):Cf()}):cx(t$,Ef)}function Kp(){return rm===0&&(rm=T()),rm}function by(m,y){if(Xy===null){var S=Xy=[];g3=0,sm=Kp(),om={status:"pending",value:void 0,then:function(N){S.push(N)}}}return g3++,y.then(Rf,Rf),y}function Rf(){if(--g3===0&&Xy!==null){om!==null&&(om.status="fulfilled");var m=Xy;Xy=null,sm=0,om=null;for(var y=0;y<m.length;y++)(0,m[y])()}}function vy(m,y){var S=[],N={status:"pending",value:null,reason:null,then:function(O){S.push(O)}};return m.then(function(){N.status="fulfilled",N.value=y;for(var O=0;O<S.length;O++)(0,S[O])(y)},function(O){for(N.status="rejected",N.reason=O,O=0;O<S.length;O++)(0,S[O])(void 0)}),N}function Jp(){var m=yh.current;return m!==null?m:Nn.pooledCache}function uc(m,y){y===null?_(yh,yh.current):_(yh,y.pool)}function Of(){var m=Jp();return m===null?null:{parent:ua?ti._currentValue:ti._currentValue2,pool:m}}function pc(m,y){if(ns(m,y))return!0;if(typeof m!="object"||m===null||typeof y!="object"||y===null)return!1;var S=Object.keys(m),N=Object.keys(y);if(S.length!==N.length)return!1;for(N=0;N<S.length;N++){var O=S[N];if(!Vpt.call(y,O)||!ns(m[O],y[O]))return!1}return!0}function Lf(m){return m=m.status,m==="fulfilled"||m==="rejected"}function hc(){}function Ff(m,y,S){switch(S=m[S],S===void 0?m.push(y):S!==y&&(y.then(hc,hc),y=S),y.status){case"fulfilled":return y.value;case"rejected":throw m=y.reason,$f(m),m;default:if(typeof y.status=="string")y.then(hc,hc);else{if(m=Nn,m!==null&&100<m.shellSuspendCounter)throw Error(i(482));m=y,m.status="pending",m.then(function(N){if(y.status==="pending"){var O=y;O.status="fulfilled",O.value=N}},function(N){if(y.status==="pending"){var O=y;O.status="rejected",O.reason=N}})}switch(y.status){case"fulfilled":return y.value;case"rejected":throw m=y.reason,$f(m),m}throw am=y,Uy}}function zf(){if(am===null)throw Error(i(459));var m=am;return am=null,m}function $f(m){if(m===Uy||m===mx)throw Error(i(483))}function dc(){for(var m=cm,y=b3=cm=0;y<m;){var S=gs[y];gs[y++]=null;var N=gs[y];gs[y++]=null;var O=gs[y];gs[y++]=null;var $=gs[y];if(gs[y++]=null,N!==null&&O!==null){var K=N.pending;K===null?O.next=O:(O.next=K.next,K.next=O),N.pending=O}$!==0&&Df(S,O,$)}}function fc(m,y,S,N){gs[cm++]=m,gs[cm++]=y,gs[cm++]=S,gs[cm++]=N,b3|=N,m.lanes|=N,m=m.alternate,m!==null&&(m.lanes|=N)}function Qp(m,y,S,N){return fc(m,y,S,N),mc(m)}function wo(m,y){return fc(m,null,null,y),mc(m)}function Df(m,y,S){m.lanes|=S;var N=m.alternate;N!==null&&(N.lanes|=S);for(var O=!1,$=m.return;$!==null;)$.childLanes|=S,N=$.alternate,N!==null&&(N.childLanes|=S),$.tag===22&&(m=$.stateNode,m===null||m._visibility&1||(O=!0)),m=$,$=$.return;return m.tag===3?($=m.stateNode,O&&y!==null&&(O=31-ts(S),m=$.hiddenUpdates,N=m[O],N===null?m[O]=[y]:N.push(y),y.lane=S|536870912),$):null}function mc(m){if(50<Zy)throw Zy=0,N3=null,Error(i(185));for(var y=m.return;y!==null;)m=y,y=m.return;return m.tag===3?m.stateNode:null}function th(m){m.updateQueue={baseState:m.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function eh(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 ds(m){return{lane:m,tag:0,payload:null,callback:null,next:null}}function fs(m,y,S){var N=m.updateQueue;if(N===null)return null;if(N=N.shared,(Je&2)!==0){var O=N.pending;return O===null?y.next=y:(y.next=O.next,O.next=y),N.pending=y,y=mc(m),Df(m,null,S),y}return fc(m,N,y,S),mc(m)}function ra(m,y,S){if(y=y.updateQueue,y!==null&&(y=y.shared,(S&4194048)!==0)){var N=y.lanes;N&=m.pendingLanes,S|=N,y.lanes=S,A(m,S)}}function nh(m,y){var S=m.updateQueue,N=m.alternate;if(N!==null&&(N=N.updateQueue,S===N)){var O=null,$=null;if(S=S.firstBaseUpdate,S!==null){do{var K={lane:S.lane,tag:S.tag,payload:S.payload,callback:null,next:null};$===null?O=$=K:$=$.next=K,S=S.next}while(S!==null);$===null?O=$=y:$=$.next=y}else O=$=y;S={baseState:N.baseState,firstBaseUpdate:O,lastBaseUpdate:$,shared:N.shared,callbacks:N.callbacks},m.updateQueue=S;return}m=S.lastBaseUpdate,m===null?S.firstBaseUpdate=y:m.next=y,S.lastBaseUpdate=y}function sa(){if(v3){var m=om;if(m!==null)throw m}}function oa(m,y,S,N){v3=!1;var O=m.updateQueue;Tc=!1;var $=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?$=It:K.next=It,K=xt;var $t=m.alternate;$t!==null&&($t=$t.updateQueue,ct=$t.lastBaseUpdate,ct!==K&&(ct===null?$t.firstBaseUpdate=It:ct.next=It,$t.lastBaseUpdate=xt))}if($!==null){var Xt=O.baseState;K=0,$t=It=xt=null,ct=$;do{var Wt=ct.lane&-536870913,Le=Wt!==ct.lane;if(Le?(tn&Wt)===Wt:(N&Wt)===Wt){Wt!==0&&Wt===sm&&(v3=!0),$t!==null&&($t=$t.next={lane:0,tag:ct.tag,payload:ct.payload,callback:null,next:null});t:{var vs=m,Ky=ct;Wt=y;var bh=S;switch(Ky.tag){case 1:if(vs=Ky.payload,typeof vs=="function"){Xt=vs.call(bh,Xt,Wt);break t}Xt=vs;break t;case 3:vs.flags=vs.flags&-65537|128;case 0:if(vs=Ky.payload,Wt=typeof vs=="function"?vs.call(bh,Xt,Wt):vs,Wt==null)break t;Xt=QT({},Xt,Wt);break t;case 2:Tc=!0}}Wt=ct.callback,Wt!==null&&(m.flags|=64,Le&&(m.flags|=8192),Le=O.callbacks,Le===null?O.callbacks=[Wt]:Le.push(Wt))}else Le={lane:Wt,tag:ct.tag,payload:ct.payload,callback:ct.callback,next:null},$t===null?(It=$t=Le,xt=Xt):$t=$t.next=Le,K|=Wt;if(ct=ct.next,ct===null){if(ct=O.shared.pending,ct===null)break;Le=ct,ct=Le.next,Le.next=null,O.lastBaseUpdate=Le,O.shared.pending=null}}while(!0);$t===null&&(xt=Xt),O.baseState=xt,O.firstBaseUpdate=It,O.lastBaseUpdate=$t,$===null&&(O.shared.lanes=0),Cc|=K,m.lanes=K,m.memoizedState=Xt}}function jf(m,y){if(typeof m!="function")throw Error(i(191,m));m.call(y)}function Bf(m,y){var S=m.callbacks;if(S!==null)for(m.callbacks=null,m=0;m<S.length;m++)jf(S[m],y)}function Yf(m,y){m=_a,_(yx,m),_(lm,y),_a=m|y.baseLanes}function ih(){_(yx,_a),_(lm,lm.current)}function rh(){_a=yx.current,d(lm),d(yx)}function Ln(){throw Error(i(321))}function sh(m,y){if(y===null)return!1;for(var S=0;S<y.length&&S<m.length;S++)if(!ns(m[S],y[S]))return!1;return!0}function oh(m,y,S,N,O,$){return Mc=$,De=y,y.memoizedState=null,y.updateQueue=null,y.lanes=0,_e.H=m===null||m.memoizedState===null?r$:s$,gh=!1,$=S(N,O),gh=!1,um&&($=Y0(y,S,N,O)),B0(m),$}function B0(m){_e.H=bx;var y=wn!==null&&wn.next!==null;if(Mc=0,di=wn=De=null,gx=!1,Vy=0,pm=null,y)throw Error(i(300));m===null||Ni||(m=m.dependencies,m!==null&&Kt(m)&&(Ni=!0))}function Y0(m,y,S,N){De=m;var O=0;do{if(um&&(pm=null),Vy=0,um=!1,25<=O)throw Error(i(301));if(O+=1,di=wn=null,m.updateQueue!=null){var $=m.updateQueue;$.lastEffect=null,$.events=null,$.stores=null,$.memoCache!=null&&($.memoCache.index=0)}_e.H=Hpt,$=y(S,N)}while(um);return $}function mT(){var m=_e.H,y=m.useState()[0];return y=typeof y.then=="function"?ah(y):y,m=m.useState()[0],(wn!==null?wn.memoizedState:null)!==m&&(De.flags|=1024),y}function Sy(){var m=xx!==0;return xx=0,m}function wy(m,y,S){y.updateQueue=m.updateQueue,y.flags&=-2053,m.lanes&=~S}function Py(m){if(gx){for(m=m.memoizedState;m!==null;){var y=m.queue;y!==null&&(y.pending=null),m=m.next}gx=!1}Mc=0,di=wn=De=null,um=!1,Vy=xx=0,pm=null}function or(){var m={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return di===null?De.memoizedState=di=m:di=di.next=m,di}function Qn(){if(wn===null){var m=De.alternate;m=m!==null?m.memoizedState:null}else m=wn.next;var y=di===null?De.memoizedState:di.next;if(y!==null)di=y,wn=m;else{if(m===null)throw De.alternate===null?Error(i(467)):Error(i(310));wn=m,m={memoizedState:wn.memoizedState,baseState:wn.baseState,baseQueue:wn.baseQueue,queue:wn.queue,next:null},di===null?De.memoizedState=di=m:di=di.next=m}return di}function ky(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function ah(m){var y=Vy;return Vy+=1,pm===null&&(pm=[]),m=Ff(pm,m,y),y=De,(di===null?y.memoizedState:di.next)===null&&(y=y.alternate,_e.H=y===null||y.memoizedState===null?r$:s$),m}function Xf(m){if(m!==null&&typeof m=="object"){if(typeof m.then=="function")return ah(m);if(m.$$typeof===Sc)return Jt(m)}throw Error(i(438,String(m)))}function Ty(m){var y=null,S=De.updateQueue;if(S!==null&&(y=S.memoCache),y==null){var N=De.alternate;N!==null&&(N=N.updateQueue,N!==null&&(N=N.memoCache,N!=null&&(y={data:N.data.map(function(O){return O.slice()}),index:0})))}if(y==null&&(y={data:[],index:0}),S===null&&(S=ky(),De.updateQueue=S),S.memoCache=y,S=y.data[y.index],S===void 0)for(S=y.data[y.index]=Array(m),N=0;N<m;N++)S[N]=_ut;return y.index++,S}function Vs(m,y){return typeof y=="function"?y(m):y}function Uf(m){var y=Qn();return My(y,wn,m)}function My(m,y,S){var N=m.queue;if(N===null)throw Error(i(311));N.lastRenderedReducer=S;var O=m.baseQueue,$=N.pending;if($!==null){if(O!==null){var K=O.next;O.next=$.next,$.next=K}y.baseQueue=O=$,N.pending=null}if($=m.baseState,O===null)m.memoizedState=$;else{y=O.next;var ct=K=null,xt=null,It=y,$t=!1;do{var Xt=It.lane&-536870913;if(Xt!==It.lane?(tn&Xt)===Xt:(Mc&Xt)===Xt){var Wt=It.revertLane;if(Wt===0)xt!==null&&(xt=xt.next={lane:0,revertLane:0,action:It.action,hasEagerState:It.hasEagerState,eagerState:It.eagerState,next:null}),Xt===sm&&($t=!0);else if((Mc&Wt)===Wt){It=It.next,Wt===sm&&($t=!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=$):xt=xt.next=Xt,De.lanes|=Wt,Cc|=Wt;Xt=It.action,gh&&S($,Xt),$=It.hasEagerState?It.eagerState:S($,Xt)}else Wt={lane:Xt,revertLane:It.revertLane,action:It.action,hasEagerState:It.hasEagerState,eagerState:It.eagerState,next:null},xt===null?(ct=xt=Wt,K=$):xt=xt.next=Wt,De.lanes|=Xt,Cc|=Xt;It=It.next}while(It!==null&&It!==y);if(xt===null?K=$:xt.next=ct,!ns($,m.memoizedState)&&(Ni=!0,$t&&(S=om,S!==null)))throw S;m.memoizedState=$,m.baseState=K,m.baseQueue=xt,N.lastRenderedState=$}return O===null&&(N.lanes=0),[m.memoizedState,N.dispatch]}function Ey(m){var y=Qn(),S=y.queue;if(S===null)throw Error(i(311));S.lastRenderedReducer=m;var N=S.dispatch,O=S.pending,$=y.memoizedState;if(O!==null){S.pending=null;var K=O=O.next;do $=m($,K.action),K=K.next;while(K!==O);ns($,y.memoizedState)||(Ni=!0),y.memoizedState=$,y.baseQueue===null&&(y.baseState=$),S.lastRenderedState=$}return[$,N]}function F7(m,y,S){var N=De,O=Qn(),$=mn;if($){if(S===void 0)throw Error(i(407));S=S()}else S=y();var K=!ns((wn||O).memoizedState,S);K&&(O.memoizedState=S,Ni=!0),O=O.queue;var ct=D7.bind(null,N,O,m);if(Cy(2048,8,ct,[m]),O.getSnapshot!==y||K||di!==null&&di.memoizedState.tag&1){if(N.flags|=2048,Vf(9,X0(),$7.bind(null,N,O,S,y),null),Nn===null)throw Error(i(349));$||(Mc&124)!==0||z7(N,y,S)}return S}function z7(m,y,S){m.flags|=16384,m={getSnapshot:y,value:S},y=De.updateQueue,y===null?(y=ky(),De.updateQueue=y,y.stores=[m]):(S=y.stores,S===null?y.stores=[m]:S.push(m))}function $7(m,y,S,N){y.value=S,y.getSnapshot=N,j7(y)&&B7(m)}function D7(m,y,S){return S(function(){j7(y)&&B7(m)})}function j7(m){var y=m.getSnapshot;m=m.value;try{var S=y();return!ns(m,S)}catch{return!0}}function B7(m){var y=wo(m,2);y!==null&&Jr(y,m,2)}function _T(m){var y=or();if(typeof m=="function"){var S=m;if(m=S(),gh){j(!0);try{S()}finally{j(!1)}}}return y.memoizedState=y.baseState=m,y.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Vs,lastRenderedState:m},y}function Y7(m,y,S,N){return m.baseState=S,My(m,wn,typeof N=="function"?N:Vs)}function Hlt(m,y,S,N,O){if(V0(m))throw Error(i(485));if(m=y.action,m!==null){var $={payload:O,action:m,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(K){$.listeners.push(K)}};_e.T!==null?S(!0):$.isTransition=!1,N($),S=y.pending,S===null?($.next=y.pending=$,X7(y,$)):($.next=S.next,y.pending=S.next=$)}}function X7(m,y){var S=y.action,N=y.payload,O=m.state;if(y.isTransition){var $=_e.T,K={};_e.T=K;try{var ct=S(O,N),xt=_e.S;xt!==null&&xt(K,ct),U7(m,y,ct)}catch(It){yT(m,y,It)}finally{_e.T=$}}else try{$=S(O,N),U7(m,y,$)}catch(It){yT(m,y,It)}}function U7(m,y,S){S!==null&&typeof S=="object"&&typeof S.then=="function"?S.then(function(N){V7(m,y,N)},function(N){return yT(m,y,N)}):V7(m,y,S)}function V7(m,y,S){y.status="fulfilled",y.value=S,G7(y),m.state=S,y=m.pending,y!==null&&(S=y.next,S===y?m.pending=null:(S=S.next,y.next=S,X7(m,S)))}function yT(m,y,S){var N=m.pending;if(m.pending=null,N!==null){N=N.next;do y.status="rejected",y.reason=S,G7(y),y=y.next;while(y!==N)}m.action=null}function G7(m){m=m.listeners;for(var y=0;y<m.length;y++)(0,m[y])()}function H7(m,y){return y}function W7(m,y){if(mn){var S=Nn.formState;if(S!==null){t:{var N=De;if(mn){if(Si){var O=cpt(Si,To);if(O){Si=Yz(O),N=lpt(O);break t}}ot(N)}N=!1}N&&(y=S[0])}}S=or(),S.memoizedState=S.baseState=y,N={pending:null,lanes:0,dispatch:null,lastRenderedReducer:H7,lastRenderedState:y},S.queue=N,S=hF.bind(null,De,N),N.dispatch=S,N=_T(!1);var $=vT.bind(null,De,!1,N.queue);return N=or(),O={state:y,dispatch:null,action:m,pending:null},N.queue=O,S=Hlt.bind(null,De,O,$,S),O.dispatch=S,N.memoizedState=m,[y,S,!1]}function q7(m){var y=Qn();return Z7(y,wn,m)}function Z7(m,y,S){if(y=My(m,y,H7)[0],m=Uf(Vs)[0],typeof y=="object"&&y!==null&&typeof y.then=="function")try{var N=ah(y)}catch(K){throw K===Uy?mx:K}else N=y;y=Qn();var O=y.queue,$=O.dispatch;return S!==y.memoizedState&&(De.flags|=2048,Vf(9,X0(),Wlt.bind(null,O,S),null)),[N,$,m]}function Wlt(m,y){m.action=y}function K7(m){var y=Qn(),S=wn;if(S!==null)return Z7(y,S,m);Qn(),y=y.memoizedState,S=Qn();var N=S.queue.dispatch;return S.memoizedState=m,[y,N,!1]}function Vf(m,y,S,N){return m={tag:m,create:S,deps:N,inst:y,next:null},y=De.updateQueue,y===null&&(y=ky(),De.updateQueue=y),S=y.lastEffect,S===null?y.lastEffect=m.next=m:(N=S.next,S.next=m,m.next=N,y.lastEffect=m),m}function X0(){return{destroy:void 0,resource:void 0}}function J7(){return Qn().memoizedState}function U0(m,y,S,N){var O=or();N=N===void 0?null:N,De.flags|=m,O.memoizedState=Vf(1|y,X0(),S,N)}function Cy(m,y,S,N){var O=Qn();N=N===void 0?null:N;var $=O.memoizedState.inst;wn!==null&&N!==null&&sh(N,wn.memoizedState.deps)?O.memoizedState=Vf(y,$,S,N):(De.flags|=m,O.memoizedState=Vf(1|y,$,S,N))}function Q7(m,y){U0(8390656,8,m,y)}function tF(m,y){Cy(2048,8,m,y)}function eF(m,y){return Cy(4,2,m,y)}function nF(m,y){return Cy(4,4,m,y)}function iF(m,y){if(typeof y=="function"){m=m();var S=y(m);return function(){typeof S=="function"?S():y(null)}}if(y!=null)return m=m(),y.current=m,function(){y.current=null}}function rF(m,y,S){S=S!=null?S.concat([m]):null,Cy(4,4,iF.bind(null,y,m),S)}function gT(){}function sF(m,y){var S=Qn();y=y===void 0?null:y;var N=S.memoizedState;return y!==null&&sh(y,N[1])?N[0]:(S.memoizedState=[m,y],m)}function oF(m,y){var S=Qn();y=y===void 0?null:y;var N=S.memoizedState;if(y!==null&&sh(y,N[1]))return N[0];if(N=m(),gh){j(!0);try{m()}finally{j(!1)}}return S.memoizedState=[N,y],N}function xT(m,y,S){return S===void 0||(Mc&1073741824)!==0?m.memoizedState=y:(m.memoizedState=S,m=iz(),De.lanes|=m,Cc|=m,S)}function aF(m,y,S,N){return ns(S,y)?S:lm.current!==null?(m=xT(m,S,N),ns(m,y)||(Ni=!0),m):(Mc&42)===0?(Ni=!0,m.memoizedState=S):(m=iz(),De.lanes|=m,Cc|=m,y)}function cF(m,y,S,N,O){var $=pa();Ii($!==0&&8>$?$:8);var K=_e.T,ct={};_e.T=ct,vT(m,!1,y,S);try{var xt=O(),It=_e.S;if(It!==null&&It(ct,xt),xt!==null&&typeof xt=="object"&&typeof xt.then=="function"){var $t=vy(xt,N);Iy(m,y,$t,Kr(m))}else Iy(m,y,N,Kr(m))}catch(Xt){Iy(m,y,{then:function(){},status:"rejected",reason:Xt},Kr())}finally{Ii($),_e.T=K}}function lF(m){var y=m.memoizedState;if(y!==null)return y;y={memoizedState:Kf,baseState:Kf,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Vs,lastRenderedState:Kf},next:null};var S={};return y.next={memoizedState:S,baseState:S,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Vs,lastRenderedState:S},next:null},m.memoizedState=y,m=m.alternate,m!==null&&(m.memoizedState=y),y}function bT(){return Jt(dh)}function uF(){return Qn().memoizedState}function pF(){return Qn().memoizedState}function qlt(m){for(var y=m.return;y!==null;){switch(y.tag){case 24:case 3:var S=Kr();m=ds(S);var N=fs(y,m,S);N!==null&&(Jr(N,y,S),ra(N,y,S)),y={cache:Cr()},m.payload=y;return}y=y.return}}function Zlt(m,y,S){var N=Kr();S={lane:N,revertLane:0,action:S,hasEagerState:!1,eagerState:null,next:null},V0(m)?dF(y,S):(S=Qp(m,y,S,N),S!==null&&(Jr(S,m,N),fF(S,y,N)))}function hF(m,y,S){var N=Kr();Iy(m,y,S,N)}function Iy(m,y,S,N){var O={lane:N,revertLane:0,action:S,hasEagerState:!1,eagerState:null,next:null};if(V0(m))dF(y,O);else{var $=m.alternate;if(m.lanes===0&&($===null||$.lanes===0)&&($=y.lastRenderedReducer,$!==null))try{var K=y.lastRenderedState,ct=$(K,S);if(O.hasEagerState=!0,O.eagerState=ct,ns(ct,K))return fc(m,y,O,0),Nn===null&&dc(),!1}catch{}finally{}if(S=Qp(m,y,O,N),S!==null)return Jr(S,m,N),fF(S,y,N),!0}return!1}function vT(m,y,S,N){if(N={lane:2,revertLane:Kp(),action:N,hasEagerState:!1,eagerState:null,next:null},V0(m)){if(y)throw Error(i(479))}else y=Qp(m,S,N,2),y!==null&&Jr(y,m,2)}function V0(m){var y=m.alternate;return m===De||y!==null&&y===De}function dF(m,y){um=gx=!0;var S=m.pending;S===null?y.next=y:(y.next=S.next,S.next=y),m.pending=y}function fF(m,y,S){if((S&4194048)!==0){var N=y.lanes;N&=m.pendingLanes,S|=N,y.lanes=S,A(m,S)}}function G0(m){var y=Gy;return Gy+=1,hm===null&&(hm=[]),Ff(hm,m,y)}function Ny(m,y){y=y.props.ref,m.ref=y!==void 0?y:null}function H0(m,y){throw y.$$typeof===fut?Error(i(525)):(m=Object.prototype.toString.call(y),Error(i(31,m==="[object Object]"?"object with keys {"+Object.keys(y).join(", ")+"}":m)))}function mF(m){var y=m._init;return y(m._payload)}function _F(m){function y(gt,dt){if(m){var vt=gt.deletions;vt===null?(gt.deletions=[dt],gt.flags|=16):vt.push(dt)}}function S(gt,dt){if(!m)return null;for(;dt!==null;)y(gt,dt),dt=dt.sibling;return null}function N(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=la(gt,dt),gt.index=0,gt.sibling=null,gt}function $(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,zt){return dt===null||dt.tag!==6?(dt=ZT(vt,gt.mode,zt),dt.return=gt,dt):(dt=O(dt,vt),dt.return=gt,dt)}function xt(gt,dt,vt,zt){var ce=vt.type;return ce===Zf?$t(gt,dt,vt.props.children,zt,vt.key):dt!==null&&(dt.elementType===ce||typeof ce=="object"&&ce!==null&&ce.$$typeof===wc&&mF(ce)===dt.type)?(dt=O(dt,vt.props),Ny(dt,vt),dt.return=gt,dt):(dt=nx(vt.type,vt.key,vt.props,null,gt.mode,zt),Ny(dt,vt),dt.return=gt,dt)}function It(gt,dt,vt,zt){return dt===null||dt.tag!==4||dt.stateNode.containerInfo!==vt.containerInfo||dt.stateNode.implementation!==vt.implementation?(dt=KT(vt,gt.mode,zt),dt.return=gt,dt):(dt=O(dt,vt.children||[]),dt.return=gt,dt)}function $t(gt,dt,vt,zt,ce){return dt===null||dt.tag!==7?(dt=ph(vt,gt.mode,zt,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=ZT(""+dt,gt.mode,vt),dt.return=gt,dt;if(typeof dt=="object"&&dt!==null){switch(dt.$$typeof){case ix:return vt=nx(dt.type,dt.key,dt.props,null,gt.mode,vt),Ny(vt,dt),vt.return=gt,vt;case qf:return dt=KT(dt,gt.mode,vt),dt.return=gt,dt;case wc:var zt=dt._init;return dt=zt(dt._payload),Xt(gt,dt,vt)}if(rx(dt)||l(dt))return dt=ph(dt,gt.mode,vt,null),dt.return=gt,dt;if(typeof dt.then=="function")return Xt(gt,G0(dt),vt);if(dt.$$typeof===Sc)return Xt(gt,Wn(gt,dt),vt);H0(gt,dt)}return null}function Wt(gt,dt,vt,zt){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,zt);if(typeof vt=="object"&&vt!==null){switch(vt.$$typeof){case ix:return vt.key===ce?xt(gt,dt,vt,zt):null;case qf:return vt.key===ce?It(gt,dt,vt,zt):null;case wc:return ce=vt._init,vt=ce(vt._payload),Wt(gt,dt,vt,zt)}if(rx(vt)||l(vt))return ce!==null?null:$t(gt,dt,vt,zt,null);if(typeof vt.then=="function")return Wt(gt,dt,G0(vt),zt);if(vt.$$typeof===Sc)return Wt(gt,dt,Wn(gt,vt),zt);H0(gt,vt)}return null}function Le(gt,dt,vt,zt,ce){if(typeof zt=="string"&&zt!==""||typeof zt=="number"||typeof zt=="bigint")return gt=gt.get(vt)||null,ct(dt,gt,""+zt,ce);if(typeof zt=="object"&&zt!==null){switch(zt.$$typeof){case ix:return gt=gt.get(zt.key===null?vt:zt.key)||null,xt(dt,gt,zt,ce);case qf:return gt=gt.get(zt.key===null?vt:zt.key)||null,It(dt,gt,zt,ce);case wc:var Fn=zt._init;return zt=Fn(zt._payload),Le(gt,dt,vt,zt,ce)}if(rx(zt)||l(zt))return gt=gt.get(vt)||null,$t(dt,gt,zt,ce,null);if(typeof zt.then=="function")return Le(gt,dt,vt,G0(zt),ce);if(zt.$$typeof===Sc)return Le(gt,dt,vt,Wn(dt,zt),ce);H0(dt,zt)}return null}function vs(gt,dt,vt,zt){for(var ce=null,Fn=null,ke=dt,sn=dt=0,Ri=null;ke!==null&&sn<vt.length;sn++){ke.index>sn?(Ri=ke,ke=null):Ri=ke.sibling;var on=Wt(gt,ke,vt[sn],zt);if(on===null){ke===null&&(ke=Ri);break}m&&ke&&on.alternate===null&&y(gt,ke),dt=$(on,dt,sn),Fn===null?ce=on:Fn.sibling=on,Fn=on,ke=Ri}if(sn===vt.length)return S(gt,ke),mn&&mt(gt,sn),ce;if(ke===null){for(;sn<vt.length;sn++)ke=Xt(gt,vt[sn],zt),ke!==null&&(dt=$(ke,dt,sn),Fn===null?ce=ke:Fn.sibling=ke,Fn=ke);return mn&&mt(gt,sn),ce}for(ke=N(ke);sn<vt.length;sn++)Ri=Le(ke,gt,sn,vt[sn],zt),Ri!==null&&(m&&Ri.alternate!==null&&ke.delete(Ri.key===null?sn:Ri.key),dt=$(Ri,dt,sn),Fn===null?ce=Ri:Fn.sibling=Ri,Fn=Ri);return m&&ke.forEach(function(Ac){return y(gt,Ac)}),mn&&mt(gt,sn),ce}function Ky(gt,dt,vt,zt){if(vt==null)throw Error(i(151));for(var ce=null,Fn=null,ke=dt,sn=dt=0,Ri=null,on=vt.next();ke!==null&&!on.done;sn++,on=vt.next()){ke.index>sn?(Ri=ke,ke=null):Ri=ke.sibling;var Ac=Wt(gt,ke,on.value,zt);if(Ac===null){ke===null&&(ke=Ri);break}m&&ke&&Ac.alternate===null&&y(gt,ke),dt=$(Ac,dt,sn),Fn===null?ce=Ac:Fn.sibling=Ac,Fn=Ac,ke=Ri}if(on.done)return S(gt,ke),mn&&mt(gt,sn),ce;if(ke===null){for(;!on.done;sn++,on=vt.next())on=Xt(gt,on.value,zt),on!==null&&(dt=$(on,dt,sn),Fn===null?ce=on:Fn.sibling=on,Fn=on);return mn&&mt(gt,sn),ce}for(ke=N(ke);!on.done;sn++,on=vt.next())on=Le(ke,gt,sn,on.value,zt),on!==null&&(m&&on.alternate!==null&&ke.delete(on.key===null?sn:on.key),dt=$(on,dt,sn),Fn===null?ce=on:Fn.sibling=on,Fn=on);return m&&ke.forEach(function(Zpt){return y(gt,Zpt)}),mn&&mt(gt,sn),ce}function bh(gt,dt,vt,zt){if(typeof vt=="object"&&vt!==null&&vt.type===Zf&&vt.key===null&&(vt=vt.props.children),typeof vt=="object"&&vt!==null){switch(vt.$$typeof){case ix:t:{for(var ce=vt.key;dt!==null;){if(dt.key===ce){if(ce=vt.type,ce===Zf){if(dt.tag===7){S(gt,dt.sibling),zt=O(dt,vt.props.children),zt.return=gt,gt=zt;break t}}else if(dt.elementType===ce||typeof ce=="object"&&ce!==null&&ce.$$typeof===wc&&mF(ce)===dt.type){S(gt,dt.sibling),zt=O(dt,vt.props),Ny(zt,vt),zt.return=gt,gt=zt;break t}S(gt,dt);break}else y(gt,dt);dt=dt.sibling}vt.type===Zf?(zt=ph(vt.props.children,gt.mode,zt,vt.key),zt.return=gt,gt=zt):(zt=nx(vt.type,vt.key,vt.props,null,gt.mode,zt),Ny(zt,vt),zt.return=gt,gt=zt)}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){S(gt,dt.sibling),zt=O(dt,vt.children||[]),zt.return=gt,gt=zt;break t}else{S(gt,dt);break}else y(gt,dt);dt=dt.sibling}zt=KT(vt,gt.mode,zt),zt.return=gt,gt=zt}return K(gt);case wc:return ce=vt._init,vt=ce(vt._payload),bh(gt,dt,vt,zt)}if(rx(vt))return vs(gt,dt,vt,zt);if(l(vt)){if(ce=l(vt),typeof ce!="function")throw Error(i(150));return vt=ce.call(vt),Ky(gt,dt,vt,zt)}if(typeof vt.then=="function")return bh(gt,dt,G0(vt),zt);if(vt.$$typeof===Sc)return bh(gt,dt,Wn(gt,vt),zt);H0(gt,vt)}return typeof vt=="string"&&vt!==""||typeof vt=="number"||typeof vt=="bigint"?(vt=""+vt,dt!==null&&dt.tag===6?(S(gt,dt.sibling),zt=O(dt,vt),zt.return=gt,gt=zt):(S(gt,dt),zt=ZT(vt,gt.mode,zt),zt.return=gt,gt=zt),K(gt)):S(gt,dt)}return function(gt,dt,vt,zt){try{Gy=0;var ce=bh(gt,dt,vt,zt);return hm=null,ce}catch(ke){if(ke===Uy||ke===mx)throw ke;var Fn=e(29,ke,null,gt.mode);return Fn.lanes=zt,Fn.return=gt,Fn}finally{}}}function _c(m){var y=m.alternate;_(wi,wi.current&1),_(xs,m),Mo===null&&(y===null||lm.current!==null||y.memoizedState!==null)&&(Mo=m)}function yF(m){if(m.tag===22){if(_(wi,wi.current),_(xs,m),Mo===null){var y=m.alternate;y!==null&&y.memoizedState!==null&&(Mo=m)}}else yc(m)}function yc(){_(wi,wi.current),_(xs,xs.current)}function aa(m){d(xs),Mo===m&&(Mo=null),d(wi)}function W0(m){for(var y=m;y!==null;){if(y.tag===13){var S=y.memoizedState;if(S!==null&&(S=S.dehydrated,S===null||a3(S)||c3(S)))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 ST(m,y,S,N){y=m.memoizedState,S=S(N,y),S=S==null?y:QT({},y,S),m.memoizedState=S,m.lanes===0&&(m.updateQueue.baseState=S)}function gF(m,y,S,N,O,$,K){return m=m.stateNode,typeof m.shouldComponentUpdate=="function"?m.shouldComponentUpdate(N,$,K):y.prototype&&y.prototype.isPureReactComponent?!pc(S,N)||!pc(O,$):!0}function xF(m,y,S,N){m=y.state,typeof y.componentWillReceiveProps=="function"&&y.componentWillReceiveProps(S,N),typeof y.UNSAFE_componentWillReceiveProps=="function"&&y.UNSAFE_componentWillReceiveProps(S,N),y.state!==m&&S3.enqueueReplaceState(y,y.state,null)}function ch(m,y){var S=y;if("ref"in y){S={};for(var N in y)N!=="ref"&&(S[N]=y[N])}if(m=m.defaultProps){S===y&&(S=QT({},S));for(var O in m)S[O]===void 0&&(S[O]=m[O])}return S}function q0(m,y){try{var S=m.onUncaughtError;S(y.value,{componentStack:y.stack})}catch(N){setTimeout(function(){throw N})}}function bF(m,y,S){try{var N=m.onCaughtError;N(S.value,{componentStack:S.stack,errorBoundary:y.tag===1?y.stateNode:null})}catch(O){setTimeout(function(){throw O})}}function wT(m,y,S){return S=ds(S),S.tag=3,S.payload={element:null},S.callback=function(){q0(m,y)},S}function vF(m){return m=ds(m),m.tag=3,m}function SF(m,y,S,N){var O=S.type.getDerivedStateFromError;if(typeof O=="function"){var $=N.value;m.payload=function(){return O($)},m.callback=function(){bF(y,S,N)}}var K=S.stateNode;K!==null&&typeof K.componentDidCatch=="function"&&(m.callback=function(){bF(y,S,N),typeof O!="function"&&(Ic===null?Ic=new Set([this]):Ic.add(this));var ct=N.stack;this.componentDidCatch(N.value,{componentStack:ct!==null?ct:""})})}function Klt(m,y,S,N,O){if(S.flags|=32768,N!==null&&typeof N=="object"&&typeof N.then=="function"){if(y=S.alternate,y!==null&&Se(y,S,O,!0),S=xs.current,S!==null){switch(S.tag){case 13:return Mo===null?GT():S.alternate===null&&ei===0&&(ei=3),S.flags&=-257,S.flags|=65536,S.lanes=O,N===_x?S.flags|=16384:(y=S.updateQueue,y===null?S.updateQueue=new Set([N]):y.add(N),WT(m,N,O)),!1;case 22:return S.flags|=65536,N===_x?S.flags|=16384:(y=S.updateQueue,y===null?(y={transitions:null,markerInstances:null,retryQueue:new Set([N])},S.updateQueue=y):(S=y.retryQueue,S===null?y.retryQueue=new Set([N]):S.add(N)),WT(m,N,O)),!1}throw Error(i(435,S.tag))}return WT(m,N,O),GT(),!1}if(mn)return y=xs.current,y!==null?((y.flags&65536)===0&&(y.flags|=256),y.flags|=65536,y.lanes=O,N!==m3&&(m=Error(i(422),{cause:N}),Z(tt(m,S)))):(N!==m3&&(y=Error(i(423),{cause:N}),Z(tt(y,S))),m=m.current.alternate,m.flags|=65536,O&=-O,m.lanes|=O,N=tt(N,S),O=wT(m.stateNode,N,O),nh(m,O),ei!==4&&(ei=2)),!1;var $=Error(i(520),{cause:N});if($=tt($,S),Wy===null?Wy=[$]:Wy.push($),ei!==4&&(ei=2),y===null)return!0;N=tt(N,S),S=y;do{switch(S.tag){case 3:return S.flags|=65536,m=O&-O,S.lanes|=m,m=wT(S.stateNode,N,m),nh(S,m),!1;case 1:if(y=S.type,$=S.stateNode,(S.flags&128)===0&&(typeof y.getDerivedStateFromError=="function"||$!==null&&typeof $.componentDidCatch=="function"&&(Ic===null||!Ic.has($))))return S.flags|=65536,O&=-O,S.lanes|=O,O=vF(O),SF(O,m,S,N),nh(S,O),!1}S=S.return}while(S!==null);return!1}function Wi(m,y,S,N){y.child=m===null?o$(y,null,S,N):dm(y,m.child,S,N)}function wF(m,y,S,N,O){S=S.render;var $=y.ref;if("ref"in N){var K={};for(var ct in N)ct!=="ref"&&(K[ct]=N[ct])}else K=N;return le(y),N=oh(m,y,S,K,$,O),ct=Sy(),m!==null&&!Ni?(wy(m,y,O),ca(m,y,O)):(mn&&ct&&Q(y),y.flags|=1,Wi(m,y,N,O),y.child)}function PF(m,y,S,N,O){if(m===null){var $=S.type;return typeof $=="function"&&!qT($)&&$.defaultProps===void 0&&S.compare===null?(y.tag=15,y.type=$,kF(m,y,$,N,O)):(m=nx(S.type,null,N,y,y.mode,O),m.ref=y.ref,m.return=y,y.child=m)}if($=m.child,!IT(m,O)){var K=$.memoizedProps;if(S=S.compare,S=S!==null?S:pc,S(K,N)&&m.ref===y.ref)return ca(m,y,O)}return y.flags|=1,m=la($,N),m.ref=y.ref,m.return=y,y.child=m}function kF(m,y,S,N,O){if(m!==null){var $=m.memoizedProps;if(pc($,N)&&m.ref===y.ref)if(Ni=!1,y.pendingProps=N=$,IT(m,O))(m.flags&131072)!==0&&(Ni=!0);else return y.lanes=m.lanes,ca(m,y,O)}return PT(m,y,S,N,O)}function TF(m,y,S){var N=y.pendingProps,O=N.children,$=m!==null?m.memoizedState:null;if(N.mode==="hidden"){if((y.flags&128)!==0){if(N=$!==null?$.baseLanes|S:S,m!==null){for(O=y.child=m.child,$=0;O!==null;)$=$|O.lanes|O.childLanes,O=O.sibling;y.childLanes=$&~N}else y.childLanes=0,y.child=null;return MF(m,y,N,S)}if((S&536870912)!==0)y.memoizedState={baseLanes:0,cachePool:null},m!==null&&uc(y,$!==null?$.cachePool:null),$!==null?Yf(y,$):ih(),yF(y);else return y.lanes=y.childLanes=536870912,MF(m,y,$!==null?$.baseLanes|S:S,S)}else $!==null?(uc(y,$.cachePool),Yf(y,$),yc(y),y.memoizedState=null):(m!==null&&uc(y,null),ih(),yc(y));return Wi(m,y,O,S),y.child}function MF(m,y,S,N){var O=Jp();return O=O===null?null:{parent:ua?ti._currentValue:ti._currentValue2,pool:O},y.memoizedState={baseLanes:S,cachePool:O},m!==null&&uc(y,null),ih(),yF(y),m!==null&&Se(m,y,N,!0),null}function Z0(m,y){var S=y.ref;if(S===null)m!==null&&m.ref!==null&&(y.flags|=4194816);else{if(typeof S!="function"&&typeof S!="object")throw Error(i(284));(m===null||m.ref!==S)&&(y.flags|=4194816)}}function PT(m,y,S,N,O){return le(y),S=oh(m,y,S,N,void 0,O),N=Sy(),m!==null&&!Ni?(wy(m,y,O),ca(m,y,O)):(mn&&N&&Q(y),y.flags|=1,Wi(m,y,S,O),y.child)}function EF(m,y,S,N,O,$){return le(y),y.updateQueue=null,S=Y0(y,N,S,O),B0(m),N=Sy(),m!==null&&!Ni?(wy(m,y,$),ca(m,y,$)):(mn&&N&&Q(y),y.flags|=1,Wi(m,y,S,$),y.child)}function CF(m,y,S,N,O){if(le(y),y.stateNode===null){var $=tm,K=S.contextType;typeof K=="object"&&K!==null&&($=Jt(K)),$=new S(N,$),y.memoizedState=$.state!==null&&$.state!==void 0?$.state:null,$.updater=S3,y.stateNode=$,$._reactInternals=y,$=y.stateNode,$.props=N,$.state=y.memoizedState,$.refs={},th(y),K=S.contextType,$.context=typeof K=="object"&&K!==null?Jt(K):tm,$.state=y.memoizedState,K=S.getDerivedStateFromProps,typeof K=="function"&&(ST(y,S,K,N),$.state=y.memoizedState),typeof S.getDerivedStateFromProps=="function"||typeof $.getSnapshotBeforeUpdate=="function"||typeof $.UNSAFE_componentWillMount!="function"&&typeof $.componentWillMount!="function"||(K=$.state,typeof $.componentWillMount=="function"&&$.componentWillMount(),typeof $.UNSAFE_componentWillMount=="function"&&$.UNSAFE_componentWillMount(),K!==$.state&&S3.enqueueReplaceState($,$.state,null),oa(y,N,$,O),sa(),$.state=y.memoizedState),typeof $.componentDidMount=="function"&&(y.flags|=4194308),N=!0}else if(m===null){$=y.stateNode;var ct=y.memoizedProps,xt=ch(S,ct);$.props=xt;var It=$.context,$t=S.contextType;K=tm,typeof $t=="object"&&$t!==null&&(K=Jt($t));var Xt=S.getDerivedStateFromProps;$t=typeof Xt=="function"||typeof $.getSnapshotBeforeUpdate=="function",ct=y.pendingProps!==ct,$t||typeof $.UNSAFE_componentWillReceiveProps!="function"&&typeof $.componentWillReceiveProps!="function"||(ct||It!==K)&&xF(y,$,N,K),Tc=!1;var Wt=y.memoizedState;$.state=Wt,oa(y,N,$,O),sa(),It=y.memoizedState,ct||Wt!==It||Tc?(typeof Xt=="function"&&(ST(y,S,Xt,N),It=y.memoizedState),(xt=Tc||gF(y,S,xt,N,Wt,It,K))?($t||typeof $.UNSAFE_componentWillMount!="function"&&typeof $.componentWillMount!="function"||(typeof $.componentWillMount=="function"&&$.componentWillMount(),typeof $.UNSAFE_componentWillMount=="function"&&$.UNSAFE_componentWillMount()),typeof $.componentDidMount=="function"&&(y.flags|=4194308)):(typeof $.componentDidMount=="function"&&(y.flags|=4194308),y.memoizedProps=N,y.memoizedState=It),$.props=N,$.state=It,$.context=K,N=xt):(typeof $.componentDidMount=="function"&&(y.flags|=4194308),N=!1)}else{$=y.stateNode,eh(m,y),K=y.memoizedProps,$t=ch(S,K),$.props=$t,Xt=y.pendingProps,Wt=$.context,It=S.contextType,xt=tm,typeof It=="object"&&It!==null&&(xt=Jt(It)),ct=S.getDerivedStateFromProps,(It=typeof ct=="function"||typeof $.getSnapshotBeforeUpdate=="function")||typeof $.UNSAFE_componentWillReceiveProps!="function"&&typeof $.componentWillReceiveProps!="function"||(K!==Xt||Wt!==xt)&&xF(y,$,N,xt),Tc=!1,Wt=y.memoizedState,$.state=Wt,oa(y,N,$,O),sa();var Le=y.memoizedState;K!==Xt||Wt!==Le||Tc||m!==null&&m.dependencies!==null&&Kt(m.dependencies)?(typeof ct=="function"&&(ST(y,S,ct,N),Le=y.memoizedState),($t=Tc||gF(y,S,$t,N,Wt,Le,xt)||m!==null&&m.dependencies!==null&&Kt(m.dependencies))?(It||typeof $.UNSAFE_componentWillUpdate!="function"&&typeof $.componentWillUpdate!="function"||(typeof $.componentWillUpdate=="function"&&$.componentWillUpdate(N,Le,xt),typeof $.UNSAFE_componentWillUpdate=="function"&&$.UNSAFE_componentWillUpdate(N,Le,xt)),typeof $.componentDidUpdate=="function"&&(y.flags|=4),typeof $.getSnapshotBeforeUpdate=="function"&&(y.flags|=1024)):(typeof $.componentDidUpdate!="function"||K===m.memoizedProps&&Wt===m.memoizedState||(y.flags|=4),typeof $.getSnapshotBeforeUpdate!="function"||K===m.memoizedProps&&Wt===m.memoizedState||(y.flags|=1024),y.memoizedProps=N,y.memoizedState=Le),$.props=N,$.state=Le,$.context=xt,N=$t):(typeof $.componentDidUpdate!="function"||K===m.memoizedProps&&Wt===m.memoizedState||(y.flags|=4),typeof $.getSnapshotBeforeUpdate!="function"||K===m.memoizedProps&&Wt===m.memoizedState||(y.flags|=1024),N=!1)}return $=N,Z0(m,y),N=(y.flags&128)!==0,$||N?($=y.stateNode,S=N&&typeof S.getDerivedStateFromError!="function"?null:$.render(),y.flags|=1,m!==null&&N?(y.child=dm(y,m.child,null,O),y.child=dm(y,null,S,O)):Wi(m,y,S,O),y.memoizedState=$.state,m=y.child):m=ca(m,y,O),m}function IF(m,y,S,N){return ut(),y.flags|=256,Wi(m,y,S,N),y.child}function kT(m){return{baseLanes:m,cachePool:Of()}}function TT(m,y,S){return m=m!==null?m.childLanes&~S:0,y&&(m|=bs),m}function NF(m,y,S){var N=y.pendingProps,O=!1,$=(y.flags&128)!==0,K;if((K=$)||(K=m!==null&&m.memoizedState===null?!1:(wi.current&2)!==0),K&&(O=!0,y.flags&=-129),K=(y.flags&32)!==0,y.flags&=-33,m===null){if(mn){if(O?_c(y):yc(y),mn){var ct=Si,xt;(xt=ct)&&(ct=ypt(ct,To),ct!==null?(y.memoizedState={dehydrated:ct,treeContext:fh!==null?{id:ha,overflow:da}:null,retryLane:536870912,hydrationErrors:null},xt=e(18,null,null,0),xt.stateNode=ct,xt.return=y,y.child=xt,vr=y,Si=null,xt=!0):xt=!1),xt||ot(y)}if(ct=y.memoizedState,ct!==null&&(ct=ct.dehydrated,ct!==null))return c3(ct)?y.lanes=32:y.lanes=536870912,null;aa(y)}return ct=N.children,N=N.fallback,O?(yc(y),O=y.mode,ct=K0({mode:"hidden",children:ct},O),N=ph(N,O,S,null),ct.return=y,N.return=y,ct.sibling=N,y.child=ct,O=y.child,O.memoizedState=kT(S),O.childLanes=TT(m,K,S),y.memoizedState=w3,N):(_c(y),MT(y,ct))}if(xt=m.memoizedState,xt!==null&&(ct=xt.dehydrated,ct!==null)){if($)y.flags&256?(_c(y),y.flags&=-257,y=ET(m,y,S)):y.memoizedState!==null?(yc(y),y.child=m.child,y.flags|=128,y=null):(yc(y),O=N.fallback,ct=y.mode,N=K0({mode:"visible",children:N.children},ct),O=ph(O,ct,S,null),O.flags|=2,N.return=y,O.return=y,N.sibling=O,y.child=N,dm(y,m.child,null,S),N=y.child,N.memoizedState=kT(S),N.childLanes=TT(m,K,S),y.memoizedState=w3,y=O);else if(_c(y),c3(ct))K=opt(ct).digest,N=Error(i(419)),N.stack="",N.digest=K,Z({value:N,source:null,stack:null}),y=ET(m,y,S);else if(Ni||Se(m,y,S,!1),K=(S&m.childLanes)!==0,Ni||K){if(K=Nn,K!==null&&(N=S&-S,N=(N&42)!==0?1:R(N),N=(N&(K.suspendedLanes|S))!==0?0:N,N!==0&&N!==xt.retryLane))throw xt.retryLane=N,wo(m,N),Jr(K,m,N),c$;a3(ct)||GT(),y=ET(m,y,S)}else a3(ct)?(y.flags|=192,y.child=m.child,y=null):(m=xt.treeContext,ms&&(Si=dpt(ct),vr=y,mn=!0,mh=null,To=!1,m!==null&&(_s[ys++]=ha,_s[ys++]=da,_s[ys++]=fh,ha=m.id,da=m.overflow,fh=y)),y=MT(y,N.children),y.flags|=4096);return y}return O?(yc(y),O=N.fallback,ct=y.mode,xt=m.child,$=xt.sibling,N=la(xt,{mode:"hidden",children:N.children}),N.subtreeFlags=xt.subtreeFlags&65011712,$!==null?O=la($,O):(O=ph(O,ct,S,null),O.flags|=2),O.return=y,N.return=y,N.sibling=O,y.child=N,N=O,O=y.child,ct=m.child.memoizedState,ct===null?ct=kT(S):(xt=ct.cachePool,xt!==null?($=ua?ti._currentValue:ti._currentValue2,xt=xt.parent!==$?{parent:$,pool:$}:xt):xt=Of(),ct={baseLanes:ct.baseLanes|S,cachePool:xt}),O.memoizedState=ct,O.childLanes=TT(m,K,S),y.memoizedState=w3,N):(_c(y),S=m.child,m=S.sibling,S=la(S,{mode:"visible",children:N.children}),S.return=y,S.sibling=null,m!==null&&(K=y.deletions,K===null?(y.deletions=[m],y.flags|=16):K.push(m)),y.child=S,y.memoizedState=null,S)}function MT(m,y){return y=K0({mode:"visible",children:y},m.mode),y.return=m,m.child=y}function K0(m,y){return m=e(22,m,null,y),m.lanes=0,m.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null},m}function ET(m,y,S){return dm(y,m.child,null,S),m=MT(y,y.pendingProps.children),m.flags|=2,y.memoizedState=null,m}function AF(m,y,S){m.lanes|=y;var N=m.alternate;N!==null&&(N.lanes|=y),Ot(m.return,y,S)}function CT(m,y,S,N,O){var $=m.memoizedState;$===null?m.memoizedState={isBackwards:y,rendering:null,renderingStartTime:0,last:N,tail:S,tailMode:O}:($.isBackwards=y,$.rendering=null,$.renderingStartTime=0,$.last=N,$.tail=S,$.tailMode=O)}function RF(m,y,S){var N=y.pendingProps,O=N.revealOrder,$=N.tail;if(Wi(m,y,N.children,S),N=wi.current,(N&2)!==0)N=N&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&&AF(m,S,y);else if(m.tag===19)AF(m,S,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}N&=1}switch(_(wi,N),O){case"forwards":for(S=y.child,O=null;S!==null;)m=S.alternate,m!==null&&W0(m)===null&&(O=S),S=S.sibling;S=O,S===null?(O=y.child,y.child=null):(O=S.sibling,S.sibling=null),CT(y,!1,O,S,$);break;case"backwards":for(S=null,O=y.child,y.child=null;O!==null;){if(m=O.alternate,m!==null&&W0(m)===null){y.child=O;break}m=O.sibling,O.sibling=S,S=O,O=m}CT(y,!0,S,null,$);break;case"together":CT(y,!1,null,null,void 0);break;default:y.memoizedState=null}return y.child}function ca(m,y,S){if(m!==null&&(y.dependencies=m.dependencies),Cc|=y.lanes,(S&y.childLanes)===0)if(m!==null){if(Se(m,y,S,!1),(S&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,S=la(m,m.pendingProps),y.child=S,S.return=y;m.sibling!==null;)m=m.sibling,S=S.sibling=la(m,m.pendingProps),S.return=y;S.sibling=null}return y.child}function IT(m,y){return(m.lanes&y)!==0?!0:(m=m.dependencies,!!(m!==null&&Kt(m)))}function Jlt(m,y,S){switch(y.tag){case 3:pt(y,y.stateNode.containerInfo),Mt(y,ti,m.memoizedState.cache),ut();break;case 27:case 5:wt(y);break;case 4:pt(y,y.stateNode.containerInfo);break;case 10:Mt(y,y.type,y.memoizedProps.value);break;case 13:var N=y.memoizedState;if(N!==null)return N.dehydrated!==null?(_c(y),y.flags|=128,null):(S&y.child.childLanes)!==0?NF(m,y,S):(_c(y),m=ca(m,y,S),m!==null?m.sibling:null);_c(y);break;case 19:var O=(m.flags&128)!==0;if(N=(S&y.childLanes)!==0,N||(Se(m,y,S,!1),N=(S&y.childLanes)!==0),O){if(N)return RF(m,y,S);y.flags|=128}if(O=y.memoizedState,O!==null&&(O.rendering=null,O.tail=null,O.lastEffect=null),_(wi,wi.current),N)break;return null;case 22:case 23:return y.lanes=0,TF(m,y,S);case 24:Mt(y,ti,m.memoizedState.cache)}return ca(m,y,S)}function OF(m,y,S){if(m!==null)if(m.memoizedProps!==y.pendingProps)Ni=!0;else{if(!IT(m,S)&&(y.flags&128)===0)return Ni=!1,Jlt(m,y,S);Ni=(m.flags&131072)!==0}else Ni=!1,mn&&(y.flags&1048576)!==0&&G(y,ux,y.index);switch(y.lanes=0,y.tag){case 16:t:{m=y.pendingProps;var N=y.elementType,O=N._init;if(N=O(N._payload),y.type=N,typeof N=="function")qT(N)?(m=ch(N,m),y.tag=1,y=CF(null,y,N,m,S)):(y.tag=0,y=PT(null,y,N,m,S));else{if(N!=null){if(O=N.$$typeof,O===e3){y.tag=11,y=wF(null,y,N,m,S);break t}else if(O===r3){y.tag=14,y=PF(null,y,N,m,S);break t}}throw y=u(N)||N,Error(i(306,y,""))}}return y;case 0:return PT(m,y,y.type,y.pendingProps,S);case 1:return N=y.type,O=ch(N,y.pendingProps),CF(m,y,N,O,S);case 3:t:{if(pt(y,y.stateNode.containerInfo),m===null)throw Error(i(387));var $=y.pendingProps;O=y.memoizedState,N=O.element,eh(m,y),oa(y,$,null,S);var K=y.memoizedState;if($=K.cache,Mt(y,ti,$),$!==O.cache&&Ce(y,[ti],S,!0),sa(),$=K.element,ms&&O.isDehydrated)if(O={element:$,isDehydrated:!1,cache:K.cache},y.updateQueue.baseState=O,y.memoizedState=O,y.flags&256){y=IF(m,y,$,S);break t}else if($!==N){N=tt(Error(i(424)),y),Z(N),y=IF(m,y,$,S);break t}else for(ms&&(Si=hpt(y.stateNode.containerInfo),vr=y,mn=!0,mh=null,To=!0),S=o$(y,null,$,S),y.child=S;S;)S.flags=S.flags&-3|4096,S=S.sibling;else{if(ut(),$===N){y=ca(m,y,S);break t}Wi(m,y,$,S)}y=y.child}return y;case 26:if(Hs)return Z0(m,y),m===null?(S=Vz(y.type,null,y.pendingProps,null))?y.memoizedState=S:mn||(y.stateNode=Cpt(y.type,y.pendingProps,kc.current,y)):y.memoizedState=Vz(y.type,m.memoizedProps,y.pendingProps,m.memoizedState),null;case 27:if(vi)return wt(y),m===null&&vi&&mn&&(N=y.stateNode=Kz(y.type,y.pendingProps,kc.current,qi.current,!1),vr=y,To=!0,Si=fpt(y.type,N,Si)),Wi(m,y,y.pendingProps.children,S),Z0(m,y),m===null&&(y.flags|=4194304),y.child;case 5:return m===null&&mn&&(Tpt(y.type,y.pendingProps,qi.current),(O=N=Si)&&(N=mpt(N,y.type,y.pendingProps,To),N!==null?(y.stateNode=N,vr=y,Si=ppt(N),To=!1,O=!0):O=!1),O||ot(y)),wt(y),O=y.type,$=y.pendingProps,K=m!==null?m.memoizedProps:null,N=$.children,sx(O,$)?N=null:K!==null&&sx(O,K)&&(y.flags|=32),y.memoizedState!==null&&(O=oh(m,y,mT,null,null,S),ua?dh._currentValue=O:dh._currentValue2=O),Z0(m,y),Wi(m,y,N,S),y.child;case 6:return m===null&&mn&&(Mpt(y.pendingProps,qi.current),(m=S=Si)&&(S=_pt(S,y.pendingProps,To),S!==null?(y.stateNode=S,vr=y,Si=null,m=!0):m=!1),m||ot(y)),null;case 13:return NF(m,y,S);case 4:return pt(y,y.stateNode.containerInfo),N=y.pendingProps,m===null?y.child=dm(y,null,N,S):Wi(m,y,N,S),y.child;case 11:return wF(m,y,y.type,y.pendingProps,S);case 7:return Wi(m,y,y.pendingProps,S),y.child;case 8:return Wi(m,y,y.pendingProps.children,S),y.child;case 12:return Wi(m,y,y.pendingProps.children,S),y.child;case 10:return N=y.pendingProps,Mt(y,y.type,N.value),Wi(m,y,N.children,S),y.child;case 9:return O=y.type._context,N=y.pendingProps.children,le(y),O=Jt(O),N=N(O),y.flags|=1,Wi(m,y,N,S),y.child;case 14:return PF(m,y,y.type,y.pendingProps,S);case 15:return kF(m,y,y.type,y.pendingProps,S);case 19:return RF(m,y,S);case 31:return N=y.pendingProps,S=y.mode,N={mode:N.mode,children:N.children},m===null?(S=K0(N,S),S.ref=y.ref,y.child=S,S.return=y,y=S):(S=la(m.child,N),S.ref=y.ref,y.child=S,S.return=y,y=S),y;case 22:return TF(m,y,S);case 24:return le(y),N=Jt(ti),m===null?(O=Jp(),O===null&&(O=Nn,$=Cr(),O.pooledCache=$,$.refCount++,$!==null&&(O.pooledCacheLanes|=S),O=$),y.memoizedState={parent:N,cache:O},th(y),Mt(y,ti,O)):((m.lanes&S)!==0&&(eh(m,y),oa(y,null,null,S),sa()),O=m.memoizedState,$=y.memoizedState,O.parent!==N?(O={parent:N,cache:N},y.memoizedState=O,y.lanes===0&&(y.memoizedState=y.updateQueue.baseState=O),Mt(y,ti,N)):(N=$.cache,Mt(y,ti,N),N!==O.cache&&Ce(y,[ti],S,!0))),Wi(m,y,y.pendingProps.children,S),y.child;case 29:throw y.pendingProps}throw Error(i(156,y.tag))}function Zr(m){m.flags|=4}function LF(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 NT(m,y,S,N){if(ar)for(S=y.child;S!==null;){if(S.tag===5||S.tag===6)o3(m,S.stateNode);else if(!(S.tag===4||vi&&S.tag===27)&&S.child!==null){S.child.return=S,S=S.child;continue}if(S===y)break;for(;S.sibling===null;){if(S.return===null||S.return===y)return;S=S.return}S.sibling.return=S.return,S=S.sibling}else if(Pc)for(var O=y.child;O!==null;){if(O.tag===5){var $=O.stateNode;S&&N&&($=jz($,O.type,O.memoizedProps)),o3(m,$)}else if(O.tag===6)$=O.stateNode,S&&N&&($=Bz($,O.memoizedProps)),o3(m,$);else if(O.tag!==4){if(O.tag===22&&O.memoizedState!==null)$=O.child,$!==null&&($.return=O),NT(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 FF(m,y,S,N){var O=!1;if(Pc)for(var $=y.child;$!==null;){if($.tag===5){var K=$.stateNode;S&&N&&(K=jz(K,$.type,$.memoizedProps)),$z(m,K)}else if($.tag===6)K=$.stateNode,S&&N&&(K=Bz(K,$.memoizedProps)),$z(m,K);else if($.tag!==4){if($.tag===22&&$.memoizedState!==null)O=$.child,O!==null&&(O.return=$),FF(m,$,!0,!0),O=!0;else if($.child!==null){$.child.return=$,$=$.child;continue}}if($===y)break;for(;$.sibling===null;){if($.return===null||$.return===y)return O;$=$.return}$.sibling.return=$.return,$=$.sibling}return O}function zF(m,y){if(Pc&&LF(m,y)){m=y.stateNode;var S=m.containerInfo,N=zz();FF(N,y,!1,!1),m.pendingChildren=N,Zr(y),spt(S,N)}}function AT(m,y,S,N){if(ar)m.memoizedProps!==N&&Zr(y);else if(Pc){var O=m.stateNode,$=m.memoizedProps;if((m=LF(m,y))||$!==N){var K=qi.current;$=rpt(O,S,$,N,!m,null),$===O?y.stateNode=O:(Az($,S,N,K)&&Zr(y),y.stateNode=$,m?NT($,y,!1,!1):Zr(y))}else y.stateNode=O}}function RT(m,y,S){if(Aut(y,S)){if(m.flags|=16777216,!Oz(y,S))if(cz())m.flags|=8192;else throw am=_x,x3}else m.flags&=-16777217}function $F(m,y){if(Npt(y)){if(m.flags|=16777216,!Zz(y))if(cz())m.flags|=8192;else throw am=_x,x3}else m.flags&=-16777217}function J0(m,y){y!==null&&(m.flags|=4),m.flags&16384&&(y=m.tag!==22?k():536870912,m.lanes|=y,_m|=y)}function Ay(m,y){if(!mn)switch(m.tailMode){case"hidden":y=m.tail;for(var S=null;y!==null;)y.alternate!==null&&(S=y),y=y.sibling;S===null?m.tail=null:S.sibling=null;break;case"collapsed":S=m.tail;for(var N=null;S!==null;)S.alternate!==null&&(N=S),S=S.sibling;N===null?y||m.tail===null?m.tail=null:m.tail.sibling=null:N.sibling=null}}function qn(m){var y=m.alternate!==null&&m.alternate.child===m.child,S=0,N=0;if(y)for(var O=m.child;O!==null;)S|=O.lanes|O.childLanes,N|=O.subtreeFlags&65011712,N|=O.flags&65011712,O.return=m,O=O.sibling;else for(O=m.child;O!==null;)S|=O.lanes|O.childLanes,N|=O.subtreeFlags,N|=O.flags,O.return=m,O=O.sibling;return m.subtreeFlags|=N,m.childLanes=S,y}function Qlt(m,y,S){var N=y.pendingProps;switch(nt(y),y.tag){case 31:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return qn(y),null;case 1:return qn(y),null;case 3:return S=y.stateNode,N=null,m!==null&&(N=m.memoizedState.cache),y.memoizedState.cache!==N&&(y.flags|=2048),Ft(ti),ht(),S.pendingContext&&(S.context=S.pendingContext,S.pendingContext=null),(m===null||m.child===null)&&(rt(y)?Zr(y):m===null||m.memoizedState.isDehydrated&&(y.flags&256)===0||(y.flags|=1024,yt())),zF(m,y),qn(y),null;case 26:if(Hs){S=y.type;var O=y.memoizedState;return m===null?(Zr(y),O!==null?(qn(y),$F(y,O)):(qn(y),RT(y,S,N))):O?O!==m.memoizedState?(Zr(y),qn(y),$F(y,O)):(qn(y),y.flags&=-16777217):(ar?m.memoizedProps!==N&&Zr(y):AT(m,y,S,N),qn(y),RT(y,S,N)),null}case 27:if(vi){if(Et(y),S=kc.current,O=y.type,m!==null&&y.stateNode!=null)ar?m.memoizedProps!==N&&Zr(y):AT(m,y,O,N);else{if(!N){if(y.stateNode===null)throw Error(i(166));return qn(y),null}m=qi.current,rt(y)?X(y,m):(m=Kz(O,N,S,m,!0),y.stateNode=m,Zr(y))}return qn(y),null}case 5:if(Et(y),S=y.type,m!==null&&y.stateNode!=null)AT(m,y,S,N);else{if(!N){if(y.stateNode===null)throw Error(i(166));return qn(y),null}m=qi.current,rt(y)?X(y,m):(O=Put(S,N,kc.current,m,y),NT(O,y,!1,!1),y.stateNode=O,Az(O,S,N,m)&&Zr(y))}return qn(y),RT(y,y.type,y.pendingProps),null;case 6:if(m&&y.stateNode!=null)S=m.memoizedProps,ar?S!==N&&Zr(y):Pc&&(S!==N?(y.stateNode=Rz(N,kc.current,qi.current,y),Zr(y)):y.stateNode=m.stateNode);else{if(typeof N!="string"&&y.stateNode===null)throw Error(i(166));if(m=kc.current,S=qi.current,rt(y)){if(!ms)throw Error(i(176));if(m=y.stateNode,S=y.memoizedProps,N=null,O=vr,O!==null)switch(O.tag){case 27:case 5:N=O.memoizedProps}xpt(m,S,y,N)||ot(y)}else y.stateNode=Rz(N,m,S,y)}return qn(y),null;case 13:if(N=y.memoizedState,m===null||m.memoizedState!==null&&m.memoizedState.dehydrated!==null){if(O=rt(y),N!==null&&N.dehydrated!==null){if(m===null){if(!O)throw Error(i(318));if(!ms)throw Error(i(344));if(O=y.memoizedState,O=O!==null?O.dehydrated:null,!O)throw Error(i(317));bpt(O,y)}else ut(),(y.flags&128)===0&&(y.memoizedState=null),y.flags|=4;qn(y),O=!1}else O=yt(),m!==null&&m.memoizedState!==null&&(m.memoizedState.hydrationErrors=O),O=!0;if(!O)return y.flags&256?(aa(y),y):(aa(y),null)}if(aa(y),(y.flags&128)!==0)return y.lanes=S,y;if(S=N!==null,m=m!==null&&m.memoizedState!==null,S){N=y.child,O=null,N.alternate!==null&&N.alternate.memoizedState!==null&&N.alternate.memoizedState.cachePool!==null&&(O=N.alternate.memoizedState.cachePool.pool);var $=null;N.memoizedState!==null&&N.memoizedState.cachePool!==null&&($=N.memoizedState.cachePool.pool),$!==O&&(N.flags|=2048)}return S!==m&&S&&(y.child.flags|=8192),J0(y,y.updateQueue),qn(y),null;case 4:return ht(),zF(m,y),m===null&&Eut(y.stateNode.containerInfo),qn(y),null;case 10:return Ft(y.type),qn(y),null;case 19:if(d(wi),O=y.memoizedState,O===null)return qn(y),null;if(N=(y.flags&128)!==0,$=O.rendering,$===null)if(N)Ay(O,!1);else{if(ei!==0||m!==null&&(m.flags&128)!==0)for(m=y.child;m!==null;){if($=W0(m),$!==null){for(y.flags|=128,Ay(O,!1),m=$.updateQueue,y.updateQueue=m,J0(y,m),y.subtreeFlags=0,m=S,S=y.child;S!==null;)Sz(S,m),S=S.sibling;return _(wi,wi.current&1|2),y.child}m=m.sibling}O.tail!==null&&Ws()>qy&&(y.flags|=128,N=!0,Ay(O,!1),y.lanes=4194304)}else{if(!N)if(m=W0($),m!==null){if(y.flags|=128,N=!0,m=m.updateQueue,y.updateQueue=m,J0(y,m),Ay(O,!0),O.tail===null&&O.tailMode==="hidden"&&!$.alternate&&!mn)return qn(y),null}else 2*Ws()-O.renderingStartTime>qy&&S!==536870912&&(y.flags|=128,N=!0,Ay(O,!1),y.lanes=4194304);O.isBackwards?($.sibling=y.child,y.child=$):(m=O.last,m!==null?m.sibling=$:y.child=$,O.last=$)}return O.tail!==null?(y=O.tail,O.rendering=y,O.tail=y.sibling,O.renderingStartTime=Ws(),y.sibling=null,m=wi.current,_(wi,N?m&1|2:m&1),y):(qn(y),null);case 22:case 23:return aa(y),rh(),N=y.memoizedState!==null,m!==null?m.memoizedState!==null!==N&&(y.flags|=8192):N&&(y.flags|=8192),N?(S&536870912)!==0&&(y.flags&128)===0&&(qn(y),y.subtreeFlags&6&&(y.flags|=8192)):qn(y),S=y.updateQueue,S!==null&&J0(y,S.retryQueue),S=null,m!==null&&m.memoizedState!==null&&m.memoizedState.cachePool!==null&&(S=m.memoizedState.cachePool.pool),N=null,y.memoizedState!==null&&y.memoizedState.cachePool!==null&&(N=y.memoizedState.cachePool.pool),N!==S&&(y.flags|=2048),m!==null&&d(yh),null;case 24:return S=null,m!==null&&(S=m.memoizedState.cache),y.memoizedState.cache!==S&&(y.flags|=2048),Ft(ti),qn(y),null;case 25:return null;case 30:return null}throw Error(i(156,y.tag))}function tut(m,y){switch(nt(y),y.tag){case 1:return m=y.flags,m&65536?(y.flags=m&-65537|128,y):null;case 3:return Ft(ti),ht(),m=y.flags,(m&65536)!==0&&(m&128)===0?(y.flags=m&-65537|128,y):null;case 26:case 27:case 5:return Et(y),null;case 13:if(aa(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(wi),null;case 4:return ht(),null;case 10:return Ft(y.type),null;case 22:case 23:return aa(y),rh(),m!==null&&d(yh),m=y.flags,m&65536?(y.flags=m&-65537|128,y):null;case 24:return Ft(ti),null;case 25:return null;default:return null}}function DF(m,y){switch(nt(y),y.tag){case 3:Ft(ti),ht();break;case 26:case 27:case 5:Et(y);break;case 4:ht();break;case 13:aa(y);break;case 19:d(wi);break;case 10:Ft(y.type);break;case 22:case 23:aa(y),rh(),m!==null&&d(yh);break;case 24:Ft(ti)}}function Ry(m,y){try{var S=y.updateQueue,N=S!==null?S.lastEffect:null;if(N!==null){var O=N.next;S=O;do{if((S.tag&m)===m){N=void 0;var $=S.create,K=S.inst;N=$(),K.destroy=N}S=S.next}while(S!==O)}}catch(ct){gn(y,y.return,ct)}}function gc(m,y,S){try{var N=y.updateQueue,O=N!==null?N.lastEffect:null;if(O!==null){var $=O.next;N=$;do{if((N.tag&m)===m){var K=N.inst,ct=K.destroy;if(ct!==void 0){K.destroy=void 0,O=y;var xt=S,It=ct;try{It()}catch($t){gn(O,xt,$t)}}}N=N.next}while(N!==$)}}catch($t){gn(y,y.return,$t)}}function jF(m){var y=m.updateQueue;if(y!==null){var S=m.stateNode;try{Bf(y,S)}catch(N){gn(m,m.return,N)}}}function BF(m,y,S){S.props=ch(m.type,m.memoizedProps),S.state=m.memoizedState;try{S.componentWillUnmount()}catch(N){gn(m,y,N)}}function Oy(m,y){try{var S=m.ref;if(S!==null){switch(m.tag){case 26:case 27:case 5:var N=$y(m.stateNode);break;case 30:N=m.stateNode;break;default:N=m.stateNode}typeof S=="function"?m.refCleanup=S(N):S.current=N}}catch(O){gn(m,y,O)}}function Po(m,y){var S=m.ref,N=m.refCleanup;if(S!==null)if(typeof N=="function")try{N()}catch(O){gn(m,y,O)}finally{m.refCleanup=null,m=m.alternate,m!=null&&(m.refCleanup=null)}else if(typeof S=="function")try{S(null)}catch(O){gn(m,y,O)}else S.current=null}function YF(m){var y=m.type,S=m.memoizedProps,N=m.stateNode;try{Hut(N,y,S,m)}catch(O){gn(m,m.return,O)}}function OT(m,y,S){try{Wut(m.stateNode,m.type,S,y,m)}catch(N){gn(m,m.return,N)}}function XF(m){return m.tag===5||m.tag===3||(Hs?m.tag===26:!1)||(vi?m.tag===27&&Jf(m.type):!1)||m.tag===4}function LT(m){t:for(;;){for(;m.sibling===null;){if(m.return===null||XF(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(vi&&m.tag===27&&Jf(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 FT(m,y,S){var N=m.tag;if(N===5||N===6)m=m.stateNode,y?Zut(S,m,y):Vut(S,m);else if(N!==4&&(vi&&N===27&&Jf(m.type)&&(S=m.stateNode,y=null),m=m.child,m!==null))for(FT(m,y,S),m=m.sibling;m!==null;)FT(m,y,S),m=m.sibling}function Q0(m,y,S){var N=m.tag;if(N===5||N===6)m=m.stateNode,y?qut(S,m,y):Uut(S,m);else if(N!==4&&(vi&&N===27&&Jf(m.type)&&(S=m.stateNode),m=m.child,m!==null))for(Q0(m,y,S),m=m.sibling;m!==null;)Q0(m,y,S),m=m.sibling}function UF(m,y,S){m=m.containerInfo;try{Dz(m,S)}catch(N){gn(y,y.return,N)}}function VF(m){var y=m.stateNode,S=m.memoizedProps;try{Rpt(m.type,S,y,m)}catch(N){gn(m,m.return,N)}}function eut(m,y){for(Sut(m.containerInfo),Ai=y;Ai!==null;)if(m=Ai,y=m.child,(m.subtreeFlags&1024)!==0&&y!==null)y.return=m,Ai=y;else for(;Ai!==null;){m=Ai;var S=m.alternate;switch(y=m.flags,m.tag){case 0:break;case 11:case 15:break;case 1:if((y&1024)!==0&&S!==null){y=void 0;var N=m,O=S.memoizedProps;S=S.memoizedState;var $=N.stateNode;try{var K=ch(N.type,O,N.elementType===N.type);y=$.getSnapshotBeforeUpdate(K,S),$.__reactInternalSnapshotBeforeUpdate=y}catch(ct){gn(N,N.return,ct)}}break;case 3:(y&1024)!==0&&ar&&ipt(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,Ai=y;break}Ai=m.return}}function GF(m,y,S){var N=S.flags;switch(S.tag){case 0:case 11:case 15:xc(m,S),N&4&&Ry(5,S);break;case 1:if(xc(m,S),N&4)if(m=S.stateNode,y===null)try{m.componentDidMount()}catch(K){gn(S,S.return,K)}else{var O=ch(S.type,y.memoizedProps);y=y.memoizedState;try{m.componentDidUpdate(O,y,m.__reactInternalSnapshotBeforeUpdate)}catch(K){gn(S,S.return,K)}}N&64&&jF(S),N&512&&Oy(S,S.return);break;case 3:if(xc(m,S),N&64&&(m=S.updateQueue,m!==null)){if(y=null,S.child!==null)switch(S.child.tag){case 27:case 5:y=$y(S.child.stateNode);break;case 1:y=S.child.stateNode}try{Bf(m,y)}catch(K){gn(S,S.return,K)}}break;case 27:vi&&y===null&&N&4&&VF(S);case 26:case 5:xc(m,S),y===null&&N&4&&YF(S),N&512&&Oy(S,S.return);break;case 12:xc(m,S);break;case 13:xc(m,S),N&4&&WF(m,S),N&64&&(m=S.memoizedState,m!==null&&(m=m.dehydrated,m!==null&&(S=cut.bind(null,S),apt(m,S))));break;case 22:if(N=S.memoizedState!==null||ma,!N){y=y!==null&&y.memoizedState!==null||ui,O=ma;var $=ui;ma=N,(ui=y)&&!$?bc(m,S,(S.subtreeFlags&8772)!==0):xc(m,S),ma=O,ui=$}break;case 30:break;default:xc(m,S)}}function HF(m){var y=m.alternate;y!==null&&(m.alternate=null,HF(y)),m.child=null,m.deletions=null,m.sibling=null,m.tag===5&&(y=m.stateNode,y!==null&&Nut(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 Gs(m,y,S){for(S=S.child;S!==null;)zT(m,y,S),S=S.sibling}function zT(m,y,S){if(es&&typeof es.onCommitFiberUnmount=="function")try{es.onCommitFiberUnmount(By,S)}catch{}switch(S.tag){case 26:if(Hs){ui||Po(S,y),Gs(m,y,S),S.memoizedState?Hz(S.memoizedState):S.stateNode&&qz(S.stateNode);break}case 27:if(vi){ui||Po(S,y);var N=fi,O=Ar;Jf(S.type)&&(fi=S.stateNode,Ar=!1),Gs(m,y,S),Jz(S.stateNode),fi=N,Ar=O;break}case 5:ui||Po(S,y);case 6:if(ar){if(N=fi,O=Ar,fi=null,Gs(m,y,S),fi=N,Ar=O,fi!==null)if(Ar)try{Jut(fi,S.stateNode)}catch($){gn(S,y,$)}else try{Kut(fi,S.stateNode)}catch($){gn(S,y,$)}}else Gs(m,y,S);break;case 18:ar&&fi!==null&&(Ar?kpt(fi,S.stateNode):Ppt(fi,S.stateNode));break;case 4:ar?(N=fi,O=Ar,fi=S.stateNode.containerInfo,Ar=!0,Gs(m,y,S),fi=N,Ar=O):(Pc&&UF(S.stateNode,S,zz()),Gs(m,y,S));break;case 0:case 11:case 14:case 15:ui||gc(2,S,y),ui||gc(4,S,y),Gs(m,y,S);break;case 1:ui||(Po(S,y),N=S.stateNode,typeof N.componentWillUnmount=="function"&&BF(S,y,N)),Gs(m,y,S);break;case 21:Gs(m,y,S);break;case 22:ui=(N=ui)||S.memoizedState!==null,Gs(m,y,S),ui=N;break;default:Gs(m,y,S)}}function WF(m,y){if(ms&&y.memoizedState===null&&(m=y.alternate,m!==null&&(m=m.memoizedState,m!==null&&(m=m.dehydrated,m!==null))))try{wpt(m)}catch(S){gn(y,y.return,S)}}function nut(m){switch(m.tag){case 13:case 19:var y=m.stateNode;return y===null&&(y=m.stateNode=new l$),y;case 22:return m=m.stateNode,y=m._retryCache,y===null&&(y=m._retryCache=new l$),y;default:throw Error(i(435,m.tag))}}function $T(m,y){var S=nut(m);y.forEach(function(N){var O=lut.bind(null,m,N);S.has(N)||(S.add(N),N.then(O,O))})}function br(m,y){var S=y.deletions;if(S!==null)for(var N=0;N<S.length;N++){var O=S[N],$=m,K=y;if(ar){var ct=K;t:for(;ct!==null;){switch(ct.tag){case 27:if(vi){if(Jf(ct.type)){fi=ct.stateNode,Ar=!1;break t}break}case 5:fi=ct.stateNode,Ar=!1;break t;case 3:case 4:fi=ct.stateNode.containerInfo,Ar=!0;break t}ct=ct.return}if(fi===null)throw Error(i(160));zT($,K,O),fi=null,Ar=!1}else zT($,K,O);$=O.alternate,$!==null&&($.return=null),O.return=null}if(y.subtreeFlags&13878)for(y=y.child;y!==null;)qF(y,m),y=y.sibling}function qF(m,y){var S=m.alternate,N=m.flags;switch(m.tag){case 0:case 11:case 14:case 15:br(y,m),Nr(m),N&4&&(gc(3,m,m.return),Ry(3,m),gc(5,m,m.return));break;case 1:br(y,m),Nr(m),N&512&&(ui||S===null||Po(S,S.return)),N&64&&ma&&(m=m.updateQueue,m!==null&&(N=m.callbacks,N!==null&&(S=m.shared.hiddenCallbacks,m.shared.hiddenCallbacks=S===null?N:S.concat(N))));break;case 26:if(Hs){var O=qs;if(br(y,m),Nr(m),N&512&&(ui||S===null||Po(S,S.return)),N&4){N=S!==null?S.memoizedState:null;var $=m.memoizedState;S===null?$===null?m.stateNode===null?m.stateNode=Ept(O,m.type,m.memoizedProps,m):Wz(O,m.type,m.stateNode):m.stateNode=Gz(O,$,m.memoizedProps):N!==$?(N===null?S.stateNode!==null&&qz(S.stateNode):Hz(N),$===null?Wz(O,m.type,m.stateNode):Gz(O,$,m.memoizedProps)):$===null&&m.stateNode!==null&&OT(m,m.memoizedProps,S.memoizedProps)}break}case 27:if(vi){br(y,m),Nr(m),N&512&&(ui||S===null||Po(S,S.return)),S!==null&&N&4&&OT(m,m.memoizedProps,S.memoizedProps);break}case 5:if(br(y,m),Nr(m),N&512&&(ui||S===null||Po(S,S.return)),ar){if(m.flags&32){O=m.stateNode;try{Fz(O)}catch($t){gn(m,m.return,$t)}}N&4&&m.stateNode!=null&&(O=m.memoizedProps,OT(m,O,S!==null?S.memoizedProps:O)),N&1024&&(P3=!0)}break;case 6:if(br(y,m),Nr(m),N&4&&ar){if(m.stateNode===null)throw Error(i(162));N=m.memoizedProps,S=S!==null?S.memoizedProps:N,O=m.stateNode;try{Gut(O,S,N)}catch($t){gn(m,m.return,$t)}}break;case 3:if(Hs?(Ipt(),O=qs,qs=l3(y.containerInfo),br(y,m),qs=O):br(y,m),Nr(m),N&4){if(ar&&ms&&S!==null&&S.memoizedState.isDehydrated)try{Spt(y.containerInfo)}catch($t){gn(m,m.return,$t)}if(Pc){N=y.containerInfo,S=y.pendingChildren;try{Dz(N,S)}catch($t){gn(m,m.return,$t)}}}P3&&(P3=!1,ZF(m));break;case 4:Hs?(S=qs,qs=l3(m.stateNode.containerInfo),br(y,m),Nr(m),qs=S):(br(y,m),Nr(m)),N&4&&Pc&&UF(m.stateNode,m,m.stateNode.pendingChildren);break;case 12:br(y,m),Nr(m);break;case 13:br(y,m),Nr(m),m.child.flags&8192&&m.memoizedState!==null!=(S!==null&&S.memoizedState!==null)&&(E3=Ws()),N&4&&(N=m.updateQueue,N!==null&&(m.updateQueue=null,$T(m,N)));break;case 22:O=m.memoizedState!==null;var K=S!==null&&S.memoizedState!==null,ct=ma,xt=ui;if(ma=ct||O,ui=xt||K,br(y,m),ui=xt,ma=ct,Nr(m),N&8192&&(y=m.stateNode,y._visibility=O?y._visibility&-2:y._visibility|1,O&&(S===null||K||ma||ui||lh(m)),ar)){t:if(S=null,ar)for(y=m;;){if(y.tag===5||Hs&&y.tag===26){if(S===null){K=S=y;try{$=K.stateNode,O?Qut($):ept(K.stateNode,K.memoizedProps)}catch($t){gn(K,K.return,$t)}}}else if(y.tag===6){if(S===null){K=y;try{var It=K.stateNode;O?tpt(It):npt(It,K.memoizedProps)}catch($t){gn(K,K.return,$t)}}}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;S===y&&(S=null),y=y.return}S===y&&(S=null),y.sibling.return=y.return,y=y.sibling}}N&4&&(N=m.updateQueue,N!==null&&(S=N.retryQueue,S!==null&&(N.retryQueue=null,$T(m,S))));break;case 19:br(y,m),Nr(m),N&4&&(N=m.updateQueue,N!==null&&(m.updateQueue=null,$T(m,N)));break;case 30:break;case 21:break;default:br(y,m),Nr(m)}}function Nr(m){var y=m.flags;if(y&2){try{if(ar){for(var S,N=m.return;N!==null;){if(XF(N)){S=N;break}N=N.return}if(S==null)throw Error(i(160));switch(S.tag){case 27:if(vi){var O=S.stateNode,$=LT(m);Q0(m,$,O);break}case 5:var K=S.stateNode;S.flags&32&&(Fz(K),S.flags&=-33);var ct=LT(m);Q0(m,ct,K);break;case 3:case 4:var xt=S.stateNode.containerInfo,It=LT(m);FT(m,It,xt);break;default:throw Error(i(161))}}}catch($t){gn(m,m.return,$t)}m.flags&=-3}y&4096&&(m.flags&=-4097)}function ZF(m){if(m.subtreeFlags&1024)for(m=m.child;m!==null;){var y=m;ZF(y),y.tag===5&&y.flags&1024&&Lut(y.stateNode),m=m.sibling}}function xc(m,y){if(y.subtreeFlags&8772)for(y=y.child;y!==null;)GF(m,y.alternate,y),y=y.sibling}function lh(m){for(m=m.child;m!==null;){var y=m;switch(y.tag){case 0:case 11:case 14:case 15:gc(4,y,y.return),lh(y);break;case 1:Po(y,y.return);var S=y.stateNode;typeof S.componentWillUnmount=="function"&&BF(y,y.return,S),lh(y);break;case 27:vi&&Jz(y.stateNode);case 26:case 5:Po(y,y.return),lh(y);break;case 22:y.memoizedState===null&&lh(y);break;case 30:lh(y);break;default:lh(y)}m=m.sibling}}function bc(m,y,S){for(S=S&&(y.subtreeFlags&8772)!==0,y=y.child;y!==null;){var N=y.alternate,O=m,$=y,K=$.flags;switch($.tag){case 0:case 11:case 15:bc(O,$,S),Ry(4,$);break;case 1:if(bc(O,$,S),N=$,O=N.stateNode,typeof O.componentDidMount=="function")try{O.componentDidMount()}catch(It){gn(N,N.return,It)}if(N=$,O=N.updateQueue,O!==null){var ct=N.stateNode;try{var xt=O.shared.hiddenCallbacks;if(xt!==null)for(O.shared.hiddenCallbacks=null,O=0;O<xt.length;O++)jf(xt[O],ct)}catch(It){gn(N,N.return,It)}}S&&K&64&&jF($),Oy($,$.return);break;case 27:vi&&VF($);case 26:case 5:bc(O,$,S),S&&N===null&&K&4&&YF($),Oy($,$.return);break;case 12:bc(O,$,S);break;case 13:bc(O,$,S),S&&K&4&&WF(O,$);break;case 22:$.memoizedState===null&&bc(O,$,S),Oy($,$.return);break;case 30:break;default:bc(O,$,S)}y=y.sibling}}function DT(m,y){var S=null;m!==null&&m.memoizedState!==null&&m.memoizedState.cachePool!==null&&(S=m.memoizedState.cachePool.pool),m=null,y.memoizedState!==null&&y.memoizedState.cachePool!==null&&(m=y.memoizedState.cachePool.pool),m!==S&&(m!=null&&m.refCount++,S!=null&&Us(S))}function jT(m,y){m=null,y.alternate!==null&&(m=y.alternate.memoizedState.cache),y=y.memoizedState.cache,y!==m&&(y.refCount++,m!=null&&Us(m))}function ko(m,y,S,N){if(y.subtreeFlags&10256)for(y=y.child;y!==null;)KF(m,y,S,N),y=y.sibling}function KF(m,y,S,N){var O=y.flags;switch(y.tag){case 0:case 11:case 15:ko(m,y,S,N),O&2048&&Ry(9,y);break;case 1:ko(m,y,S,N);break;case 3:ko(m,y,S,N),O&2048&&(m=null,y.alternate!==null&&(m=y.alternate.memoizedState.cache),y=y.memoizedState.cache,y!==m&&(y.refCount++,m!=null&&Us(m)));break;case 12:if(O&2048){ko(m,y,S,N),m=y.stateNode;try{var $=y.memoizedProps,K=$.id,ct=$.onPostCommit;typeof ct=="function"&&ct(K,y.alternate===null?"mount":"update",m.passiveEffectDuration,-0)}catch(xt){gn(y,y.return,xt)}}else ko(m,y,S,N);break;case 13:ko(m,y,S,N);break;case 23:break;case 22:$=y.stateNode,K=y.alternate,y.memoizedState!==null?$._visibility&2?ko(m,y,S,N):Ly(m,y):$._visibility&2?ko(m,y,S,N):($._visibility|=2,Gf(m,y,S,N,(y.subtreeFlags&10256)!==0)),O&2048&&DT(K,y);break;case 24:ko(m,y,S,N),O&2048&&jT(y.alternate,y);break;default:ko(m,y,S,N)}}function Gf(m,y,S,N,O){for(O=O&&(y.subtreeFlags&10256)!==0,y=y.child;y!==null;){var $=m,K=y,ct=S,xt=N,It=K.flags;switch(K.tag){case 0:case 11:case 15:Gf($,K,ct,xt,O),Ry(8,K);break;case 23:break;case 22:var $t=K.stateNode;K.memoizedState!==null?$t._visibility&2?Gf($,K,ct,xt,O):Ly($,K):($t._visibility|=2,Gf($,K,ct,xt,O)),O&&It&2048&&DT(K.alternate,K);break;case 24:Gf($,K,ct,xt,O),O&&It&2048&&jT(K.alternate,K);break;default:Gf($,K,ct,xt,O)}y=y.sibling}}function Ly(m,y){if(y.subtreeFlags&10256)for(y=y.child;y!==null;){var S=m,N=y,O=N.flags;switch(N.tag){case 22:Ly(S,N),O&2048&&DT(N.alternate,N);break;case 24:Ly(S,N),O&2048&&jT(N.alternate,N);break;default:Ly(S,N)}y=y.sibling}}function uh(m){if(m.subtreeFlags&fm)for(m=m.child;m!==null;)JF(m),m=m.sibling}function JF(m){switch(m.tag){case 26:uh(m),m.flags&fm&&(m.memoizedState!==null?Apt(qs,m.memoizedState,m.memoizedProps):Lz(m.type,m.memoizedProps));break;case 5:uh(m),m.flags&fm&&Lz(m.type,m.memoizedProps);break;case 3:case 4:if(Hs){var y=qs;qs=l3(m.stateNode.containerInfo),uh(m),qs=y}else uh(m);break;case 22:m.memoizedState===null&&(y=m.alternate,y!==null&&y.memoizedState!==null?(y=fm,fm=16777216,uh(m),fm=y):uh(m));break;default:uh(m)}}function QF(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 Fy(m){var y=m.deletions;if((m.flags&16)!==0){if(y!==null)for(var S=0;S<y.length;S++){var N=y[S];Ai=N,ez(N,m)}QF(m)}if(m.subtreeFlags&10256)for(m=m.child;m!==null;)tz(m),m=m.sibling}function tz(m){switch(m.tag){case 0:case 11:case 15:Fy(m),m.flags&2048&&gc(9,m,m.return);break;case 3:Fy(m);break;case 12:Fy(m);break;case 22:var y=m.stateNode;m.memoizedState!==null&&y._visibility&2&&(m.return===null||m.return.tag!==13)?(y._visibility&=-3,tx(m)):Fy(m);break;default:Fy(m)}}function tx(m){var y=m.deletions;if((m.flags&16)!==0){if(y!==null)for(var S=0;S<y.length;S++){var N=y[S];Ai=N,ez(N,m)}QF(m)}for(m=m.child;m!==null;){switch(y=m,y.tag){case 0:case 11:case 15:gc(8,y,y.return),tx(y);break;case 22:S=y.stateNode,S._visibility&2&&(S._visibility&=-3,tx(y));break;default:tx(y)}m=m.sibling}}function ez(m,y){for(;Ai!==null;){var S=Ai;switch(S.tag){case 0:case 11:case 15:gc(8,S,y);break;case 23:case 22:if(S.memoizedState!==null&&S.memoizedState.cachePool!==null){var N=S.memoizedState.cachePool.pool;N!=null&&N.refCount++}break;case 24:Us(S.memoizedState.cache)}if(N=S.child,N!==null)N.return=S,Ai=N;else t:for(S=m;Ai!==null;){N=Ai;var O=N.sibling,$=N.return;if(HF(N),N===S){Ai=null;break t}if(O!==null){O.return=$,Ai=O;break t}Ai=$}}}function BT(m){var y=Mut(m);if(y!=null){if(typeof y.memoizedProps["data-testname"]!="string")throw Error(i(364));return y}if(m=$ut(m),m===null)throw Error(i(362));return m.stateNode.current}function YT(m,y){var S=m.tag;switch(y.$$typeof){case vx:if(m.type===y.value)return!0;break;case Sx:t:{for(y=y.value,m=[m,0],S=0;S<m.length;){var N=m[S++],O=N.tag,$=m[S++],K=y[$];if(O!==5&&O!==26&&O!==27||!jy(N)){for(;K!=null&&YT(N,K);)$++,K=y[$];if($===y.length){y=!0;break t}else for(N=N.child;N!==null;)m.push(N,$),N=N.sibling}}y=!1}return y;case wx:if((S===5||S===26||S===27)&&But(m.stateNode,y.value))return!0;break;case kx:if((S===5||S===6||S===26||S===27)&&(m=jut(m),m!==null&&0<=m.indexOf(y.value)))return!0;break;case Px:if((S===5||S===26||S===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 XT(m){switch(m.$$typeof){case vx:return"<"+(u(m.value)||"Unknown")+">";case Sx:return":has("+(XT(m)||"")+")";case wx:return'[role="'+m.value+'"]';case kx:return'"'+m.value+'"';case Px:return'[data-testname="'+m.value+'"]';default:throw Error(i(365))}}function nz(m,y){var S=[];m=[m,0];for(var N=0;N<m.length;){var O=m[N++],$=O.tag,K=m[N++],ct=y[K];if($!==5&&$!==26&&$!==27||!jy(O)){for(;ct!=null&&YT(O,ct);)K++,ct=y[K];if(K===y.length)S.push(O);else for(O=O.child;O!==null;)m.push(O,K),O=O.sibling}}return S}function UT(m,y){if(!Dy)throw Error(i(363));m=BT(m),m=nz(m,y),y=[],m=Array.from(m);for(var S=0;S<m.length;){var N=m[S++],O=N.tag;if(O===5||O===26||O===27)jy(N)||y.push(N.stateNode);else for(N=N.child;N!==null;)m.push(N),N=N.sibling}return y}function Kr(){if((Je&2)!==0&&tn!==0)return tn&-tn;if(_e.T!==null){var m=sm;return m!==0?m:Kp()}return Cut()}function iz(){bs===0&&(bs=(tn&536870912)===0||mn?T():536870912);var m=xs.current;return m!==null&&(m.flags|=32),bs}function Jr(m,y,S){(m===Nn&&(xn===2||xn===9)||m.cancelPendingCommit!==null)&&(Hf(m,0),vc(m,tn,bs,!1)),M(m,S),((Je&2)===0||m!==Nn)&&(m===Nn&&((Je&2)===0&&(xh|=S),ei===4&&vc(m,tn,bs,!1)),Ir(m))}function rz(m,y,S){if((Je&6)!==0)throw Error(i(327));var N=!S&&(y&124)===0&&(y&m.expiredLanes)===0||P(m,y),O=N?sut(m,y):HT(m,y,!0),$=N;do{if(O===0){mm&&!N&&vc(m,y,0,!1);break}else{if(S=m.current.alternate,$&&!iut(S)){O=HT(m,y,!1),$=!1;continue}if(O===2){if($=y,m.errorRecoveryDisabledLanes&$)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=Wy;var xt=ms&&ct.current.memoizedState.isDehydrated;if(xt&&(Hf(ct,K).flags|=256),K=HT(ct,K,!1),K!==2){if(k3&&!xt){ct.errorRecoveryDisabledLanes|=$,xh|=$,O=4;break t}$=Rr,Rr=O,$!==null&&(Rr===null?Rr=$:Rr.push.apply(Rr,$))}O=K}if($=!1,O!==2)continue}}if(O===1){Hf(m,0),vc(m,y,0,!0);break}t:{switch(N=m,$=O,$){case 0:case 1:throw Error(i(345));case 4:if((y&4194048)!==y)break;case 6:vc(N,y,bs,!Ec);break t;case 2:Rr=null;break;case 3:case 5:break;default:throw Error(i(329))}if((y&62914560)===y&&(O=E3+300-Ws(),10<O)){if(vc(N,y,bs,!Ec),v(N,0,!0)!==0)break t;N.timeoutHandle=kut(sz.bind(null,N,S,Rr,Tx,M3,y,bs,xh,_m,Ec,$,2,-0,0),O);break t}sz(N,S,Rr,Tx,M3,y,bs,xh,_m,Ec,$,0,-0,0)}}break}while(!0);Ir(m)}function sz(m,y,S,N,O,$,K,ct,xt,It,$t,Xt,Wt,Le){if(m.timeoutHandle=hh,Xt=y.subtreeFlags,(Xt&8192||(Xt&16785408)===16785408)&&(Rut(),JF(y),Xt=Out(),Xt!==null)){m.cancelPendingCommit=Xt(fz.bind(null,m,y,$,S,N,O,K,ct,xt,$t,1,Wt,Le)),vc(m,$,K,!It);return}fz(m,y,$,S,N,O,K,ct,xt)}function iut(m){for(var y=m;;){var S=y.tag;if((S===0||S===11||S===15)&&y.flags&16384&&(S=y.updateQueue,S!==null&&(S=S.stores,S!==null)))for(var N=0;N<S.length;N++){var O=S[N],$=O.getSnapshot;O=O.value;try{if(!ns($(),O))return!1}catch{return!1}}if(S=y.child,y.subtreeFlags&16384&&S!==null)S.return=y,y=S;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 vc(m,y,S,N){y&=~T3,y&=~xh,m.suspendedLanes|=y,m.pingedLanes&=~y,N&&(m.warmLanes|=y),N=m.expirationTimes;for(var O=y;0<O;){var $=31-ts(O),K=1<<$;N[$]=-1,O&=~K}S!==0&&E(m,S,y)}function oz(){return(Je&6)===0?(So(0,!1),!1):!0}function VT(){if(Ue!==null){if(xn===0)var m=Ue.return;else m=Ue,fa=_h=null,Py(m),hm=null,Gy=0,m=Ue;for(;m!==null;)DF(m.alternate,m),m=m.return;Ue=null}}function Hf(m,y){var S=m.timeoutHandle;S!==hh&&(m.timeoutHandle=hh,Tut(S)),S=m.cancelPendingCommit,S!==null&&(m.cancelPendingCommit=null,S()),VT(),Nn=m,Ue=S=la(m.current,null),tn=y,xn=0,is=null,Ec=!1,mm=P(m,y),k3=!1,_m=bs=T3=xh=Cc=ei=0,Rr=Wy=null,M3=!1,(y&8)!==0&&(y|=y&32);var N=m.entangledLanes;if(N!==0)for(m=m.entanglements,N&=y;0<N;){var O=31-ts(N),$=1<<O;y|=m[O],N&=~$}return _a=y,dc(),S}function az(m,y){De=null,_e.H=bx,y===Uy||y===mx?(y=zf(),xn=3):y===x3?(y=zf(),xn=4):xn=y===c$?8:y!==null&&typeof y=="object"&&typeof y.then=="function"?6:1,is=y,Ue===null&&(ei=1,q0(m,tt(y,m.current)))}function cz(){var m=xs.current;return m===null?!0:(tn&4194048)===tn?Mo===null:(tn&62914560)===tn||(tn&536870912)!==0?m===Mo:!1}function lz(){var m=_e.H;return _e.H=bx,m===null?bx:m}function uz(){var m=_e.A;return _e.A=Wpt,m}function GT(){ei=4,Ec||(tn&4194048)!==tn&&xs.current!==null||(mm=!0),(Cc&134217727)===0&&(xh&134217727)===0||Nn===null||vc(Nn,tn,bs,!1)}function HT(m,y,S){var N=Je;Je|=2;var O=lz(),$=uz();(Nn!==m||tn!==y)&&(Tx=null,Hf(m,y)),y=!1;var K=ei;t:do try{if(xn!==0&&Ue!==null){var ct=Ue,xt=is;switch(xn){case 8:VT(),K=6;break t;case 3:case 2:case 9:case 6:xs.current===null&&(y=!0);var It=xn;if(xn=0,is=null,Wf(m,ct,xt,It),S&&mm){K=0;break t}break;default:It=xn,xn=0,is=null,Wf(m,ct,xt,It)}}rut(),K=ei;break}catch($t){az(m,$t)}while(!0);return y&&m.shellSuspendCounter++,fa=_h=null,Je=N,_e.H=O,_e.A=$,Ue===null&&(Nn=null,tn=0,dc()),K}function rut(){for(;Ue!==null;)pz(Ue)}function sut(m,y){var S=Je;Je|=2;var N=lz(),O=uz();Nn!==m||tn!==y?(Tx=null,qy=Ws()+500,Hf(m,y)):mm=P(m,y);t:do try{if(xn!==0&&Ue!==null){y=Ue;var $=is;e:switch(xn){case 1:xn=0,is=null,Wf(m,y,$,1);break;case 2:case 9:if(Lf($)){xn=0,is=null,hz(y);break}y=function(){xn!==2&&xn!==9||Nn!==m||(xn=7),Ir(m)},$.then(y,y);break t;case 3:xn=7;break t;case 4:xn=5;break t;case 7:Lf($)?(xn=0,is=null,hz(y)):(xn=0,is=null,Wf(m,y,$,7));break;case 5:var K=null;switch(Ue.tag){case 26:K=Ue.memoizedState;case 5:case 27:var ct=Ue,xt=ct.type,It=ct.pendingProps;if(K?Zz(K):Oz(xt,It)){xn=0,is=null;var $t=ct.sibling;if($t!==null)Ue=$t;else{var Xt=ct.return;Xt!==null?(Ue=Xt,ex(Xt)):Ue=null}break e}}xn=0,is=null,Wf(m,y,$,5);break;case 6:xn=0,is=null,Wf(m,y,$,6);break;case 8:VT(),ei=6;break t;default:throw Error(i(462))}}out();break}catch(Wt){az(m,Wt)}while(!0);return fa=_h=null,_e.H=N,_e.A=O,Je=S,Ue!==null?0:(Nn=null,tn=0,dc(),ei)}function out(){for(;Ue!==null&&!Fpt();)pz(Ue)}function pz(m){var y=OF(m.alternate,m,_a);m.memoizedProps=m.pendingProps,y===null?ex(m):Ue=y}function hz(m){var y=m,S=y.alternate;switch(y.tag){case 15:case 0:y=EF(S,y,y.pendingProps,y.type,void 0,tn);break;case 11:y=EF(S,y,y.pendingProps,y.type.render,y.ref,tn);break;case 5:Py(y);default:DF(S,y),y=Ue=Sz(y,_a),y=OF(S,y,_a)}m.memoizedProps=m.pendingProps,y===null?ex(m):Ue=y}function Wf(m,y,S,N){fa=_h=null,Py(y),hm=null,Gy=0;var O=y.return;try{if(Klt(m,O,y,S,tn)){ei=1,q0(m,tt(S,m.current)),Ue=null;return}}catch($){if(O!==null)throw Ue=O,$;ei=1,q0(m,tt(S,m.current)),Ue=null;return}y.flags&32768?(mn||N===1?m=!0:mm||(tn&536870912)!==0?m=!1:(Ec=m=!0,(N===2||N===9||N===3||N===6)&&(N=xs.current,N!==null&&N.tag===13&&(N.flags|=16384))),dz(y,m)):ex(y)}function ex(m){var y=m;do{if((y.flags&32768)!==0){dz(y,Ec);return}m=y.return;var S=Qlt(y.alternate,y,_a);if(S!==null){Ue=S;return}if(y=y.sibling,y!==null){Ue=y;return}Ue=y=m}while(y!==null);ei===0&&(ei=5)}function dz(m,y){do{var S=tut(m.alternate,m);if(S!==null){S.flags&=32767,Ue=S;return}if(S=m.return,S!==null&&(S.flags|=32768,S.subtreeFlags=0,S.deletions=null),!y&&(m=m.sibling,m!==null)){Ue=m;return}Ue=m=S}while(m!==null);ei=6,Ue=null}function fz(m,y,S,N,O,$,K,ct,xt){m.cancelPendingCommit=null;do zy();while(Zi!==0);if((Je&6)!==0)throw Error(i(327));if(y!==null){if(y===m.current)throw Error(i(177));if($=y.lanes|y.childLanes,$|=b3,I(m,S,$,K,ct,xt),m===Nn&&(Ue=Nn=null,tn=0),ym=y,Nc=m,gm=S,C3=$,I3=O,u$=N,(y.subtreeFlags&10256)!==0||(y.flags&10256)!==0?(m.callbackNode=null,m.callbackPriority=0,uut(h3,function(){return xz(!0),null})):(m.callbackNode=null,m.callbackPriority=0),N=(y.flags&13878)!==0,(y.subtreeFlags&13878)!==0||N){N=_e.T,_e.T=null,O=pa(),Ii(2),K=Je,Je|=4;try{eut(m,y,S)}finally{Je=K,Ii(O),_e.T=N}}Zi=1,mz(),_z(),yz()}}function mz(){if(Zi===1){Zi=0;var m=Nc,y=ym,S=(y.flags&13878)!==0;if((y.subtreeFlags&13878)!==0||S){S=_e.T,_e.T=null;var N=pa();Ii(2);var O=Je;Je|=4;try{qF(y,m),wut(m.containerInfo)}finally{Je=O,Ii(N),_e.T=S}}m.current=y,Zi=2}}function _z(){if(Zi===2){Zi=0;var m=Nc,y=ym,S=(y.flags&8772)!==0;if((y.subtreeFlags&8772)!==0||S){S=_e.T,_e.T=null;var N=pa();Ii(2);var O=Je;Je|=4;try{GF(m,y.alternate,y)}finally{Je=O,Ii(N),_e.T=S}}Zi=3}}function yz(){if(Zi===4||Zi===3){Zi=0,zpt();var m=Nc,y=ym,S=gm,N=u$;(y.subtreeFlags&10256)!==0||(y.flags&10256)!==0?Zi=5:(Zi=0,ym=Nc=null,gz(m,m.pendingLanes));var O=m.pendingLanes;if(O===0&&(Ic=null),B(S),y=y.stateNode,es&&typeof es.onCommitFiberRoot=="function")try{es.onCommitFiberRoot(By,y,void 0,(y.current.flags&128)===128)}catch{}if(N!==null){y=_e.T,O=pa(),Ii(2),_e.T=null;try{for(var $=m.onRecoverableError,K=0;K<N.length;K++){var ct=N[K];$(ct.value,{componentStack:ct.stack})}}finally{_e.T=y,Ii(O)}}(gm&3)!==0&&zy(),Ir(m),O=m.pendingLanes,(S&4194090)!==0&&(O&42)!==0?m===N3?Zy++:(Zy=0,N3=m):Zy=0,So(0,!1)}}function gz(m,y){(m.pooledCacheLanes&=y)===0&&(y=m.pooledCache,y!=null&&(m.pooledCache=null,Us(y)))}function zy(m){return mz(),_z(),yz(),xz(m)}function xz(){if(Zi!==5)return!1;var m=Nc,y=C3;C3=0;var S=B(gm),N=32>S?32:S;S=_e.T;var O=pa();try{Ii(N),_e.T=null,N=I3,I3=null;var $=Nc,K=gm;if(Zi=0,ym=Nc=null,gm=0,(Je&6)!==0)throw Error(i(331));var ct=Je;if(Je|=4,tz($.current),KF($,$.current,K,N),Je=ct,So(0,!1),es&&typeof es.onPostCommitFiberRoot=="function")try{es.onPostCommitFiberRoot(By,$)}catch{}return!0}finally{Ii(O),_e.T=S,gz(m,y)}}function bz(m,y,S){y=tt(S,y),y=wT(m.stateNode,y,2),m=fs(m,y,2),m!==null&&(M(m,2),Ir(m))}function gn(m,y,S){if(m.tag===3)bz(m,m,S);else for(;y!==null;){if(y.tag===3){bz(y,m,S);break}else if(y.tag===1){var N=y.stateNode;if(typeof y.type.getDerivedStateFromError=="function"||typeof N.componentDidCatch=="function"&&(Ic===null||!Ic.has(N))){m=tt(S,m),S=vF(2),N=fs(y,S,2),N!==null&&(SF(S,N,y,m),M(N,2),Ir(N));break}}y=y.return}}function WT(m,y,S){var N=m.pingCache;if(N===null){N=m.pingCache=new qpt;var O=new Set;N.set(y,O)}else O=N.get(y),O===void 0&&(O=new Set,N.set(y,O));O.has(S)||(k3=!0,O.add(S),m=aut.bind(null,m,y,S),y.then(m,m))}function aut(m,y,S){var N=m.pingCache;N!==null&&N.delete(y),m.pingedLanes|=m.suspendedLanes&S,m.warmLanes&=~S,Nn===m&&(tn&S)===S&&(ei===4||ei===3&&(tn&62914560)===tn&&300>Ws()-E3?(Je&2)===0&&Hf(m,0):T3|=S,_m===tn&&(_m=0)),Ir(m)}function vz(m,y){y===0&&(y=k()),m=wo(m,y),m!==null&&(M(m,y),Ir(m))}function cut(m){var y=m.memoizedState,S=0;y!==null&&(S=y.retryLane),vz(m,S)}function lut(m,y){var S=0;switch(m.tag){case 13:var N=m.stateNode,O=m.memoizedState;O!==null&&(S=O.retryLane);break;case 19:N=m.stateNode;break;case 22:N=m.stateNode._retryCache;break;default:throw Error(i(314))}N!==null&&N.delete(y),vz(m,S)}function uut(m,y){return cx(m,y)}function put(m,y,S,N){this.tag=m,this.key=S,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=N,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function qT(m){return m=m.prototype,!(!m||!m.isReactComponent)}function la(m,y){var S=m.alternate;return S===null?(S=e(m.tag,y,m.key,m.mode),S.elementType=m.elementType,S.type=m.type,S.stateNode=m.stateNode,S.alternate=m,m.alternate=S):(S.pendingProps=y,S.type=m.type,S.flags=0,S.subtreeFlags=0,S.deletions=null),S.flags=m.flags&65011712,S.childLanes=m.childLanes,S.lanes=m.lanes,S.child=m.child,S.memoizedProps=m.memoizedProps,S.memoizedState=m.memoizedState,S.updateQueue=m.updateQueue,y=m.dependencies,S.dependencies=y===null?null:{lanes:y.lanes,firstContext:y.firstContext},S.sibling=m.sibling,S.index=m.index,S.ref=m.ref,S.refCleanup=m.refCleanup,S}function Sz(m,y){m.flags&=65011714;var S=m.alternate;return S===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=S.childLanes,m.lanes=S.lanes,m.child=S.child,m.subtreeFlags=0,m.deletions=null,m.memoizedProps=S.memoizedProps,m.memoizedState=S.memoizedState,m.updateQueue=S.updateQueue,m.type=S.type,y=S.dependencies,m.dependencies=y===null?null:{lanes:y.lanes,firstContext:y.firstContext}),m}function nx(m,y,S,N,O,$){var K=0;if(N=m,typeof m=="function")qT(m)&&(K=1);else if(typeof m=="string")K=Hs&&vi?Uz(m,S,qi.current)?26:Qz(m)?27:5:Hs?Uz(m,S,qi.current)?26:5:vi&&Qz(m)?27:5;else t:switch(m){case s3:return m=e(31,S,y,O),m.elementType=s3,m.lanes=$,m;case Zf:return ph(S.children,O,$,y);case Ez:K=8,O|=24;break;case t3:return m=e(12,S,y,O|2),m.elementType=t3,m.lanes=$,m;case n3:return m=e(13,S,y,O),m.elementType=n3,m.lanes=$,m;case i3:return m=e(19,S,y,O),m.elementType=i3,m.lanes=$,m;default:if(typeof m=="object"&&m!==null)switch(m.$$typeof){case mut:case Sc:K=10;break t;case Cz:K=9;break t;case e3:K=11;break t;case r3:K=14;break t;case wc:K=16,N=null;break t}K=29,S=Error(i(130,m===null?"null":typeof m,"")),N=null}return y=e(K,S,y,O),y.elementType=m,y.type=N,y.lanes=$,y}function ph(m,y,S,N){return m=e(7,m,N,y),m.lanes=S,m}function ZT(m,y,S){return m=e(6,m,null,y),m.lanes=S,m}function KT(m,y,S){return y=e(4,m.children!==null?m.children:[],m.key,y),y.lanes=S,y.stateNode={containerInfo:m.containerInfo,pendingChildren:null,implementation:m.implementation},y}function hut(m,y,S,N,O,$,K,ct){this.tag=1,this.containerInfo=m,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=hh,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=C(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=C(0),this.hiddenUpdates=C(null),this.identifierPrefix=N,this.onUncaughtError=O,this.onCaughtError=$,this.onRecoverableError=K,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=ct,this.incompleteTransitions=new Map}function wz(m,y,S,N,O,$,K,ct,xt,It,$t,Xt){return m=new hut(m,y,S,K,ct,xt,It,Xt),y=1,$===!0&&(y|=24),$=e(3,null,null,y),m.current=$,$.stateNode=m,y=Cr(),y.refCount++,m.pooledCache=y,y.refCount++,$.memoizedState={element:N,isDehydrated:S,cache:y},th($),m}function Pz(m){return m?(m=tm,m):tm}function kz(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:$y(m.stateNode)}function Tz(m,y,S,N,O,$){O=Pz(O),N.context===null?N.context=O:N.pendingContext=O,N=ds(y),N.payload={element:S},$=$===void 0?null:$,$!==null&&(N.callback=$),S=fs(m,N,y),S!==null&&(Jr(S,m,y),ra(S,m,y))}function Mz(m,y){if(m=m.memoizedState,m!==null&&m.dehydrated!==null){var S=m.retryLane;m.retryLane=S!==0&&S<y?S:y}}function JT(m,y){Mz(m,y),(m=m.alternate)&&Mz(m,y)}var Xe={},dut=Zs(),Qr=HB(),QT=Object.assign,fut=Symbol.for("react.element"),ix=Symbol.for("react.transitional.element"),qf=Symbol.for("react.portal"),Zf=Symbol.for("react.fragment"),Ez=Symbol.for("react.strict_mode"),t3=Symbol.for("react.profiler"),mut=Symbol.for("react.provider"),Cz=Symbol.for("react.consumer"),Sc=Symbol.for("react.context"),e3=Symbol.for("react.forward_ref"),n3=Symbol.for("react.suspense"),i3=Symbol.for("react.suspense_list"),r3=Symbol.for("react.memo"),wc=Symbol.for("react.lazy");Symbol.for("react.scope");var s3=Symbol.for("react.activity");Symbol.for("react.legacy_hidden"),Symbol.for("react.tracing_marker");var _ut=Symbol.for("react.memo_cache_sentinel");Symbol.for("react.view_transition");var Iz=Symbol.iterator,yut=Symbol.for("react.client.reference"),rx=Array.isArray,_e=dut.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,gut=n.rendererVersion,xut=n.rendererPackageName,Nz=n.extraDevToolsConfig,$y=n.getPublicInstance,but=n.getRootHostContext,vut=n.getChildHostContext,Sut=n.prepareForCommit,wut=n.resetAfterCommit,Put=n.createInstance;n.cloneMutableInstance;var o3=n.appendInitialChild,Az=n.finalizeInitialChildren,sx=n.shouldSetTextContent,Rz=n.createTextInstance;n.cloneMutableTextInstance;var kut=n.scheduleTimeout,Tut=n.cancelTimeout,hh=n.noTimeout,ua=n.isPrimaryRenderer;n.warnsIfNotActing;var ar=n.supportsMutation,Pc=n.supportsPersistence,ms=n.supportsHydration,Mut=n.getInstanceFromNode;n.beforeActiveInstanceBlur;var Eut=n.preparePortalMount;n.prepareScopeUpdate,n.getInstanceFromScope;var Ii=n.setCurrentUpdatePriority,pa=n.getCurrentUpdatePriority,Cut=n.resolveUpdatePriority;n.trackSchedulerEvent,n.resolveEventType,n.resolveEventTimeStamp;var Iut=n.shouldAttemptEagerTransition,Nut=n.detachDeletedInstance;n.requestPostPaintCallback;var Aut=n.maySuspendCommit,Oz=n.preloadInstance,Rut=n.startSuspendingCommit,Lz=n.suspendInstance;n.suspendOnActiveViewTransition;var Out=n.waitForCommitToBeReady,Kf=n.NotPendingTransition,dh=n.HostTransitionContext,Lut=n.resetFormInstance;n.bindToConsole;var Fut=n.supportsMicrotasks,zut=n.scheduleMicrotask,Dy=n.supportsTestSelectors,$ut=n.findFiberRoot,Dut=n.getBoundingRect,jut=n.getTextContent,jy=n.isHiddenSubtree,But=n.matchAccessibilityRole,Yut=n.setFocusIfFocusable,Xut=n.setupIntersectionObserver,Uut=n.appendChild,Vut=n.appendChildToContainer,Gut=n.commitTextUpdate,Hut=n.commitMount,Wut=n.commitUpdate,qut=n.insertBefore,Zut=n.insertInContainerBefore,Kut=n.removeChild,Jut=n.removeChildFromContainer,Fz=n.resetTextContent,Qut=n.hideInstance,tpt=n.hideTextInstance,ept=n.unhideInstance,npt=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 ipt=n.clearContainer;n.createFragmentInstance,n.updateFragmentInstanceFiber,n.commitNewChildToFragmentInstance,n.deleteChildFromFragmentInstance;var rpt=n.cloneInstance,zz=n.createContainerChildSet,$z=n.appendChildToContainerChildSet,spt=n.finalizeContainerChildren,Dz=n.replaceContainerChildren,jz=n.cloneHiddenInstance,Bz=n.cloneHiddenTextInstance,a3=n.isSuspenseInstancePending,c3=n.isSuspenseInstanceFallback,opt=n.getSuspenseInstanceFallbackErrorDetails,apt=n.registerSuspenseInstanceRetry,cpt=n.canHydrateFormStateMarker,lpt=n.isFormStateMarkerMatching,Yz=n.getNextHydratableSibling,upt=n.getNextHydratableSiblingAfterSingleton,ppt=n.getFirstHydratableChild,hpt=n.getFirstHydratableChildWithinContainer,dpt=n.getFirstHydratableChildWithinSuspenseInstance,fpt=n.getFirstHydratableChildWithinSingleton,mpt=n.canHydrateInstance,_pt=n.canHydrateTextInstance,ypt=n.canHydrateSuspenseInstance,gpt=n.hydrateInstance,xpt=n.hydrateTextInstance,bpt=n.hydrateSuspenseInstance,vpt=n.getNextHydratableInstanceAfterSuspenseInstance,Spt=n.commitHydratedContainer,wpt=n.commitHydratedSuspenseInstance,Ppt=n.clearSuspenseBoundary,kpt=n.clearSuspenseBoundaryFromContainer,Xz=n.shouldDeleteUnhydratedTailInstances;n.diffHydratedPropsForDevWarnings,n.diffHydratedTextForDevWarnings,n.describeHydratableInstanceForDevWarnings;var Tpt=n.validateHydratableInstance,Mpt=n.validateHydratableTextInstance,Hs=n.supportsResources,Uz=n.isHostHoistableType,l3=n.getHoistableRoot,Vz=n.getResource,Gz=n.acquireResource,Hz=n.releaseResource,Ept=n.hydrateHoistable,Wz=n.mountHoistable,qz=n.unmountHoistable,Cpt=n.createHoistableInstance,Ipt=n.prepareToCommitHoistables,Npt=n.mayResourceSuspendCommit,Zz=n.preloadResource,Apt=n.suspendResource,vi=n.supportsSingletons,Kz=n.resolveSingletonInstance,Rpt=n.acquireSingletonInstance,Jz=n.releaseSingletonInstance,Qz=n.isHostSingletonType,Jf=n.isSingletonScope,u3=[],Qf=-1,tm={},ts=Math.clz32?Math.clz32:g,Opt=Math.log,Lpt=Math.LN2,ox=256,ax=4194304,cx=Qr.unstable_scheduleCallback,p3=Qr.unstable_cancelCallback,Fpt=Qr.unstable_shouldYield,zpt=Qr.unstable_requestPaint,Ws=Qr.unstable_now,t$=Qr.unstable_ImmediatePriority,$pt=Qr.unstable_UserBlockingPriority,h3=Qr.unstable_NormalPriority,Dpt=Qr.unstable_IdlePriority,jpt=Qr.log,Bpt=Qr.unstable_setDisableYieldValue,By=null,es=null,d3,e$,f3=!1,n$=new WeakMap,em=[],nm=0,lx=null,ux=0,_s=[],ys=0,fh=null,ha=1,da="",qi=h(null),Yy=h(null),kc=h(null),px=h(null),vr=null,Si=null,mn=!1,mh=null,To=!1,m3=Error(i(519)),ns=typeof Object.is=="function"?Object.is:at,hx=h(null),_h=null,fa=null,Ypt=typeof AbortController<"u"?AbortController:function(){var m=[],y=this.signal={aborted:!1,addEventListener:function(S,N){m.push(N)}};this.abort=function(){y.aborted=!0,m.forEach(function(S){return S()})}},Xpt=Qr.unstable_scheduleCallback,Upt=Qr.unstable_NormalPriority,ti={$$typeof:Sc,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0},dx=null,im=null,_3=!1,fx=!1,y3=!1,rm=0,Xy=null,g3=0,sm=0,om=null,i$=_e.S;_e.S=function(m,y){typeof y=="object"&&y!==null&&typeof y.then=="function"&&by(m,y),i$!==null&&i$(m,y)};var yh=h(null),Vpt=Object.prototype.hasOwnProperty,Uy=Error(i(460)),x3=Error(i(474)),mx=Error(i(542)),_x={then:function(){}},am=null,gs=[],cm=0,b3=0,Tc=!1,v3=!1,lm=h(null),yx=h(0),Mc=0,De=null,wn=null,di=null,gx=!1,um=!1,gh=!1,xx=0,Vy=0,pm=null,Gpt=0,bx={readContext:Jt,use:Xf,useCallback:Ln,useContext:Ln,useEffect:Ln,useImperativeHandle:Ln,useLayoutEffect:Ln,useInsertionEffect:Ln,useMemo:Ln,useReducer:Ln,useRef:Ln,useState:Ln,useDebugValue:Ln,useDeferredValue:Ln,useTransition:Ln,useSyncExternalStore:Ln,useId:Ln,useHostTransitionStatus:Ln,useFormState:Ln,useActionState:Ln,useOptimistic:Ln,useMemoCache:Ln,useCacheRefresh:Ln},r$={readContext:Jt,use:Xf,useCallback:function(m,y){return or().memoizedState=[m,y===void 0?null:y],m},useContext:Jt,useEffect:Q7,useImperativeHandle:function(m,y,S){S=S!=null?S.concat([m]):null,U0(4194308,4,iF.bind(null,y,m),S)},useLayoutEffect:function(m,y){return U0(4194308,4,m,y)},useInsertionEffect:function(m,y){U0(4,2,m,y)},useMemo:function(m,y){var S=or();y=y===void 0?null:y;var N=m();if(gh){j(!0);try{m()}finally{j(!1)}}return S.memoizedState=[N,y],N},useReducer:function(m,y,S){var N=or();if(S!==void 0){var O=S(y);if(gh){j(!0);try{S(y)}finally{j(!1)}}}else O=y;return N.memoizedState=N.baseState=O,m={pending:null,lanes:0,dispatch:null,lastRenderedReducer:m,lastRenderedState:O},N.queue=m,m=m.dispatch=Zlt.bind(null,De,m),[N.memoizedState,m]},useRef:function(m){var y=or();return m={current:m},y.memoizedState=m},useState:function(m){m=_T(m);var y=m.queue,S=hF.bind(null,De,y);return y.dispatch=S,[m.memoizedState,S]},useDebugValue:gT,useDeferredValue:function(m,y){var S=or();return xT(S,m,y)},useTransition:function(){var m=_T(!1);return m=cF.bind(null,De,m.queue,!0,!1),or().memoizedState=m,[!1,m]},useSyncExternalStore:function(m,y,S){var N=De,O=or();if(mn){if(S===void 0)throw Error(i(407));S=S()}else{if(S=y(),Nn===null)throw Error(i(349));(tn&124)!==0||z7(N,y,S)}O.memoizedState=S;var $={value:S,getSnapshot:y};return O.queue=$,Q7(D7.bind(null,N,$,m),[m]),N.flags|=2048,Vf(9,X0(),$7.bind(null,N,$,S,y),null),S},useId:function(){var m=or(),y=Nn.identifierPrefix;if(mn){var S=da,N=ha;S=(N&~(1<<32-ts(N)-1)).toString(32)+S,y="\xAB"+y+"R"+S,S=xx++,0<S&&(y+="H"+S.toString(32)),y+="\xBB"}else S=Gpt++,y="\xAB"+y+"r"+S.toString(32)+"\xBB";return m.memoizedState=y},useHostTransitionStatus:bT,useFormState:W7,useActionState:W7,useOptimistic:function(m){var y=or();y.memoizedState=y.baseState=m;var S={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return y.queue=S,y=vT.bind(null,De,!0,S),S.dispatch=y,[m,y]},useMemoCache:Ty,useCacheRefresh:function(){return or().memoizedState=qlt.bind(null,De)}},s$={readContext:Jt,use:Xf,useCallback:sF,useContext:Jt,useEffect:tF,useImperativeHandle:rF,useInsertionEffect:eF,useLayoutEffect:nF,useMemo:oF,useReducer:Uf,useRef:J7,useState:function(){return Uf(Vs)},useDebugValue:gT,useDeferredValue:function(m,y){var S=Qn();return aF(S,wn.memoizedState,m,y)},useTransition:function(){var m=Uf(Vs)[0],y=Qn().memoizedState;return[typeof m=="boolean"?m:ah(m),y]},useSyncExternalStore:F7,useId:uF,useHostTransitionStatus:bT,useFormState:q7,useActionState:q7,useOptimistic:function(m,y){var S=Qn();return Y7(S,wn,m,y)},useMemoCache:Ty,useCacheRefresh:pF},Hpt={readContext:Jt,use:Xf,useCallback:sF,useContext:Jt,useEffect:tF,useImperativeHandle:rF,useInsertionEffect:eF,useLayoutEffect:nF,useMemo:oF,useReducer:Ey,useRef:J7,useState:function(){return Ey(Vs)},useDebugValue:gT,useDeferredValue:function(m,y){var S=Qn();return wn===null?xT(S,m,y):aF(S,wn.memoizedState,m,y)},useTransition:function(){var m=Ey(Vs)[0],y=Qn().memoizedState;return[typeof m=="boolean"?m:ah(m),y]},useSyncExternalStore:F7,useId:uF,useHostTransitionStatus:bT,useFormState:K7,useActionState:K7,useOptimistic:function(m,y){var S=Qn();return wn!==null?Y7(S,wn,m,y):(S.baseState=m,[m,S.queue.dispatch])},useMemoCache:Ty,useCacheRefresh:pF},hm=null,Gy=0,dm=_F(!0),o$=_F(!1),xs=h(null),Mo=null,wi=h(0),S3={enqueueSetState:function(m,y,S){m=m._reactInternals;var N=Kr(),O=ds(N);O.payload=y,S!=null&&(O.callback=S),y=fs(m,O,N),y!==null&&(Jr(y,m,N),ra(y,m,N))},enqueueReplaceState:function(m,y,S){m=m._reactInternals;var N=Kr(),O=ds(N);O.tag=1,O.payload=y,S!=null&&(O.callback=S),y=fs(m,O,N),y!==null&&(Jr(y,m,N),ra(y,m,N))},enqueueForceUpdate:function(m,y){m=m._reactInternals;var S=Kr(),N=ds(S);N.tag=2,y!=null&&(N.callback=y),y=fs(m,N,S),y!==null&&(Jr(y,m,S),ra(y,m,S))}},a$=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)},c$=Error(i(461)),Ni=!1,w3={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null},ma=!1,ui=!1,P3=!1,l$=typeof WeakSet=="function"?WeakSet:Set,Ai=null,fi=null,Ar=!1,qs=null,fm=8192,Wpt={getCacheForType:function(m){var y=Jt(ti),S=y.data.get(m);return S===void 0&&(S=m(),y.data.set(m,S)),S}},vx=0,Sx=1,wx=2,Px=3,kx=4;if(typeof Symbol=="function"&&Symbol.for){var Hy=Symbol.for;vx=Hy("selector.component"),Sx=Hy("selector.has_pseudo_class"),wx=Hy("selector.role"),Px=Hy("selector.test_id"),kx=Hy("selector.text")}var qpt=typeof WeakMap=="function"?WeakMap:Map,Je=0,Nn=null,Ue=null,tn=0,xn=0,is=null,Ec=!1,mm=!1,k3=!1,_a=0,ei=0,Cc=0,xh=0,T3=0,bs=0,_m=0,Wy=null,Rr=null,M3=!1,E3=0,qy=1/0,Tx=null,Ic=null,Zi=0,Nc=null,ym=null,gm=0,C3=0,I3=null,u$=null,Zy=0,N3=null;return Xe.attemptContinuousHydration=function(m){if(m.tag===13){var y=wo(m,67108864);y!==null&&Jr(y,m,67108864),JT(m,67108864)}},Xe.attemptHydrationAtCurrentPriority=function(m){if(m.tag===13){var y=Kr();y=R(y);var S=wo(m,y);S!==null&&Jr(S,m,y),JT(m,y)}},Xe.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 S=1<<31-ts(y);m.entanglements[1]|=S,y&=~S}Ir(m),(Je&6)===0&&(qy=Ws()+500,So(0,!1))}}break;case 13:y=wo(m,2),y!==null&&Jr(y,m,2),oz(),JT(m,2)}},Xe.batchedUpdates=function(m,y){return m(y)},Xe.createComponentSelector=function(m){return{$$typeof:vx,value:m}},Xe.createContainer=function(m,y,S,N,O,$,K,ct,xt,It){return wz(m,y,!1,null,S,N,$,K,ct,xt,It,null)},Xe.createHasPseudoClassSelector=function(m){return{$$typeof:Sx,value:m}},Xe.createHydrationContainer=function(m,y,S,N,O,$,K,ct,xt,It,$t,Xt,Wt){return m=wz(S,N,!0,m,O,$,ct,xt,It,$t,Xt,Wt),m.context=Pz(null),S=m.current,N=Kr(),N=R(N),O=ds(N),O.callback=y??null,fs(S,O,N),y=N,m.current.lanes=y,M(m,y),Ir(m),m},Xe.createPortal=function(m,y,S){var N=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:qf,key:N==null?null:""+N,children:m,containerInfo:y,implementation:S}},Xe.createRoleSelector=function(m){return{$$typeof:wx,value:m}},Xe.createTestNameSelector=function(m){return{$$typeof:Px,value:m}},Xe.createTextSelector=function(m){return{$$typeof:kx,value:m}},Xe.defaultOnCaughtError=function(m){console.error(m)},Xe.defaultOnRecoverableError=function(m){a$(m)},Xe.defaultOnUncaughtError=function(m){a$(m)},Xe.deferredUpdates=function(m){var y=_e.T,S=pa();try{return Ii(32),_e.T=null,m()}finally{Ii(S),_e.T=y}},Xe.discreteUpdates=function(m,y,S,N,O){var $=_e.T,K=pa();try{return Ii(2),_e.T=null,m(y,S,N,O)}finally{Ii(K),_e.T=$,Je===0&&(qy=Ws()+500)}},Xe.findAllNodes=UT,Xe.findBoundingRects=function(m,y){if(!Dy)throw Error(i(363));y=UT(m,y),m=[];for(var S=0;S<y.length;S++)m.push(Dut(y[S]));for(y=m.length-1;0<y;y--){S=m[y];for(var N=S.x,O=N+S.width,$=S.y,K=$+S.height,ct=y-1;0<=ct;ct--)if(y!==ct){var xt=m[ct],It=xt.x,$t=It+xt.width,Xt=xt.y,Wt=Xt+xt.height;if(N>=It&&$>=Xt&&O<=$t&&K<=Wt){m.splice(y,1);break}else if(N!==It||S.width!==xt.width||Wt<$||Xt>K){if(!($!==Xt||S.height!==xt.height||$t<N||It>O)){It>N&&(xt.width+=It-N,xt.x=N),$t<O&&(xt.width=O-It),m.splice(y,1);break}}else{Xt>$&&(xt.height+=Xt-$,xt.y=$),Wt<K&&(xt.height=K-Xt),m.splice(y,1);break}}}return m},Xe.findHostInstance=kz,Xe.findHostInstanceWithNoPortals=function(m){return m=o(m),m=m!==null?c(m):null,m===null?null:$y(m.stateNode)},Xe.findHostInstanceWithWarning=function(m){return kz(m)},Xe.flushPassiveEffects=zy,Xe.flushSyncFromReconciler=function(m){var y=Je;Je|=1;var S=_e.T,N=pa();try{if(Ii(2),_e.T=null,m)return m()}finally{Ii(N),_e.T=S,Je=y,(Je&6)===0&&So(0,!1)}},Xe.flushSyncWork=oz,Xe.focusWithin=function(m,y){if(!Dy)throw Error(i(363));for(m=BT(m),y=nz(m,y),y=Array.from(y),m=0;m<y.length;){var S=y[m++],N=S.tag;if(!jy(S)){if((N===5||N===26||N===27)&&Yut(S.stateNode))return!0;for(S=S.child;S!==null;)y.push(S),S=S.sibling}}return!1},Xe.getFindAllNodesFailureDescription=function(m,y){if(!Dy)throw Error(i(363));var S=0,N=[];m=[BT(m),0];for(var O=0;O<m.length;){var $=m[O++],K=$.tag,ct=m[O++],xt=y[ct];if((K!==5&&K!==26&&K!==27||!jy($))&&(YT($,xt)&&(N.push(XT(xt)),ct++,ct>S&&(S=ct)),ct<y.length))for($=$.child;$!==null;)m.push($,ct),$=$.sibling}if(S<y.length){for(m=[];S<y.length;S++)m.push(XT(y[S]));return`findAllNodes was able to match part of the selector:
9
9
  `+(N.join(" > ")+`
10
10
 
11
11
  No matching component was found for:
@@ -65,13 +65,13 @@ You passed in: '`+this.raw_options[n]+"'");return i};tl.prototype._is_valid_sele
65
65
  `);break}}return n}});var qK=ue((vle,WK)=>{"use strict";var M5t=RK(),E5t=HK(),C5t=bN(),I5t={unformatted:["code","pre","em","strong","span"],indent_inner_html:!0,indent_char:" ",indent_size:2,sep:`
66
66
  `};WK.exports=function(e,t){var i=C5t({},I5t,t);return e=M5t.html(e,i),i.ocd===!0?(i.newlines&&(i.sep=i.newlines),N5t(e,i)):e};function N5t(n,e){return E5t(n,e).replace(/^\s+/g,"").replace(/\s+$/g,`
67
67
  `).replace(/(\s*<!--)/g,`
68
- $1`).replace(/>(\s*)(?=<!--\s*\/)/g,"> ")}});var ott=ue(Fw=>{"use strict";var i6t=Symbol.for("react.transitional.element"),r6t=Symbol.for("react.fragment");function stt(n,e,t){var i=null;if(t!==void 0&&(i=""+t),e.key!==void 0&&(i=""+e.key),"key"in e){t={};for(var r in e)r!=="key"&&(t[r]=e[r])}else t=e;return e=t.ref,{$$typeof:i6t,type:n,key:i,ref:e!==void 0?e:null,props:t}}Fw.Fragment=r6t;Fw.jsx=stt;Fw.jsxs=stt});var Md=ue((Rhe,att)=>{"use strict";att.exports=ott()});function st(n,e){return Array.isArray(e)?[n.a*e[0]+n.c*e[1]+n.e,n.b*e[0]+n.d*e[1]+n.f]:{x:n.a*e.x+n.c*e.y+n.e,y:n.b*e.x+n.d*e.y+n.f}}var IA=qt(()=>{"use strict"});var NA=qt(()=>{"use strict"});var ctt=qt(()=>{"use strict"});var ltt=qt(()=>{"use strict"});function utt(n){let{a:e,b:t,c:i,d:r,e:s,f:o}=n,a=e*r-t*i;return{a:r/a,b:t/-a,c:i/-a,d:e/a,e:(r*s-i*o)/-a,f:(t*s-e*o)/a}}var AA=qt(()=>{"use strict"});function Ed(n){return typeof n>"u"}var zw=qt(()=>{"use strict"});var ptt=qt(()=>{"use strict";zw()});function yn(n,e=0){return{a:1,c:0,e:n,b:0,d:1,f:e}}var R_=qt(()=>{"use strict"});function pl(...n){n=Array.isArray(n[0])?n[0]:n;let e=(t,i)=>({a:t.a*i.a+t.c*i.b,c:t.a*i.c+t.c*i.d,e:t.a*i.e+t.c*i.f+t.e,b:t.b*i.a+t.d*i.b,d:t.b*i.c+t.d*i.d,f:t.b*i.e+t.d*i.f+t.f});switch(n.length){case 0:throw new Error("no matrices provided");case 1:return n[0];case 2:return e(n[0],n[1]);default:{let[t,i,...r]=n,s=e(t,i);return pl(s,...r)}}}function Fe(...n){return pl(...n)}var Cd=qt(()=>{"use strict"});function ls(n,e,t){let i=s6t(n),r=o6t(n),s={a:i,c:-r,e:0,b:r,d:i,f:0};return Ed(e)||Ed(t)?s:pl([yn(e,t),s,yn(-e,-t)])}var s6t,o6t,qhe,$w=qt(()=>{"use strict";zw();R_();Cd();({cos:s6t,sin:o6t,PI:qhe}=Math)});function ki(n,e=void 0,t=void 0,i=void 0){Ed(e)&&(e=n);let r={a:n,c:0,e:0,b:0,d:e,f:0};return Ed(t)||Ed(i)?r:pl([yn(t,i),r,yn(-t,-i)])}var M1=qt(()=>{"use strict";zw();R_();Cd()});var RA=qt(()=>{"use strict"});var nde,OA=qt(()=>{"use strict";({tan:nde}=Math)});function htt(n){return Ba(n)}function Ba(n){return`matrix(${n.a},${n.b},${n.c},${n.d},${n.e},${n.f})`}var dtt=qt(()=>{"use strict"});function ftt(n,e=1e10){return{a:Math.round(n.a*e)/e,b:Math.round(n.b*e)/e,c:Math.round(n.c*e)/e,d:Math.round(n.d*e)/e,e:Math.round(n.e*e)/e,f:Math.round(n.f*e)/e}}var LA=qt(()=>{"use strict"});function mtt(n,e){let t=n[0].x!=null?n[0].x:n[0][0],i=n[0].y!=null?n[0].y:n[0][1],r=e[0].x!=null?e[0].x:e[0][0],s=e[0].y!=null?e[0].y:e[0][1],o=n[1].x!=null?n[1].x:n[1][0],a=n[1].y!=null?n[1].y:n[1][1],c=e[1].x!=null?e[1].x:e[1][0],l=e[1].y!=null?e[1].y:e[1][1],u=n[2].x!=null?n[2].x:n[2][0],h=n[2].y!=null?n[2].y:n[2][1],d=e[2].x!=null?e[2].x:e[2][0],_=e[2].y!=null?e[2].y:e[2][1],g={a:t-u,b:i-h,c:o-u,d:a-h,e:u,f:h},x={a:r-d,b:s-_,c:c-d,d:l-_,e:d,f:_},v=utt(g),P=pl([x,v]);return ftt(P)}var _tt=qt(()=>{"use strict";AA();Cd();LA()});var ytt=qt(()=>{"use strict";NA();R_();M1();$w();OA();RA()});function a6t(n,e){function t(){this.constructor=n}t.prototype=e.prototype,n.prototype=new t}function Dw(n,e,t,i){var r=Error.call(this,n);return Object.setPrototypeOf&&Object.setPrototypeOf(r,Dw.prototype),r.expected=e,r.found=t,r.location=i,r.name="SyntaxError",r}function FA(n,e,t){return t=t||" ",n.length>e?n:(e-=n.length,t+=t.repeat(e),n+t.slice(0,e))}var gtt=qt(()=>{"use strict";a6t(Dw,Error);Dw.prototype.format=function(n){var e="Error: "+this.message;if(this.location){var t=null,i;for(i=0;i<n.length;i++)if(n[i].source===this.location.source){t=n[i].text.split(/\r\n|\n|\r/g);break}var r=this.location.start,s=this.location.source&&typeof this.location.source.offset=="function"?this.location.source.offset(r):r,o=this.location.source+":"+s.line+":"+s.column;if(t){var a=this.location.end,c=FA("",s.line.toString().length," "),l=t[r.line-1],u=r.line===a.line?a.column:l.length+1,h=u-r.column||1;e+=`
68
+ $1`).replace(/>(\s*)(?=<!--\s*\/)/g,"> ")}});var ott=ue(Fw=>{"use strict";var i6t=Symbol.for("react.transitional.element"),r6t=Symbol.for("react.fragment");function stt(n,e,t){var i=null;if(t!==void 0&&(i=""+t),e.key!==void 0&&(i=""+e.key),"key"in e){t={};for(var r in e)r!=="key"&&(t[r]=e[r])}else t=e;return e=t.ref,{$$typeof:i6t,type:n,key:i,ref:e!==void 0?e:null,props:t}}Fw.Fragment=r6t;Fw.jsx=stt;Fw.jsxs=stt});var Md=ue((Rhe,att)=>{"use strict";att.exports=ott()});function st(n,e){return Array.isArray(e)?[n.a*e[0]+n.c*e[1]+n.e,n.b*e[0]+n.d*e[1]+n.f]:{x:n.a*e.x+n.c*e.y+n.e,y:n.b*e.x+n.d*e.y+n.f}}var IA=qt(()=>{"use strict"});var NA=qt(()=>{"use strict"});var ctt=qt(()=>{"use strict"});var ltt=qt(()=>{"use strict"});function utt(n){let{a:e,b:t,c:i,d:r,e:s,f:o}=n,a=e*r-t*i;return{a:r/a,b:t/-a,c:i/-a,d:e/a,e:(r*s-i*o)/-a,f:(t*s-e*o)/a}}var AA=qt(()=>{"use strict"});function Ed(n){return typeof n>"u"}var zw=qt(()=>{"use strict"});var ptt=qt(()=>{"use strict";zw()});function yn(n,e=0){return{a:1,c:0,e:n,b:0,d:1,f:e}}var R_=qt(()=>{"use strict"});function pl(...n){n=Array.isArray(n[0])?n[0]:n;let e=(t,i)=>({a:t.a*i.a+t.c*i.b,c:t.a*i.c+t.c*i.d,e:t.a*i.e+t.c*i.f+t.e,b:t.b*i.a+t.d*i.b,d:t.b*i.c+t.d*i.d,f:t.b*i.e+t.d*i.f+t.f});switch(n.length){case 0:throw new Error("no matrices provided");case 1:return n[0];case 2:return e(n[0],n[1]);default:{let[t,i,...r]=n,s=e(t,i);return pl(s,...r)}}}function Fe(...n){return pl(...n)}var Cd=qt(()=>{"use strict"});function ls(n,e,t){let i=s6t(n),r=o6t(n),s={a:i,c:-r,e:0,b:r,d:i,f:0};return Ed(e)||Ed(t)?s:pl([yn(e,t),s,yn(-e,-t)])}var s6t,o6t,qhe,$w=qt(()=>{"use strict";zw();R_();Cd();({cos:s6t,sin:o6t,PI:qhe}=Math)});function Ti(n,e=void 0,t=void 0,i=void 0){Ed(e)&&(e=n);let r={a:n,c:0,e:0,b:0,d:e,f:0};return Ed(t)||Ed(i)?r:pl([yn(t,i),r,yn(-t,-i)])}var M1=qt(()=>{"use strict";zw();R_();Cd()});var RA=qt(()=>{"use strict"});var nde,OA=qt(()=>{"use strict";({tan:nde}=Math)});function htt(n){return Ba(n)}function Ba(n){return`matrix(${n.a},${n.b},${n.c},${n.d},${n.e},${n.f})`}var dtt=qt(()=>{"use strict"});function ftt(n,e=1e10){return{a:Math.round(n.a*e)/e,b:Math.round(n.b*e)/e,c:Math.round(n.c*e)/e,d:Math.round(n.d*e)/e,e:Math.round(n.e*e)/e,f:Math.round(n.f*e)/e}}var LA=qt(()=>{"use strict"});function mtt(n,e){let t=n[0].x!=null?n[0].x:n[0][0],i=n[0].y!=null?n[0].y:n[0][1],r=e[0].x!=null?e[0].x:e[0][0],s=e[0].y!=null?e[0].y:e[0][1],o=n[1].x!=null?n[1].x:n[1][0],a=n[1].y!=null?n[1].y:n[1][1],c=e[1].x!=null?e[1].x:e[1][0],l=e[1].y!=null?e[1].y:e[1][1],u=n[2].x!=null?n[2].x:n[2][0],h=n[2].y!=null?n[2].y:n[2][1],d=e[2].x!=null?e[2].x:e[2][0],_=e[2].y!=null?e[2].y:e[2][1],g={a:t-u,b:i-h,c:o-u,d:a-h,e:u,f:h},x={a:r-d,b:s-_,c:c-d,d:l-_,e:d,f:_},v=utt(g),P=pl([x,v]);return ftt(P)}var _tt=qt(()=>{"use strict";AA();Cd();LA()});var ytt=qt(()=>{"use strict";NA();R_();M1();$w();OA();RA()});function a6t(n,e){function t(){this.constructor=n}t.prototype=e.prototype,n.prototype=new t}function Dw(n,e,t,i){var r=Error.call(this,n);return Object.setPrototypeOf&&Object.setPrototypeOf(r,Dw.prototype),r.expected=e,r.found=t,r.location=i,r.name="SyntaxError",r}function FA(n,e,t){return t=t||" ",n.length>e?n:(e-=n.length,t+=t.repeat(e),n+t.slice(0,e))}var gtt=qt(()=>{"use strict";a6t(Dw,Error);Dw.prototype.format=function(n){var e="Error: "+this.message;if(this.location){var t=null,i;for(i=0;i<n.length;i++)if(n[i].source===this.location.source){t=n[i].text.split(/\r\n|\n|\r/g);break}var r=this.location.start,s=this.location.source&&typeof this.location.source.offset=="function"?this.location.source.offset(r):r,o=this.location.source+":"+s.line+":"+s.column;if(t){var a=this.location.end,c=FA("",s.line.toString().length," "),l=t[r.line-1],u=r.line===a.line?a.column:l.length+1,h=u-r.column||1;e+=`
69
69
  --> `+o+`
70
70
  `+c+` |
71
71
  `+s.line+" | "+l+`
72
72
  `+c+" | "+FA("",r.column-1," ")+FA("",h,"^")}else e+=`
73
- at `+o}return e};Dw.buildMessage=function(n,e){var t={literal:function(l){return'"'+r(l.text)+'"'},class:function(l){var u=l.parts.map(function(h){return Array.isArray(h)?s(h[0])+"-"+s(h[1]):s(h)});return"["+(l.inverted?"^":"")+u.join("")+"]"},any:function(){return"any character"},end:function(){return"end of input"},other:function(l){return l.description}};function i(l){return l.charCodeAt(0).toString(16).toUpperCase()}function r(l){return l.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(u){return"\\x0"+i(u)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(u){return"\\x"+i(u)})}function s(l){return l.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(u){return"\\x0"+i(u)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(u){return"\\x"+i(u)})}function o(l){return t[l.type](l)}function a(l){var u=l.map(o),h,d;if(u.sort(),u.length>0){for(h=1,d=1;h<u.length;h++)u[h-1]!==u[h]&&(u[d]=u[h],d++);u.length=d}switch(u.length){case 1:return u[0];case 2:return u[0]+" or "+u[1];default:return u.slice(0,-1).join(", ")+", or "+u[u.length-1]}}function c(l){return l?'"'+r(l)+'"':"end of input"}return"Expected "+a(n)+" but "+c(e)+" found."}});var xtt=qt(()=>{"use strict";gtt()});var btt=qt(()=>{"use strict";M1();Cd()});var vtt=qt(()=>{"use strict"});var Stt=qt(()=>{"use strict";R_();IA();$w();M1();Cd()});var Yt=qt(()=>{"use strict";IA();NA();ctt();ltt();AA();ptt();$w();M1();RA();OA();dtt();Cd();R_();_tt();LA();ytt();xtt();btt();vtt();Stt()});var _et={};vh(_et,{CIRCUIT_TO_SVG_VERSION:()=>ml,circuitJsonToPcbSvg:()=>fRt,circuitJsonToSchematicSvg:()=>M8t,convertCircuitJsonToAssemblySvg:()=>kRt,convertCircuitJsonToPcbSvg:()=>Ztt,convertCircuitJsonToPinoutSvg:()=>HRt,convertCircuitJsonToSchematicSimulationSvg:()=>K8t,convertCircuitJsonToSchematicSvg:()=>VA,convertCircuitJsonToSimulationGraphSvg:()=>pet,convertCircuitJsonToSolderPasteMask:()=>tOt,createErrorTextOverlay:()=>$_,createSvgObjectsForSchComponentPortHovers:()=>aet,getSoftwareUsedString:()=>fl,isSimulationExperiment:()=>HA,isSimulationTransientVoltageGraph:()=>GA,isSimulationVoltageProbe:()=>uet});function c6t(n,e,t){let{transform:i,shouldDrawErrors:r}=t;if(!r)return[];let{pcb_port_ids:s}=n,o=e.find(d=>d.type==="pcb_port"&&d.pcb_port_id===s?.[0]),a=e.find(d=>d.type==="pcb_port"&&d.pcb_port_id===s?.[1]);if(!o||!a){let _=n.message?.match(/pcb_via\[#?(pcb_via_\d+)\]/)?.[1],g=e.find(x=>x.type==="pcb_via"&&x.pcb_via_id===_);if(g&&g.type==="pcb_via")return l6t(n,g,t);if(n.center){let x=st(i,{x:n.center.x,y:n.center.y});return YA([{name:"rect",type:"element",attributes:{x:(x.x-5).toString(),y:(x.y-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${x.x} ${x.y})`},children:[],value:""},{name:"text",type:"element",attributes:{x:x.x.toString(),y:(x.y-15).toString(),fill:"red","font-family":"sans-serif","font-size":"12","text-anchor":"middle"},children:[{type:"text",value:n.message||"Pcb Trace Error",name:"",attributes:{},children:[]}],value:""}])}else return[]}let c=st(i,{x:o.x,y:o.y}),l=st(i,{x:a.x,y:a.y}),u={x:(c.x+l.x)/2,y:(c.y+l.y)/2};if(isNaN(c.x)||isNaN(c.y)||isNaN(l.x)||isNaN(l.y)||isNaN(u.x)||isNaN(u.y))return[];let h=[{name:"line",type:"element",attributes:{x1:c.x.toString(),y1:c.y.toString(),x2:u.x.toString(),y2:u.y.toString(),stroke:"red","stroke-width":"1.5","stroke-dasharray":"2,2"},children:[],value:""},{name:"line",type:"element",attributes:{x1:u.x.toString(),y1:u.y.toString(),x2:l.x.toString(),y2:l.y.toString(),stroke:"red","stroke-width":"1.5","stroke-dasharray":"2,2"},children:[],value:""},{name:"rect",type:"element",attributes:{x:(u.x-5).toString(),y:(u.y-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${u.x} ${u.y})`},children:[],value:""},{name:"text",type:"element",attributes:{x:u.x.toString(),y:(u.y-15).toString(),fill:"red","font-family":"sans-serif","font-size":"12","text-anchor":"middle"},children:[{type:"text",value:n.message||"Pcb Trace Error",name:"",attributes:{},children:[]}],value:""}];return YA(h)}function l6t(n,e,t){let{transform:i}=t;if(n.center&&e){let r=st(i,{x:n.center.x,y:n.center.y}),s=st(i,{x:e.x,y:e.y}),o=s.x-r.x,a=s.y-r.y,c=Math.sqrt(o*o+a*a),l=Math.atan2(a,o)*180/Math.PI,h=c+10*2,d=20,_=(r.x+s.x)/2,g=(r.y+s.y)/2;return YA([{name:"rect",type:"element",attributes:{x:(_-h/2).toString(),y:(g-d/2).toString(),width:h.toString(),height:d.toString(),fill:"none",stroke:"red","stroke-width":"1","stroke-dasharray":"3,2",transform:`rotate(${l} ${_} ${g})`},children:[],value:""},{name:"rect",type:"element",attributes:{x:(_-5).toString(),y:(g-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${_} ${g})`},children:[],value:""},{name:"text",type:"element",attributes:{x:_.toString(),y:(g-d/2-5).toString(),fill:"red","font-family":"sans-serif","font-size":"12","text-anchor":"middle"},children:[{type:"text",value:n.message||"Pcb Trace Error",name:"",attributes:{},children:[]}],value:""}])}return[]}function YA(n){return n.map(e=>({...e,attributes:{...e.attributes??{},"data-type":e.attributes?.["data-type"]??"pcb_trace_error","data-pcb-layer":e.attributes?.["data-pcb-layer"]??"overlay"},children:(e.children??[]).map(t=>t?.type==="element"?{...t,attributes:{...t.attributes??{},"data-type":t.attributes?.["data-type"]??"pcb_trace_error","data-pcb-layer":t.attributes?.["data-pcb-layer"]??"overlay"}}:t)}))}function u6t(n){return n.map(e=>({...e,attributes:{...e.attributes??{},"data-type":e.attributes?.["data-type"]??"pcb_footprint_overlap_error","data-pcb-layer":e.attributes?.["data-pcb-layer"]??"overlay"},children:(e.children??[]).map(t=>t?.type==="element"?{...t,attributes:{...t.attributes??{},"data-type":t.attributes?.["data-type"]??"pcb_footprint_overlap_error","data-pcb-layer":t.attributes?.["data-pcb-layer"]??"overlay"}}:t)}))}function p6t(n,e,t){let{transform:i,shouldDrawErrors:r}=t;if(!r)return[];let s=[],o=[],a=[];if(n.pcb_smtpad_ids)for(let u of n.pcb_smtpad_ids){let h=e.find(d=>d.type==="pcb_smtpad"&&d.pcb_smtpad_id===u);h&&(o.push({x:h.x,y:h.y,type:"pcb_smtpad",id:u,pcb_port_id:h.pcb_port_id}),h.pcb_port_id&&a.push(h.pcb_port_id))}let c=a.length>1&&a.every(u=>u===a[0]),l=o;if(c&&(l=o.filter(u=>u.type!=="pcb_smtpad")),n.pcb_plated_hole_ids)for(let u of n.pcb_plated_hole_ids){let h=e.find(d=>d.type==="pcb_plated_hole"&&d.pcb_plated_hole_id===u);h&&l.push({x:h.x,y:h.y,type:"pcb_plated_hole",id:u})}if(n.pcb_hole_ids)for(let u of n.pcb_hole_ids){let h=e.find(d=>d.type==="pcb_hole"&&d.pcb_hole_id===u);h&&l.push({x:h.x,y:h.y,type:"pcb_hole",id:u})}if(l.length>0){let u=l.reduce((_,g)=>_+g.x,0)/l.length,h=l.reduce((_,g)=>_+g.y,0)/l.length,d=st(i,{x:u,y:h});s.push({name:"rect",type:"element",attributes:{x:(d.x-5).toString(),y:(d.y-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${d.x} ${d.y})`},children:[],value:""}),s.push({name:"text",type:"element",attributes:{x:d.x.toString(),y:(d.y-15).toString(),fill:"red","font-family":"sans-serif","font-size":"12","text-anchor":"middle"},children:[{type:"text",value:n.message||"PCB Footprint Overlap Error",name:"",attributes:{},children:[]}],value:""});for(let _ of l){let g=st(i,{x:_.x,y:_.y});s.push({name:"rect",type:"element",attributes:{x:(g.x-5).toString(),y:(g.y-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${g.x} ${g.y})`},children:[],value:""}),l.length>1&&s.push({name:"line",type:"element",attributes:{x1:d.x.toString(),y1:d.y.toString(),x2:g.x.toString(),y2:g.y.toString(),stroke:"red","stroke-width":"1.5","stroke-dasharray":"2,2"},children:[],value:""})}}return u6t(s)}function h6t(n,e){let{transform:t,layer:i}=e;if(!n.route||!Array.isArray(n.route))return[];let r=n.route[0],s=n.route[n.route.length-1],o=r.x===s.x&&r.y===s.y,a=n.route.slice(0,o?-1:void 0).map((c,l)=>{let[u,h]=st(t,[c.x,c.y]);return l===0?`M ${u} ${h}`:`L ${u} ${h}`}).join(" ")+(o?" Z":"");return[{name:"path",type:"element",attributes:{class:"pcb-fabrication-note-path",stroke:n.color||"rgba(255,255,255,0.5)",fill:"none",d:a,"stroke-width":(n.stroke_width*Math.abs(t.a)).toString(),"data-pcb-component-id":n.pcb_component_id,"data-pcb-fabrication-note-path-id":n.pcb_fabrication_note_path_id,"data-type":"pcb_fabrication_note_path","data-pcb-layer":"overlay"},value:"",children:[]}]}function d6t(n,e){let{transform:t,layer:i}=e,{anchor_position:r,anchor_alignment:s,text:o,font_size:a=1,layer:c="top",color:l}=n;if(i&&c!==i)return[];if(!r||typeof r.x!="number"||typeof r.y!="number")return console.error("Invalid anchor_position:",r),[];let[u,h]=st(t,[r.x,r.y]),d=a*Math.abs(t.a),_=Fe(yn(u,h),ls(Math.PI/180));return[{name:"text",type:"element",attributes:{x:"0",y:"0","font-family":"Arial, sans-serif","font-size":d.toString(),"text-anchor":"middle","dominant-baseline":"central",transform:Ba(_),class:"pcb-fabrication-note-text",fill:l||"rgba(255,255,255,0.5)","data-type":"pcb_fabrication_note_text","data-pcb-layer":"overlay"},children:[{type:"text",value:o,name:"",attributes:{},children:[]}],value:""}]}function _6t(n,e){let{transform:t,layer:i}=e,{center:r,width:s,height:o,stroke_width:a,is_filled:c,has_stroke:l,is_stroke_dashed:u,color:h,layer:d="top",pcb_component_id:_,pcb_fabrication_note_rect_id:g,corner_radius:x}=n;if(i&&d!==i)return[];if(!r||typeof r.x!="number"||typeof r.y!="number"||typeof s!="number"||typeof o!="number")return console.error("Invalid pcb_fabrication_note_rect data",{center:r,width:s,height:o}),[];let v=s/2,P=o/2,[w,T]=st(t,[r.x-v,r.y+P]),[k,C]=st(t,[r.x+v,r.y-P]),M=Math.min(w,k),I=Math.min(T,C),E=Math.abs(k-w),A=Math.abs(C-T),B=(typeof a=="number"?a:0)*Math.abs(t.a),j=h??f6t,U=typeof x=="number"&&x>0?x:0,V=U*Math.abs(t.a),H=U*Math.abs(t.d),et={x:M.toString(),y:I.toString(),width:E.toString(),height:A.toString(),class:"pcb-fabrication-note-rect","data-type":"pcb_fabrication_note_rect","data-pcb-fabrication-note-rect-id":g,"data-pcb-layer":"overlay"};if(_!==void 0&&(et["data-pcb-component-id"]=_),V>0&&(et.rx=V.toString()),H>0&&(et.ry=H.toString()),c?et.fill=h??m6t:et.fill="none",l??B>0){if(et.stroke=j,et["stroke-width"]=B.toString(),u){let G=.2*Math.abs(t.a),Q=.1*Math.abs(t.a);et["stroke-dasharray"]=`${G} ${Q}`}}else et.stroke="none";return[{name:"rect",type:"element",value:"",attributes:et,children:[]}]}function zA(n){let e=Math.hypot(n.x,n.y)||1;return{x:n.x/e,y:n.y/e}}function wtt(n){return n.map((e,t)=>t===0?`M ${e.x} ${e.y}`:`L ${e.x} ${e.y}`).join(" ")}function y6t(n,e){let{transform:t,layer:i}=e,{from:r,to:s,text:o,font_size:a=1,color:c,arrow_size:l,layer:u,pcb_component_id:h,pcb_fabrication_note_dimension_id:d,offset_distance:_,offset_direction:g}=n;if(i&&u&&u!==i)return[];if(!r||!s||typeof r!="object"||typeof s!="object")return console.error("Invalid pcb_fabrication_note_dimension endpoints",{from:r,to:s}),[];if(typeof r.x!="number"||typeof r.y!="number"||typeof s.x!="number"||typeof s.y!="number")return console.error("Invalid pcb_fabrication_note_dimension point values",{from:r,to:s}),[];let x=typeof l=="number"?l:void 0;if(x===void 0||!Number.isFinite(x)||x<=0)return console.error("Invalid pcb_fabrication_note_dimension arrow_size",l),[];let v=x,P=zA({x:s.x-r.x,y:s.y-r.y});if(Number.isNaN(P.x)||Number.isNaN(P.y))return[];let w={x:-P.y,y:P.x},T=g&&typeof g.x=="number"&&typeof g.y=="number",k=T?zA({x:g.x,y:g.y}):{x:0,y:0},C=typeof _=="number"?_:0,M={x:k.x*C,y:k.y*C},I=le=>({x:le.x+M.x,y:le.y+M.y}),E=I(r),A=I(s),R=v/2,B={x:E.x+P.x*v,y:E.y+P.y*v},j={x:A.x-P.x*v,y:A.y-P.y*v},U=[Kt(E),Kt({x:B.x+w.x*R,y:B.y+w.y*R}),Kt({x:B.x-w.x*R,y:B.y-w.y*R})],V=[Kt(A),Kt({x:j.x+w.x*R,y:j.y+w.y*R}),Kt({x:j.x-w.x*R,y:j.y-w.y*R})],[H,et]=st(t,[B.x,B.y]),[tt,mt]=st(t,[j.x,j.y]),G=v/5*Math.abs(t.a),Q=c||"rgba(255,255,255,0.5)",nt=T&&(Math.abs(k.x)>Number.EPSILON||Math.abs(k.y)>Number.EPSILON)?k:w,pt=C+v,ht=le=>{let Jt={x:le.x+nt.x*pt,y:le.y+nt.y*pt},[Wn,Ci]=st(t,[le.x,le.y]),[Cr,Us]=st(t,[Jt.x,Jt.y]);return{name:"path",type:"element",value:"",attributes:{d:`M ${Wn} ${Ci} L ${Cr} ${Us}`,stroke:Q,fill:"none","stroke-width":G.toString(),"stroke-linecap":"round",class:"pcb-fabrication-note-dimension-extension"},children:[]}},wt=[ht(r),ht(s)],Et={x:(r.x+s.x)/2+M.x,y:(r.y+s.y)/2+M.y},ot=v*1.5,X={x:Et.x+w.x*ot,y:Et.y+w.y*ot},[W,rt]=st(t,[X.x,X.y]),[ut,yt]=st(t,[E.x,E.y]),[Z,at]=st(t,[A.x,A.y]),Mt=zA({x:Z-ut,y:at-yt}),Ft=Math.atan2(Mt.y,Mt.x)*180/Math.PI;(Ft>90||Ft<-90)&&(Ft+=180);let Ot=a*Math.abs(t.a),Ce=[...wt,{name:"path",type:"element",value:"",attributes:{d:`M ${H} ${et} L ${tt} ${mt}`,stroke:Q,fill:"none","stroke-width":G.toString(),"stroke-linecap":"round",class:"pcb-fabrication-note-dimension-line"},children:[]},{name:"path",type:"element",value:"",attributes:{d:`${wtt(U)} Z`,fill:Q,class:"pcb-fabrication-note-dimension-arrow"},children:[]},{name:"path",type:"element",value:"",attributes:{d:`${wtt(V)} Z`,fill:Q,class:"pcb-fabrication-note-dimension-arrow"},children:[]}];o&&Ce.push({name:"text",type:"element",value:"",attributes:{x:W.toString(),y:rt.toString(),fill:Q,"font-size":Ot.toString(),"font-family":"Arial, sans-serif","text-anchor":"middle","dominant-baseline":"central",class:"pcb-fabrication-note-dimension-text",transform:`rotate(${Ft} ${W} ${rt})`},children:[{type:"text",name:"",value:o,attributes:{},children:[]}]});let Se={class:"pcb-fabrication-note-dimension","data-type":"pcb_fabrication_note_dimension","data-pcb-fabrication-note-dimension-id":d,"data-pcb-layer":u??"overlay"};return h!==void 0&&(Se["data-pcb-component-id"]=h),[{name:"g",type:"element",value:"",attributes:Se,children:Ce}];function Kt(le){let[Jt,Wn]=st(t,[le.x,le.y]);return{x:Jt,y:Wn}}}function $A(n){let e=Math.hypot(n.x,n.y)||1;return{x:n.x/e,y:n.y/e}}function Ptt(n){return n.map((e,t)=>t===0?`M ${e.x} ${e.y}`:`L ${e.x} ${e.y}`).join(" ")}function g6t(n,e){let{transform:t}=e,{from:i,to:r,text:s,font_size:o=1,color:a,arrow_size:c,offset_distance:l,offset_direction:u}=n;if(!i||!r)return console.error("Invalid pcb_note_dimension endpoints",{from:i,to:r}),[];if(!Number.isFinite(c)||c<=0)return console.error("Invalid pcb_note_dimension arrow_size",c),[];let h=$A({x:r.x-i.x,y:r.y-i.y});if(Number.isNaN(h.x)||Number.isNaN(h.y))return[];let d={x:-h.y,y:h.x},_=u&&typeof u.x=="number"&&typeof u.y=="number",g=_?$A({x:u.x,y:u.y}):{x:0,y:0},x=typeof l=="number"?l:0,v={x:g.x*x,y:g.y*x},P=at=>({x:at.x+v.x,y:at.y+v.y}),w=P(i),T=P(r),k=c/2,C={x:w.x+h.x*c,y:w.y+h.y*c},M={x:T.x-h.x*c,y:T.y-h.y*c},I=[Z(w),Z({x:C.x+d.x*k,y:C.y+d.y*k}),Z({x:C.x-d.x*k,y:C.y-d.y*k})],E=[Z(T),Z({x:M.x+d.x*k,y:M.y+d.y*k}),Z({x:M.x-d.x*k,y:M.y-d.y*k})],[A,R]=st(t,[C.x,C.y]),[B,j]=st(t,[M.x,M.y]),U=c/5*Math.abs(t.a),V=a||Mi.board.user_2,H=_&&(Math.abs(g.x)>Number.EPSILON||Math.abs(g.y)>Number.EPSILON)?g:d,et=x+c,tt=at=>{let Mt={x:at.x+H.x*et,y:at.y+H.y*et},[Ft,Ot]=st(t,[at.x,at.y]),[Ce,Se]=st(t,[Mt.x,Mt.y]);return{name:"path",type:"element",value:"",attributes:{d:`M ${Ft} ${Ot} L ${Ce} ${Se}`,stroke:V,fill:"none","stroke-width":U.toString(),"stroke-linecap":"round",class:"pcb-note-dimension-extension"},children:[]}},mt=[tt(i),tt(r)],G={x:(i.x+r.x)/2+v.x,y:(i.y+r.y)/2+v.y},Q=c*1.5,nt={x:G.x+d.x*Q,y:G.y+d.y*Q},[pt,ht]=st(t,[nt.x,nt.y]),[wt,Et]=st(t,[w.x,w.y]),[ot,X]=st(t,[T.x,T.y]),W=$A({x:ot-wt,y:X-Et}),rt=Math.atan2(W.y,W.x)*180/Math.PI;(rt>90||rt<-90)&&(rt+=180);let ut=o*Math.abs(t.a),yt=[...mt,{name:"path",type:"element",value:"",attributes:{d:`M ${A} ${R} L ${B} ${j}`,stroke:V,fill:"none","stroke-width":U.toString(),"stroke-linecap":"round",class:"pcb-note-dimension-line"},children:[]},{name:"path",type:"element",value:"",attributes:{d:`${Ptt(I)} Z`,fill:V,class:"pcb-note-dimension-arrow"},children:[]},{name:"path",type:"element",value:"",attributes:{d:`${Ptt(E)} Z`,fill:V,class:"pcb-note-dimension-arrow"},children:[]}];return s&&yt.push({name:"text",type:"element",value:"",attributes:{x:pt.toString(),y:ht.toString(),fill:V,"font-size":ut.toString(),"font-family":"Arial, sans-serif","text-anchor":"middle","dominant-baseline":"central",class:"pcb-note-dimension-text",transform:`rotate(${rt} ${pt} ${ht})`},children:[{type:"text",name:"",value:s,attributes:{},children:[]}]}),[{name:"g",type:"element",value:"",attributes:{class:"pcb-note-dimension","data-type":"pcb_note_dimension","data-pcb-note-dimension-id":n.pcb_note_dimension_id,"data-pcb-layer":"overlay"},children:yt}];function Z(at){let[Mt,Ft]=st(t,[at.x,at.y]);return{x:Mt,y:Ft}}}function b6t(n,e){let{transform:t}=e,{anchor_position:i,text:r,font_size:s=1,anchor_alignment:o="center",color:a}=n;if(!i||typeof i.x!="number"||typeof i.y!="number")return console.error("Invalid pcb_note_text anchor_position",i),[];if(typeof r!="string"||r.length===0)return console.error("Invalid pcb_note_text text",r),[];let[c,l]=st(t,[i.x,i.y]),u=s*Math.abs(t.a),h="middle",d="central";switch(o){case"top_left":h="start",d="text-before-edge";break;case"top_right":h="end",d="text-before-edge";break;case"bottom_left":h="start",d="text-after-edge";break;case"bottom_right":h="end",d="text-after-edge";break;case"center":default:h="middle",d="central";break}return[{name:"text",type:"element",value:"",attributes:{x:c.toString(),y:l.toString(),fill:a??x6t,"font-family":"Arial, sans-serif","font-size":u.toString(),"text-anchor":h,"dominant-baseline":d,class:"pcb-note-text","data-type":"pcb_note_text","data-pcb-note-text-id":n.pcb_note_text_id,"data-pcb-layer":"overlay"},children:[{type:"text",name:"",value:r,attributes:{},children:[]}]}]}function w6t(n,e){let{transform:t}=e,{center:i,width:r,height:s,stroke_width:o,is_filled:a,has_stroke:c,is_stroke_dashed:l,color:u,corner_radius:h}=n;if(!i||typeof i.x!="number"||typeof i.y!="number"||typeof r!="number"||typeof s!="number")return console.error("Invalid pcb_note_rect data",{center:i,width:r,height:s}),[];let d=r/2,_=s/2,[g,x]=st(t,[i.x-d,i.y+_]),[v,P]=st(t,[i.x+d,i.y-_]),w=Math.min(g,v),T=Math.min(x,P),k=Math.abs(v-g),C=Math.abs(P-x),I=(typeof o=="number"?o:0)*Math.abs(t.a),E=typeof h=="number"&&h>0?h:0,A=E*Math.abs(t.a),R=E*Math.abs(t.d),B=u??v6t,j={x:w.toString(),y:T.toString(),width:k.toString(),height:C.toString(),class:"pcb-note-rect","data-type":"pcb_note_rect","data-pcb-note-rect-id":n.pcb_note_rect_id,"data-pcb-layer":"overlay"};if(A>0&&(j.rx=A.toString()),R>0&&(j.ry=R.toString()),a?j.fill=u??S6t:j.fill="none",c??I>0){if(j.stroke=B,j["stroke-width"]=I.toString(),l){let H=.2*Math.abs(t.a),et=.1*Math.abs(t.a);j["stroke-dasharray"]=`${H} ${et}`}}else j.stroke="none";return[{name:"rect",type:"element",value:"",attributes:j,children:[]}]}function k6t(n,e){let{transform:t}=e;if(!Array.isArray(n.route)||n.route.length===0)return console.error("Invalid pcb_note_path route",n.route),[];for(let o of n.route)if(typeof o.x!="number"||typeof o.y!="number")return console.error("Invalid point in pcb_note_path",o),[];let i=n.route.map((o,a)=>{let[c,l]=st(t,[o.x,o.y]);return a===0?`M ${c} ${l}`:`L ${c} ${l}`}).join(" "),r=n.stroke_width*Math.abs(t.a);return[{name:"path",type:"element",value:"",attributes:{d:i,stroke:n.color??P6t,fill:"none","stroke-width":r.toString(),class:"pcb-note-path","data-type":"pcb_note_path","data-pcb-note-path-id":n.pcb_note_path_id,"data-pcb-layer":"overlay"},children:[]}]}function M6t(n,e){let{transform:t}=e,{x1:i,y1:r,x2:s,y2:o,stroke_width:a,color:c,is_dashed:l}=n;if(typeof i!="number"||typeof r!="number"||typeof s!="number"||typeof o!="number")return console.error("Invalid pcb_note_line coordinates",{x1:i,y1:r,x2:s,y2:o}),[];let[u,h]=st(t,[i,r]),[d,_]=st(t,[s,o]),x=(typeof a=="number"?a:0)*Math.abs(t.a),v={x1:u.toString(),y1:h.toString(),x2:d.toString(),y2:_.toString(),stroke:c??T6t,"stroke-width":x.toString(),"stroke-linecap":"round",class:"pcb-note-line","data-type":"pcb_note_line","data-pcb-note-line-id":n.pcb_note_line_id,"data-pcb-layer":"overlay"};if(l){let w=.2*Math.abs(t.a),T=.1*Math.abs(t.a);v["stroke-dasharray"]=`${w} ${T}`}return[{name:"line",type:"element",value:"",attributes:v,children:[]}]}function E6t(n,e){let{transform:t,colorMap:i,showSolderMask:r}=e,[s,o]=st(t,[n.x,n.y]),a=Array.isArray(n.layers)&&n.layers[0]||n.layer||"top",c=!!n.is_covered_with_solder_mask,l=(n.soldermask_margin??0)*Math.abs(t.a),u=r&&c&&l!==0,h=i.soldermaskWithCopperUnderneath.top;if(n.shape==="pill"){let d=n.outer_width*Math.abs(t.a),_=n.outer_height*Math.abs(t.a),g=n.hole_width*Math.abs(t.a),x=n.hole_height*Math.abs(t.a),v=n.ccw_rotation||0,P=v?`translate(${s} ${o}) rotate(${-v})`:`translate(${s} ${o})`,w=v?`translate(${s} ${o}) rotate(${-v})`:`translate(${s} ${o})`,T=(C,M)=>{if(C>M){let I=M/2,E=C-2*I;return`M${-C/2+I},${-I} h${E} a${I},${I} 0 0 1 0,${M} h${-E} a${I},${I} 0 0 1 0,${-M} z`}else if(M>C){let I=C/2,E=M-2*I;return`M${I},${-M/2+I} v${E} a${I},${I} 0 0 1 ${-C},0 v${-E} a${I},${I} 0 0 1 ${C},0 z`}else{let I=C/2;return`M${-I},0 a${I},${I} 0 0 1 ${C},0 a${I},${I} 0 0 1 ${-C},0 z`}},k=[{name:"path",type:"element",attributes:{class:"pcb-hole-outer",fill:i.copper.top,d:T(d,_),transform:P,"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"path",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,d:T(g,x),transform:w,"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];if(u){let C=d+2*l,M=_+2*l;l<0?k=[{name:"path",type:"element",attributes:{class:"pcb-hole-outer-covered",fill:h,d:T(d,_),transform:P,"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"path",type:"element",attributes:{class:"pcb-hole-outer-exposed",fill:i.copper.top,d:T(C,M),transform:P,"data-type":"pcb_soldermask"},value:"",children:[]},k[1]]:k.unshift({name:"path",type:"element",attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,d:T(C,M),transform:P,"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"},value:"",children:[]})}return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through"},children:k,value:""}]}if(n.shape==="oval"){let d=n.outer_width*Math.abs(t.a),_=n.outer_height*Math.abs(t.a),g=n.hole_width*Math.abs(t.a),x=n.hole_height*Math.abs(t.a),v=n.ccw_rotation||0,P=v?`translate(${s} ${o}) rotate(${-v})`:`translate(${s} ${o})`,w=[{name:"ellipse",type:"element",attributes:{class:"pcb-hole-outer",fill:i.copper.top,cx:"0",cy:"0",rx:(d/2).toString(),ry:(_/2).toString(),transform:P,"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"ellipse",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,cx:"0",cy:"0",rx:(g/2).toString(),ry:(x/2).toString(),transform:P,"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through"},children:w,value:""}]}if(n.shape==="circle"){let d=n.outer_diameter*Math.abs(t.a),_=n.outer_diameter*Math.abs(t.a),g=n.hole_diameter*Math.abs(t.a),x=n.hole_diameter*Math.abs(t.a),v=Math.min(d,_)/2,P=Math.min(g,x)/2,w=[{name:"circle",type:"element",attributes:{class:"pcb-hole-outer",fill:i.copper.top,cx:s.toString(),cy:o.toString(),r:v.toString(),"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,cx:s.toString(),cy:o.toString(),r:P.toString(),"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];if(u){let T=v+l;l<0?w=[{name:"circle",type:"element",attributes:{class:"pcb-hole-outer-covered",fill:h,cx:s.toString(),cy:o.toString(),r:v.toString(),"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"pcb-hole-outer-exposed",fill:i.copper.top,cx:s.toString(),cy:o.toString(),r:T.toString(),"data-type":"pcb_soldermask"},value:"",children:[]},w[1]]:w.unshift({name:"circle",type:"element",attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,cx:s.toString(),cy:o.toString(),r:T.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"},value:"",children:[]})}return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through"},children:w,value:""}]}if(n.shape==="circular_hole_with_rect_pad"){let d=n,_=n.hole_diameter*Math.abs(t.a),g=n.rect_pad_width*Math.abs(t.a),x=n.rect_pad_height*Math.abs(t.a),v=(n.rect_border_radius??0)*Math.abs(t.a),P=_/2,[w,T]=st(t,[d.x+(d.hole_offset_x??0),d.y+(d.hole_offset_y??0)]),k=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-pad",fill:i.copper.top,x:(s-g/2).toString(),y:(o-x/2).toString(),width:g.toString(),height:x.toString(),...v?{rx:v.toString(),ry:v.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,cx:w.toString(),cy:T.toString(),r:P.toString(),"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];if(u){let C=g+2*l,M=x+2*l,I=v+l;l<0?k=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-covered",fill:h,x:(s-g/2).toString(),y:(o-x/2).toString(),width:g.toString(),height:x.toString(),...v?{rx:v.toString(),ry:v.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-exposed",fill:i.copper.top,x:(s-C/2).toString(),y:(o-M/2).toString(),width:C.toString(),height:M.toString(),...I>0?{rx:I.toString(),ry:I.toString()}:{},"data-type":"pcb_soldermask"},value:"",children:[]},k[1]]:k.unshift({name:"rect",type:"element",attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,x:(s-C/2).toString(),y:(o-M/2).toString(),width:C.toString(),height:M.toString(),...v?{rx:I.toString(),ry:I.toString()}:{},"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"},value:"",children:[]})}return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through"},children:k,value:""}]}if(n.shape==="pill_hole_with_rect_pad"){let d=n,_=d.rect_pad_width*Math.abs(t.a),g=d.rect_pad_height*Math.abs(t.a),x=(d.rect_border_radius??0)*Math.abs(t.a),v=d.hole_height*Math.abs(t.a),P=d.hole_width*Math.abs(t.a),w=d,T=w.hole_offset_x??0,k=w.hole_offset_y??0,[C,M]=st(t,[d.x+T,d.y+k]),I=Math.min(v,P)/2,E=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-pad",fill:i.copper.top,x:(s-_/2).toString(),y:(o-g/2).toString(),width:_.toString(),height:g.toString(),...x?{rx:x.toString(),ry:x.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,x:(C-P/2).toString(),y:(M-v/2).toString(),width:P.toString(),height:v.toString(),rx:I.toString(),ry:I.toString(),"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];if(u){let A=_+2*l,R=g+2*l,B=x+l;l<0?E=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-covered",fill:h,x:(s-_/2).toString(),y:(o-g/2).toString(),width:_.toString(),height:g.toString(),...x?{rx:x.toString(),ry:x.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-exposed",fill:i.copper.top,x:(s-A/2).toString(),y:(o-R/2).toString(),width:A.toString(),height:R.toString(),...B>0?{rx:B.toString(),ry:B.toString()}:{},"data-type":"pcb_soldermask"},value:"",children:[]},E[1]]:E.unshift({name:"rect",type:"element",attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,x:(s-A/2).toString(),y:(o-R/2).toString(),width:A.toString(),height:R.toString(),...x?{rx:B.toString(),ry:B.toString()}:{},"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"},value:"",children:[]})}return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through"},children:E,value:""}]}if(n.shape==="rotated_pill_hole_with_rect_pad"){let d=n,_=d.rect_pad_width*Math.abs(t.a),g=d.rect_pad_height*Math.abs(t.a),x=(d.rect_border_radius??0)*Math.abs(t.a),v=d.hole_height*Math.abs(t.a),P=d.hole_width*Math.abs(t.a),w=d,T=w.hole_offset_x??0,k=w.hole_offset_y??0,[C,M]=st(t,[d.x+T,d.y+k]),I=Math.min(v,P)/2,E=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-pad",fill:i.copper.top,x:(-_/2).toString(),y:(-g/2).toString(),width:_.toString(),height:g.toString(),transform:`translate(${s} ${o}) rotate(${-d.rect_ccw_rotation})`,...x?{rx:x.toString(),ry:x.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,x:(-P/2).toString(),y:(-v/2).toString(),width:P.toString(),height:v.toString(),rx:I.toString(),ry:I.toString(),transform:`translate(${C} ${M}) rotate(${-d.hole_ccw_rotation})`,"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];if(u){let A=_+2*l,R=g+2*l,B=x+l;l<0?E=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-covered",fill:h,x:(-_/2).toString(),y:(-g/2).toString(),width:_.toString(),height:g.toString(),transform:`translate(${s} ${o}) rotate(${-d.rect_ccw_rotation})`,...x?{rx:x.toString(),ry:x.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-exposed",fill:i.copper.top,x:(-A/2).toString(),y:(-R/2).toString(),width:A.toString(),height:R.toString(),transform:`translate(${s} ${o}) rotate(${-d.rect_ccw_rotation})`,...B>0?{rx:B.toString(),ry:B.toString()}:{},"data-type":"pcb_soldermask"},value:"",children:[]},E[1]]:E.push({name:"rect",type:"element",attributes:{class:"pcb-solder-mask",fill:h,x:(-A/2).toString(),y:(-R/2).toString(),width:A.toString(),height:R.toString(),transform:`translate(${s} ${o}) rotate(${-d.rect_ccw_rotation})`,...x?{rx:B.toString(),ry:B.toString()}:{},"data-type":"pcb_soldermask"},value:"",children:[]})}return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through"},children:E,value:""}]}if(n.shape==="hole_with_polygon_pad"){let d=n,_=d.pad_outline||[],g=d.x??0,x=d.y??0,P=_.map(C=>st(t,[g+C.x,x+C.y])).map(C=>C.join(",")).join(" "),[w,T]=st(t,[g+d.hole_offset_x,x+d.hole_offset_y]),k=()=>{if(d.hole_shape==="circle"){let M=(d.hole_diameter??0)*Math.abs(t.a)/2;return{name:"circle",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,cx:w.toString(),cy:T.toString(),r:M.toString(),"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}}if(d.hole_shape==="oval"){let C=(d.hole_width??0)*Math.abs(t.a),M=(d.hole_height??0)*Math.abs(t.a),I=C/2,E=M/2;return{name:"ellipse",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,cx:w.toString(),cy:T.toString(),rx:I.toString(),ry:E.toString(),"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}}if(d.hole_shape==="pill"||d.hole_shape==="rotated_pill"){let C=(d.hole_width??0)*Math.abs(t.a),M=(d.hole_height??0)*Math.abs(t.a),I=C>M,E=Math.min(C,M)/2,A=Math.abs(I?C-M:M-C),R=I?`M${-A/2},${-E} h${A} a${E},${E} 0 0 1 0,${M} h-${A} a${E},${E} 0 0 1 0,-${M} z`:`M${-E},${-A/2} v${A} a${E},${E} 0 0 0 ${C},0 v-${A} a${E},${E} 0 0 0 -${C},0 z`;return{name:"path",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,d:R,transform:`translate(${w} ${T})`,"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}}return{name:"g",type:"element",attributes:{},value:"",children:[]}};return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through"},children:[{name:"polygon",type:"element",attributes:{class:"pcb-hole-outer-pad",fill:i.copper.top,points:P,"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},k()],value:""}]}return[]}function C6t(n,e){let{transform:t,layer:i,colorMap:r}=e;if(!n.route||!Array.isArray(n.route))return[];let s=n.route.map((u,h)=>{let[d,_]=st(t,[u.x,u.y]);return h===0?`M ${d} ${_}`:`L ${d} ${_}`}).join(" "),o=n.route[0],a=n.route[n.route.length-1];o&&a&&o.x===a.x&&o.y===a.y&&(s+=" Z");let c=n.layer||"top";if(i&&c!==i)return[];let l=c==="bottom"?r.silkscreen.bottom:r.silkscreen.top;return[{name:"path",type:"element",attributes:{class:`pcb-silkscreen pcb-silkscreen-${c}`,d:s,fill:"none",stroke:l,"stroke-width":(n.stroke_width*Math.abs(t.a)).toString(),"stroke-linecap":"round","stroke-linejoin":"round","data-pcb-component-id":n.pcb_component_id,"data-pcb-silkscreen-path-id":n.pcb_silkscreen_path_id,"data-type":"pcb_silkscreen_path","data-pcb-layer":c},value:"",children:[]}]}function I6t(n,e){let{transform:t,layer:i,colorMap:r,circuitJson:s}=e,{anchor_position:o,text:a,font_size:c=1,layer:l="top",ccw_rotation:u=0,anchor_alignment:h="center"}=n;if(i&&l!==i)return[];if(!o||typeof o.x!="number"||typeof o.y!="number")return console.error("Invalid anchor_position:",o),[];let[d,_]=st(t,[o.x,o.y]),g=c*Math.abs(t.a),x="middle",v="central",P=0,w=0;switch(h){case"top_left":x="start",v="text-before-edge";break;case"top_center":x="middle",v="text-before-edge";break;case"top_right":x="end",v="text-before-edge";break;case"center_left":x="start",v="central";break;case"center_right":x="end",v="central";break;case"bottom_left":x="start",v="text-after-edge";break;case"bottom_center":x="middle",v="text-after-edge";break;case"bottom_right":x="end",v="text-after-edge";break;case"center":default:x="middle",v="central";break}let T=Fe(yn(d,_),ls(-u*Math.PI/180),...l==="bottom"?[ki(-1,1)]:[]),k=l==="bottom"?r.silkscreen.bottom:r.silkscreen.top,C=a.split(`
74
- `),M=C.length===1?[{type:"text",value:a,name:"",attributes:{},children:[]}]:C.map((E,A)=>({type:"element",name:"tspan",value:"",attributes:{x:"0",...A>0?{dy:g.toString()}:{}},children:[{type:"text",value:E,name:"",attributes:{},children:[]}]}));return[{name:"text",type:"element",attributes:{x:"0",y:"0",dx:P.toString(),dy:w.toString(),fill:k,"font-family":"Arial, sans-serif","font-size":g.toString(),"text-anchor":x,"dominant-baseline":v,transform:Ba(T),class:`pcb-silkscreen-text pcb-silkscreen-${l}`,"data-pcb-silkscreen-text-id":n.pcb_component_id,stroke:"none","data-type":"pcb_silkscreen_text","data-pcb-layer":l},children:M,value:""}]}function N6t(n,e){let{transform:t,layer:i,colorMap:r}=e,{center:s,width:o,height:a,layer:c="top",pcb_silkscreen_rect_id:l,stroke_width:u,is_filled:h,has_stroke:d,is_stroke_dashed:_,corner_radius:g}=n;if(i&&c!==i)return[];if(!s||typeof s.x!="number"||typeof s.y!="number"||typeof o!="number"||typeof a!="number")return console.error("Invalid rectangle data:",{center:s,width:o,height:a}),[];let[x,v]=st(t,[s.x,s.y]),P=typeof g=="number"&&g>0?g:0,w=P*Math.abs(t.a),T=P*Math.abs(t.d),k=o*Math.abs(t.a),C=a*Math.abs(t.d),M=u*Math.abs(t.a),I=c==="bottom"?r.silkscreen.bottom:r.silkscreen.top,E={x:(x-k/2).toString(),y:(v-C/2).toString(),width:k.toString(),height:C.toString(),class:`pcb-silkscreen-rect pcb-silkscreen-${c}`,"data-pcb-silkscreen-rect-id":l,"data-type":"pcb_silkscreen_rect","data-pcb-layer":c};w>0&&(E.rx=w.toString()),T>0&&(E.ry=T.toString()),E.fill=h?I:"none";let A;if(d===void 0?A=M>0:A=d,A){if(E.stroke=I,E["stroke-width"]=M.toString(),_){let B=.1*Math.abs(t.a),j=.05*Math.abs(t.a);E["stroke-dasharray"]=`${B} ${j}`}}else E.stroke="none";return[{name:"rect",type:"element",attributes:E,value:"",children:[]}]}function A6t(n,e){let{transform:t,layer:i,colorMap:r}=e,{center:s,radius:o,layer:a="top",pcb_silkscreen_circle_id:c,stroke_width:l=1}=n;if(i&&a!==i)return[];if(!s||typeof s.x!="number"||typeof s.y!="number"||typeof o!="number")return console.error("Invalid PCB Silkscreen Circle data:",{center:s,radius:o}),[];let[u,h]=st(t,[s.x,s.y]),d=o*Math.abs(t.a),_=l*Math.abs(t.a),g=a==="bottom"?r.silkscreen.bottom:r.silkscreen.top;return[{name:"circle",type:"element",attributes:{cx:u.toString(),cy:h.toString(),r:d.toString(),class:`pcb-silkscreen-circle pcb-silkscreen-${a}`,stroke:g,"stroke-width":_.toString(),"data-pcb-silkscreen-circle-id":c,"data-type":"pcb_silkscreen_circle","data-pcb-layer":a},value:"",children:[]}]}function R6t(n,e){let{transform:t,layer:i,colorMap:r}=e,{x1:s,y1:o,x2:a,y2:c,stroke_width:l,layer:u="top",pcb_silkscreen_line_id:h}=n;if(i&&u!==i)return[];if(typeof s!="number"||typeof o!="number"||typeof a!="number"||typeof c!="number")return console.error("Invalid coordinates:",{x1:s,y1:o,x2:a,y2:c}),[];let[d,_]=st(t,[s,o]),[g,x]=st(t,[a,c]),v=l*Math.abs(t.a),P=u==="bottom"?r.silkscreen.bottom:r.silkscreen.top;return[{name:"line",type:"element",attributes:{x1:d.toString(),y1:_.toString(),x2:g.toString(),y2:x.toString(),stroke:P,"stroke-width":v.toString(),class:`pcb-silkscreen-line pcb-silkscreen-${u}`,"data-pcb-silkscreen-line-id":h,"data-type":"pcb_silkscreen_line","data-pcb-layer":u},value:"",children:[]}]}function O6t(n,e){let{transform:t,layer:i,colorMap:r}=e,{center:s,width:o,height:a,layer:c="top",pcb_courtyard_rect_id:l}=n;if(i&&c!==i)return[];if(!s||typeof s.x!="number"||typeof s.y!="number"||typeof o!="number"||typeof a!="number")return console.error("Invalid courtyard rectangle data:",{center:s,width:o,height:a}),[];let[u,h]=st(t,[s.x,s.y]),d=o*Math.abs(t.a),_=a*Math.abs(t.d),g=.05*Math.abs(t.a),x=r.courtyard,v={x:(u-d/2).toString(),y:(h-_/2).toString(),width:d.toString(),height:_.toString(),class:`pcb-courtyard-rect pcb-courtyard-${c}`,"data-pcb-courtyard-rect-id":l,"data-type":"pcb_courtyard_rect","data-pcb-layer":c};return v.fill="none",v.stroke=x,v["stroke-width"]=g.toString(),[{name:"rect",type:"element",attributes:v,value:"",children:[]}]}function L6t(n){let e=[];for(let t=0;t<n.length-1;t++)e.push([n[t],n[t+1]]);return e}function Os(n,e=Ti){return e.copper[n]??"white"}function jw(n){return F6t[n]??"rgb(105, 105, 105)"}function z6t(n,e){let{transform:t,layer:i,colorMap:r,showSolderMask:s}=e;if(!n.route||!Array.isArray(n.route)||n.route.length<2)return[];let o=L6t(n.route),a=[];for(let[c,l]of o){let u=st(t,[c.x,c.y]),h=st(t,[l.x,l.y]),d="layer"in c?c.layer:"layer"in l?l.layer:null;if(!d||i&&d!==i)continue;let _=Os(d,r),g=r.soldermaskWithCopperUnderneath[d],x="width"in c?c.width:"width"in l?l.width:null,v=x?(x*Math.abs(t.a)).toString():"0.3";if(s){let P={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask",stroke:g,fill:"none",d:`M ${u[0]} ${u[1]} L ${h[0]} ${h[1]}`,"stroke-width":v,"stroke-linecap":"round","stroke-linejoin":"round","shape-rendering":"crispEdges","data-type":"pcb_trace_soldermask","data-pcb-layer":d}};a.push(P)}else{let P={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-trace",stroke:_,fill:"none",d:`M ${u[0]} ${u[1]} L ${h[0]} ${h[1]}`,"stroke-width":v,"stroke-linecap":"round","stroke-linejoin":"round","shape-rendering":"crispEdges","data-type":s?"pcb_soldermask":"pcb_trace","data-pcb-layer":d}};a.push(P)}}return a}function $6t(n,e){let{transform:t,layer:i,colorMap:r,showSolderMask:s}=e;if(i&&n.layer!==i)return[];let o=!!n?.is_covered_with_solder_mask,a=s&&o,c=r.soldermaskWithCopperUnderneath[n.layer]??r.soldermaskWithCopperUnderneath.top,l=(n.soldermask_margin??0)*Math.abs(t.a);if(n.shape==="rect"||n.shape==="rotated_rect"){let u=n.width*Math.abs(t.a),h=n.height*Math.abs(t.d),[d,_]=st(t,[n.x,n.y]),x=(n.corner_radius??n.rect_border_radius??0)*Math.abs(t.a);if(n.shape==="rotated_rect"&&n.ccw_rotation){let C={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad",fill:Os(n.layer,r),x:(-u/2).toString(),y:(-h/2).toString(),width:u.toString(),height:h.toString(),transform:`translate(${d} ${_}) rotate(${-n.ccw_rotation})`,"data-type":"pcb_smtpad","data-pcb-layer":n.layer,...x?{rx:x.toString(),ry:x.toString()}:{}}};if(!a)return[C];let M=u+2*l,I=h+2*l,E=x?x+l:0;if(l<0){let R={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(-u/2).toString(),y:(-h/2).toString(),width:u.toString(),height:h.toString(),transform:`translate(${d} ${_}) rotate(${-n.ccw_rotation})`,"data-type":"pcb_smtpad","data-pcb-layer":n.layer,...x?{rx:x.toString(),ry:x.toString()}:{}}},B={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-exposed",fill:Os(n.layer,r),x:(-M/2).toString(),y:(-I/2).toString(),width:M.toString(),height:I.toString(),transform:`translate(${d} ${_}) rotate(${-n.ccw_rotation})`,"data-type":"pcb_soldermask","data-pcb-layer":n.layer,...E>0?{rx:E.toString(),ry:E.toString()}:{}}};return[R,B]}return l===0?[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(-u/2).toString(),y:(-h/2).toString(),width:u.toString(),height:h.toString(),transform:`translate(${d} ${_}) rotate(${-n.ccw_rotation})`,"data-type":"pcb_smtpad","data-pcb-layer":n.layer,...x?{rx:x.toString(),ry:x.toString()}:{}}}]:[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:r.substrate,x:(-M/2).toString(),y:(-I/2).toString(),width:M.toString(),height:I.toString(),transform:`translate(${d} ${_}) rotate(${-n.ccw_rotation})`,...E>0?{rx:E.toString(),ry:E.toString()}:{},"data-type":"pcb_soldermask_opening","data-pcb-layer":`soldermask-${n.layer}`}},C]}let v={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad",fill:Os(n.layer,r),x:(d-u/2).toString(),y:(_-h/2).toString(),width:u.toString(),height:h.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer,...x?{rx:x.toString(),ry:x.toString()}:{}}};if(!a)return[v];let P=u+2*l,w=h+2*l,T=x?x+l:0;if(l<0){let C={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(d-u/2).toString(),y:(_-h/2).toString(),width:u.toString(),height:h.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer,...x?{rx:x.toString(),ry:x.toString()}:{}}},M={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-exposed",fill:Os(n.layer,r),x:(d-P/2).toString(),y:(_-w/2).toString(),width:P.toString(),height:w.toString(),"data-type":"pcb_soldermask","data-pcb-layer":n.layer,...T>0?{rx:T.toString(),ry:T.toString()}:{}}};return[C,M]}return l===0?[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(d-u/2).toString(),y:(_-h/2).toString(),width:u.toString(),height:h.toString(),...T>0?{rx:x.toString(),ry:x.toString()}:{},"data-type":"pcb_smtpad","data-pcb-layer":n.layer}}]:[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:r.substrate,x:(d-P/2).toString(),y:(_-w/2).toString(),width:P.toString(),height:w.toString(),...T>0?{rx:T.toString(),ry:T.toString()}:{},"data-type":"pcb_soldermask_opening","data-pcb-layer":`soldermask-${n.layer}`}},v]}if(n.shape==="pill"){let u=n.width*Math.abs(t.a),h=n.height*Math.abs(t.d),d=n.radius*Math.abs(t.a),[_,g]=st(t,[n.x,n.y]),x={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad",fill:Os(n.layer,r),x:(_-u/2).toString(),y:(g-h/2).toString(),width:u.toString(),height:h.toString(),rx:d.toString(),ry:d.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}};if(!a)return[x];let v=u+2*l,P=h+2*l,w=d+l;if(l<0){let k={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(_-u/2).toString(),y:(g-h/2).toString(),width:u.toString(),height:h.toString(),rx:d.toString(),ry:d.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}},C={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-exposed",fill:Os(n.layer,r),x:(_-v/2).toString(),y:(g-P/2).toString(),width:v.toString(),height:P.toString(),rx:w.toString(),ry:w.toString(),"data-type":"pcb_soldermask","data-pcb-layer":n.layer}};return[k,C]}return l===0?[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(_-u/2).toString(),y:(g-h/2).toString(),width:u.toString(),height:h.toString(),rx:d.toString(),ry:d.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}}]:[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:r.substrate,x:(_-v/2).toString(),y:(g-P/2).toString(),width:v.toString(),height:P.toString(),rx:w.toString(),ry:w.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":`soldermask-${n.layer}`}},x]}if(n.shape==="circle"){let u=n.radius*Math.abs(t.a),[h,d]=st(t,[n.x,n.y]),_={name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-pad",fill:Os(n.layer,r),cx:h.toString(),cy:d.toString(),r:u.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}};if(!a)return[_];let g=u+l;if(l<0){let v={name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,cx:h.toString(),cy:d.toString(),r:u.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}},P={name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-pad-exposed",fill:Os(n.layer,r),cx:h.toString(),cy:d.toString(),r:g.toString(),"data-type":"pcb_soldermask","data-pcb-layer":n.layer}};return[v,P]}return l===0?[{name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,cx:h.toString(),cy:d.toString(),r:u.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}}]:[{name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:r.substrate,cx:h.toString(),cy:d.toString(),r:g.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":`soldermask-${n.layer}`}},_]}if(n.shape==="polygon"){let u=(n.points??[]).map(g=>st(t,[g.x,g.y])),h={name:"polygon",type:"element",value:"",children:[],attributes:{class:"pcb-pad",fill:Os(n.layer,r),points:u.map(g=>g.join(",")).join(" "),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}};if(!a)return[h];let d=u;if(l!==0){let g=u.reduce((v,P)=>v+P[0],0)/u.length,x=u.reduce((v,P)=>v+P[1],0)/u.length;d=u.map(([v,P])=>{let w=v-g,T=P-x,k=Math.sqrt(w*w+T*T);if(k===0)return[v,P];let C=w/k,M=T/k;return[v+C*l,P+M*l]})}if(l<0){let g={name:"polygon",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,points:u.map(v=>v.join(",")).join(" "),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}},x={name:"polygon",type:"element",value:"",children:[],attributes:{class:"pcb-pad-exposed",fill:Os(n.layer,r),points:d.map(v=>v.join(",")).join(" "),"data-type":"pcb_soldermask","data-pcb-layer":n.layer}};return[g,x]}return l===0?[{name:"polygon",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,points:u.map(x=>x.join(",")).join(" "),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}}]:[{name:"polygon",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:r.substrate,points:d.map(g=>g.join(",")).join(" "),"data-type":"pcb_soldermask_opening","data-pcb-layer":`soldermask-${n.layer}`}},h]}return[]}function Wtt(n,e){let{transform:t,colorMap:i,showSolderMask:r}=e,{width:s,height:o,center:a,outline:c}=n,l;if(c&&Array.isArray(c)&&c.length>=3)l=c.map((h,d)=>{let[_,g]=st(t,[h.x,h.y]);return d===0?`M ${_} ${g}`:`L ${_} ${g}`}).join(" ");else{let h=s/2,d=o/2,_=st(t,[a.x-h,a.y-d]),g=st(t,[a.x+h,a.y-d]),x=st(t,[a.x+h,a.y+d]),v=st(t,[a.x-h,a.y+d]);l=`M ${_[0]} ${_[1]} L ${g[0]} ${g[1]} L ${x[0]} ${x[1]} L ${v[0]} ${v[1]}`}l+=" Z";let u=[];return r&&u.push({name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-board-soldermask",d:l,fill:i.soldermask.top,"fill-opacity":"0.8",stroke:"none","data-type":"pcb_soldermask","data-pcb-layer":"soldermask-top"}}),u.push({name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-board",d:l,fill:"none",stroke:i.boardOutline,"stroke-width":(.1*Math.abs(t.a)).toString(),"data-type":"pcb_board","data-pcb-layer":"board"}}),u}function D6t(n,e){let{transform:t,colorMap:i,showSolderMask:r}=e,s=Number(n.width),o=Number(n.height),a=n.center??{x:s/2,y:o/2},c=s/2,l=o/2,u=st(t,[a.x-c,a.y-l]),h=st(t,[a.x+c,a.y-l]),d=st(t,[a.x+c,a.y+l]),_=st(t,[a.x-c,a.y+l]),g=`M ${u[0]} ${u[1]} L ${h[0]} ${h[1]} L ${d[0]} ${d[1]} L ${_[0]} ${_[1]} Z`,x=n.covered_with_solder_mask!==!1,v=!!(r&&x);return[{name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-panel",d:g,fill:"none",stroke:i.boardOutline,"stroke-width":(.1*Math.abs(t.a)).toString(),"data-type":"pcb_panel","data-pcb-layer":"board"}}]}function j6t(n,e){let{transform:t,colorMap:i}=e,[r,s]=st(t,[n.x,n.y]),o=n.outer_diameter*Math.abs(t.a),a=n.outer_diameter*Math.abs(t.a),c=n.hole_diameter*Math.abs(t.a),l=n.hole_diameter*Math.abs(t.a),u=Math.min(o,a)/2,h=Math.min(c,l)/2;return{name:"g",type:"element",attributes:{"data-type":"pcb_via","data-pcb-layer":"through"},children:[{name:"circle",type:"element",attributes:{class:"pcb-hole-outer",fill:i.copper.top,cx:r.toString(),cy:s.toString(),r:u.toString(),"data-type":"pcb_via","data-pcb-layer":"top"}},{name:"circle",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,cx:r.toString(),cy:s.toString(),r:h.toString(),"data-type":"pcb_via","data-pcb-layer":"drill"}}]}}function B6t(n,e){let{transform:t,colorMap:i,showSolderMask:r}=e,[s,o]=st(t,[n.x,n.y]),a=!!n.is_covered_with_solder_mask,c=(n.soldermask_margin??0)*Math.abs(t.a),l=r&&a&&c!==0,u=i.soldermask.top;if(n.hole_shape==="circle"||n.hole_shape==="square"){let h=n.hole_diameter*Math.abs(t.a),d=h/2;if(n.hole_shape==="circle"){let v={name:"circle",type:"element",attributes:{class:"pcb-hole",cx:s.toString(),cy:o.toString(),r:d.toString(),fill:i.drill,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[v];let P=d+c;if(c<0){let T={name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,cx:s.toString(),cy:o.toString(),r:d.toString(),"data-type":"pcb_hole","data-pcb-layer":"drill"}},k={name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:i.drill,cx:s.toString(),cy:o.toString(),r:P.toString(),"data-type":"pcb_soldermask"}};return[T,k]}return[{name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,cx:s.toString(),cy:o.toString(),r:P.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"}},v]}let _={name:"rect",type:"element",attributes:{class:"pcb-hole",x:(s-d).toString(),y:(o-d).toString(),width:h.toString(),height:h.toString(),fill:i.drill,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[_];let g=h+2*c;if(c<0){let v={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,x:(s-d).toString(),y:(o-d).toString(),width:h.toString(),height:h.toString(),"data-type":"pcb_hole","data-pcb-layer":"drill"}},P={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:i.drill,x:(s-g/2).toString(),y:(o-g/2).toString(),width:g.toString(),height:g.toString(),"data-type":"pcb_soldermask"}};return[v,P]}return[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,x:(s-g/2).toString(),y:(o-g/2).toString(),width:g.toString(),height:g.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"}},_]}if(n.hole_shape==="oval"){let h=n.hole_width*Math.abs(t.a),d=n.hole_height*Math.abs(t.a),_=h/2,g=d/2,x={name:"ellipse",type:"element",attributes:{class:"pcb-hole",cx:s.toString(),cy:o.toString(),rx:_.toString(),ry:g.toString(),fill:i.drill,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[x];let v=_+c,P=g+c;if(c<0){let T={name:"ellipse",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,cx:s.toString(),cy:o.toString(),rx:_.toString(),ry:g.toString(),"data-type":"pcb_hole","data-pcb-layer":"drill"}},k={name:"ellipse",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:i.drill,cx:s.toString(),cy:o.toString(),rx:v.toString(),ry:P.toString(),"data-type":"pcb_soldermask"}};return[T,k]}return[{name:"ellipse",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,cx:s.toString(),cy:o.toString(),rx:v.toString(),ry:P.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"}},x]}if(n.hole_shape==="rect"){let h=n.hole_width*Math.abs(t.a),d=n.hole_height*Math.abs(t.a),_={name:"rect",type:"element",attributes:{class:"pcb-hole",x:(s-h/2).toString(),y:(o-d/2).toString(),width:h.toString(),height:d.toString(),fill:i.drill,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[_];let g=h+2*c,x=d+2*c;if(c<0){let P={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,x:(s-h/2).toString(),y:(o-d/2).toString(),width:h.toString(),height:d.toString(),"data-type":"pcb_hole","data-pcb-layer":"drill"}},w={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:i.drill,x:(s-g/2).toString(),y:(o-x/2).toString(),width:g.toString(),height:x.toString(),"data-type":"pcb_soldermask"}};return[P,w]}return[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,x:(s-g/2).toString(),y:(o-x/2).toString(),width:g.toString(),height:x.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"}},_]}if(n.hole_shape==="pill"){let h=n.hole_width*Math.abs(t.a),d=n.hole_height*Math.abs(t.a),_=h>d,g=Math.min(h,d)/2,x=Math.abs(_?h-d:d-h),v=_?`M${s-x/2},${o-g} h${x} a${g},${g} 0 0 1 0,${d} h-${x} a${g},${g} 0 0 1 0,-${d} z`:`M${s-g},${o-x/2} v${x} a${g},${g} 0 0 0 ${h},0 v-${x} a${g},${g} 0 0 0 -${h},0 z`,P={name:"path",type:"element",attributes:{class:"pcb-hole",fill:i.drill,d:v,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[P];let w=h+2*c,T=d+2*c,k=w>T,C=Math.min(w,T)/2,M=Math.abs(k?w-T:T-w),I=k?`M${s-M/2},${o-C} h${M} a${C},${C} 0 0 1 0,${T} h-${M} a${C},${C} 0 0 1 0,-${T} z`:`M${s-C},${o-M/2} v${M} a${C},${C} 0 0 0 ${w},0 v-${M} a${C},${C} 0 0 0 -${w},0 z`;if(c<0){let A={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,d:v,"data-type":"pcb_hole","data-pcb-layer":"drill"}},R={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:i.drill,d:I,"data-type":"pcb_soldermask"}};return[A,R]}return[{name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,d:I,"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"}},P]}if(n.hole_shape==="rotated_pill"){let h=n.hole_width*Math.abs(t.a),d=n.hole_height*Math.abs(t.a),_="ccw_rotation"in n?n.ccw_rotation??0:0,g=h>d,x=Math.min(h,d)/2,v=Math.abs(g?h-d:d-h),P=g?`M${-v/2},${-x} h${v} a${x},${x} 0 0 1 0,${d} h-${v} a${x},${x} 0 0 1 0,-${d} z`:`M${-x},${-v/2} v${v} a${x},${x} 0 0 0 ${h},0 v-${v} a${x},${x} 0 0 0 -${h},0 z`,w={name:"path",type:"element",attributes:{class:"pcb-hole",fill:i.drill,d:P,transform:`translate(${s} ${o}) rotate(${-_})`,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[w];let T=h+2*c,k=d+2*c,C=T>k,M=Math.min(T,k)/2,I=Math.abs(C?T-k:k-T),E=C?`M${-I/2},${-M} h${I} a${M},${M} 0 0 1 0,${k} h-${I} a${M},${M} 0 0 1 0,-${k} z`:`M${-M},${-I/2} v${I} a${M},${M} 0 0 0 ${T},0 v-${I} a${M},${M} 0 0 0 -${T},0 z`;if(c<0){let R={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,d:P,transform:`translate(${s} ${o}) rotate(${-_})`,"data-type":"pcb_hole","data-pcb-layer":"drill"}},B={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:i.drill,d:E,transform:`translate(${s} ${o}) rotate(${-_})`,"data-type":"pcb_soldermask"}};return[R,B]}return[{name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,d:E,"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"}},w]}return[]}function U6t(n,e){let{transform:t}=e,i=tr(n),r=n.filter(c=>c.type==="pcb_port"),s=n.filter(c=>c.type==="source_trace"),o=[];r.forEach((c,l)=>{let u=c.pcb_port_id;if(!u)return;let h=i.getNetConnectedToId(u);if(!h)return;let d=!1,_=Ee(n).source_port.getWhere({pcb_port_id:u});if(_&&_.source_port_id){let v=_.source_port_id;for(let P of s)if(Array.isArray(P.connected_source_port_ids)&&P.connected_source_port_ids.includes(v)&&Array.isArray(P.connected_source_net_ids)&&P.connected_source_net_ids.length>0){d=!0;break}}let g={x:c.x,y:c.y},x=X6t(g,h,i,n);x&&o.push({key:`${u}-${l}`,startPoint:g,endPoint:x,isInNet:d})});let a=[];for(let c of o){let l=st(t,[c.startPoint.x,c.startPoint.y]),u=st(t,[c.endPoint.x,c.endPoint.y]),h={x1:l[0].toString(),y1:l[1].toString(),x2:u[0].toString(),y2:u[1].toString(),stroke:"white","stroke-width":"1","stroke-dasharray":"6,6","data-type":"pcb_rats_nest","data-pcb-layer":"overlay"};a.push({name:"line",type:"element",attributes:h,value:"",children:[]})}return a}function V6t(n,e){let{transform:t,colorMap:i}=e;if(n.shape==="rect"){let r=n,[s,o]=st(t,[r.center.x,r.center.y]),a=r.width*Math.abs(t.a),c=r.height*Math.abs(t.d),l=-(r.rotation??0),{corner_radius:u}=r,h=typeof u=="number"&&u>0?u:0,d=h*Math.abs(t.a),_=h*Math.abs(t.d),g={class:"pcb-cutout pcb-cutout-rect",x:(-a/2).toString(),y:(-c/2).toString(),width:a.toString(),height:c.toString(),fill:i.drill,transform:Ba(Fe(yn(s,o),ls(l*Math.PI/180))),"data-type":"pcb_cutout","data-pcb-layer":"drill"};return d>0&&(g.rx=d.toString()),_>0&&(g.ry=_.toString()),[{name:"rect",type:"element",attributes:g,children:[],value:""}]}if(n.shape==="circle"){let r=n,[s,o]=st(t,[r.center.x,r.center.y]),a=r.radius*Math.abs(t.a);return[{name:"circle",type:"element",attributes:{class:"pcb-cutout pcb-cutout-circle",cx:s.toString(),cy:o.toString(),r:a.toString(),fill:i.drill,"data-type":"pcb_cutout","data-pcb-layer":"drill"},children:[],value:""}]}if(n.shape==="polygon"){let r=n;return!r.points||r.points.length===0?[]:[{name:"polygon",type:"element",attributes:{class:"pcb-cutout pcb-cutout-polygon",points:r.points.map(a=>st(t,[a.x,a.y])).map(a=>`${a[0]},${a[1]}`).join(" "),fill:i.drill,"data-type":"pcb_cutout","data-pcb-layer":"drill"},children:[],value:""}]}return[]}function ktt(n,e){if(n.length===0)return"";let t=n.map(r=>{let[s,o]=st(e,[r.x,r.y]);return{...r,x:s,y:o}}),i=`M ${t[0].x} ${t[0].y}`;for(let r=0;r<t.length;r++){let s=t[r],o=t[(r+1)%t.length];if(s.bulge){if(Math.hypot(o.x-s.x,o.y-s.y)<1e-9)continue;let a=s.bulge,c=o.x-s.x,l=o.y-s.y,u=Math.hypot(c,l),h=Math.abs(u/4/a*(a*a+1)),d=a<0?1:0,_=Math.abs(a)>1?1:0;i+=` A ${h} ${h} 0 ${_} ${d} ${o.x} ${o.y}`}else i+=` L ${o.x} ${o.y}`}return i+=" Z",i}function G6t(n,e){let{transform:t,layer:i,colorMap:r}=e,{layer:s}=n;if(i&&s!==i)return[];let o=Os(s,r),a="0.5";if(n.shape==="rect"){let[c,l]=st(t,[n.center.x,n.center.y]),u=n.width*Math.abs(t.a),h=n.height*Math.abs(t.d),d=-(n.rotation??0);return[{name:"rect",type:"element",attributes:{class:"pcb-copper-pour pcb-copper-pour-rect",x:(-u/2).toString(),y:(-h/2).toString(),width:u.toString(),height:h.toString(),fill:o,"fill-opacity":a,transform:Ba(Fe(yn(c,l),ls(d*Math.PI/180))),"data-type":"pcb_copper_pour","data-pcb-layer":s},children:[],value:""}]}if(n.shape==="polygon")return!n.points||n.points.length===0?[]:[{name:"polygon",type:"element",attributes:{class:"pcb-copper-pour pcb-copper-pour-polygon",points:n.points.map(u=>st(t,[u.x,u.y])).map(u=>`${u[0]},${u[1]}`).join(" "),fill:o,"fill-opacity":a,"data-type":"pcb_copper_pour","data-pcb-layer":s},children:[],value:""}];if(n.shape==="brep"){let{brep_shape:c}=n,l=ktt(c.outer_ring.vertices,t);for(let u of c.inner_rings??[])l+=` ${ktt(u.vertices,t)}`;return[{name:"path",type:"element",attributes:{class:"pcb-copper-pour pcb-copper-pour-brep",d:l,fill:o,"fill-rule":"evenodd","fill-opacity":a,"data-type":"pcb_copper_pour","data-pcb-layer":s},children:[],value:""}]}return[]}function W6t({grid:n,svgWidth:e,svgHeight:t}){if(!n)return{};let i=n.lineColor??H6t,r=n.cellSize,s=n.majorCellSize,o=n.majorLineColor??i;if(s!==void 0){if(!r||r<=0)throw new Error("grid.majorCellSize requires a positive grid.cellSize");if(s<=0)throw new Error("grid.majorCellSize must be a positive multiple of grid.cellSize");let h=s/r,d=Math.round(h);if(!Number.isFinite(h)||Math.abs(h-d)>1e-6)throw new Error("grid.majorCellSize must be a positive multiple of grid.cellSize")}if(!r||r<=0)return{};let a=s!==void 0,c=a?q6t(r,s,i,o):[{name:"path",type:"element",value:"",attributes:{d:`M ${r} 0 L 0 0 0 ${r}`,fill:"none",stroke:i,"stroke-width":"1","shape-rendering":"crispEdges"},children:[]}],l={name:"defs",type:"element",value:"",attributes:{},children:[{name:"pattern",type:"element",value:"",attributes:{id:Ttt,width:a?s.toString():r.toString(),height:a?s.toString():r.toString(),patternUnits:"userSpaceOnUse"},children:c}]},u={name:"rect",type:"element",value:"",attributes:{x:"0",y:"0",width:e.toString(),height:t.toString(),fill:`url(#${Ttt})`,"pointer-events":"none","data-type":"pcb_grid","data-pcb-layer":"global"},children:[]};return{defs:l,rect:u}}function q6t(n,e,t,i){let r=[],s=Math.round(e/n);for(let o=0;o<s;o+=1){let c=Number((o*n).toFixed(6)).toString(),l=o===0?i:t,u=e.toString();r.push({name:"line",type:"element",value:"",attributes:{x1:c,y1:"0",x2:c,y2:u,stroke:l,"stroke-width":"1","shape-rendering":"crispEdges"},children:[]}),r.push({name:"line",type:"element",value:"",attributes:{x1:"0",y1:c,x2:u,y2:c,stroke:l,"stroke-width":"1","shape-rendering":"crispEdges"},children:[]})}return r}function tRt(n){let{groupAnchorPosition:e,componentPosition:t,transform:i,componentWidth:r=0,componentHeight:s=0}=n,o=[],[a,c]=st(i,[e.x,e.y]),[l,u]=st(i,[t.x,t.y]),h=t.x-e.x,d=t.y-e.y,_=Math.abs(i.a),g=r*_,x=s*_;o.push(eRt(a,c)),o.push({name:"line",type:"element",attributes:{x1:a.toString(),y1:c.toString(),x2:l.toString(),y2:u.toString(),stroke:"#ffffff","stroke-width":"0.5","stroke-dasharray":"3,3",opacity:"0.5",class:"anchor-offset-connector"},children:[],value:""}),o.push({name:"circle",type:"element",attributes:{cx:l.toString(),cy:u.toString(),r:"2",fill:"#ffffff",opacity:"0.7",class:"anchor-offset-component-marker"},children:[],value:""});let v=Math.abs(u-c),P=Math.abs(l-a),w=Math.sqrt(P*P+v*v),T=x/2+Z6t,k=Math.max(T,Math.min(Q6t,w*J6t)),C=d>0?u-k:u+k,M=g/2+K6t,I=h>0?l+M:l-M;return Math.abs(h)>Mtt&&o.push(...nRt({startX:a,endX:l,y:C,offsetMm:h,offsetY:d})),Math.abs(d)>Mtt&&o.push(...iRt({x:I,startY:c,endY:u,offsetMm:-d,offsetX:h})),o}function eRt(n,e){return{name:"g",type:"element",attributes:{class:"anchor-offset-marker","data-type":"anchor_offset_marker"},children:[{name:"line",type:"element",attributes:{x1:n.toString(),y1:(e-Bw).toString(),x2:n.toString(),y2:(e+Bw).toString(),stroke:"#ffffff","stroke-width":Ctt.toString(),"stroke-linecap":"round"},children:[],value:""},{name:"line",type:"element",attributes:{x1:(n-Bw).toString(),y1:e.toString(),x2:(n+Bw).toString(),y2:e.toString(),stroke:"#ffffff","stroke-width":Ctt.toString(),"stroke-linecap":"round"},children:[],value:""}],value:""}}function nRt({startX:n,endX:e,y:t,offsetMm:i,offsetY:r}){let s=[];s.push({name:"line",type:"element",attributes:{x1:n.toString(),y1:t.toString(),x2:e.toString(),y2:t.toString(),stroke:"#ffffff","stroke-width":O_.toString(),class:"anchor-offset-dimension-x"},children:[],value:""}),s.push({name:"line",type:"element",attributes:{x1:n.toString(),y1:(t-Ls).toString(),x2:n.toString(),y2:(t+Ls).toString(),stroke:"#ffffff","stroke-width":O_.toString()},children:[],value:""}),s.push({name:"line",type:"element",attributes:{x1:e.toString(),y1:(t-Ls).toString(),x2:e.toString(),y2:(t+Ls).toString(),stroke:"#ffffff","stroke-width":O_.toString()},children:[],value:""});let o=(n+e)/2,a=r>0?t-Ls-Ett:t+Ls+Ett;return s.push({name:"text",type:"element",attributes:{x:o.toString(),y:a.toString(),fill:"#ffffff","font-size":qtt.toString(),"font-family":"Arial, sans-serif","text-anchor":"middle","dominant-baseline":r>0?"baseline":"hanging",class:"anchor-offset-label"},children:[{type:"text",value:`X: ${i.toFixed(2)}mm`,name:"",attributes:{},children:[]}],value:""}),s}function iRt({x:n,startY:e,endY:t,offsetMm:i,offsetX:r}){let s=[];s.push({name:"line",type:"element",attributes:{x1:n.toString(),y1:e.toString(),x2:n.toString(),y2:t.toString(),stroke:"#ffffff","stroke-width":O_.toString(),class:"anchor-offset-dimension-y"},children:[],value:""}),s.push({name:"line",type:"element",attributes:{x1:(n-Ls).toString(),y1:e.toString(),x2:(n+Ls).toString(),y2:e.toString(),stroke:"#ffffff","stroke-width":O_.toString()},children:[],value:""}),s.push({name:"line",type:"element",attributes:{x1:(n-Ls).toString(),y1:t.toString(),x2:(n+Ls).toString(),y2:t.toString(),stroke:"#ffffff","stroke-width":O_.toString()},children:[],value:""});let o=(e+t)/2,a=r<0?n-Ls-4:n+Ls+4;return s.push({name:"text",type:"element",attributes:{x:a.toString(),y:o.toString(),fill:"#ffffff","font-size":qtt.toString(),"font-family":"Arial, sans-serif","text-anchor":r<0?"end":"start","dominant-baseline":"middle",class:"anchor-offset-label"},children:[{type:"text",value:`Y: ${i.toFixed(2)}mm`,name:"",attributes:{},children:[]}],value:""}),s}function rRt(n,e){let{transform:t,circuitJson:i}=e,{center:r,width:s,height:o,rotation:a=0}=n,[c,l]=st(t,[r.x,r.y]),u=s*Math.abs(t.a),h=o*Math.abs(t.d),d=`translate(${c}, ${l}) rotate(${-a}) scale(1, -1)`,_=[];if(e.showAnchorOffsets&&n.positioned_relative_to_pcb_group_id&&n.position_mode==="relative"&&i){let g=i.find(x=>x.type==="pcb_group"&&x.pcb_group_id===n.positioned_relative_to_pcb_group_id);g?.center&&_.push(...tRt({groupAnchorPosition:g.center,componentPosition:r,transform:t,componentWidth:s,componentHeight:o}))}return!e.colorMap.debugComponent?.fill&&!e.colorMap.debugComponent?.stroke||_.push({name:"g",type:"element",attributes:{transform:d,"data-type":"pcb_component","data-pcb-layer":n.layer??"top"},children:[{name:"rect",type:"element",attributes:{class:"pcb-component",x:(-u/2).toString(),y:(-h/2).toString(),width:u.toString(),height:h.toString(),fill:e.colorMap.debugComponent.fill??"transparent",stroke:e.colorMap.debugComponent.stroke??"transparent","data-type":"pcb_component","data-pcb-layer":n.layer??"top"}}],value:""}),_}function aRt(n,e){let{transform:t}=e,{center:i,width:r,height:s}=n,o=Array.isArray(n.outline)?n.outline:void 0,a=oRt*Math.abs(t.a),c=.3*Math.abs(t.a),l=.15*Math.abs(t.a),u={class:"pcb-group",fill:"none",stroke:sRt,"stroke-width":a.toString(),"stroke-dasharray":`${c} ${l}`,"data-type":"pcb_group","data-pcb-group-id":n.pcb_group_id,"data-pcb-layer":"overlay"};if(n.name&&(u["data-group-name"]=n.name),o&&o.length>=3&&o.every(M=>M&&typeof M.x=="number"&&typeof M.y=="number")){let M=o.map((I,E)=>{let[A,R]=st(t,[I.x,I.y]);return E===0?`M ${A} ${R}`:`L ${A} ${R}`}).join(" ");return[{name:"path",type:"element",value:"",children:[],attributes:{...u,d:`${M} Z`}}]}if(!i||typeof i.x!="number"||typeof i.y!="number"||typeof r!="number"||typeof s!="number")return console.error("Invalid pcb_group data",{center:i,width:r,height:s}),[];let h=r/2,d=s/2,[_,g]=st(t,[i.x-h,i.y+d]),[x,v]=st(t,[i.x+h,i.y-d]),P=Math.min(_,x),w=Math.min(g,v),T=Math.abs(x-_),k=Math.abs(v-g);return[{name:"rect",type:"element",value:"",attributes:{...u,x:P.toString(),y:w.toString(),width:T.toString(),height:k.toString()},children:[]}]}function fl(n){return n.find(t=>t.type==="project_software_metadata"||t.type==="source_project_metadata")?.software_used_string}function Ntt(n){return n.map((e,t)=>({object:e,index:t,layerPriority:uRt(e.attributes?.["data-pcb-layer"]??void 0),typePriority:pRt(e.attributes?.["data-type"]??void 0)})).sort((e,t)=>e.layerPriority!==t.layerPriority?e.layerPriority-t.layerPriority:e.typePriority!==t.typePriority?e.typePriority-t.typePriority:e.index-t.index).map(({object:e})=>e)}function uRt(n){if(!n)return 500;let e=n.toLowerCase();if(e==="global")return-100;if(e==="bottom")return 0;if(e==="board")return 2;if(e==="soldermask-top"||e==="soldermask-bottom")return 3;if(e.startsWith("inner")){let t=e.match(/\d+/);return 5+(t?Number.parseInt(t[0],10):0)}return e==="through"?18:e==="top"?17:e==="drill"?30:e==="overlay"?40:10}function pRt(n){return n?lRt[n]??Itt:Itt}function $_(n,e="error_text_overlay"){let t=n.filter(s=>s.type.endsWith("_error"));if(t.length===0)return null;let i=t.map(s=>s.message).filter(s=>!!s);return i.length===0?null:{name:"text",type:"element",value:"",attributes:{x:"10",y:"20",fill:"red","font-family":"monospace","font-size":"12px","data-type":e,"data-layer":"global"},children:i.map((s,o)=>({name:"tspan",type:"element",value:"",attributes:{x:"10",dy:o===0?"0":"1.2em"},children:[{type:"text",value:s,name:"",attributes:{},children:[]}]}))}}function Ztt(n,e){let t=e?.drawPaddingOutsideBoard??!0,i=e?.layer,r=e?.colorOverrides,s={...Ti.copper};if(r?.copper)for(let[Z,at]of Object.entries(r.copper))at!==void 0&&(s[Z]=at);let o={copper:s,drill:r?.drill??Ti.drill,silkscreen:{top:r?.silkscreen?.top??Ti.silkscreen.top,bottom:r?.silkscreen?.bottom??Ti.silkscreen.bottom},boardOutline:r?.boardOutline??Ti.boardOutline,soldermask:{top:r?.soldermask?.top??Ti.soldermask.top,bottom:r?.soldermask?.bottom??Ti.soldermask.bottom},soldermaskWithCopperUnderneath:{top:r?.soldermaskWithCopperUnderneath?.top??Ti.soldermaskWithCopperUnderneath.top,bottom:r?.soldermaskWithCopperUnderneath?.bottom??Ti.soldermaskWithCopperUnderneath.bottom},substrate:r?.substrate??Ti.substrate,courtyard:r?.courtyard??Ti.courtyard,debugComponent:{fill:r?.debugComponent?.fill??Ti.debugComponent.fill,stroke:r?.debugComponent?.stroke??Ti.debugComponent.stroke}},a=Number.POSITIVE_INFINITY,c=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY,u=Number.NEGATIVE_INFINITY,h=!1,d=Number.POSITIVE_INFINITY,_=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,x=Number.NEGATIVE_INFINITY,v=!1;for(let Z of n)if(Z.type==="pcb_panel"){let at=Z,Mt=Y.parse(at.width),Ft=Y.parse(at.height);if(Mt===void 0||Ft===void 0)continue;let Ot=at.center??{x:Mt/2,y:Ft/2};ot(Ot,Mt,Ft)}else if(Z.type==="pcb_board")Z.outline&&Array.isArray(Z.outline)&&Z.outline.length>=3?(W(Z.outline),rt(Z.outline)):"center"in Z&&"width"in Z&&"height"in Z&&(ot(Z.center,Z.width,Z.height),X(Z.center,Z.width,Z.height));else if(Z.type==="pcb_smtpad"){let at=Z;if(at.shape==="rect"||at.shape==="rotated_rect"||at.shape==="pill")ot({x:at.x,y:at.y},at.width,at.height);else if(at.shape==="circle"){let Mt=Y.parse(at.radius);Mt!==void 0&&ot({x:at.x,y:at.y},Mt*2,Mt*2)}else at.shape==="polygon"&&ut(at.points)}else if("x"in Z&&"y"in Z)ot({x:Z.x,y:Z.y},0,0);else if("route"in Z)ut(Z.route);else if(Z.type==="pcb_note_rect"||Z.type==="pcb_fabrication_note_rect")ot(Z.center,Z.width,Z.height);else if(Z.type==="pcb_cutout"){let at=Z;if(at.shape==="rect")ot(at.center,at.width,at.height);else if(at.shape==="circle"){let Mt=Y.parse(at.radius);Mt!==void 0&&ot(at.center,Mt*2,Mt*2)}else at.shape==="polygon"&&ut(at.points)}else Z.type==="pcb_silkscreen_text"||Z.type==="pcb_silkscreen_rect"||Z.type==="pcb_silkscreen_circle"||Z.type==="pcb_silkscreen_line"?yt(Z):Z.type==="pcb_copper_pour"&&(Z.shape==="rect"?ot(Z.center,Z.width,Z.height):Z.shape==="polygon"&&ut(Z.points));let P=t?1:0,w=t||!Number.isFinite(d)?a:d,T=t||!Number.isFinite(_)?c:_,k=t||!Number.isFinite(g)?l:g,C=t||!Number.isFinite(x)?u:x,M=k-w+2*P,I=C-T+2*P,E=e?.width??800,A=e?.height??600;if(e?.matchBoardAspectRatio){let Z=g-d,at=x-_;if(Z>0&&at>0){let Mt=Z/at;e?.width&&!e?.height?A=e.width/Mt:e?.height&&!e?.width?E=e.height*Mt:A=E/Mt}}let R=[];for(let Z of n)"route"in Z&&Z.route!==void 0&&R.push(Z.route);let B=E/M,j=A/I,U=Math.min(B,j),V=(E-M*U)/2,H=(A-I*U)/2,et=Fe(yn(V-w*U+P*U,A-H+T*U-P*U),ki(U,-U)),tt={transform:et,layer:i,shouldDrawErrors:e?.shouldDrawErrors,showCourtyards:e?.showCourtyards,showPcbGroups:e?.showPcbGroups,drawPaddingOutsideBoard:t,colorMap:o,showSolderMask:e?.showSolderMask,showAnchorOffsets:e?.showAnchorOffsets,circuitJson:n},mt=n.flatMap(Z=>hRt({elm:Z,circuitJson:n,ctx:tt})),G=Ntt(mt),Q=String(.05*U);for(let Z of n)if("stroke_width"in Z){Q=String(U*Z.stroke_width);break}if(e?.shouldDrawRatsNest){let Z=U6t(n,tt);G=Ntt([...G,...Z])}let nt=[{name:"style",type:"element",value:"",attributes:{},children:[{type:"text",value:"",name:"",attributes:{},children:[]}]}],pt=W6t({grid:e?.grid,svgWidth:E,svgHeight:A});if(pt.defs&&nt.push(pt.defs),nt.push({name:"rect",type:"element",value:"",attributes:{class:"boundary",x:"0",y:"0",fill:e?.backgroundColor??"#000",width:E.toString(),height:A.toString(),"data-type":"pcb_background","data-pcb-layer":"global"},children:[]}),t&&nt.push(dRt(et,a,c,l,u)),nt.push(...G),pt.rect&&nt.push(pt.rect),e?.showErrorsInTextOverlay){let Z=$_(n,"pcb_error_text_overlay");Z&&nt.push(Z)}let ht=fl(n),wt=ml,Et={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:E.toString(),height:A.toString(),...ht&&{"data-software-used-string":ht},...e?.includeVersion&&{"data-circuit-to-svg-version":wt}},value:"",children:nt.filter(Z=>Z!==null)};try{return(0,Htt.stringify)(Et)}catch(Z){throw console.error("Error stringifying SVG object:",Z),Z}function ot(Z,at,Mt){if(!Z)return;let Ft=Y.parse(Z.x),Ot=Y.parse(Z.y);if(Ft===void 0||Ot===void 0)return;let Ce=Y.parse(at)??0,Se=Y.parse(Mt)??0,Kt=Ce/2,le=Se/2;a=Math.min(a,Ft-Kt),c=Math.min(c,Ot-le),l=Math.max(l,Ft+Kt),u=Math.max(u,Ot+le),h=!0}function X(Z,at,Mt){if(!Z)return;let Ft=Y.parse(Z.x),Ot=Y.parse(Z.y);if(Ft===void 0||Ot===void 0)return;let Ce=Y.parse(at)??0,Se=Y.parse(Mt)??0,Kt=Ce/2,le=Se/2;d=Math.min(d,Ft-Kt),_=Math.min(_,Ot-le),g=Math.max(g,Ft+Kt),x=Math.max(x,Ot+le),h=!0,v=!0}function W(Z){let at=!1;for(let Mt of Z){let Ft=Y.parse(Mt.x),Ot=Y.parse(Mt.y);Ft===void 0||Ot===void 0||(a=Math.min(a,Ft),c=Math.min(c,Ot),l=Math.max(l,Ft),u=Math.max(u,Ot),at=!0)}at&&(h=!0)}function rt(Z){let at=!1;for(let Mt of Z){let Ft=Y.parse(Mt.x),Ot=Y.parse(Mt.y);Ft===void 0||Ot===void 0||(d=Math.min(d,Ft),_=Math.min(_,Ot),g=Math.max(g,Ft),x=Math.max(x,Ot),at=!0)}at&&(h=!0,v=!0)}function ut(Z){let at=!1;for(let Mt of Z){let Ft=Y.parse(Mt?.x),Ot=Y.parse(Mt?.y);Ft===void 0||Ot===void 0||(a=Math.min(a,Ft),c=Math.min(c,Ot),l=Math.max(l,Ft),u=Math.max(u,Ot),at=!0)}at&&(h=!0)}function yt(Z){if(Z.type==="pcb_silkscreen_text")ot(Z.anchor_position,0,0);else if(Z.type==="pcb_silkscreen_path")ut(Z.route);else if(Z.type==="pcb_silkscreen_rect")ot(Z.center,Z.width,Z.height);else if(Z.type==="pcb_silkscreen_circle"){let at=Y.parse(Z.radius);at!==void 0&&ot(Z.center,at*2,at*2)}else if(Z.type==="pcb_silkscreen_line")ot({x:Z.x1,y:Z.y1},0,0),ot({x:Z.x2,y:Z.y2},0,0);else if(Z.type==="pcb_cutout"){let at=Z;if(at.shape==="rect")ot(at.center,at.width,at.height);else if(at.shape==="circle"){let Mt=Y.parse(at.radius);Mt!==void 0&&ot(at.center,Mt*2,Mt*2)}else at.shape==="polygon"&&ut(at.points)}}}function hRt({elm:n,circuitJson:e,ctx:t}){switch(n.type){case"pcb_trace_error":return c6t(n,e,t).filter(Boolean);case"pcb_footprint_overlap_error":return p6t(n,e,t).filter(Boolean);case"pcb_component":return rRt(n,t).filter(Boolean);case"pcb_trace":return z6t(n,t);case"pcb_copper_pour":return G6t(n,t);case"pcb_plated_hole":return E6t(n,t).filter(Boolean);case"pcb_hole":return B6t(n,t);case"pcb_smtpad":return $6t(n,t);case"pcb_silkscreen_text":return I6t(n,t);case"pcb_silkscreen_rect":return N6t(n,t);case"pcb_silkscreen_circle":return A6t(n,t);case"pcb_silkscreen_line":return R6t(n,t);case"pcb_courtyard_rect":return t.showCourtyards?O6t(n,t):[];case"pcb_fabrication_note_path":return h6t(n,t);case"pcb_fabrication_note_text":return d6t(n,t);case"pcb_fabrication_note_rect":return _6t(n,t);case"pcb_fabrication_note_dimension":return y6t(n,t);case"pcb_note_dimension":return g6t(n,t);case"pcb_note_text":return b6t(n,t);case"pcb_note_rect":return w6t(n,t);case"pcb_note_path":return k6t(n,t);case"pcb_note_line":return M6t(n,t);case"pcb_silkscreen_path":return C6t(n,t);case"pcb_panel":return t.drawPaddingOutsideBoard?D6t(n,t):[];case"pcb_board":return t.drawPaddingOutsideBoard?Wtt(n,t):[];case"pcb_via":return j6t(n,t);case"pcb_cutout":return V6t(n,t);case"pcb_group":return t.showPcbGroups?aRt(n,t):[];default:return[]}}function dRt(n,e,t,i,r){let[s,o]=st(n,[e,t]),[a,c]=st(n,[i,r]),l=Math.abs(a-s),u=Math.abs(c-o),h=Math.min(s,a),d=Math.min(o,c);return{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-boundary",fill:"none",stroke:"#fff","stroke-width":"0.3",x:h.toString(),y:d.toString(),width:l.toString(),height:u.toString(),"data-type":"pcb_boundary","data-pcb-layer":"global"}}}function mRt(n,e,t={}){let{width:i,height:r,center:s,outline:o}=n,a;if(o&&Array.isArray(o)&&o.length>=3)a=o.map((c,l)=>{let[u,h]=st(e,[c.x,c.y]);return l===0?`M ${u} ${h}`:`L ${u} ${h}`}).join(" ");else{let c=i/2,l=r/2,u=st(e,[s.x-c,s.y-l]),h=st(e,[s.x+c,s.y-l]),d=st(e,[s.x+c,s.y+l]),_=st(e,[s.x-c,s.y+l]);a=`M ${u[0]} ${u[1]} L ${h[0]} ${h[1]} L ${d[0]} ${d[1]} L ${_[0]} ${_[1]}`}return a+=" Z",[{name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-board",d:a,fill:t.fill??Yw.fill,stroke:t.stroke??Yw.stroke,"stroke-opacity":t.strokeOpacity??Yw.strokeOpacity,"stroke-width":((t.strokeWidthFactor??Yw.strokeWidthFactor)*Math.abs(e.a)).toString()}}]}function yRt(n,e){let{elm:t,portPosition:i,name:r,arePinsInterchangeable:s}=n,{transform:o}=e,{center:a,width:c,height:l,rotation:u=0,layer:h="top"}=t;if(!a||typeof c!="number"||typeof l!="number")return null;let[d,_]=st(o,[a.x,a.y]),[g,x]=st(o,[i.x,i.y]),v=c*Math.abs(o.a),P=l*Math.abs(o.d),w=h==="top",T=x>_,k=g<d,C=[gRt(v,P,u,h),xRt(v,P,r??"",o)];return s||C.push(bRt(v,P,u,h,T,k)),{name:"g",type:"element",value:"",attributes:{transform:`translate(${d}, ${_}) scale(1, -1)`},children:C}}function gRt(n,e,t,i){let r=n/2,s=e/2;return{name:"path",type:"element",attributes:{class:"assembly-component",d:vRt(r,s,t),"stroke-width":.8.toFixed(2),transform:`rotate(${-t})`,"stroke-dasharray":i==="bottom"?"2,2":""},value:"",children:[]}}function xRt(n,e,t,i){let r=Math.min(n,e),c=Math.min(58,Math.max(3,r*.8)),l=e>n;return{name:"text",type:"element",attributes:{x:"0",y:"0",class:"assembly-component-label","text-anchor":"middle",dy:".10em",style:"pointer-events: none","font-size":`${c.toFixed(1)}px`,transform:l?"rotate(90) scale(1, -1)":"scale(1, -1)"},children:[{type:"text",value:t||"",name:"",attributes:{},children:[]}],value:""}}function bRt(n,e,t,i,r,s){let o=n/2,a=e/2,c=Math.min(o,a)*.5,l;return r&&s?l=[[-o,-a],[-o+c,-a],[-o,-a+c]]:r&&!s?l=[[o,-a],[o-c,-a],[o,-a+c]]:!r&&s?l=[[-o,a],[-o+c,a],[-o,a-c]]:l=[[o,a],[o-c,a],[o,a-c]],{name:"polygon",type:"element",attributes:{class:"assembly-pin1-indicator",points:l.map(h=>h.join(",")).join(" "),fill:"#333",stroke:"none",transform:`rotate(${-t})`},value:"",children:[]}}function vRt(n,e,t){let i=(a,c,l)=>{let u=Math.PI/180*l,h=Math.cos(u),d=Math.sin(u);return[a*h-c*d,a*d+c*h]};return`${[[-n,-e],[n,-e],[n,e],[-n,e]].map(([a,c])=>i(a,c,t)).map(([a,c],l)=>l===0?`M${a},${c}`:`L${a},${c}`).join(" ")} Z`}function SRt(n,e){let{transform:t}=e,[i,r]=st(t,[n.x,n.y]);if(n.hole_shape==="circle"||n.hole_shape==="square"){let s=n.hole_diameter*Math.abs(t.a),o=s/2;return n.hole_shape==="circle"?[{name:"circle",type:"element",attributes:{class:"assembly-hole",cx:i.toString(),cy:r.toString(),r:o.toString(),fill:DA},children:[],value:""}]:[{name:"rect",type:"element",attributes:{class:"assembly-hole",x:(i-o).toString(),y:(r-o).toString(),width:s.toString(),height:s.toString(),fill:DA},children:[],value:""}]}if(n.hole_shape==="oval"){let s=n.hole_width*Math.abs(t.a),o=n.hole_height*Math.abs(t.a),a=s/2,c=o/2;return[{name:"ellipse",type:"element",attributes:{class:"assembly-hole",cx:i.toString(),cy:r.toString(),rx:a.toString(),ry:c.toString(),fill:DA},children:[],value:""}]}return[]}function wRt(n,e){let{transform:t}=e,[i,r]=st(t,[n.x,n.y]);if(n.shape==="pill"){let s=n.outer_width*Math.abs(t.a),o=n.outer_height*Math.abs(t.a),a=n.hole_width*Math.abs(t.a),c=n.hole_height*Math.abs(t.a),l=s/2,u=o-s,h=a/2;return[{name:"g",type:"element",children:[{name:"path",type:"element",attributes:{class:"assembly-hole-outer",fill:E1,d:`M${i-l},${r-u/2} v${u} a${l},${l} 0 0 0 ${s},0 v-${u} a${l},${l} 0 0 0 -${s},0 z`},value:"",children:[]},{name:"path",type:"element",attributes:{class:"assembly-hole-inner",fill:C1,d:`M${i-h},${r-(c-a)/2} v${c-a} a${h},${h} 0 0 0 ${a},0 v-${c-a} a${h},${h} 0 0 0 -${a},0 z`},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="circle"){let s=n.outer_diameter*Math.abs(t.a),o=n.outer_diameter*Math.abs(t.a),a=n.hole_diameter*Math.abs(t.a),c=n.hole_diameter*Math.abs(t.a),l=Math.min(s,o)/2,u=Math.min(a,c)/2;return[{name:"g",type:"element",children:[{name:"circle",type:"element",attributes:{class:"assembly-hole-outer",fill:E1,cx:i.toString(),cy:r.toString(),r:l.toString()},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"assembly-hole-inner",fill:C1,cx:i.toString(),cy:r.toString(),r:u.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="circular_hole_with_rect_pad"){let s=n,o=s.hole_diameter*Math.abs(t.a),a=s.rect_pad_width*Math.abs(t.a),c=s.rect_pad_height*Math.abs(t.a),l=(s.rect_border_radius??0)*Math.abs(t.a),u=o/2,[h,d]=st(t,[s.x+s.hole_offset_x,s.y+s.hole_offset_y]);return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"assembly-hole-outer-pad",fill:E1,x:(i-a/2).toString(),y:(r-c/2).toString(),width:a.toString(),height:c.toString(),...l?{rx:l.toString(),ry:l.toString()}:{}},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"assembly-hole-inner",fill:C1,cx:h.toString(),cy:d.toString(),r:u.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="pill_hole_with_rect_pad"){let s=n,o=s.rect_pad_width*Math.abs(t.a),a=s.rect_pad_height*Math.abs(t.a),c=(s.rect_border_radius??0)*Math.abs(t.a),l=s.hole_height*Math.abs(t.a),u=s.hole_width*Math.abs(t.a),h=s,d=h.hole_offset_x??0,_=h.hole_offset_y??0,[g,x]=st(t,[s.x+d,s.y+_]),v=Math.min(l,u)/2;return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"assembly-hole-outer-pad",fill:E1,x:(i-o/2).toString(),y:(r-a/2).toString(),width:o.toString(),height:a.toString(),...c?{rx:c.toString(),ry:c.toString()}:{}},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"assembly-hole-inner",fill:C1,x:(g-u/2).toString(),y:(x-l/2).toString(),width:u.toString(),height:l.toString(),rx:v.toString(),ry:v.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="rotated_pill_hole_with_rect_pad"){let s=n,o=s.rect_pad_width*Math.abs(t.a),a=s.rect_pad_height*Math.abs(t.a),c=(s.rect_border_radius??0)*Math.abs(t.a),l=s.hole_height*Math.abs(t.a),u=s.hole_width*Math.abs(t.a),h=s,d=h.hole_offset_x??0,_=h.hole_offset_y??0,[g,x]=st(t,[s.x+d,s.y+_]),v=Math.min(l,u)/2;return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"assembly-hole-outer-pad",fill:E1,x:(-o/2).toString(),y:(-a/2).toString(),width:o.toString(),height:a.toString(),transform:`translate(${i} ${r}) rotate(${-s.rect_ccw_rotation})`,...c?{rx:c.toString(),ry:c.toString()}:{}},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"assembly-hole-inner",fill:C1,x:(-u/2).toString(),y:(-l/2).toString(),width:u.toString(),height:l.toString(),rx:v.toString(),ry:v.toString(),transform:`translate(${g} ${x}) rotate(${-s.hole_ccw_rotation})`},value:"",children:[]}],value:"",attributes:{}}]}return[]}function PRt(n,e){let{transform:t}=e;if(n.shape==="rect"||n.shape==="rotated_rect"){let i=n.width*Math.abs(t.a),r=n.height*Math.abs(t.d),[s,o]=st(t,[n.x,n.y]),a=(n.rect_border_radius??0)*Math.abs(t.a);return n.shape==="rotated_rect"&&n.ccw_rotation?[{name:"rect",type:"element",attributes:{class:"assembly-pad",fill:I1,x:(-i/2).toString(),y:(-r/2).toString(),width:i.toString(),height:r.toString(),transform:`translate(${s} ${o}) rotate(${-n.ccw_rotation})`,"data-layer":n.layer,...a?{rx:a.toString(),ry:a.toString()}:{}},value:"",children:[]}]:[{name:"rect",type:"element",attributes:{class:"assembly-pad",fill:I1,x:(s-i/2).toString(),y:(o-r/2).toString(),width:i.toString(),height:r.toString(),"data-layer":n.layer,...a?{rx:a.toString(),ry:a.toString()}:{}},value:"",children:[]}]}if(n.shape==="pill"){let i=n.width*Math.abs(t.a),r=n.height*Math.abs(t.d),s=n.radius*Math.abs(t.a),[o,a]=st(t,[n.x,n.y]);return[{name:"rect",type:"element",attributes:{class:"assembly-pad",fill:I1,x:(o-i/2).toString(),y:(a-r/2).toString(),width:i.toString(),height:r.toString(),rx:s.toString(),ry:s.toString(),"data-layer":n.layer},value:"",children:[]}]}if(n.shape==="circle"){let i=n.radius*Math.abs(t.a),[r,s]=st(t,[n.x,n.y]);return[{name:"circle",type:"element",attributes:{class:"assembly-pad",fill:I1,cx:r.toString(),cy:s.toString(),r:i.toString(),"data-layer":n.layer},value:"",children:[]}]}if(n.shape==="polygon"){let i=(n.points??[]).map(r=>st(t,[r.x,r.y]));return[{name:"polygon",type:"element",attributes:{class:"assembly-pad",fill:I1,points:i.map(r=>r.join(",")).join(" "),"data-layer":n.layer},value:"",children:[]}]}return[]}function kRt(n,e){let t=Number.POSITIVE_INFINITY,i=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let I of n)if(I.type==="pcb_board"){let E=I.center,A=I.width||0,R=I.height||0;t=Math.min(t,E.x-A/2),i=Math.min(i,E.y-R/2),r=Math.max(r,E.x+A/2),s=Math.max(s,E.y+R/2)}let o=1,a=r-t+2*o,c=s-i+2*o,l=e?.width??800,u=e?.height??600,h=l/a,d=u/c,_=Math.min(h,d),g=(l-a*_)/2,x=(u-c*_)/2,v=Fe(yn(g-t*_+o*_,u-x+i*_-o*_),ki(_,-_)),P={transform:v},w=n.sort((I,E)=>(Att.indexOf(E.type)??9999)-(Att.indexOf(I.type)??9999)).flatMap(I=>TRt(I,P,n)),T=fl(n),k=ml,C=[{name:"style",type:"element",children:[{type:"text",value:`
73
+ at `+o}return e};Dw.buildMessage=function(n,e){var t={literal:function(l){return'"'+r(l.text)+'"'},class:function(l){var u=l.parts.map(function(h){return Array.isArray(h)?s(h[0])+"-"+s(h[1]):s(h)});return"["+(l.inverted?"^":"")+u.join("")+"]"},any:function(){return"any character"},end:function(){return"end of input"},other:function(l){return l.description}};function i(l){return l.charCodeAt(0).toString(16).toUpperCase()}function r(l){return l.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(u){return"\\x0"+i(u)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(u){return"\\x"+i(u)})}function s(l){return l.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(u){return"\\x0"+i(u)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(u){return"\\x"+i(u)})}function o(l){return t[l.type](l)}function a(l){var u=l.map(o),h,d;if(u.sort(),u.length>0){for(h=1,d=1;h<u.length;h++)u[h-1]!==u[h]&&(u[d]=u[h],d++);u.length=d}switch(u.length){case 1:return u[0];case 2:return u[0]+" or "+u[1];default:return u.slice(0,-1).join(", ")+", or "+u[u.length-1]}}function c(l){return l?'"'+r(l)+'"':"end of input"}return"Expected "+a(n)+" but "+c(e)+" found."}});var xtt=qt(()=>{"use strict";gtt()});var btt=qt(()=>{"use strict";M1();Cd()});var vtt=qt(()=>{"use strict"});var Stt=qt(()=>{"use strict";R_();IA();$w();M1();Cd()});var Yt=qt(()=>{"use strict";IA();NA();ctt();ltt();AA();ptt();$w();M1();RA();OA();dtt();Cd();R_();_tt();LA();ytt();xtt();btt();vtt();Stt()});var _et={};vh(_et,{CIRCUIT_TO_SVG_VERSION:()=>ml,circuitJsonToPcbSvg:()=>fRt,circuitJsonToSchematicSvg:()=>M8t,convertCircuitJsonToAssemblySvg:()=>kRt,convertCircuitJsonToPcbSvg:()=>Ztt,convertCircuitJsonToPinoutSvg:()=>HRt,convertCircuitJsonToSchematicSimulationSvg:()=>K8t,convertCircuitJsonToSchematicSvg:()=>VA,convertCircuitJsonToSimulationGraphSvg:()=>pet,convertCircuitJsonToSolderPasteMask:()=>tOt,createErrorTextOverlay:()=>$_,createSvgObjectsForSchComponentPortHovers:()=>aet,getSoftwareUsedString:()=>fl,isSimulationExperiment:()=>HA,isSimulationTransientVoltageGraph:()=>GA,isSimulationVoltageProbe:()=>uet});function c6t(n,e,t){let{transform:i,shouldDrawErrors:r}=t;if(!r)return[];let{pcb_port_ids:s}=n,o=e.find(d=>d.type==="pcb_port"&&d.pcb_port_id===s?.[0]),a=e.find(d=>d.type==="pcb_port"&&d.pcb_port_id===s?.[1]);if(!o||!a){let _=n.message?.match(/pcb_via\[#?(pcb_via_\d+)\]/)?.[1],g=e.find(x=>x.type==="pcb_via"&&x.pcb_via_id===_);if(g&&g.type==="pcb_via")return l6t(n,g,t);if(n.center){let x=st(i,{x:n.center.x,y:n.center.y});return YA([{name:"rect",type:"element",attributes:{x:(x.x-5).toString(),y:(x.y-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${x.x} ${x.y})`},children:[],value:""},{name:"text",type:"element",attributes:{x:x.x.toString(),y:(x.y-15).toString(),fill:"red","font-family":"sans-serif","font-size":"12","text-anchor":"middle"},children:[{type:"text",value:n.message||"Pcb Trace Error",name:"",attributes:{},children:[]}],value:""}])}else return[]}let c=st(i,{x:o.x,y:o.y}),l=st(i,{x:a.x,y:a.y}),u={x:(c.x+l.x)/2,y:(c.y+l.y)/2};if(isNaN(c.x)||isNaN(c.y)||isNaN(l.x)||isNaN(l.y)||isNaN(u.x)||isNaN(u.y))return[];let h=[{name:"line",type:"element",attributes:{x1:c.x.toString(),y1:c.y.toString(),x2:u.x.toString(),y2:u.y.toString(),stroke:"red","stroke-width":"1.5","stroke-dasharray":"2,2"},children:[],value:""},{name:"line",type:"element",attributes:{x1:u.x.toString(),y1:u.y.toString(),x2:l.x.toString(),y2:l.y.toString(),stroke:"red","stroke-width":"1.5","stroke-dasharray":"2,2"},children:[],value:""},{name:"rect",type:"element",attributes:{x:(u.x-5).toString(),y:(u.y-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${u.x} ${u.y})`},children:[],value:""},{name:"text",type:"element",attributes:{x:u.x.toString(),y:(u.y-15).toString(),fill:"red","font-family":"sans-serif","font-size":"12","text-anchor":"middle"},children:[{type:"text",value:n.message||"Pcb Trace Error",name:"",attributes:{},children:[]}],value:""}];return YA(h)}function l6t(n,e,t){let{transform:i}=t;if(n.center&&e){let r=st(i,{x:n.center.x,y:n.center.y}),s=st(i,{x:e.x,y:e.y}),o=s.x-r.x,a=s.y-r.y,c=Math.sqrt(o*o+a*a),l=Math.atan2(a,o)*180/Math.PI,h=c+10*2,d=20,_=(r.x+s.x)/2,g=(r.y+s.y)/2;return YA([{name:"rect",type:"element",attributes:{x:(_-h/2).toString(),y:(g-d/2).toString(),width:h.toString(),height:d.toString(),fill:"none",stroke:"red","stroke-width":"1","stroke-dasharray":"3,2",transform:`rotate(${l} ${_} ${g})`},children:[],value:""},{name:"rect",type:"element",attributes:{x:(_-5).toString(),y:(g-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${_} ${g})`},children:[],value:""},{name:"text",type:"element",attributes:{x:_.toString(),y:(g-d/2-5).toString(),fill:"red","font-family":"sans-serif","font-size":"12","text-anchor":"middle"},children:[{type:"text",value:n.message||"Pcb Trace Error",name:"",attributes:{},children:[]}],value:""}])}return[]}function YA(n){return n.map(e=>({...e,attributes:{...e.attributes??{},"data-type":e.attributes?.["data-type"]??"pcb_trace_error","data-pcb-layer":e.attributes?.["data-pcb-layer"]??"overlay"},children:(e.children??[]).map(t=>t?.type==="element"?{...t,attributes:{...t.attributes??{},"data-type":t.attributes?.["data-type"]??"pcb_trace_error","data-pcb-layer":t.attributes?.["data-pcb-layer"]??"overlay"}}:t)}))}function u6t(n){return n.map(e=>({...e,attributes:{...e.attributes??{},"data-type":e.attributes?.["data-type"]??"pcb_footprint_overlap_error","data-pcb-layer":e.attributes?.["data-pcb-layer"]??"overlay"},children:(e.children??[]).map(t=>t?.type==="element"?{...t,attributes:{...t.attributes??{},"data-type":t.attributes?.["data-type"]??"pcb_footprint_overlap_error","data-pcb-layer":t.attributes?.["data-pcb-layer"]??"overlay"}}:t)}))}function p6t(n,e,t){let{transform:i,shouldDrawErrors:r}=t;if(!r)return[];let s=[],o=[],a=[];if(n.pcb_smtpad_ids)for(let u of n.pcb_smtpad_ids){let h=e.find(d=>d.type==="pcb_smtpad"&&d.pcb_smtpad_id===u);h&&(o.push({x:h.x,y:h.y,type:"pcb_smtpad",id:u,pcb_port_id:h.pcb_port_id}),h.pcb_port_id&&a.push(h.pcb_port_id))}let c=a.length>1&&a.every(u=>u===a[0]),l=o;if(c&&(l=o.filter(u=>u.type!=="pcb_smtpad")),n.pcb_plated_hole_ids)for(let u of n.pcb_plated_hole_ids){let h=e.find(d=>d.type==="pcb_plated_hole"&&d.pcb_plated_hole_id===u);h&&l.push({x:h.x,y:h.y,type:"pcb_plated_hole",id:u})}if(n.pcb_hole_ids)for(let u of n.pcb_hole_ids){let h=e.find(d=>d.type==="pcb_hole"&&d.pcb_hole_id===u);h&&l.push({x:h.x,y:h.y,type:"pcb_hole",id:u})}if(l.length>0){let u=l.reduce((_,g)=>_+g.x,0)/l.length,h=l.reduce((_,g)=>_+g.y,0)/l.length,d=st(i,{x:u,y:h});s.push({name:"rect",type:"element",attributes:{x:(d.x-5).toString(),y:(d.y-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${d.x} ${d.y})`},children:[],value:""}),s.push({name:"text",type:"element",attributes:{x:d.x.toString(),y:(d.y-15).toString(),fill:"red","font-family":"sans-serif","font-size":"12","text-anchor":"middle"},children:[{type:"text",value:n.message||"PCB Footprint Overlap Error",name:"",attributes:{},children:[]}],value:""});for(let _ of l){let g=st(i,{x:_.x,y:_.y});s.push({name:"rect",type:"element",attributes:{x:(g.x-5).toString(),y:(g.y-5).toString(),width:"10",height:"10",fill:"red",transform:`rotate(45 ${g.x} ${g.y})`},children:[],value:""}),l.length>1&&s.push({name:"line",type:"element",attributes:{x1:d.x.toString(),y1:d.y.toString(),x2:g.x.toString(),y2:g.y.toString(),stroke:"red","stroke-width":"1.5","stroke-dasharray":"2,2"},children:[],value:""})}}return u6t(s)}function h6t(n,e){let{transform:t,layer:i}=e;if(!n.route||!Array.isArray(n.route))return[];let r=n.route[0],s=n.route[n.route.length-1],o=r.x===s.x&&r.y===s.y,a=n.route.slice(0,o?-1:void 0).map((c,l)=>{let[u,h]=st(t,[c.x,c.y]);return l===0?`M ${u} ${h}`:`L ${u} ${h}`}).join(" ")+(o?" Z":"");return[{name:"path",type:"element",attributes:{class:"pcb-fabrication-note-path",stroke:n.color||"rgba(255,255,255,0.5)",fill:"none",d:a,"stroke-width":(n.stroke_width*Math.abs(t.a)).toString(),"data-pcb-component-id":n.pcb_component_id,"data-pcb-fabrication-note-path-id":n.pcb_fabrication_note_path_id,"data-type":"pcb_fabrication_note_path","data-pcb-layer":"overlay"},value:"",children:[]}]}function d6t(n,e){let{transform:t,layer:i}=e,{anchor_position:r,anchor_alignment:s,text:o,font_size:a=1,layer:c="top",color:l}=n;if(i&&c!==i)return[];if(!r||typeof r.x!="number"||typeof r.y!="number")return console.error("Invalid anchor_position:",r),[];let[u,h]=st(t,[r.x,r.y]),d=a*Math.abs(t.a),_=Fe(yn(u,h),ls(Math.PI/180));return[{name:"text",type:"element",attributes:{x:"0",y:"0","font-family":"Arial, sans-serif","font-size":d.toString(),"text-anchor":"middle","dominant-baseline":"central",transform:Ba(_),class:"pcb-fabrication-note-text",fill:l||"rgba(255,255,255,0.5)","data-type":"pcb_fabrication_note_text","data-pcb-layer":"overlay"},children:[{type:"text",value:o,name:"",attributes:{},children:[]}],value:""}]}function _6t(n,e){let{transform:t,layer:i}=e,{center:r,width:s,height:o,stroke_width:a,is_filled:c,has_stroke:l,is_stroke_dashed:u,color:h,layer:d="top",pcb_component_id:_,pcb_fabrication_note_rect_id:g,corner_radius:x}=n;if(i&&d!==i)return[];if(!r||typeof r.x!="number"||typeof r.y!="number"||typeof s!="number"||typeof o!="number")return console.error("Invalid pcb_fabrication_note_rect data",{center:r,width:s,height:o}),[];let v=s/2,P=o/2,[w,T]=st(t,[r.x-v,r.y+P]),[k,C]=st(t,[r.x+v,r.y-P]),M=Math.min(w,k),I=Math.min(T,C),E=Math.abs(k-w),A=Math.abs(C-T),B=(typeof a=="number"?a:0)*Math.abs(t.a),j=h??f6t,U=typeof x=="number"&&x>0?x:0,V=U*Math.abs(t.a),H=U*Math.abs(t.d),et={x:M.toString(),y:I.toString(),width:E.toString(),height:A.toString(),class:"pcb-fabrication-note-rect","data-type":"pcb_fabrication_note_rect","data-pcb-fabrication-note-rect-id":g,"data-pcb-layer":"overlay"};if(_!==void 0&&(et["data-pcb-component-id"]=_),V>0&&(et.rx=V.toString()),H>0&&(et.ry=H.toString()),c?et.fill=h??m6t:et.fill="none",l??B>0){if(et.stroke=j,et["stroke-width"]=B.toString(),u){let G=.2*Math.abs(t.a),Q=.1*Math.abs(t.a);et["stroke-dasharray"]=`${G} ${Q}`}}else et.stroke="none";return[{name:"rect",type:"element",value:"",attributes:et,children:[]}]}function zA(n){let e=Math.hypot(n.x,n.y)||1;return{x:n.x/e,y:n.y/e}}function wtt(n){return n.map((e,t)=>t===0?`M ${e.x} ${e.y}`:`L ${e.x} ${e.y}`).join(" ")}function y6t(n,e){let{transform:t,layer:i}=e,{from:r,to:s,text:o,font_size:a=1,color:c,arrow_size:l,layer:u,pcb_component_id:h,pcb_fabrication_note_dimension_id:d,offset_distance:_,offset_direction:g}=n;if(i&&u&&u!==i)return[];if(!r||!s||typeof r!="object"||typeof s!="object")return console.error("Invalid pcb_fabrication_note_dimension endpoints",{from:r,to:s}),[];if(typeof r.x!="number"||typeof r.y!="number"||typeof s.x!="number"||typeof s.y!="number")return console.error("Invalid pcb_fabrication_note_dimension point values",{from:r,to:s}),[];let x=typeof l=="number"?l:void 0;if(x===void 0||!Number.isFinite(x)||x<=0)return console.error("Invalid pcb_fabrication_note_dimension arrow_size",l),[];let v=x,P=zA({x:s.x-r.x,y:s.y-r.y});if(Number.isNaN(P.x)||Number.isNaN(P.y))return[];let w={x:-P.y,y:P.x},T=g&&typeof g.x=="number"&&typeof g.y=="number",k=T?zA({x:g.x,y:g.y}):{x:0,y:0},C=typeof _=="number"?_:0,M={x:k.x*C,y:k.y*C},I=le=>({x:le.x+M.x,y:le.y+M.y}),E=I(r),A=I(s),R=v/2,B={x:E.x+P.x*v,y:E.y+P.y*v},j={x:A.x-P.x*v,y:A.y-P.y*v},U=[Kt(E),Kt({x:B.x+w.x*R,y:B.y+w.y*R}),Kt({x:B.x-w.x*R,y:B.y-w.y*R})],V=[Kt(A),Kt({x:j.x+w.x*R,y:j.y+w.y*R}),Kt({x:j.x-w.x*R,y:j.y-w.y*R})],[H,et]=st(t,[B.x,B.y]),[tt,mt]=st(t,[j.x,j.y]),G=v/5*Math.abs(t.a),Q=c||"rgba(255,255,255,0.5)",nt=T&&(Math.abs(k.x)>Number.EPSILON||Math.abs(k.y)>Number.EPSILON)?k:w,pt=C+v,ht=le=>{let Jt={x:le.x+nt.x*pt,y:le.y+nt.y*pt},[Wn,Ci]=st(t,[le.x,le.y]),[Cr,Us]=st(t,[Jt.x,Jt.y]);return{name:"path",type:"element",value:"",attributes:{d:`M ${Wn} ${Ci} L ${Cr} ${Us}`,stroke:Q,fill:"none","stroke-width":G.toString(),"stroke-linecap":"round",class:"pcb-fabrication-note-dimension-extension"},children:[]}},wt=[ht(r),ht(s)],Et={x:(r.x+s.x)/2+M.x,y:(r.y+s.y)/2+M.y},ot=v*1.5,X={x:Et.x+w.x*ot,y:Et.y+w.y*ot},[W,rt]=st(t,[X.x,X.y]),[ut,yt]=st(t,[E.x,E.y]),[Z,at]=st(t,[A.x,A.y]),Mt=zA({x:Z-ut,y:at-yt}),Ft=Math.atan2(Mt.y,Mt.x)*180/Math.PI;(Ft>90||Ft<-90)&&(Ft+=180);let Ot=a*Math.abs(t.a),Ce=[...wt,{name:"path",type:"element",value:"",attributes:{d:`M ${H} ${et} L ${tt} ${mt}`,stroke:Q,fill:"none","stroke-width":G.toString(),"stroke-linecap":"round",class:"pcb-fabrication-note-dimension-line"},children:[]},{name:"path",type:"element",value:"",attributes:{d:`${wtt(U)} Z`,fill:Q,class:"pcb-fabrication-note-dimension-arrow"},children:[]},{name:"path",type:"element",value:"",attributes:{d:`${wtt(V)} Z`,fill:Q,class:"pcb-fabrication-note-dimension-arrow"},children:[]}];o&&Ce.push({name:"text",type:"element",value:"",attributes:{x:W.toString(),y:rt.toString(),fill:Q,"font-size":Ot.toString(),"font-family":"Arial, sans-serif","text-anchor":"middle","dominant-baseline":"central",class:"pcb-fabrication-note-dimension-text",transform:`rotate(${Ft} ${W} ${rt})`},children:[{type:"text",name:"",value:o,attributes:{},children:[]}]});let Se={class:"pcb-fabrication-note-dimension","data-type":"pcb_fabrication_note_dimension","data-pcb-fabrication-note-dimension-id":d,"data-pcb-layer":u??"overlay"};return h!==void 0&&(Se["data-pcb-component-id"]=h),[{name:"g",type:"element",value:"",attributes:Se,children:Ce}];function Kt(le){let[Jt,Wn]=st(t,[le.x,le.y]);return{x:Jt,y:Wn}}}function $A(n){let e=Math.hypot(n.x,n.y)||1;return{x:n.x/e,y:n.y/e}}function Ptt(n){return n.map((e,t)=>t===0?`M ${e.x} ${e.y}`:`L ${e.x} ${e.y}`).join(" ")}function g6t(n,e){let{transform:t}=e,{from:i,to:r,text:s,font_size:o=1,color:a,arrow_size:c,offset_distance:l,offset_direction:u}=n;if(!i||!r)return console.error("Invalid pcb_note_dimension endpoints",{from:i,to:r}),[];if(!Number.isFinite(c)||c<=0)return console.error("Invalid pcb_note_dimension arrow_size",c),[];let h=$A({x:r.x-i.x,y:r.y-i.y});if(Number.isNaN(h.x)||Number.isNaN(h.y))return[];let d={x:-h.y,y:h.x},_=u&&typeof u.x=="number"&&typeof u.y=="number",g=_?$A({x:u.x,y:u.y}):{x:0,y:0},x=typeof l=="number"?l:0,v={x:g.x*x,y:g.y*x},P=at=>({x:at.x+v.x,y:at.y+v.y}),w=P(i),T=P(r),k=c/2,C={x:w.x+h.x*c,y:w.y+h.y*c},M={x:T.x-h.x*c,y:T.y-h.y*c},I=[Z(w),Z({x:C.x+d.x*k,y:C.y+d.y*k}),Z({x:C.x-d.x*k,y:C.y-d.y*k})],E=[Z(T),Z({x:M.x+d.x*k,y:M.y+d.y*k}),Z({x:M.x-d.x*k,y:M.y-d.y*k})],[A,R]=st(t,[C.x,C.y]),[B,j]=st(t,[M.x,M.y]),U=c/5*Math.abs(t.a),V=a||Ei.board.user_2,H=_&&(Math.abs(g.x)>Number.EPSILON||Math.abs(g.y)>Number.EPSILON)?g:d,et=x+c,tt=at=>{let Mt={x:at.x+H.x*et,y:at.y+H.y*et},[Ft,Ot]=st(t,[at.x,at.y]),[Ce,Se]=st(t,[Mt.x,Mt.y]);return{name:"path",type:"element",value:"",attributes:{d:`M ${Ft} ${Ot} L ${Ce} ${Se}`,stroke:V,fill:"none","stroke-width":U.toString(),"stroke-linecap":"round",class:"pcb-note-dimension-extension"},children:[]}},mt=[tt(i),tt(r)],G={x:(i.x+r.x)/2+v.x,y:(i.y+r.y)/2+v.y},Q=c*1.5,nt={x:G.x+d.x*Q,y:G.y+d.y*Q},[pt,ht]=st(t,[nt.x,nt.y]),[wt,Et]=st(t,[w.x,w.y]),[ot,X]=st(t,[T.x,T.y]),W=$A({x:ot-wt,y:X-Et}),rt=Math.atan2(W.y,W.x)*180/Math.PI;(rt>90||rt<-90)&&(rt+=180);let ut=o*Math.abs(t.a),yt=[...mt,{name:"path",type:"element",value:"",attributes:{d:`M ${A} ${R} L ${B} ${j}`,stroke:V,fill:"none","stroke-width":U.toString(),"stroke-linecap":"round",class:"pcb-note-dimension-line"},children:[]},{name:"path",type:"element",value:"",attributes:{d:`${Ptt(I)} Z`,fill:V,class:"pcb-note-dimension-arrow"},children:[]},{name:"path",type:"element",value:"",attributes:{d:`${Ptt(E)} Z`,fill:V,class:"pcb-note-dimension-arrow"},children:[]}];return s&&yt.push({name:"text",type:"element",value:"",attributes:{x:pt.toString(),y:ht.toString(),fill:V,"font-size":ut.toString(),"font-family":"Arial, sans-serif","text-anchor":"middle","dominant-baseline":"central",class:"pcb-note-dimension-text",transform:`rotate(${rt} ${pt} ${ht})`},children:[{type:"text",name:"",value:s,attributes:{},children:[]}]}),[{name:"g",type:"element",value:"",attributes:{class:"pcb-note-dimension","data-type":"pcb_note_dimension","data-pcb-note-dimension-id":n.pcb_note_dimension_id,"data-pcb-layer":"overlay"},children:yt}];function Z(at){let[Mt,Ft]=st(t,[at.x,at.y]);return{x:Mt,y:Ft}}}function b6t(n,e){let{transform:t}=e,{anchor_position:i,text:r,font_size:s=1,anchor_alignment:o="center",color:a}=n;if(!i||typeof i.x!="number"||typeof i.y!="number")return console.error("Invalid pcb_note_text anchor_position",i),[];if(typeof r!="string"||r.length===0)return console.error("Invalid pcb_note_text text",r),[];let[c,l]=st(t,[i.x,i.y]),u=s*Math.abs(t.a),h="middle",d="central";switch(o){case"top_left":h="start",d="text-before-edge";break;case"top_right":h="end",d="text-before-edge";break;case"bottom_left":h="start",d="text-after-edge";break;case"bottom_right":h="end",d="text-after-edge";break;case"center":default:h="middle",d="central";break}return[{name:"text",type:"element",value:"",attributes:{x:c.toString(),y:l.toString(),fill:a??x6t,"font-family":"Arial, sans-serif","font-size":u.toString(),"text-anchor":h,"dominant-baseline":d,class:"pcb-note-text","data-type":"pcb_note_text","data-pcb-note-text-id":n.pcb_note_text_id,"data-pcb-layer":"overlay"},children:[{type:"text",name:"",value:r,attributes:{},children:[]}]}]}function w6t(n,e){let{transform:t}=e,{center:i,width:r,height:s,stroke_width:o,is_filled:a,has_stroke:c,is_stroke_dashed:l,color:u,corner_radius:h}=n;if(!i||typeof i.x!="number"||typeof i.y!="number"||typeof r!="number"||typeof s!="number")return console.error("Invalid pcb_note_rect data",{center:i,width:r,height:s}),[];let d=r/2,_=s/2,[g,x]=st(t,[i.x-d,i.y+_]),[v,P]=st(t,[i.x+d,i.y-_]),w=Math.min(g,v),T=Math.min(x,P),k=Math.abs(v-g),C=Math.abs(P-x),I=(typeof o=="number"?o:0)*Math.abs(t.a),E=typeof h=="number"&&h>0?h:0,A=E*Math.abs(t.a),R=E*Math.abs(t.d),B=u??v6t,j={x:w.toString(),y:T.toString(),width:k.toString(),height:C.toString(),class:"pcb-note-rect","data-type":"pcb_note_rect","data-pcb-note-rect-id":n.pcb_note_rect_id,"data-pcb-layer":"overlay"};if(A>0&&(j.rx=A.toString()),R>0&&(j.ry=R.toString()),a?j.fill=u??S6t:j.fill="none",c??I>0){if(j.stroke=B,j["stroke-width"]=I.toString(),l){let H=.2*Math.abs(t.a),et=.1*Math.abs(t.a);j["stroke-dasharray"]=`${H} ${et}`}}else j.stroke="none";return[{name:"rect",type:"element",value:"",attributes:j,children:[]}]}function k6t(n,e){let{transform:t}=e;if(!Array.isArray(n.route)||n.route.length===0)return console.error("Invalid pcb_note_path route",n.route),[];for(let o of n.route)if(typeof o.x!="number"||typeof o.y!="number")return console.error("Invalid point in pcb_note_path",o),[];let i=n.route.map((o,a)=>{let[c,l]=st(t,[o.x,o.y]);return a===0?`M ${c} ${l}`:`L ${c} ${l}`}).join(" "),r=n.stroke_width*Math.abs(t.a);return[{name:"path",type:"element",value:"",attributes:{d:i,stroke:n.color??P6t,fill:"none","stroke-width":r.toString(),class:"pcb-note-path","data-type":"pcb_note_path","data-pcb-note-path-id":n.pcb_note_path_id,"data-pcb-layer":"overlay"},children:[]}]}function M6t(n,e){let{transform:t}=e,{x1:i,y1:r,x2:s,y2:o,stroke_width:a,color:c,is_dashed:l}=n;if(typeof i!="number"||typeof r!="number"||typeof s!="number"||typeof o!="number")return console.error("Invalid pcb_note_line coordinates",{x1:i,y1:r,x2:s,y2:o}),[];let[u,h]=st(t,[i,r]),[d,_]=st(t,[s,o]),x=(typeof a=="number"?a:0)*Math.abs(t.a),v={x1:u.toString(),y1:h.toString(),x2:d.toString(),y2:_.toString(),stroke:c??T6t,"stroke-width":x.toString(),"stroke-linecap":"round",class:"pcb-note-line","data-type":"pcb_note_line","data-pcb-note-line-id":n.pcb_note_line_id,"data-pcb-layer":"overlay"};if(l){let w=.2*Math.abs(t.a),T=.1*Math.abs(t.a);v["stroke-dasharray"]=`${w} ${T}`}return[{name:"line",type:"element",value:"",attributes:v,children:[]}]}function E6t(n,e){let{transform:t,colorMap:i,showSolderMask:r}=e,[s,o]=st(t,[n.x,n.y]),a=Array.isArray(n.layers)&&n.layers[0]||n.layer||"top",c=!!n.is_covered_with_solder_mask,l=(n.soldermask_margin??0)*Math.abs(t.a),u=r&&c&&l!==0,h=i.soldermaskWithCopperUnderneath.top;if(n.shape==="pill"){let d=n.outer_width*Math.abs(t.a),_=n.outer_height*Math.abs(t.a),g=n.hole_width*Math.abs(t.a),x=n.hole_height*Math.abs(t.a),v=n.ccw_rotation||0,P=v?`translate(${s} ${o}) rotate(${-v})`:`translate(${s} ${o})`,w=v?`translate(${s} ${o}) rotate(${-v})`:`translate(${s} ${o})`,T=(C,M)=>{if(C>M){let I=M/2,E=C-2*I;return`M${-C/2+I},${-I} h${E} a${I},${I} 0 0 1 0,${M} h${-E} a${I},${I} 0 0 1 0,${-M} z`}else if(M>C){let I=C/2,E=M-2*I;return`M${I},${-M/2+I} v${E} a${I},${I} 0 0 1 ${-C},0 v${-E} a${I},${I} 0 0 1 ${C},0 z`}else{let I=C/2;return`M${-I},0 a${I},${I} 0 0 1 ${C},0 a${I},${I} 0 0 1 ${-C},0 z`}},k=[{name:"path",type:"element",attributes:{class:"pcb-hole-outer",fill:i.copper.top,d:T(d,_),transform:P,"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"path",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,d:T(g,x),transform:w,"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];if(u){let C=d+2*l,M=_+2*l;l<0?k=[{name:"path",type:"element",attributes:{class:"pcb-hole-outer-covered",fill:h,d:T(d,_),transform:P,"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"path",type:"element",attributes:{class:"pcb-hole-outer-exposed",fill:i.copper.top,d:T(C,M),transform:P,"data-type":"pcb_soldermask"},value:"",children:[]},k[1]]:k.unshift({name:"path",type:"element",attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,d:T(C,M),transform:P,"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"},value:"",children:[]})}return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through"},children:k,value:""}]}if(n.shape==="oval"){let d=n.outer_width*Math.abs(t.a),_=n.outer_height*Math.abs(t.a),g=n.hole_width*Math.abs(t.a),x=n.hole_height*Math.abs(t.a),v=n.ccw_rotation||0,P=v?`translate(${s} ${o}) rotate(${-v})`:`translate(${s} ${o})`,w=[{name:"ellipse",type:"element",attributes:{class:"pcb-hole-outer",fill:i.copper.top,cx:"0",cy:"0",rx:(d/2).toString(),ry:(_/2).toString(),transform:P,"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"ellipse",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,cx:"0",cy:"0",rx:(g/2).toString(),ry:(x/2).toString(),transform:P,"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through"},children:w,value:""}]}if(n.shape==="circle"){let d=n.outer_diameter*Math.abs(t.a),_=n.outer_diameter*Math.abs(t.a),g=n.hole_diameter*Math.abs(t.a),x=n.hole_diameter*Math.abs(t.a),v=Math.min(d,_)/2,P=Math.min(g,x)/2,w=[{name:"circle",type:"element",attributes:{class:"pcb-hole-outer",fill:i.copper.top,cx:s.toString(),cy:o.toString(),r:v.toString(),"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,cx:s.toString(),cy:o.toString(),r:P.toString(),"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];if(u){let T=v+l;l<0?w=[{name:"circle",type:"element",attributes:{class:"pcb-hole-outer-covered",fill:h,cx:s.toString(),cy:o.toString(),r:v.toString(),"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"pcb-hole-outer-exposed",fill:i.copper.top,cx:s.toString(),cy:o.toString(),r:T.toString(),"data-type":"pcb_soldermask"},value:"",children:[]},w[1]]:w.unshift({name:"circle",type:"element",attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,cx:s.toString(),cy:o.toString(),r:T.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"},value:"",children:[]})}return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through"},children:w,value:""}]}if(n.shape==="circular_hole_with_rect_pad"){let d=n,_=n.hole_diameter*Math.abs(t.a),g=n.rect_pad_width*Math.abs(t.a),x=n.rect_pad_height*Math.abs(t.a),v=(n.rect_border_radius??0)*Math.abs(t.a),P=_/2,[w,T]=st(t,[d.x+(d.hole_offset_x??0),d.y+(d.hole_offset_y??0)]),k=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-pad",fill:i.copper.top,x:(s-g/2).toString(),y:(o-x/2).toString(),width:g.toString(),height:x.toString(),...v?{rx:v.toString(),ry:v.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,cx:w.toString(),cy:T.toString(),r:P.toString(),"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];if(u){let C=g+2*l,M=x+2*l,I=v+l;l<0?k=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-covered",fill:h,x:(s-g/2).toString(),y:(o-x/2).toString(),width:g.toString(),height:x.toString(),...v?{rx:v.toString(),ry:v.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-exposed",fill:i.copper.top,x:(s-C/2).toString(),y:(o-M/2).toString(),width:C.toString(),height:M.toString(),...I>0?{rx:I.toString(),ry:I.toString()}:{},"data-type":"pcb_soldermask"},value:"",children:[]},k[1]]:k.unshift({name:"rect",type:"element",attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,x:(s-C/2).toString(),y:(o-M/2).toString(),width:C.toString(),height:M.toString(),...v?{rx:I.toString(),ry:I.toString()}:{},"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"},value:"",children:[]})}return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through"},children:k,value:""}]}if(n.shape==="pill_hole_with_rect_pad"){let d=n,_=d.rect_pad_width*Math.abs(t.a),g=d.rect_pad_height*Math.abs(t.a),x=(d.rect_border_radius??0)*Math.abs(t.a),v=d.hole_height*Math.abs(t.a),P=d.hole_width*Math.abs(t.a),w=d,T=w.hole_offset_x??0,k=w.hole_offset_y??0,[C,M]=st(t,[d.x+T,d.y+k]),I=Math.min(v,P)/2,E=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-pad",fill:i.copper.top,x:(s-_/2).toString(),y:(o-g/2).toString(),width:_.toString(),height:g.toString(),...x?{rx:x.toString(),ry:x.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,x:(C-P/2).toString(),y:(M-v/2).toString(),width:P.toString(),height:v.toString(),rx:I.toString(),ry:I.toString(),"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];if(u){let A=_+2*l,R=g+2*l,B=x+l;l<0?E=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-covered",fill:h,x:(s-_/2).toString(),y:(o-g/2).toString(),width:_.toString(),height:g.toString(),...x?{rx:x.toString(),ry:x.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-exposed",fill:i.copper.top,x:(s-A/2).toString(),y:(o-R/2).toString(),width:A.toString(),height:R.toString(),...B>0?{rx:B.toString(),ry:B.toString()}:{},"data-type":"pcb_soldermask"},value:"",children:[]},E[1]]:E.unshift({name:"rect",type:"element",attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,x:(s-A/2).toString(),y:(o-R/2).toString(),width:A.toString(),height:R.toString(),...x?{rx:B.toString(),ry:B.toString()}:{},"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"},value:"",children:[]})}return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through"},children:E,value:""}]}if(n.shape==="rotated_pill_hole_with_rect_pad"){let d=n,_=d.rect_pad_width*Math.abs(t.a),g=d.rect_pad_height*Math.abs(t.a),x=(d.rect_border_radius??0)*Math.abs(t.a),v=d.hole_height*Math.abs(t.a),P=d.hole_width*Math.abs(t.a),w=d,T=w.hole_offset_x??0,k=w.hole_offset_y??0,[C,M]=st(t,[d.x+T,d.y+k]),I=Math.min(v,P)/2,E=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-pad",fill:i.copper.top,x:(-_/2).toString(),y:(-g/2).toString(),width:_.toString(),height:g.toString(),transform:`translate(${s} ${o}) rotate(${-d.rect_ccw_rotation})`,...x?{rx:x.toString(),ry:x.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,x:(-P/2).toString(),y:(-v/2).toString(),width:P.toString(),height:v.toString(),rx:I.toString(),ry:I.toString(),transform:`translate(${C} ${M}) rotate(${-d.hole_ccw_rotation})`,"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}];if(u){let A=_+2*l,R=g+2*l,B=x+l;l<0?E=[{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-covered",fill:h,x:(-_/2).toString(),y:(-g/2).toString(),width:_.toString(),height:g.toString(),transform:`translate(${s} ${o}) rotate(${-d.rect_ccw_rotation})`,...x?{rx:x.toString(),ry:x.toString()}:{},"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pcb-hole-outer-exposed",fill:i.copper.top,x:(-A/2).toString(),y:(-R/2).toString(),width:A.toString(),height:R.toString(),transform:`translate(${s} ${o}) rotate(${-d.rect_ccw_rotation})`,...B>0?{rx:B.toString(),ry:B.toString()}:{},"data-type":"pcb_soldermask"},value:"",children:[]},E[1]]:E.push({name:"rect",type:"element",attributes:{class:"pcb-solder-mask",fill:h,x:(-A/2).toString(),y:(-R/2).toString(),width:A.toString(),height:R.toString(),transform:`translate(${s} ${o}) rotate(${-d.rect_ccw_rotation})`,...x?{rx:B.toString(),ry:B.toString()}:{},"data-type":"pcb_soldermask"},value:"",children:[]})}return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through"},children:E,value:""}]}if(n.shape==="hole_with_polygon_pad"){let d=n,_=d.pad_outline||[],g=d.x??0,x=d.y??0,P=_.map(C=>st(t,[g+C.x,x+C.y])).map(C=>C.join(",")).join(" "),[w,T]=st(t,[g+d.hole_offset_x,x+d.hole_offset_y]),k=()=>{if(d.hole_shape==="circle"){let M=(d.hole_diameter??0)*Math.abs(t.a)/2;return{name:"circle",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,cx:w.toString(),cy:T.toString(),r:M.toString(),"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}}if(d.hole_shape==="oval"){let C=(d.hole_width??0)*Math.abs(t.a),M=(d.hole_height??0)*Math.abs(t.a),I=C/2,E=M/2;return{name:"ellipse",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,cx:w.toString(),cy:T.toString(),rx:I.toString(),ry:E.toString(),"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}}if(d.hole_shape==="pill"||d.hole_shape==="rotated_pill"){let C=(d.hole_width??0)*Math.abs(t.a),M=(d.hole_height??0)*Math.abs(t.a),I=C>M,E=Math.min(C,M)/2,A=Math.abs(I?C-M:M-C),R=I?`M${-A/2},${-E} h${A} a${E},${E} 0 0 1 0,${M} h-${A} a${E},${E} 0 0 1 0,-${M} z`:`M${-E},${-A/2} v${A} a${E},${E} 0 0 0 ${C},0 v-${A} a${E},${E} 0 0 0 -${C},0 z`;return{name:"path",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,d:R,transform:`translate(${w} ${T})`,"data-type":"pcb_plated_hole_drill","data-pcb-layer":"drill"},value:"",children:[]}}return{name:"g",type:"element",attributes:{},value:"",children:[]}};return[{name:"g",type:"element",attributes:{"data-type":"pcb_plated_hole","data-pcb-layer":"through"},children:[{name:"polygon",type:"element",attributes:{class:"pcb-hole-outer-pad",fill:i.copper.top,points:P,"data-type":"pcb_plated_hole","data-pcb-layer":a},value:"",children:[]},k()],value:""}]}return[]}function C6t(n,e){let{transform:t,layer:i,colorMap:r}=e;if(!n.route||!Array.isArray(n.route))return[];let s=n.route.map((u,h)=>{let[d,_]=st(t,[u.x,u.y]);return h===0?`M ${d} ${_}`:`L ${d} ${_}`}).join(" "),o=n.route[0],a=n.route[n.route.length-1];o&&a&&o.x===a.x&&o.y===a.y&&(s+=" Z");let c=n.layer||"top";if(i&&c!==i)return[];let l=c==="bottom"?r.silkscreen.bottom:r.silkscreen.top;return[{name:"path",type:"element",attributes:{class:`pcb-silkscreen pcb-silkscreen-${c}`,d:s,fill:"none",stroke:l,"stroke-width":(n.stroke_width*Math.abs(t.a)).toString(),"stroke-linecap":"round","stroke-linejoin":"round","data-pcb-component-id":n.pcb_component_id,"data-pcb-silkscreen-path-id":n.pcb_silkscreen_path_id,"data-type":"pcb_silkscreen_path","data-pcb-layer":c},value:"",children:[]}]}function I6t(n,e){let{transform:t,layer:i,colorMap:r,circuitJson:s}=e,{anchor_position:o,text:a,font_size:c=1,layer:l="top",ccw_rotation:u=0,anchor_alignment:h="center"}=n;if(i&&l!==i)return[];if(!o||typeof o.x!="number"||typeof o.y!="number")return console.error("Invalid anchor_position:",o),[];let[d,_]=st(t,[o.x,o.y]),g=c*Math.abs(t.a),x="middle",v="central",P=0,w=0;switch(h){case"top_left":x="start",v="text-before-edge";break;case"top_center":x="middle",v="text-before-edge";break;case"top_right":x="end",v="text-before-edge";break;case"center_left":x="start",v="central";break;case"center_right":x="end",v="central";break;case"bottom_left":x="start",v="text-after-edge";break;case"bottom_center":x="middle",v="text-after-edge";break;case"bottom_right":x="end",v="text-after-edge";break;case"center":default:x="middle",v="central";break}let T=Fe(yn(d,_),ls(-u*Math.PI/180),...l==="bottom"?[Ti(-1,1)]:[]),k=l==="bottom"?r.silkscreen.bottom:r.silkscreen.top,C=a.split(`
74
+ `),M=C.length===1?[{type:"text",value:a,name:"",attributes:{},children:[]}]:C.map((E,A)=>({type:"element",name:"tspan",value:"",attributes:{x:"0",...A>0?{dy:g.toString()}:{}},children:[{type:"text",value:E,name:"",attributes:{},children:[]}]}));return[{name:"text",type:"element",attributes:{x:"0",y:"0",dx:P.toString(),dy:w.toString(),fill:k,"font-family":"Arial, sans-serif","font-size":g.toString(),"text-anchor":x,"dominant-baseline":v,transform:Ba(T),class:`pcb-silkscreen-text pcb-silkscreen-${l}`,"data-pcb-silkscreen-text-id":n.pcb_component_id,stroke:"none","data-type":"pcb_silkscreen_text","data-pcb-layer":l},children:M,value:""}]}function N6t(n,e){let{transform:t,layer:i,colorMap:r}=e,{center:s,width:o,height:a,layer:c="top",pcb_silkscreen_rect_id:l,stroke_width:u,is_filled:h,has_stroke:d,is_stroke_dashed:_,corner_radius:g}=n;if(i&&c!==i)return[];if(!s||typeof s.x!="number"||typeof s.y!="number"||typeof o!="number"||typeof a!="number")return console.error("Invalid rectangle data:",{center:s,width:o,height:a}),[];let[x,v]=st(t,[s.x,s.y]),P=typeof g=="number"&&g>0?g:0,w=P*Math.abs(t.a),T=P*Math.abs(t.d),k=o*Math.abs(t.a),C=a*Math.abs(t.d),M=u*Math.abs(t.a),I=c==="bottom"?r.silkscreen.bottom:r.silkscreen.top,E={x:(x-k/2).toString(),y:(v-C/2).toString(),width:k.toString(),height:C.toString(),class:`pcb-silkscreen-rect pcb-silkscreen-${c}`,"data-pcb-silkscreen-rect-id":l,"data-type":"pcb_silkscreen_rect","data-pcb-layer":c};w>0&&(E.rx=w.toString()),T>0&&(E.ry=T.toString()),E.fill=h?I:"none";let A;if(d===void 0?A=M>0:A=d,A){if(E.stroke=I,E["stroke-width"]=M.toString(),_){let B=.1*Math.abs(t.a),j=.05*Math.abs(t.a);E["stroke-dasharray"]=`${B} ${j}`}}else E.stroke="none";return[{name:"rect",type:"element",attributes:E,value:"",children:[]}]}function A6t(n,e){let{transform:t,layer:i,colorMap:r}=e,{center:s,radius:o,layer:a="top",pcb_silkscreen_circle_id:c,stroke_width:l=1}=n;if(i&&a!==i)return[];if(!s||typeof s.x!="number"||typeof s.y!="number"||typeof o!="number")return console.error("Invalid PCB Silkscreen Circle data:",{center:s,radius:o}),[];let[u,h]=st(t,[s.x,s.y]),d=o*Math.abs(t.a),_=l*Math.abs(t.a),g=a==="bottom"?r.silkscreen.bottom:r.silkscreen.top;return[{name:"circle",type:"element",attributes:{cx:u.toString(),cy:h.toString(),r:d.toString(),class:`pcb-silkscreen-circle pcb-silkscreen-${a}`,stroke:g,"stroke-width":_.toString(),"data-pcb-silkscreen-circle-id":c,"data-type":"pcb_silkscreen_circle","data-pcb-layer":a},value:"",children:[]}]}function R6t(n,e){let{transform:t,layer:i,colorMap:r}=e,{x1:s,y1:o,x2:a,y2:c,stroke_width:l,layer:u="top",pcb_silkscreen_line_id:h}=n;if(i&&u!==i)return[];if(typeof s!="number"||typeof o!="number"||typeof a!="number"||typeof c!="number")return console.error("Invalid coordinates:",{x1:s,y1:o,x2:a,y2:c}),[];let[d,_]=st(t,[s,o]),[g,x]=st(t,[a,c]),v=l*Math.abs(t.a),P=u==="bottom"?r.silkscreen.bottom:r.silkscreen.top;return[{name:"line",type:"element",attributes:{x1:d.toString(),y1:_.toString(),x2:g.toString(),y2:x.toString(),stroke:P,"stroke-width":v.toString(),class:`pcb-silkscreen-line pcb-silkscreen-${u}`,"data-pcb-silkscreen-line-id":h,"data-type":"pcb_silkscreen_line","data-pcb-layer":u},value:"",children:[]}]}function O6t(n,e){let{transform:t,layer:i,colorMap:r}=e,{center:s,width:o,height:a,layer:c="top",pcb_courtyard_rect_id:l}=n;if(i&&c!==i)return[];if(!s||typeof s.x!="number"||typeof s.y!="number"||typeof o!="number"||typeof a!="number")return console.error("Invalid courtyard rectangle data:",{center:s,width:o,height:a}),[];let[u,h]=st(t,[s.x,s.y]),d=o*Math.abs(t.a),_=a*Math.abs(t.d),g=.05*Math.abs(t.a),x=r.courtyard,v={x:(u-d/2).toString(),y:(h-_/2).toString(),width:d.toString(),height:_.toString(),class:`pcb-courtyard-rect pcb-courtyard-${c}`,"data-pcb-courtyard-rect-id":l,"data-type":"pcb_courtyard_rect","data-pcb-layer":c};return v.fill="none",v.stroke=x,v["stroke-width"]=g.toString(),[{name:"rect",type:"element",attributes:v,value:"",children:[]}]}function L6t(n){let e=[];for(let t=0;t<n.length-1;t++)e.push([n[t],n[t+1]]);return e}function Os(n,e=Mi){return e.copper[n]??"white"}function jw(n){return F6t[n]??"rgb(105, 105, 105)"}function z6t(n,e){let{transform:t,layer:i,colorMap:r,showSolderMask:s}=e;if(!n.route||!Array.isArray(n.route)||n.route.length<2)return[];let o=L6t(n.route),a=[];for(let[c,l]of o){let u=st(t,[c.x,c.y]),h=st(t,[l.x,l.y]),d="layer"in c?c.layer:"layer"in l?l.layer:null;if(!d||i&&d!==i)continue;let _=Os(d,r),g=r.soldermaskWithCopperUnderneath[d],x="width"in c?c.width:"width"in l?l.width:null,v=x?(x*Math.abs(t.a)).toString():"0.3";if(s){let P={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask",stroke:g,fill:"none",d:`M ${u[0]} ${u[1]} L ${h[0]} ${h[1]}`,"stroke-width":v,"stroke-linecap":"round","stroke-linejoin":"round","shape-rendering":"crispEdges","data-type":"pcb_trace_soldermask","data-pcb-layer":d}};a.push(P)}else{let P={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-trace",stroke:_,fill:"none",d:`M ${u[0]} ${u[1]} L ${h[0]} ${h[1]}`,"stroke-width":v,"stroke-linecap":"round","stroke-linejoin":"round","shape-rendering":"crispEdges","data-type":s?"pcb_soldermask":"pcb_trace","data-pcb-layer":d}};a.push(P)}}return a}function $6t(n,e){let{transform:t,layer:i,colorMap:r,showSolderMask:s}=e;if(i&&n.layer!==i)return[];let o=!!n?.is_covered_with_solder_mask,a=s&&o,c=r.soldermaskWithCopperUnderneath[n.layer]??r.soldermaskWithCopperUnderneath.top,l=(n.soldermask_margin??0)*Math.abs(t.a);if(n.shape==="rect"||n.shape==="rotated_rect"){let u=n.width*Math.abs(t.a),h=n.height*Math.abs(t.d),[d,_]=st(t,[n.x,n.y]),x=(n.corner_radius??n.rect_border_radius??0)*Math.abs(t.a);if(n.shape==="rotated_rect"&&n.ccw_rotation){let C={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad",fill:Os(n.layer,r),x:(-u/2).toString(),y:(-h/2).toString(),width:u.toString(),height:h.toString(),transform:`translate(${d} ${_}) rotate(${-n.ccw_rotation})`,"data-type":"pcb_smtpad","data-pcb-layer":n.layer,...x?{rx:x.toString(),ry:x.toString()}:{}}};if(!a)return[C];let M=u+2*l,I=h+2*l,E=x?x+l:0;if(l<0){let R={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(-u/2).toString(),y:(-h/2).toString(),width:u.toString(),height:h.toString(),transform:`translate(${d} ${_}) rotate(${-n.ccw_rotation})`,"data-type":"pcb_smtpad","data-pcb-layer":n.layer,...x?{rx:x.toString(),ry:x.toString()}:{}}},B={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-exposed",fill:Os(n.layer,r),x:(-M/2).toString(),y:(-I/2).toString(),width:M.toString(),height:I.toString(),transform:`translate(${d} ${_}) rotate(${-n.ccw_rotation})`,"data-type":"pcb_soldermask","data-pcb-layer":n.layer,...E>0?{rx:E.toString(),ry:E.toString()}:{}}};return[R,B]}return l===0?[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(-u/2).toString(),y:(-h/2).toString(),width:u.toString(),height:h.toString(),transform:`translate(${d} ${_}) rotate(${-n.ccw_rotation})`,"data-type":"pcb_smtpad","data-pcb-layer":n.layer,...x?{rx:x.toString(),ry:x.toString()}:{}}}]:[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:r.substrate,x:(-M/2).toString(),y:(-I/2).toString(),width:M.toString(),height:I.toString(),transform:`translate(${d} ${_}) rotate(${-n.ccw_rotation})`,...E>0?{rx:E.toString(),ry:E.toString()}:{},"data-type":"pcb_soldermask_opening","data-pcb-layer":`soldermask-${n.layer}`}},C]}let v={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad",fill:Os(n.layer,r),x:(d-u/2).toString(),y:(_-h/2).toString(),width:u.toString(),height:h.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer,...x?{rx:x.toString(),ry:x.toString()}:{}}};if(!a)return[v];let P=u+2*l,w=h+2*l,T=x?x+l:0;if(l<0){let C={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(d-u/2).toString(),y:(_-h/2).toString(),width:u.toString(),height:h.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer,...x?{rx:x.toString(),ry:x.toString()}:{}}},M={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-exposed",fill:Os(n.layer,r),x:(d-P/2).toString(),y:(_-w/2).toString(),width:P.toString(),height:w.toString(),"data-type":"pcb_soldermask","data-pcb-layer":n.layer,...T>0?{rx:T.toString(),ry:T.toString()}:{}}};return[C,M]}return l===0?[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(d-u/2).toString(),y:(_-h/2).toString(),width:u.toString(),height:h.toString(),...T>0?{rx:x.toString(),ry:x.toString()}:{},"data-type":"pcb_smtpad","data-pcb-layer":n.layer}}]:[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:r.substrate,x:(d-P/2).toString(),y:(_-w/2).toString(),width:P.toString(),height:w.toString(),...T>0?{rx:T.toString(),ry:T.toString()}:{},"data-type":"pcb_soldermask_opening","data-pcb-layer":`soldermask-${n.layer}`}},v]}if(n.shape==="pill"){let u=n.width*Math.abs(t.a),h=n.height*Math.abs(t.d),d=n.radius*Math.abs(t.a),[_,g]=st(t,[n.x,n.y]),x={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad",fill:Os(n.layer,r),x:(_-u/2).toString(),y:(g-h/2).toString(),width:u.toString(),height:h.toString(),rx:d.toString(),ry:d.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}};if(!a)return[x];let v=u+2*l,P=h+2*l,w=d+l;if(l<0){let k={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(_-u/2).toString(),y:(g-h/2).toString(),width:u.toString(),height:h.toString(),rx:d.toString(),ry:d.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}},C={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-exposed",fill:Os(n.layer,r),x:(_-v/2).toString(),y:(g-P/2).toString(),width:v.toString(),height:P.toString(),rx:w.toString(),ry:w.toString(),"data-type":"pcb_soldermask","data-pcb-layer":n.layer}};return[k,C]}return l===0?[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,x:(_-u/2).toString(),y:(g-h/2).toString(),width:u.toString(),height:h.toString(),rx:d.toString(),ry:d.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}}]:[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:r.substrate,x:(_-v/2).toString(),y:(g-P/2).toString(),width:v.toString(),height:P.toString(),rx:w.toString(),ry:w.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":`soldermask-${n.layer}`}},x]}if(n.shape==="circle"){let u=n.radius*Math.abs(t.a),[h,d]=st(t,[n.x,n.y]),_={name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-pad",fill:Os(n.layer,r),cx:h.toString(),cy:d.toString(),r:u.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}};if(!a)return[_];let g=u+l;if(l<0){let v={name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,cx:h.toString(),cy:d.toString(),r:u.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}},P={name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-pad-exposed",fill:Os(n.layer,r),cx:h.toString(),cy:d.toString(),r:g.toString(),"data-type":"pcb_soldermask","data-pcb-layer":n.layer}};return[v,P]}return l===0?[{name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,cx:h.toString(),cy:d.toString(),r:u.toString(),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}}]:[{name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:r.substrate,cx:h.toString(),cy:d.toString(),r:g.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":`soldermask-${n.layer}`}},_]}if(n.shape==="polygon"){let u=(n.points??[]).map(g=>st(t,[g.x,g.y])),h={name:"polygon",type:"element",value:"",children:[],attributes:{class:"pcb-pad",fill:Os(n.layer,r),points:u.map(g=>g.join(",")).join(" "),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}};if(!a)return[h];let d=u;if(l!==0){let g=u.reduce((v,P)=>v+P[0],0)/u.length,x=u.reduce((v,P)=>v+P[1],0)/u.length;d=u.map(([v,P])=>{let w=v-g,T=P-x,k=Math.sqrt(w*w+T*T);if(k===0)return[v,P];let C=w/k,M=T/k;return[v+C*l,P+M*l]})}if(l<0){let g={name:"polygon",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,points:u.map(v=>v.join(",")).join(" "),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}},x={name:"polygon",type:"element",value:"",children:[],attributes:{class:"pcb-pad-exposed",fill:Os(n.layer,r),points:d.map(v=>v.join(",")).join(" "),"data-type":"pcb_soldermask","data-pcb-layer":n.layer}};return[g,x]}return l===0?[{name:"polygon",type:"element",value:"",children:[],attributes:{class:"pcb-pad-covered",fill:c,points:u.map(x=>x.join(",")).join(" "),"data-type":"pcb_smtpad","data-pcb-layer":n.layer}}]:[{name:"polygon",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:r.substrate,points:d.map(g=>g.join(",")).join(" "),"data-type":"pcb_soldermask_opening","data-pcb-layer":`soldermask-${n.layer}`}},h]}return[]}function Wtt(n,e){let{transform:t,colorMap:i,showSolderMask:r}=e,{width:s,height:o,center:a,outline:c}=n,l;if(c&&Array.isArray(c)&&c.length>=3)l=c.map((h,d)=>{let[_,g]=st(t,[h.x,h.y]);return d===0?`M ${_} ${g}`:`L ${_} ${g}`}).join(" ");else{let h=s/2,d=o/2,_=st(t,[a.x-h,a.y-d]),g=st(t,[a.x+h,a.y-d]),x=st(t,[a.x+h,a.y+d]),v=st(t,[a.x-h,a.y+d]);l=`M ${_[0]} ${_[1]} L ${g[0]} ${g[1]} L ${x[0]} ${x[1]} L ${v[0]} ${v[1]}`}l+=" Z";let u=[];return r&&u.push({name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-board-soldermask",d:l,fill:i.soldermask.top,"fill-opacity":"0.8",stroke:"none","data-type":"pcb_soldermask","data-pcb-layer":"soldermask-top"}}),u.push({name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-board",d:l,fill:"none",stroke:i.boardOutline,"stroke-width":(.1*Math.abs(t.a)).toString(),"data-type":"pcb_board","data-pcb-layer":"board"}}),u}function D6t(n,e){let{transform:t,colorMap:i,showSolderMask:r}=e,s=Number(n.width),o=Number(n.height),a=n.center??{x:s/2,y:o/2},c=s/2,l=o/2,u=st(t,[a.x-c,a.y-l]),h=st(t,[a.x+c,a.y-l]),d=st(t,[a.x+c,a.y+l]),_=st(t,[a.x-c,a.y+l]),g=`M ${u[0]} ${u[1]} L ${h[0]} ${h[1]} L ${d[0]} ${d[1]} L ${_[0]} ${_[1]} Z`,x=n.covered_with_solder_mask!==!1,v=!!(r&&x);return[{name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-panel",d:g,fill:"none",stroke:i.boardOutline,"stroke-width":(.1*Math.abs(t.a)).toString(),"data-type":"pcb_panel","data-pcb-layer":"board"}}]}function j6t(n,e){let{transform:t,colorMap:i}=e,[r,s]=st(t,[n.x,n.y]),o=n.outer_diameter*Math.abs(t.a),a=n.outer_diameter*Math.abs(t.a),c=n.hole_diameter*Math.abs(t.a),l=n.hole_diameter*Math.abs(t.a),u=Math.min(o,a)/2,h=Math.min(c,l)/2;return{name:"g",type:"element",attributes:{"data-type":"pcb_via","data-pcb-layer":"through"},children:[{name:"circle",type:"element",attributes:{class:"pcb-hole-outer",fill:i.copper.top,cx:r.toString(),cy:s.toString(),r:u.toString(),"data-type":"pcb_via","data-pcb-layer":"top"}},{name:"circle",type:"element",attributes:{class:"pcb-hole-inner",fill:i.drill,cx:r.toString(),cy:s.toString(),r:h.toString(),"data-type":"pcb_via","data-pcb-layer":"drill"}}]}}function B6t(n,e){let{transform:t,colorMap:i,showSolderMask:r}=e,[s,o]=st(t,[n.x,n.y]),a=!!n.is_covered_with_solder_mask,c=(n.soldermask_margin??0)*Math.abs(t.a),l=r&&a&&c!==0,u=i.soldermask.top;if(n.hole_shape==="circle"||n.hole_shape==="square"){let h=n.hole_diameter*Math.abs(t.a),d=h/2;if(n.hole_shape==="circle"){let v={name:"circle",type:"element",attributes:{class:"pcb-hole",cx:s.toString(),cy:o.toString(),r:d.toString(),fill:i.drill,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[v];let P=d+c;if(c<0){let T={name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,cx:s.toString(),cy:o.toString(),r:d.toString(),"data-type":"pcb_hole","data-pcb-layer":"drill"}},k={name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:i.drill,cx:s.toString(),cy:o.toString(),r:P.toString(),"data-type":"pcb_soldermask"}};return[T,k]}return[{name:"circle",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,cx:s.toString(),cy:o.toString(),r:P.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"}},v]}let _={name:"rect",type:"element",attributes:{class:"pcb-hole",x:(s-d).toString(),y:(o-d).toString(),width:h.toString(),height:h.toString(),fill:i.drill,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[_];let g=h+2*c;if(c<0){let v={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,x:(s-d).toString(),y:(o-d).toString(),width:h.toString(),height:h.toString(),"data-type":"pcb_hole","data-pcb-layer":"drill"}},P={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:i.drill,x:(s-g/2).toString(),y:(o-g/2).toString(),width:g.toString(),height:g.toString(),"data-type":"pcb_soldermask"}};return[v,P]}return[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,x:(s-g/2).toString(),y:(o-g/2).toString(),width:g.toString(),height:g.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"}},_]}if(n.hole_shape==="oval"){let h=n.hole_width*Math.abs(t.a),d=n.hole_height*Math.abs(t.a),_=h/2,g=d/2,x={name:"ellipse",type:"element",attributes:{class:"pcb-hole",cx:s.toString(),cy:o.toString(),rx:_.toString(),ry:g.toString(),fill:i.drill,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[x];let v=_+c,P=g+c;if(c<0){let T={name:"ellipse",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,cx:s.toString(),cy:o.toString(),rx:_.toString(),ry:g.toString(),"data-type":"pcb_hole","data-pcb-layer":"drill"}},k={name:"ellipse",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:i.drill,cx:s.toString(),cy:o.toString(),rx:v.toString(),ry:P.toString(),"data-type":"pcb_soldermask"}};return[T,k]}return[{name:"ellipse",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,cx:s.toString(),cy:o.toString(),rx:v.toString(),ry:P.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"}},x]}if(n.hole_shape==="rect"){let h=n.hole_width*Math.abs(t.a),d=n.hole_height*Math.abs(t.a),_={name:"rect",type:"element",attributes:{class:"pcb-hole",x:(s-h/2).toString(),y:(o-d/2).toString(),width:h.toString(),height:d.toString(),fill:i.drill,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[_];let g=h+2*c,x=d+2*c;if(c<0){let P={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,x:(s-h/2).toString(),y:(o-d/2).toString(),width:h.toString(),height:d.toString(),"data-type":"pcb_hole","data-pcb-layer":"drill"}},w={name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:i.drill,x:(s-g/2).toString(),y:(o-x/2).toString(),width:g.toString(),height:x.toString(),"data-type":"pcb_soldermask"}};return[P,w]}return[{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,x:(s-g/2).toString(),y:(o-x/2).toString(),width:g.toString(),height:x.toString(),"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"}},_]}if(n.hole_shape==="pill"){let h=n.hole_width*Math.abs(t.a),d=n.hole_height*Math.abs(t.a),_=h>d,g=Math.min(h,d)/2,x=Math.abs(_?h-d:d-h),v=_?`M${s-x/2},${o-g} h${x} a${g},${g} 0 0 1 0,${d} h-${x} a${g},${g} 0 0 1 0,-${d} z`:`M${s-g},${o-x/2} v${x} a${g},${g} 0 0 0 ${h},0 v-${x} a${g},${g} 0 0 0 -${h},0 z`,P={name:"path",type:"element",attributes:{class:"pcb-hole",fill:i.drill,d:v,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[P];let w=h+2*c,T=d+2*c,k=w>T,C=Math.min(w,T)/2,M=Math.abs(k?w-T:T-w),I=k?`M${s-M/2},${o-C} h${M} a${C},${C} 0 0 1 0,${T} h-${M} a${C},${C} 0 0 1 0,-${T} z`:`M${s-C},${o-M/2} v${M} a${C},${C} 0 0 0 ${w},0 v-${M} a${C},${C} 0 0 0 -${w},0 z`;if(c<0){let A={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,d:v,"data-type":"pcb_hole","data-pcb-layer":"drill"}},R={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:i.drill,d:I,"data-type":"pcb_soldermask"}};return[A,R]}return[{name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,d:I,"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"}},P]}if(n.hole_shape==="rotated_pill"){let h=n.hole_width*Math.abs(t.a),d=n.hole_height*Math.abs(t.a),_="ccw_rotation"in n?n.ccw_rotation??0:0,g=h>d,x=Math.min(h,d)/2,v=Math.abs(g?h-d:d-h),P=g?`M${-v/2},${-x} h${v} a${x},${x} 0 0 1 0,${d} h-${v} a${x},${x} 0 0 1 0,-${d} z`:`M${-x},${-v/2} v${v} a${x},${x} 0 0 0 ${h},0 v-${v} a${x},${x} 0 0 0 -${h},0 z`,w={name:"path",type:"element",attributes:{class:"pcb-hole",fill:i.drill,d:P,transform:`translate(${s} ${o}) rotate(${-_})`,"data-type":"pcb_hole","data-pcb-layer":"drill"},children:[],value:""};if(!l)return[w];let T=h+2*c,k=d+2*c,C=T>k,M=Math.min(T,k)/2,I=Math.abs(C?T-k:k-T),E=C?`M${-I/2},${-M} h${I} a${M},${M} 0 0 1 0,${k} h-${I} a${M},${M} 0 0 1 0,-${k} z`:`M${-M},${-I/2} v${I} a${M},${M} 0 0 0 ${T},0 v-${I} a${M},${M} 0 0 0 -${T},0 z`;if(c<0){let R={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-hole-covered",fill:u,d:P,transform:`translate(${s} ${o}) rotate(${-_})`,"data-type":"pcb_hole","data-pcb-layer":"drill"}},B={name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-hole-exposed",fill:i.drill,d:E,transform:`translate(${s} ${o}) rotate(${-_})`,"data-type":"pcb_soldermask"}};return[R,B]}return[{name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-soldermask-cutout",fill:i.substrate,d:E,"data-type":"pcb_soldermask_opening","data-pcb-layer":"soldermask-top"}},w]}return[]}function U6t(n,e){let{transform:t}=e,i=tr(n),r=n.filter(c=>c.type==="pcb_port"),s=n.filter(c=>c.type==="source_trace"),o=[];r.forEach((c,l)=>{let u=c.pcb_port_id;if(!u)return;let h=i.getNetConnectedToId(u);if(!h)return;let d=!1,_=Ee(n).source_port.getWhere({pcb_port_id:u});if(_&&_.source_port_id){let v=_.source_port_id;for(let P of s)if(Array.isArray(P.connected_source_port_ids)&&P.connected_source_port_ids.includes(v)&&Array.isArray(P.connected_source_net_ids)&&P.connected_source_net_ids.length>0){d=!0;break}}let g={x:c.x,y:c.y},x=X6t(g,h,i,n);x&&o.push({key:`${u}-${l}`,startPoint:g,endPoint:x,isInNet:d})});let a=[];for(let c of o){let l=st(t,[c.startPoint.x,c.startPoint.y]),u=st(t,[c.endPoint.x,c.endPoint.y]),h={x1:l[0].toString(),y1:l[1].toString(),x2:u[0].toString(),y2:u[1].toString(),stroke:"white","stroke-width":"1","stroke-dasharray":"6,6","data-type":"pcb_rats_nest","data-pcb-layer":"overlay"};a.push({name:"line",type:"element",attributes:h,value:"",children:[]})}return a}function V6t(n,e){let{transform:t,colorMap:i}=e;if(n.shape==="rect"){let r=n,[s,o]=st(t,[r.center.x,r.center.y]),a=r.width*Math.abs(t.a),c=r.height*Math.abs(t.d),l=-(r.rotation??0),{corner_radius:u}=r,h=typeof u=="number"&&u>0?u:0,d=h*Math.abs(t.a),_=h*Math.abs(t.d),g={class:"pcb-cutout pcb-cutout-rect",x:(-a/2).toString(),y:(-c/2).toString(),width:a.toString(),height:c.toString(),fill:i.drill,transform:Ba(Fe(yn(s,o),ls(l*Math.PI/180))),"data-type":"pcb_cutout","data-pcb-layer":"drill"};return d>0&&(g.rx=d.toString()),_>0&&(g.ry=_.toString()),[{name:"rect",type:"element",attributes:g,children:[],value:""}]}if(n.shape==="circle"){let r=n,[s,o]=st(t,[r.center.x,r.center.y]),a=r.radius*Math.abs(t.a);return[{name:"circle",type:"element",attributes:{class:"pcb-cutout pcb-cutout-circle",cx:s.toString(),cy:o.toString(),r:a.toString(),fill:i.drill,"data-type":"pcb_cutout","data-pcb-layer":"drill"},children:[],value:""}]}if(n.shape==="polygon"){let r=n;return!r.points||r.points.length===0?[]:[{name:"polygon",type:"element",attributes:{class:"pcb-cutout pcb-cutout-polygon",points:r.points.map(a=>st(t,[a.x,a.y])).map(a=>`${a[0]},${a[1]}`).join(" "),fill:i.drill,"data-type":"pcb_cutout","data-pcb-layer":"drill"},children:[],value:""}]}return[]}function ktt(n,e){if(n.length===0)return"";let t=n.map(r=>{let[s,o]=st(e,[r.x,r.y]);return{...r,x:s,y:o}}),i=`M ${t[0].x} ${t[0].y}`;for(let r=0;r<t.length;r++){let s=t[r],o=t[(r+1)%t.length];if(s.bulge){if(Math.hypot(o.x-s.x,o.y-s.y)<1e-9)continue;let a=s.bulge,c=o.x-s.x,l=o.y-s.y,u=Math.hypot(c,l),h=Math.abs(u/4/a*(a*a+1)),d=a<0?1:0,_=Math.abs(a)>1?1:0;i+=` A ${h} ${h} 0 ${_} ${d} ${o.x} ${o.y}`}else i+=` L ${o.x} ${o.y}`}return i+=" Z",i}function G6t(n,e){let{transform:t,layer:i,colorMap:r}=e,{layer:s}=n;if(i&&s!==i)return[];let o=Os(s,r),a="0.5";if(n.shape==="rect"){let[c,l]=st(t,[n.center.x,n.center.y]),u=n.width*Math.abs(t.a),h=n.height*Math.abs(t.d),d=-(n.rotation??0);return[{name:"rect",type:"element",attributes:{class:"pcb-copper-pour pcb-copper-pour-rect",x:(-u/2).toString(),y:(-h/2).toString(),width:u.toString(),height:h.toString(),fill:o,"fill-opacity":a,transform:Ba(Fe(yn(c,l),ls(d*Math.PI/180))),"data-type":"pcb_copper_pour","data-pcb-layer":s},children:[],value:""}]}if(n.shape==="polygon")return!n.points||n.points.length===0?[]:[{name:"polygon",type:"element",attributes:{class:"pcb-copper-pour pcb-copper-pour-polygon",points:n.points.map(u=>st(t,[u.x,u.y])).map(u=>`${u[0]},${u[1]}`).join(" "),fill:o,"fill-opacity":a,"data-type":"pcb_copper_pour","data-pcb-layer":s},children:[],value:""}];if(n.shape==="brep"){let{brep_shape:c}=n,l=ktt(c.outer_ring.vertices,t);for(let u of c.inner_rings??[])l+=` ${ktt(u.vertices,t)}`;return[{name:"path",type:"element",attributes:{class:"pcb-copper-pour pcb-copper-pour-brep",d:l,fill:o,"fill-rule":"evenodd","fill-opacity":a,"data-type":"pcb_copper_pour","data-pcb-layer":s},children:[],value:""}]}return[]}function W6t({grid:n,svgWidth:e,svgHeight:t}){if(!n)return{};let i=n.lineColor??H6t,r=n.cellSize,s=n.majorCellSize,o=n.majorLineColor??i;if(s!==void 0){if(!r||r<=0)throw new Error("grid.majorCellSize requires a positive grid.cellSize");if(s<=0)throw new Error("grid.majorCellSize must be a positive multiple of grid.cellSize");let h=s/r,d=Math.round(h);if(!Number.isFinite(h)||Math.abs(h-d)>1e-6)throw new Error("grid.majorCellSize must be a positive multiple of grid.cellSize")}if(!r||r<=0)return{};let a=s!==void 0,c=a?q6t(r,s,i,o):[{name:"path",type:"element",value:"",attributes:{d:`M ${r} 0 L 0 0 0 ${r}`,fill:"none",stroke:i,"stroke-width":"1","shape-rendering":"crispEdges"},children:[]}],l={name:"defs",type:"element",value:"",attributes:{},children:[{name:"pattern",type:"element",value:"",attributes:{id:Ttt,width:a?s.toString():r.toString(),height:a?s.toString():r.toString(),patternUnits:"userSpaceOnUse"},children:c}]},u={name:"rect",type:"element",value:"",attributes:{x:"0",y:"0",width:e.toString(),height:t.toString(),fill:`url(#${Ttt})`,"pointer-events":"none","data-type":"pcb_grid","data-pcb-layer":"global"},children:[]};return{defs:l,rect:u}}function q6t(n,e,t,i){let r=[],s=Math.round(e/n);for(let o=0;o<s;o+=1){let c=Number((o*n).toFixed(6)).toString(),l=o===0?i:t,u=e.toString();r.push({name:"line",type:"element",value:"",attributes:{x1:c,y1:"0",x2:c,y2:u,stroke:l,"stroke-width":"1","shape-rendering":"crispEdges"},children:[]}),r.push({name:"line",type:"element",value:"",attributes:{x1:"0",y1:c,x2:u,y2:c,stroke:l,"stroke-width":"1","shape-rendering":"crispEdges"},children:[]})}return r}function tRt(n){let{groupAnchorPosition:e,componentPosition:t,transform:i,componentWidth:r=0,componentHeight:s=0}=n,o=[],[a,c]=st(i,[e.x,e.y]),[l,u]=st(i,[t.x,t.y]),h=t.x-e.x,d=t.y-e.y,_=Math.abs(i.a),g=r*_,x=s*_;o.push(eRt(a,c)),o.push({name:"line",type:"element",attributes:{x1:a.toString(),y1:c.toString(),x2:l.toString(),y2:u.toString(),stroke:"#ffffff","stroke-width":"0.5","stroke-dasharray":"3,3",opacity:"0.5",class:"anchor-offset-connector"},children:[],value:""}),o.push({name:"circle",type:"element",attributes:{cx:l.toString(),cy:u.toString(),r:"2",fill:"#ffffff",opacity:"0.7",class:"anchor-offset-component-marker"},children:[],value:""});let v=Math.abs(u-c),P=Math.abs(l-a),w=Math.sqrt(P*P+v*v),T=x/2+Z6t,k=Math.max(T,Math.min(Q6t,w*J6t)),C=d>0?u-k:u+k,M=g/2+K6t,I=h>0?l+M:l-M;return Math.abs(h)>Mtt&&o.push(...nRt({startX:a,endX:l,y:C,offsetMm:h,offsetY:d})),Math.abs(d)>Mtt&&o.push(...iRt({x:I,startY:c,endY:u,offsetMm:-d,offsetX:h})),o}function eRt(n,e){return{name:"g",type:"element",attributes:{class:"anchor-offset-marker","data-type":"anchor_offset_marker"},children:[{name:"line",type:"element",attributes:{x1:n.toString(),y1:(e-Bw).toString(),x2:n.toString(),y2:(e+Bw).toString(),stroke:"#ffffff","stroke-width":Ctt.toString(),"stroke-linecap":"round"},children:[],value:""},{name:"line",type:"element",attributes:{x1:(n-Bw).toString(),y1:e.toString(),x2:(n+Bw).toString(),y2:e.toString(),stroke:"#ffffff","stroke-width":Ctt.toString(),"stroke-linecap":"round"},children:[],value:""}],value:""}}function nRt({startX:n,endX:e,y:t,offsetMm:i,offsetY:r}){let s=[];s.push({name:"line",type:"element",attributes:{x1:n.toString(),y1:t.toString(),x2:e.toString(),y2:t.toString(),stroke:"#ffffff","stroke-width":O_.toString(),class:"anchor-offset-dimension-x"},children:[],value:""}),s.push({name:"line",type:"element",attributes:{x1:n.toString(),y1:(t-Ls).toString(),x2:n.toString(),y2:(t+Ls).toString(),stroke:"#ffffff","stroke-width":O_.toString()},children:[],value:""}),s.push({name:"line",type:"element",attributes:{x1:e.toString(),y1:(t-Ls).toString(),x2:e.toString(),y2:(t+Ls).toString(),stroke:"#ffffff","stroke-width":O_.toString()},children:[],value:""});let o=(n+e)/2,a=r>0?t-Ls-Ett:t+Ls+Ett;return s.push({name:"text",type:"element",attributes:{x:o.toString(),y:a.toString(),fill:"#ffffff","font-size":qtt.toString(),"font-family":"Arial, sans-serif","text-anchor":"middle","dominant-baseline":r>0?"baseline":"hanging",class:"anchor-offset-label"},children:[{type:"text",value:`X: ${i.toFixed(2)}mm`,name:"",attributes:{},children:[]}],value:""}),s}function iRt({x:n,startY:e,endY:t,offsetMm:i,offsetX:r}){let s=[];s.push({name:"line",type:"element",attributes:{x1:n.toString(),y1:e.toString(),x2:n.toString(),y2:t.toString(),stroke:"#ffffff","stroke-width":O_.toString(),class:"anchor-offset-dimension-y"},children:[],value:""}),s.push({name:"line",type:"element",attributes:{x1:(n-Ls).toString(),y1:e.toString(),x2:(n+Ls).toString(),y2:e.toString(),stroke:"#ffffff","stroke-width":O_.toString()},children:[],value:""}),s.push({name:"line",type:"element",attributes:{x1:(n-Ls).toString(),y1:t.toString(),x2:(n+Ls).toString(),y2:t.toString(),stroke:"#ffffff","stroke-width":O_.toString()},children:[],value:""});let o=(e+t)/2,a=r<0?n-Ls-4:n+Ls+4;return s.push({name:"text",type:"element",attributes:{x:a.toString(),y:o.toString(),fill:"#ffffff","font-size":qtt.toString(),"font-family":"Arial, sans-serif","text-anchor":r<0?"end":"start","dominant-baseline":"middle",class:"anchor-offset-label"},children:[{type:"text",value:`Y: ${i.toFixed(2)}mm`,name:"",attributes:{},children:[]}],value:""}),s}function rRt(n,e){let{transform:t,circuitJson:i}=e,{center:r,width:s,height:o,rotation:a=0}=n,[c,l]=st(t,[r.x,r.y]),u=s*Math.abs(t.a),h=o*Math.abs(t.d),d=`translate(${c}, ${l}) rotate(${-a}) scale(1, -1)`,_=[];if(e.showAnchorOffsets&&n.positioned_relative_to_pcb_group_id&&n.position_mode==="relative"&&i){let g=i.find(x=>x.type==="pcb_group"&&x.pcb_group_id===n.positioned_relative_to_pcb_group_id);g?.center&&_.push(...tRt({groupAnchorPosition:g.center,componentPosition:r,transform:t,componentWidth:s,componentHeight:o}))}return!e.colorMap.debugComponent?.fill&&!e.colorMap.debugComponent?.stroke||_.push({name:"g",type:"element",attributes:{transform:d,"data-type":"pcb_component","data-pcb-layer":n.layer??"top"},children:[{name:"rect",type:"element",attributes:{class:"pcb-component",x:(-u/2).toString(),y:(-h/2).toString(),width:u.toString(),height:h.toString(),fill:e.colorMap.debugComponent.fill??"transparent",stroke:e.colorMap.debugComponent.stroke??"transparent","data-type":"pcb_component","data-pcb-layer":n.layer??"top"}}],value:""}),_}function aRt(n,e){let{transform:t}=e,{center:i,width:r,height:s}=n,o=Array.isArray(n.outline)?n.outline:void 0,a=oRt*Math.abs(t.a),c=.3*Math.abs(t.a),l=.15*Math.abs(t.a),u={class:"pcb-group",fill:"none",stroke:sRt,"stroke-width":a.toString(),"stroke-dasharray":`${c} ${l}`,"data-type":"pcb_group","data-pcb-group-id":n.pcb_group_id,"data-pcb-layer":"overlay"};if(n.name&&(u["data-group-name"]=n.name),o&&o.length>=3&&o.every(M=>M&&typeof M.x=="number"&&typeof M.y=="number")){let M=o.map((I,E)=>{let[A,R]=st(t,[I.x,I.y]);return E===0?`M ${A} ${R}`:`L ${A} ${R}`}).join(" ");return[{name:"path",type:"element",value:"",children:[],attributes:{...u,d:`${M} Z`}}]}if(!i||typeof i.x!="number"||typeof i.y!="number"||typeof r!="number"||typeof s!="number")return console.error("Invalid pcb_group data",{center:i,width:r,height:s}),[];let h=r/2,d=s/2,[_,g]=st(t,[i.x-h,i.y+d]),[x,v]=st(t,[i.x+h,i.y-d]),P=Math.min(_,x),w=Math.min(g,v),T=Math.abs(x-_),k=Math.abs(v-g);return[{name:"rect",type:"element",value:"",attributes:{...u,x:P.toString(),y:w.toString(),width:T.toString(),height:k.toString()},children:[]}]}function fl(n){return n.find(t=>t.type==="project_software_metadata"||t.type==="source_project_metadata")?.software_used_string}function Ntt(n){return n.map((e,t)=>({object:e,index:t,layerPriority:uRt(e.attributes?.["data-pcb-layer"]??void 0),typePriority:pRt(e.attributes?.["data-type"]??void 0)})).sort((e,t)=>e.layerPriority!==t.layerPriority?e.layerPriority-t.layerPriority:e.typePriority!==t.typePriority?e.typePriority-t.typePriority:e.index-t.index).map(({object:e})=>e)}function uRt(n){if(!n)return 500;let e=n.toLowerCase();if(e==="global")return-100;if(e==="bottom")return 0;if(e==="board")return 2;if(e==="soldermask-top"||e==="soldermask-bottom")return 3;if(e.startsWith("inner")){let t=e.match(/\d+/);return 5+(t?Number.parseInt(t[0],10):0)}return e==="through"?18:e==="top"?17:e==="drill"?30:e==="overlay"?40:10}function pRt(n){return n?lRt[n]??Itt:Itt}function $_(n,e="error_text_overlay"){let t=n.filter(s=>s.type.endsWith("_error"));if(t.length===0)return null;let i=t.map(s=>s.message).filter(s=>!!s);return i.length===0?null:{name:"text",type:"element",value:"",attributes:{x:"10",y:"20",fill:"red","font-family":"monospace","font-size":"12px","data-type":e,"data-layer":"global"},children:i.map((s,o)=>({name:"tspan",type:"element",value:"",attributes:{x:"10",dy:o===0?"0":"1.2em"},children:[{type:"text",value:s,name:"",attributes:{},children:[]}]}))}}function Ztt(n,e){let t=e?.drawPaddingOutsideBoard??!0,i=e?.layer,r=e?.colorOverrides,s={...Mi.copper};if(r?.copper)for(let[Z,at]of Object.entries(r.copper))at!==void 0&&(s[Z]=at);let o={copper:s,drill:r?.drill??Mi.drill,silkscreen:{top:r?.silkscreen?.top??Mi.silkscreen.top,bottom:r?.silkscreen?.bottom??Mi.silkscreen.bottom},boardOutline:r?.boardOutline??Mi.boardOutline,soldermask:{top:r?.soldermask?.top??Mi.soldermask.top,bottom:r?.soldermask?.bottom??Mi.soldermask.bottom},soldermaskWithCopperUnderneath:{top:r?.soldermaskWithCopperUnderneath?.top??Mi.soldermaskWithCopperUnderneath.top,bottom:r?.soldermaskWithCopperUnderneath?.bottom??Mi.soldermaskWithCopperUnderneath.bottom},substrate:r?.substrate??Mi.substrate,courtyard:r?.courtyard??Mi.courtyard,debugComponent:{fill:r?.debugComponent?.fill??Mi.debugComponent.fill,stroke:r?.debugComponent?.stroke??Mi.debugComponent.stroke}},a=Number.POSITIVE_INFINITY,c=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY,u=Number.NEGATIVE_INFINITY,h=!1,d=Number.POSITIVE_INFINITY,_=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,x=Number.NEGATIVE_INFINITY,v=!1;for(let Z of n)if(Z.type==="pcb_panel"){let at=Z,Mt=Y.parse(at.width),Ft=Y.parse(at.height);if(Mt===void 0||Ft===void 0)continue;let Ot=at.center??{x:Mt/2,y:Ft/2};ot(Ot,Mt,Ft)}else if(Z.type==="pcb_board")Z.outline&&Array.isArray(Z.outline)&&Z.outline.length>=3?(W(Z.outline),rt(Z.outline)):"center"in Z&&"width"in Z&&"height"in Z&&(ot(Z.center,Z.width,Z.height),X(Z.center,Z.width,Z.height));else if(Z.type==="pcb_smtpad"){let at=Z;if(at.shape==="rect"||at.shape==="rotated_rect"||at.shape==="pill")ot({x:at.x,y:at.y},at.width,at.height);else if(at.shape==="circle"){let Mt=Y.parse(at.radius);Mt!==void 0&&ot({x:at.x,y:at.y},Mt*2,Mt*2)}else at.shape==="polygon"&&ut(at.points)}else if("x"in Z&&"y"in Z)ot({x:Z.x,y:Z.y},0,0);else if("route"in Z)ut(Z.route);else if(Z.type==="pcb_note_rect"||Z.type==="pcb_fabrication_note_rect")ot(Z.center,Z.width,Z.height);else if(Z.type==="pcb_cutout"){let at=Z;if(at.shape==="rect")ot(at.center,at.width,at.height);else if(at.shape==="circle"){let Mt=Y.parse(at.radius);Mt!==void 0&&ot(at.center,Mt*2,Mt*2)}else at.shape==="polygon"&&ut(at.points)}else Z.type==="pcb_silkscreen_text"||Z.type==="pcb_silkscreen_rect"||Z.type==="pcb_silkscreen_circle"||Z.type==="pcb_silkscreen_line"?yt(Z):Z.type==="pcb_copper_pour"&&(Z.shape==="rect"?ot(Z.center,Z.width,Z.height):Z.shape==="polygon"&&ut(Z.points));let P=t?1:0,w=t||!Number.isFinite(d)?a:d,T=t||!Number.isFinite(_)?c:_,k=t||!Number.isFinite(g)?l:g,C=t||!Number.isFinite(x)?u:x,M=k-w+2*P,I=C-T+2*P,E=e?.width??800,A=e?.height??600;if(e?.matchBoardAspectRatio){let Z=g-d,at=x-_;if(Z>0&&at>0){let Mt=Z/at;e?.width&&!e?.height?A=e.width/Mt:e?.height&&!e?.width?E=e.height*Mt:A=E/Mt}}let R=[];for(let Z of n)"route"in Z&&Z.route!==void 0&&R.push(Z.route);let B=E/M,j=A/I,U=Math.min(B,j),V=(E-M*U)/2,H=(A-I*U)/2,et=Fe(yn(V-w*U+P*U,A-H+T*U-P*U),Ti(U,-U)),tt={transform:et,layer:i,shouldDrawErrors:e?.shouldDrawErrors,showCourtyards:e?.showCourtyards,showPcbGroups:e?.showPcbGroups,drawPaddingOutsideBoard:t,colorMap:o,showSolderMask:e?.showSolderMask,showAnchorOffsets:e?.showAnchorOffsets,circuitJson:n},mt=n.flatMap(Z=>hRt({elm:Z,circuitJson:n,ctx:tt})),G=Ntt(mt),Q=String(.05*U);for(let Z of n)if("stroke_width"in Z){Q=String(U*Z.stroke_width);break}if(e?.shouldDrawRatsNest){let Z=U6t(n,tt);G=Ntt([...G,...Z])}let nt=[{name:"style",type:"element",value:"",attributes:{},children:[{type:"text",value:"",name:"",attributes:{},children:[]}]}],pt=W6t({grid:e?.grid,svgWidth:E,svgHeight:A});if(pt.defs&&nt.push(pt.defs),nt.push({name:"rect",type:"element",value:"",attributes:{class:"boundary",x:"0",y:"0",fill:e?.backgroundColor??"#000",width:E.toString(),height:A.toString(),"data-type":"pcb_background","data-pcb-layer":"global"},children:[]}),t&&nt.push(dRt(et,a,c,l,u)),nt.push(...G),pt.rect&&nt.push(pt.rect),e?.showErrorsInTextOverlay){let Z=$_(n,"pcb_error_text_overlay");Z&&nt.push(Z)}let ht=fl(n),wt=ml,Et={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:E.toString(),height:A.toString(),...ht&&{"data-software-used-string":ht},...e?.includeVersion&&{"data-circuit-to-svg-version":wt}},value:"",children:nt.filter(Z=>Z!==null)};try{return(0,Htt.stringify)(Et)}catch(Z){throw console.error("Error stringifying SVG object:",Z),Z}function ot(Z,at,Mt){if(!Z)return;let Ft=Y.parse(Z.x),Ot=Y.parse(Z.y);if(Ft===void 0||Ot===void 0)return;let Ce=Y.parse(at)??0,Se=Y.parse(Mt)??0,Kt=Ce/2,le=Se/2;a=Math.min(a,Ft-Kt),c=Math.min(c,Ot-le),l=Math.max(l,Ft+Kt),u=Math.max(u,Ot+le),h=!0}function X(Z,at,Mt){if(!Z)return;let Ft=Y.parse(Z.x),Ot=Y.parse(Z.y);if(Ft===void 0||Ot===void 0)return;let Ce=Y.parse(at)??0,Se=Y.parse(Mt)??0,Kt=Ce/2,le=Se/2;d=Math.min(d,Ft-Kt),_=Math.min(_,Ot-le),g=Math.max(g,Ft+Kt),x=Math.max(x,Ot+le),h=!0,v=!0}function W(Z){let at=!1;for(let Mt of Z){let Ft=Y.parse(Mt.x),Ot=Y.parse(Mt.y);Ft===void 0||Ot===void 0||(a=Math.min(a,Ft),c=Math.min(c,Ot),l=Math.max(l,Ft),u=Math.max(u,Ot),at=!0)}at&&(h=!0)}function rt(Z){let at=!1;for(let Mt of Z){let Ft=Y.parse(Mt.x),Ot=Y.parse(Mt.y);Ft===void 0||Ot===void 0||(d=Math.min(d,Ft),_=Math.min(_,Ot),g=Math.max(g,Ft),x=Math.max(x,Ot),at=!0)}at&&(h=!0,v=!0)}function ut(Z){let at=!1;for(let Mt of Z){let Ft=Y.parse(Mt?.x),Ot=Y.parse(Mt?.y);Ft===void 0||Ot===void 0||(a=Math.min(a,Ft),c=Math.min(c,Ot),l=Math.max(l,Ft),u=Math.max(u,Ot),at=!0)}at&&(h=!0)}function yt(Z){if(Z.type==="pcb_silkscreen_text")ot(Z.anchor_position,0,0);else if(Z.type==="pcb_silkscreen_path")ut(Z.route);else if(Z.type==="pcb_silkscreen_rect")ot(Z.center,Z.width,Z.height);else if(Z.type==="pcb_silkscreen_circle"){let at=Y.parse(Z.radius);at!==void 0&&ot(Z.center,at*2,at*2)}else if(Z.type==="pcb_silkscreen_line")ot({x:Z.x1,y:Z.y1},0,0),ot({x:Z.x2,y:Z.y2},0,0);else if(Z.type==="pcb_cutout"){let at=Z;if(at.shape==="rect")ot(at.center,at.width,at.height);else if(at.shape==="circle"){let Mt=Y.parse(at.radius);Mt!==void 0&&ot(at.center,Mt*2,Mt*2)}else at.shape==="polygon"&&ut(at.points)}}}function hRt({elm:n,circuitJson:e,ctx:t}){switch(n.type){case"pcb_trace_error":return c6t(n,e,t).filter(Boolean);case"pcb_footprint_overlap_error":return p6t(n,e,t).filter(Boolean);case"pcb_component":return rRt(n,t).filter(Boolean);case"pcb_trace":return z6t(n,t);case"pcb_copper_pour":return G6t(n,t);case"pcb_plated_hole":return E6t(n,t).filter(Boolean);case"pcb_hole":return B6t(n,t);case"pcb_smtpad":return $6t(n,t);case"pcb_silkscreen_text":return I6t(n,t);case"pcb_silkscreen_rect":return N6t(n,t);case"pcb_silkscreen_circle":return A6t(n,t);case"pcb_silkscreen_line":return R6t(n,t);case"pcb_courtyard_rect":return t.showCourtyards?O6t(n,t):[];case"pcb_fabrication_note_path":return h6t(n,t);case"pcb_fabrication_note_text":return d6t(n,t);case"pcb_fabrication_note_rect":return _6t(n,t);case"pcb_fabrication_note_dimension":return y6t(n,t);case"pcb_note_dimension":return g6t(n,t);case"pcb_note_text":return b6t(n,t);case"pcb_note_rect":return w6t(n,t);case"pcb_note_path":return k6t(n,t);case"pcb_note_line":return M6t(n,t);case"pcb_silkscreen_path":return C6t(n,t);case"pcb_panel":return t.drawPaddingOutsideBoard?D6t(n,t):[];case"pcb_board":return t.drawPaddingOutsideBoard?Wtt(n,t):[];case"pcb_via":return j6t(n,t);case"pcb_cutout":return V6t(n,t);case"pcb_group":return t.showPcbGroups?aRt(n,t):[];default:return[]}}function dRt(n,e,t,i,r){let[s,o]=st(n,[e,t]),[a,c]=st(n,[i,r]),l=Math.abs(a-s),u=Math.abs(c-o),h=Math.min(s,a),d=Math.min(o,c);return{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-boundary",fill:"none",stroke:"#fff","stroke-width":"0.3",x:h.toString(),y:d.toString(),width:l.toString(),height:u.toString(),"data-type":"pcb_boundary","data-pcb-layer":"global"}}}function mRt(n,e,t={}){let{width:i,height:r,center:s,outline:o}=n,a;if(o&&Array.isArray(o)&&o.length>=3)a=o.map((c,l)=>{let[u,h]=st(e,[c.x,c.y]);return l===0?`M ${u} ${h}`:`L ${u} ${h}`}).join(" ");else{let c=i/2,l=r/2,u=st(e,[s.x-c,s.y-l]),h=st(e,[s.x+c,s.y-l]),d=st(e,[s.x+c,s.y+l]),_=st(e,[s.x-c,s.y+l]);a=`M ${u[0]} ${u[1]} L ${h[0]} ${h[1]} L ${d[0]} ${d[1]} L ${_[0]} ${_[1]}`}return a+=" Z",[{name:"path",type:"element",value:"",children:[],attributes:{class:"pcb-board",d:a,fill:t.fill??Yw.fill,stroke:t.stroke??Yw.stroke,"stroke-opacity":t.strokeOpacity??Yw.strokeOpacity,"stroke-width":((t.strokeWidthFactor??Yw.strokeWidthFactor)*Math.abs(e.a)).toString()}}]}function yRt(n,e){let{elm:t,portPosition:i,name:r,arePinsInterchangeable:s}=n,{transform:o}=e,{center:a,width:c,height:l,rotation:u=0,layer:h="top"}=t;if(!a||typeof c!="number"||typeof l!="number")return null;let[d,_]=st(o,[a.x,a.y]),[g,x]=st(o,[i.x,i.y]),v=c*Math.abs(o.a),P=l*Math.abs(o.d),w=h==="top",T=x>_,k=g<d,C=[gRt(v,P,u,h),xRt(v,P,r??"",o)];return s||C.push(bRt(v,P,u,h,T,k)),{name:"g",type:"element",value:"",attributes:{transform:`translate(${d}, ${_}) scale(1, -1)`},children:C}}function gRt(n,e,t,i){let r=n/2,s=e/2;return{name:"path",type:"element",attributes:{class:"assembly-component",d:vRt(r,s,t),"stroke-width":.8.toFixed(2),transform:`rotate(${-t})`,"stroke-dasharray":i==="bottom"?"2,2":""},value:"",children:[]}}function xRt(n,e,t,i){let r=Math.min(n,e),c=Math.min(58,Math.max(3,r*.8)),l=e>n;return{name:"text",type:"element",attributes:{x:"0",y:"0",class:"assembly-component-label","text-anchor":"middle",dy:".10em",style:"pointer-events: none","font-size":`${c.toFixed(1)}px`,transform:l?"rotate(90) scale(1, -1)":"scale(1, -1)"},children:[{type:"text",value:t||"",name:"",attributes:{},children:[]}],value:""}}function bRt(n,e,t,i,r,s){let o=n/2,a=e/2,c=Math.min(o,a)*.5,l;return r&&s?l=[[-o,-a],[-o+c,-a],[-o,-a+c]]:r&&!s?l=[[o,-a],[o-c,-a],[o,-a+c]]:!r&&s?l=[[-o,a],[-o+c,a],[-o,a-c]]:l=[[o,a],[o-c,a],[o,a-c]],{name:"polygon",type:"element",attributes:{class:"assembly-pin1-indicator",points:l.map(h=>h.join(",")).join(" "),fill:"#333",stroke:"none",transform:`rotate(${-t})`},value:"",children:[]}}function vRt(n,e,t){let i=(a,c,l)=>{let u=Math.PI/180*l,h=Math.cos(u),d=Math.sin(u);return[a*h-c*d,a*d+c*h]};return`${[[-n,-e],[n,-e],[n,e],[-n,e]].map(([a,c])=>i(a,c,t)).map(([a,c],l)=>l===0?`M${a},${c}`:`L${a},${c}`).join(" ")} Z`}function SRt(n,e){let{transform:t}=e,[i,r]=st(t,[n.x,n.y]);if(n.hole_shape==="circle"||n.hole_shape==="square"){let s=n.hole_diameter*Math.abs(t.a),o=s/2;return n.hole_shape==="circle"?[{name:"circle",type:"element",attributes:{class:"assembly-hole",cx:i.toString(),cy:r.toString(),r:o.toString(),fill:DA},children:[],value:""}]:[{name:"rect",type:"element",attributes:{class:"assembly-hole",x:(i-o).toString(),y:(r-o).toString(),width:s.toString(),height:s.toString(),fill:DA},children:[],value:""}]}if(n.hole_shape==="oval"){let s=n.hole_width*Math.abs(t.a),o=n.hole_height*Math.abs(t.a),a=s/2,c=o/2;return[{name:"ellipse",type:"element",attributes:{class:"assembly-hole",cx:i.toString(),cy:r.toString(),rx:a.toString(),ry:c.toString(),fill:DA},children:[],value:""}]}return[]}function wRt(n,e){let{transform:t}=e,[i,r]=st(t,[n.x,n.y]);if(n.shape==="pill"){let s=n.outer_width*Math.abs(t.a),o=n.outer_height*Math.abs(t.a),a=n.hole_width*Math.abs(t.a),c=n.hole_height*Math.abs(t.a),l=s/2,u=o-s,h=a/2;return[{name:"g",type:"element",children:[{name:"path",type:"element",attributes:{class:"assembly-hole-outer",fill:E1,d:`M${i-l},${r-u/2} v${u} a${l},${l} 0 0 0 ${s},0 v-${u} a${l},${l} 0 0 0 -${s},0 z`},value:"",children:[]},{name:"path",type:"element",attributes:{class:"assembly-hole-inner",fill:C1,d:`M${i-h},${r-(c-a)/2} v${c-a} a${h},${h} 0 0 0 ${a},0 v-${c-a} a${h},${h} 0 0 0 -${a},0 z`},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="circle"){let s=n.outer_diameter*Math.abs(t.a),o=n.outer_diameter*Math.abs(t.a),a=n.hole_diameter*Math.abs(t.a),c=n.hole_diameter*Math.abs(t.a),l=Math.min(s,o)/2,u=Math.min(a,c)/2;return[{name:"g",type:"element",children:[{name:"circle",type:"element",attributes:{class:"assembly-hole-outer",fill:E1,cx:i.toString(),cy:r.toString(),r:l.toString()},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"assembly-hole-inner",fill:C1,cx:i.toString(),cy:r.toString(),r:u.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="circular_hole_with_rect_pad"){let s=n,o=s.hole_diameter*Math.abs(t.a),a=s.rect_pad_width*Math.abs(t.a),c=s.rect_pad_height*Math.abs(t.a),l=(s.rect_border_radius??0)*Math.abs(t.a),u=o/2,[h,d]=st(t,[s.x+s.hole_offset_x,s.y+s.hole_offset_y]);return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"assembly-hole-outer-pad",fill:E1,x:(i-a/2).toString(),y:(r-c/2).toString(),width:a.toString(),height:c.toString(),...l?{rx:l.toString(),ry:l.toString()}:{}},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"assembly-hole-inner",fill:C1,cx:h.toString(),cy:d.toString(),r:u.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="pill_hole_with_rect_pad"){let s=n,o=s.rect_pad_width*Math.abs(t.a),a=s.rect_pad_height*Math.abs(t.a),c=(s.rect_border_radius??0)*Math.abs(t.a),l=s.hole_height*Math.abs(t.a),u=s.hole_width*Math.abs(t.a),h=s,d=h.hole_offset_x??0,_=h.hole_offset_y??0,[g,x]=st(t,[s.x+d,s.y+_]),v=Math.min(l,u)/2;return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"assembly-hole-outer-pad",fill:E1,x:(i-o/2).toString(),y:(r-a/2).toString(),width:o.toString(),height:a.toString(),...c?{rx:c.toString(),ry:c.toString()}:{}},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"assembly-hole-inner",fill:C1,x:(g-u/2).toString(),y:(x-l/2).toString(),width:u.toString(),height:l.toString(),rx:v.toString(),ry:v.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="rotated_pill_hole_with_rect_pad"){let s=n,o=s.rect_pad_width*Math.abs(t.a),a=s.rect_pad_height*Math.abs(t.a),c=(s.rect_border_radius??0)*Math.abs(t.a),l=s.hole_height*Math.abs(t.a),u=s.hole_width*Math.abs(t.a),h=s,d=h.hole_offset_x??0,_=h.hole_offset_y??0,[g,x]=st(t,[s.x+d,s.y+_]),v=Math.min(l,u)/2;return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"assembly-hole-outer-pad",fill:E1,x:(-o/2).toString(),y:(-a/2).toString(),width:o.toString(),height:a.toString(),transform:`translate(${i} ${r}) rotate(${-s.rect_ccw_rotation})`,...c?{rx:c.toString(),ry:c.toString()}:{}},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"assembly-hole-inner",fill:C1,x:(-u/2).toString(),y:(-l/2).toString(),width:u.toString(),height:l.toString(),rx:v.toString(),ry:v.toString(),transform:`translate(${g} ${x}) rotate(${-s.hole_ccw_rotation})`},value:"",children:[]}],value:"",attributes:{}}]}return[]}function PRt(n,e){let{transform:t}=e;if(n.shape==="rect"||n.shape==="rotated_rect"){let i=n.width*Math.abs(t.a),r=n.height*Math.abs(t.d),[s,o]=st(t,[n.x,n.y]),a=(n.rect_border_radius??0)*Math.abs(t.a);return n.shape==="rotated_rect"&&n.ccw_rotation?[{name:"rect",type:"element",attributes:{class:"assembly-pad",fill:I1,x:(-i/2).toString(),y:(-r/2).toString(),width:i.toString(),height:r.toString(),transform:`translate(${s} ${o}) rotate(${-n.ccw_rotation})`,"data-layer":n.layer,...a?{rx:a.toString(),ry:a.toString()}:{}},value:"",children:[]}]:[{name:"rect",type:"element",attributes:{class:"assembly-pad",fill:I1,x:(s-i/2).toString(),y:(o-r/2).toString(),width:i.toString(),height:r.toString(),"data-layer":n.layer,...a?{rx:a.toString(),ry:a.toString()}:{}},value:"",children:[]}]}if(n.shape==="pill"){let i=n.width*Math.abs(t.a),r=n.height*Math.abs(t.d),s=n.radius*Math.abs(t.a),[o,a]=st(t,[n.x,n.y]);return[{name:"rect",type:"element",attributes:{class:"assembly-pad",fill:I1,x:(o-i/2).toString(),y:(a-r/2).toString(),width:i.toString(),height:r.toString(),rx:s.toString(),ry:s.toString(),"data-layer":n.layer},value:"",children:[]}]}if(n.shape==="circle"){let i=n.radius*Math.abs(t.a),[r,s]=st(t,[n.x,n.y]);return[{name:"circle",type:"element",attributes:{class:"assembly-pad",fill:I1,cx:r.toString(),cy:s.toString(),r:i.toString(),"data-layer":n.layer},value:"",children:[]}]}if(n.shape==="polygon"){let i=(n.points??[]).map(r=>st(t,[r.x,r.y]));return[{name:"polygon",type:"element",attributes:{class:"assembly-pad",fill:I1,points:i.map(r=>r.join(",")).join(" "),"data-layer":n.layer},value:"",children:[]}]}return[]}function kRt(n,e){let t=Number.POSITIVE_INFINITY,i=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let I of n)if(I.type==="pcb_board"){let E=I.center,A=I.width||0,R=I.height||0;t=Math.min(t,E.x-A/2),i=Math.min(i,E.y-R/2),r=Math.max(r,E.x+A/2),s=Math.max(s,E.y+R/2)}let o=1,a=r-t+2*o,c=s-i+2*o,l=e?.width??800,u=e?.height??600,h=l/a,d=u/c,_=Math.min(h,d),g=(l-a*_)/2,x=(u-c*_)/2,v=Fe(yn(g-t*_+o*_,u-x+i*_-o*_),Ti(_,-_)),P={transform:v},w=n.sort((I,E)=>(Att.indexOf(E.type)??9999)-(Att.indexOf(I.type)??9999)).flatMap(I=>TRt(I,P,n)),T=fl(n),k=ml,C=[{name:"style",type:"element",children:[{type:"text",value:`
75
75
  .assembly-component {
76
76
  fill: none;
77
77
  stroke: #000;
@@ -93,8 +93,8 @@ $1`).replace(/>(\s*)(?=<!--\s*\/)/g,"> ")}});var ott=ue(Fw=>{"use strict";var i6
93
93
  stroke: #fff;
94
94
  stroke-width: 0.2;
95
95
  }
96
- `,name:"",attributes:{},children:[]}],value:"",attributes:{}},{name:"rect",type:"element",attributes:{fill:"#fff",x:"0",y:"0",width:l.toString(),height:u.toString()},value:"",children:[]},MRt(v,t,i,r,s),...w].filter(I=>I!==null);if(e?.showErrorsInTextOverlay){let I=$_(n);I&&C.push(I)}let M={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:l.toString(),height:u.toString(),...T&&{"data-software-used-string":T},...e?.includeVersion&&{"data-circuit-to-svg-version":k}},value:"",children:C};return(0,Ktt.stringify)(M)}function TRt(n,e,t){let i=Ee(t).source_component.list();switch(n.type){case"pcb_board":return mRt(n,e.transform);case"pcb_component":{let r=i.find(a=>a.source_component_id===n.source_component_id),o=Ee(t).pcb_port.list().filter(a=>a.pcb_component_id===n.pcb_component_id)[0];if(r&&o){let a=r.are_pins_interchangeable,c=yRt({elm:n,portPosition:{x:o.x,y:o.y},name:r.name,arePinsInterchangeable:a},e);return c?[c]:[]}return[]}case"pcb_smtpad":return PRt(n,e);case"pcb_hole":return SRt(n,e);case"pcb_plated_hole":return wRt(n,e);default:return[]}}function MRt(n,e,t,i,r){let[s,o]=st(n,[e,t]),[a,c]=st(n,[i,r]),l=Math.abs(a-s),u=Math.abs(c-o),h=Math.min(s,a),d=Math.min(o,c);return{name:"rect",type:"element",value:"",children:[],attributes:{class:"assembly-boundary",x:h.toString(),y:d.toString(),width:l.toString(),height:u.toString()}}}function IRt(n,e){let{transform:t,soup:i}=e,{width:r,height:s,center:o,outline:a}=n,l=i.find(_=>_.type==="source_board"&&_.title)?.title,u;if(a&&Array.isArray(a)&&a.length>=3)u=a.map((_,g)=>{let[x,v]=st(t,[_.x,_.y]);return g===0?`M ${x} ${v}`:`L ${x} ${v}`}).join(" ");else{let _=r/2,g=s/2,x=st(t,[o.x-_,o.y-g]),v=st(t,[o.x+_,o.y-g]),P=st(t,[o.x+_,o.y+g]),w=st(t,[o.x-_,o.y+g]);u=`M ${x[0]} ${x[1]} L ${v[0]} ${v[1]} L ${P[0]} ${P[1]} L ${w[0]} ${w[1]}`}u+=" Z";let h=Ee(i).pcb_cutout.list();for(let _ of h)if(_.shape==="rect"){let{x:g,y:x,width:v,height:P}=_.center?(()=>{let{x:E,y:A}=_.center,{width:R,height:B}=_;return{x:E,y:A,width:R,height:B}})():{x:0,y:0,width:0,height:0},w=v/2,T=P/2,[k,C,M,I]=[st(t,[g-w,x-T]),st(t,[g+w,x-T]),st(t,[g+w,x+T]),st(t,[g-w,x+T])];u+=` M ${k[0]} ${k[1]} L ${C[0]} ${C[1]} L ${M[0]} ${M[1]} L ${I[0]} ${I[1]} Z`}else _.shape;let d=[{name:"path",type:"element",value:"",children:[],attributes:{class:"pinout-board",d:u,fill:ERt,stroke:CRt,"fill-rule":"evenodd","stroke-opacity":"0.8","stroke-width":(.2*Math.abs(t.a)).toString()}}];if(l){let _=e.svgWidth/2;d.push({name:"text",type:"element",value:"",children:[{name:"",type:"text",value:l,attributes:{},children:[]}],attributes:{x:_.toString(),y:30 .toString(),"text-anchor":"middle","font-size":"18px","font-weight":"bold","font-family":"Arial, sans-serif",fill:"black",class:"pinout-board-title"}})}return d}function RRt(n,e){let{transform:t,soup:i}=e,{center:r,width:s,height:o,rotation:a=0,source_component_id:c}=n,l=Ee(i).source_component.get(c);if(!r||typeof s!="number"||typeof o!="number"||s===0||o===0)return[];let[u,h]=st(t,[r.x,r.y]),d=s*Math.abs(t.a),_=o*Math.abs(t.d),g=`translate(${u}, ${h})`,x=[{name:"rect",type:"element",attributes:{class:"pinout-component-box",x:(-d/2).toString(),y:(-_/2).toString(),width:d.toString(),height:_.toString(),fill:NRt,transform:`rotate(${a}deg)`},value:"",children:[]}];if(l?.name){let v=Math.min(d,_)*.4;x.push({name:"text",type:"element",attributes:{x:"0",y:"0",fill:ARt,"font-size":`${v}px`,"font-family":"sans-serif","text-anchor":"middle","dominant-baseline":"middle"},children:[{type:"text",value:l.name,name:"",attributes:{},children:[]}],value:""})}return[{name:"g",type:"element",attributes:{transform:g},children:x,value:""}]}function ORt(n,e){let{transform:t}=e,[i,r]=st(t,[n.x,n.y]);if(n.hole_shape==="circle"||n.hole_shape==="square"){let s=n.hole_diameter*Math.abs(t.a),o=s/2;return n.hole_shape==="circle"?[{name:"circle",type:"element",attributes:{class:"pinout-hole",cx:i.toString(),cy:r.toString(),r:o.toString(),fill:jA},children:[],value:""}]:[{name:"rect",type:"element",attributes:{class:"pinout-hole",x:(i-o).toString(),y:(r-o).toString(),width:s.toString(),height:s.toString(),fill:jA},children:[],value:""}]}if(n.hole_shape==="oval"){let s=n.hole_width*Math.abs(t.a),o=n.hole_height*Math.abs(t.a),a=s/2,c=o/2;return[{name:"ellipse",type:"element",attributes:{class:"pinout-hole",cx:i.toString(),cy:r.toString(),rx:a.toString(),ry:c.toString(),fill:jA},children:[],value:""}]}return[]}function LRt(n,e){let{transform:t}=e,[i,r]=st(t,[n.x,n.y]);if(n.shape==="pill"){let s=n.outer_width*Math.abs(t.a),o=n.outer_height*Math.abs(t.a),a=n.hole_width*Math.abs(t.a),c=n.hole_height*Math.abs(t.a),l=s/2,u=o-s,h=a/2;return[{name:"g",type:"element",children:[{name:"path",type:"element",attributes:{class:"pinout-hole-outer",fill:N1,d:`M${i-l},${r-u/2} v${u} a${l},${l} 0 0 0 ${s},0 v-${u} a${l},${l} 0 0 0 -${s},0 z`},value:"",children:[]},{name:"path",type:"element",attributes:{class:"pinout-hole-inner",fill:A1,d:`M${i-h},${r-(c-a)/2} v${c-a} a${h},${h} 0 0 0 ${a},0 v-${c-a} a${h},${h} 0 0 0 -${a},0 z`},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="circle"){let s=n.outer_diameter*Math.abs(t.a),o=n.outer_diameter*Math.abs(t.a),a=n.hole_diameter*Math.abs(t.a),c=n.hole_diameter*Math.abs(t.a),l=Math.min(s,o)/2,u=Math.min(a,c)/2;return[{name:"g",type:"element",children:[{name:"circle",type:"element",attributes:{class:"pinout-hole-outer",fill:N1,cx:i.toString(),cy:r.toString(),r:l.toString()},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"pinout-hole-inner",fill:A1,cx:i.toString(),cy:r.toString(),r:u.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="circular_hole_with_rect_pad"){let s=n.hole_diameter*Math.abs(t.a),o=n.rect_pad_width*Math.abs(t.a),a=n.rect_pad_height*Math.abs(t.a),c=s/2;return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"pinout-hole-outer-pad",fill:N1,x:(i-o/2).toString(),y:(r-a/2).toString(),width:o.toString(),height:a.toString()},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"pinout-hole-inner",fill:A1,cx:i.toString(),cy:r.toString(),r:c.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="pill_hole_with_rect_pad"){let s=n.rect_pad_width*Math.abs(t.a),o=n.rect_pad_height*Math.abs(t.a),a=n.hole_height*Math.abs(t.a),c=n.hole_width*Math.abs(t.a),l=Math.min(a,c)/2;return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"pinout-hole-outer-pad",fill:N1,x:(i-s/2).toString(),y:(r-o/2).toString(),width:s.toString(),height:o.toString()},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pinout-hole-inner",fill:A1,x:(i-c/2).toString(),y:(r-a/2).toString(),width:c.toString(),height:a.toString(),rx:l.toString(),ry:l.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="rotated_pill_hole_with_rect_pad"){let s=n.rect_pad_width*Math.abs(t.a),o=n.rect_pad_height*Math.abs(t.a),a=n.hole_height*Math.abs(t.a),c=n.hole_width*Math.abs(t.a),l=Math.min(a,c)/2;return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"pinout-hole-outer-pad",fill:N1,x:(-s/2).toString(),y:(-o/2).toString(),width:s.toString(),height:o.toString(),transform:`translate(${i} ${r}) rotate(${-n.rect_ccw_rotation})`},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pinout-hole-inner",fill:A1,x:(-c/2).toString(),y:(-a/2).toString(),width:c.toString(),height:a.toString(),rx:l.toString(),ry:l.toString(),transform:`translate(${i} ${r}) rotate(${-n.hole_ccw_rotation})`},value:"",children:[]}],value:"",attributes:{}}]}return[]}function FRt(n,e){let{transform:t}=e;if(n.shape==="rect"||n.shape==="rotated_rect"){let i=n.width*Math.abs(t.a),r=n.height*Math.abs(t.d),[s,o]=st(t,[n.x,n.y]);return n.shape==="rotated_rect"&&n.ccw_rotation?[{name:"rect",type:"element",attributes:{class:"pinout-pad",fill:R1,x:(-i/2).toString(),y:(-r/2).toString(),width:i.toString(),height:r.toString(),transform:`translate(${s} ${o}) rotate(${-n.ccw_rotation})`,"data-layer":n.layer},value:"",children:[]}]:[{name:"rect",type:"element",attributes:{class:"pinout-pad",fill:R1,x:(s-i/2).toString(),y:(o-r/2).toString(),width:i.toString(),height:r.toString(),"data-layer":n.layer},value:"",children:[]}]}if(n.shape==="pill"){let i=n.width*Math.abs(t.a),r=n.height*Math.abs(t.d),s=n.radius*Math.abs(t.a),[o,a]=st(t,[n.x,n.y]);return[{name:"rect",type:"element",attributes:{class:"pinout-pad",fill:R1,x:(o-i/2).toString(),y:(a-r/2).toString(),width:i.toString(),height:r.toString(),rx:s.toString(),ry:s.toString(),"data-layer":n.layer},value:"",children:[]}]}if(n.shape==="circle"){let i=n.radius*Math.abs(t.a),[r,s]=st(t,[n.x,n.y]);return[{name:"circle",type:"element",attributes:{class:"pinout-pad",fill:R1,cx:r.toString(),cy:s.toString(),r:i.toString(),"data-layer":n.layer},value:"",children:[]}]}if(n.shape==="polygon"){let i=(n.points??[]).map(r=>st(t,[r.x,r.y]));return[{name:"polygon",type:"element",attributes:{class:"pinout-pad",fill:R1,points:i.map(r=>r.join(",")).join(" "),"data-layer":n.layer},value:"",children:[]}]}return[]}function BA(n){let{rectX:e,rectY:t,rectWidth:i,rectHeight:r,textX:s,textY:o,text:a,fontSize:c,labelBackground:l,labelColor:u,rx:h=4,ry:d=4,fontFamily:_="Arial, sans-serif",fontWeight:g="bold",textAnchor:x="middle",dominantBaseline:v="middle"}=n;return[{name:"rect",type:"element",attributes:{x:e.toString(),y:t.toString(),width:i.toString(),height:r.toString(),fill:l,rx:typeof h=="number"?h.toString():h,ry:typeof d=="number"?d.toString():d,stroke:"none"},children:[],value:""},{name:"text",type:"element",attributes:{x:s.toString(),y:o.toString(),fill:u,"font-size":`${c}px`,"font-family":_,"font-weight":g,"text-anchor":x,"dominant-baseline":v},children:[{type:"text",value:a,name:"",attributes:{},children:[]}],value:""}]}function jRt(n,e){let t=e.label_positions.get(n.pcb_port_id);if(!t)return[];let{text:i,aliases:r,elbow_end:s,label_pos:o,edge:a}=t,[c,l]=st(e.transform,[n.x,n.y]),u=a==="left"?"x-":a==="right"?"x+":a==="top"?"y-":"y+",h=a==="left"?"x+":a==="right"?"x-":a==="top"?"y+":"y-",d=qc({x:c,y:l,facingDirection:u},{x:s.x,y:s.y,facingDirection:h},{}),_=/^pin(\d+)$/i.exec(i),g=[{text:_?_[1]:i,bg:_?$Rt:Ott,color:_?DRt:Rtt},...r.map(H=>({text:H,bg:Ott,color:Rtt}))],x=Math.abs(e.transform.a),v=e.styleScale??1,w=1.6*v*x,T=Math.max(.08,.25*v),C=.3*v*x,M=T*x,I={x:o.x+(a==="left"?-M/2:M/2),y:o.y},E=[...d,I].map(H=>`${H.x},${H.y}`).join(" "),A=w*(11/21),R=(w-A)/2,B=R,j=g.map(({text:H,bg:et,color:tt})=>{let mt=H??"",Q=mt.length*A*.6+2*R;return{text:mt,rectWidth:Q,bg:et,color:tt}}),U=o.y,V=[{name:"polyline",type:"element",attributes:{points:E,stroke:zRt,"stroke-width":(T*x).toString(),fill:"none"},children:[],value:""}];if(a==="left"){let H=o.x;for(let{text:et,rectWidth:tt,bg:mt,color:G}of j){let Q=H-tt,nt=Q+tt/2;V.push(...BA({rectX:Q,rectY:U-w/2,rectWidth:tt,rectHeight:w,textX:nt,textY:U,text:et,fontSize:A,labelBackground:mt,labelColor:G,rx:C,ry:C})),H=Q-B}}else if(a==="right"){let H=o.x;for(let{text:et,rectWidth:tt,bg:mt,color:G}of j){let Q=H,nt=Q+tt/2;V.push(...BA({rectX:Q,rectY:U-w/2,rectWidth:tt,rectHeight:w,textX:nt,textY:U,text:et,fontSize:A,labelBackground:mt,labelColor:G,rx:C,ry:C})),H=Q+tt+B}}else{let H=j.reduce((tt,mt)=>tt+mt.rectWidth,0)+B*Math.max(0,j.length-1),et=o.x-H/2;for(let{text:tt,rectWidth:mt,bg:G,color:Q}of j){let nt=et,pt=nt+mt/2;V.push(...BA({rectX:nt,rectY:U-w/2,rectWidth:mt,rectHeight:w,textX:pt,textY:U,text:tt,fontSize:A,labelBackground:G,labelColor:Q,rx:C,ry:C})),et=nt+mt+B}}return V}function Ltt(n,e,{transform:t,soup:i,board_bounds:r,svgHeight:s,styleScale:o},a){let c=e.map(V=>V.pcb_port.x),l={};for(let V of c){let H=V.toFixed(1);l[H]=(l[H]||0)+1}let u;if(Object.keys(l).length>1&&e.length>2){let V=Object.entries(l).sort((pt,ht)=>ht[1]-pt[1]),H=parseFloat(V[0][0]),et=e.filter(pt=>Math.abs(pt.pcb_port.x-H)<.2),tt=e.filter(pt=>Math.abs(pt.pcb_port.x-H)>=.2),mt=pt=>({pcb_port:pt.pcb_port,y:st(t,[pt.pcb_port.x,pt.pcb_port.y])[1],aliases:pt.aliases});et.sort((pt,ht)=>ht.pcb_port.y-pt.pcb_port.y),tt.sort((pt,ht)=>ht.pcb_port.y-pt.pcb_port.y);let G=et.length>0?Math.max(...et.map(pt=>pt.pcb_port.y)):-1/0;u=((tt.length>0?Math.max(...tt.map(pt=>pt.pcb_port.y)):-1/0)>G?[...tt,...et]:[...et,...tt]).map(mt)}else u=e.map(V=>({pcb_port:V.pcb_port,y:st(t,[V.pcb_port.x,V.pcb_port.y])[1],aliases:V.aliases})).sort((V,H)=>V.y-H.y);if(u.length===0)return;let h=st(t,[n==="left"?r.minX:r.maxX,0])[0],d=u.length,_={};for(let V of e){let H=V.pcb_port.x.toFixed(1);_[H]=(_[H]||0)+1}let g=new Set;if(Object.keys(_).length>1&&e.length>2){let V=Object.entries(_).sort((tt,mt)=>mt[1]-tt[1]),H=parseFloat(V[0][0]),et=e.filter(tt=>Math.abs(tt.pcb_port.x-H)<.2);g=new Set(et.map(tt=>tt.pcb_port.pcb_port_id))}let x=u.map((V,H)=>g.has(V.pcb_port.pcb_port_id)?H:-1).filter(V=>V!==-1),v=(d-1)/2,P=Math.abs(t.a),w=Qtt*o*P,k=Math.max(.2*P,.3*o*P),C=XRt*o*P,M=(tet+d*eet)*o*P,E=M+v*(XA*o*P)+net*o*P,A=d-x.length,R=x.length===0?d:A,B=R*w+Math.max(0,R-1)*k,j;if(x.length>0&&A>0){let V=x.map(nt=>u[nt].y),H=Math.min(...V),et=Math.max(...V),tt=H-w/2,mt=et+w/2;u.map((nt,pt)=>pt).filter(nt=>!x.includes(nt))[0]<x[0]?j=tt-(k*2+C)-B+w/2:j=mt+(k*2+C)+w/2}else j=(s-B)/2+w/2;let U=x.length===d;u.forEach(({pcb_port:V,aliases:H},et)=>{let tt;if(x.length>0)if(x.includes(et))tt=v;else{let wt=Math.min(...x),Et=Math.max(...x),ot;et<wt?ot=wt-et:ot=et-Et,tt=v-ot}else{let wt=Math.abs(et-v);tt=v-wt}let mt=M+tt*(XA*o*P),G=n==="left"?-1:1,Q=x.includes(et),nt=U||x.length>0&&Q?u[et].y:j,pt={x:h+G*mt,y:nt},ht={x:h+G*E,y:nt};a.set(V.pcb_port_id,{text:H[0],aliases:H.slice(1),elbow_end:pt,label_pos:ht,edge:n}),x.length>0&&Q||(j+=w+k)})}function VRt(n,e){let t=Ee(e).source_port.get(n.source_port_id);if(!t)return null;let i=t.port_hints?.filter(o=>!/^\d+$/.test(o)&&!["left","right","top","bottom"].includes(o))??[],r=i[0];if(r||(r=t.name),!r)return null;let s=i.filter(o=>o!==r);return{text:r,aliases:s}}function GRt(n,e){let t={left:n.x-e.minX,right:e.maxX-n.x,top:e.maxY-n.y,bottom:n.y-e.minY},i="left",r=t.left;return t.right<r&&(r=t.right,i="right"),t.top<r&&(r=t.top,i="top"),t.bottom<r&&(r=t.bottom,i="bottom"),i}function HRt(n,e){let t=Number.POSITIVE_INFINITY,i=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let Z of n)if(Z.type==="pcb_board")if("outline"in Z&&Z.outline&&Array.isArray(Z.outline)&&Z.outline.length>0)for(let at of Z.outline)t=Math.min(t,at.x),i=Math.min(i,at.y),r=Math.max(r,at.x),s=Math.max(s,at.y);else{let at=Z.center,Mt=Z.width||0,Ft=Z.height||0;t=Math.min(t,at.x-Mt/2),i=Math.min(i,at.y-Ft/2),r=Math.max(r,at.x+Mt/2),s=Math.max(s,at.y+Ft/2)}let o=2,a=e?.width??1200,c=e?.height??768,l=n.find(Z=>Z.type==="source_board"&&!!Z.title)?.title,u={minX:t,minY:i,maxX:r,maxY:s},h=n.filter(Z=>Z.type==="pcb_port"&&Z.is_board_pinout),d=[];for(let Z of h){let at=VRt(Z,n);if(!at)continue;let Mt=GRt({x:Z.x,y:Z.y},u);d.push({pcb_port:Z,aliases:[at.text,...at.aliases],edge:Mt})}let _=d.filter(Z=>Z.edge==="left"),g=d.filter(Z=>Z.edge==="right"),x=d.filter(Z=>Z.edge==="top"),v=d.filter(Z=>Z.edge==="bottom"),P=(t+r)/2;x.length>0&&(x.filter(at=>at.pcb_port.x<P).length>x.length/2?_.push(...x):g.push(...x)),v.length>0&&(v.filter(at=>at.pcb_port.x<P).length>v.length/2?_.push(...v):g.push(...v));let T=n.filter(Z=>Z.type==="pcb_smtpad").map(Z=>{if(typeof Z.height=="number")return Z.height;if(typeof Z.radius=="number")return Z.radius*2}).filter(Z=>Number.isFinite(Z)),k=T.length?T.reduce((Z,at)=>Z+at,0)/T.length:void 0,M=k?Math.max(.5,Math.min(1,k/1)):1,I=Qtt*M;function E(Z){let at=[...Z.aliases??[]];if(at.length===0)return at;let Mt=/^pin(\d+)$/i.exec(at[0]);return Mt&&(at[0]=Mt[1]),at}function A(Z){if(Z.length===0)return 0;let at=I,Mt=at*BRt,Ft=(at-Mt)/2,Ot=Ft;return Z.map(Kt=>(Kt??"").length*Mt*YRt+2*Ft).reduce((Kt,le)=>Kt+le,0)+Ot*Math.max(0,Z.length-1)}function R(Z){if(Z<=0)return 0;let at=(Z-1)/2;return(tet+Z*eet)*M+at*(XA*M)+net*M}let B=Math.max(0,..._.map(Z=>A(E(Z)))),j=Math.max(0,...g.map(Z=>A(E(Z)))),U=R(_.length)+B,V=R(g.length)+j,H=t-U,tt=r+V-H+2*o,mt=s-i+2*o,G=a/tt,Q=c/mt,nt=Math.min(G,Q),pt=(a-tt*nt)/2,ht=(c-mt*nt)/2,wt=Fe(yn(pt-H*nt+o*nt,c-ht+i*nt-o*nt),ki(nt,-nt)),Et=URt({left_labels:_,right_labels:g,transform:wt,soup:n,board_bounds:u,svgWidth:a,svgHeight:c,styleScale:M}),ot={transform:wt,soup:n,board_bounds:u,styleScale:M,label_positions:Et,svgWidth:a,svgHeight:c},X=n.sort((Z,at)=>(Ftt.indexOf(Z.type)??9999)-(Ftt.indexOf(at.type)??9999)).flatMap(Z=>WRt(Z,ot,n)),W=fl(n),rt=ml,ut=[{name:"rect",type:"element",attributes:{fill:"rgb(255, 255, 255)",x:"0",y:"0",width:a.toString(),height:c.toString()},value:"",children:[]},...X].filter(Z=>Z!==null);if(e?.showErrorsInTextOverlay){let Z=$_(n);Z&&ut.push(Z)}let yt={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:a.toString(),height:c.toString(),...W&&{"data-software-used-string":W},...e?.includeVersion&&{"data-circuit-to-svg-version":rt}},value:"",children:ut};return(0,Jtt.stringify)(yt)}function WRt(n,e,t){switch(n.type){case"pcb_board":return IRt(n,e);case"pcb_component":return RRt(n,e);case"pcb_smtpad":return FRt(n,e);case"pcb_hole":return ORt(n,e);case"pcb_plated_hole":return LRt(n,e);case"pcb_port":return n.is_board_pinout?jRt(n,e):[];default:return[]}}function qRt(n){let{minX:e,minY:t,maxX:i,maxY:r}=n.bounds,s=n.cellSize??1,o=n.labelCells??!1,a=[],c=(l,u)=>{let[h,d]=st(n.transform,[l,u]);return{x:h,y:d}};for(let l=Math.floor(e);l<=Math.ceil(i);l+=s){let u=c(l,t),h=c(l,r);a.push({name:"line",type:"element",attributes:{x1:u.x.toString(),y1:u.y.toString(),x2:h.x.toString(),y2:h.y.toString(),stroke:Mi.schematic.grid,"stroke-width":(.01*Math.abs(n.transform.a)).toString(),"stroke-opacity":"0.5"}})}for(let l=Math.floor(t);l<=Math.ceil(r);l+=s){let u=c(e,l),h=c(i,l);a.push({name:"line",type:"element",attributes:{x1:u.x.toString(),y1:u.y.toString(),x2:h.x.toString(),y2:h.y.toString(),stroke:Mi.schematic.grid,"stroke-width":(.01*Math.abs(n.transform.a)).toString(),"stroke-opacity":"0.5"}})}if(o){let l=(u,h)=>s<=.1?`${u.toFixed(1)},${h.toFixed(1)}`:`${u},${h}`;for(let u=Math.floor(e);u<=Math.ceil(i);u+=s)for(let h=Math.floor(t);h<=Math.ceil(r);h+=s){let d=c(u,h);a.push({name:"text",type:"element",attributes:{x:(d.x-2.5).toString(),y:(d.y-5).toString(),fill:Mi.schematic.grid,"font-size":(s/5*Math.abs(n.transform.a)).toString(),"fill-opacity":"0.5","text-anchor":"middle","dominant-baseline":"middle","font-family":"sans-serif"},children:[{type:"text",value:l(u,h),name:"",attributes:{},children:[]}]})}}return{name:"g",value:"",type:"element",attributes:{class:"grid"},children:a}}function ZRt(n){let{points:e,transform:t}=n,i=[];for(let r of e){let[s,o]=st(t,[r.x-.1,r.y-.1]),[a,c]=st(t,[r.x+.1,r.y+.1]),[l,u]=st(t,[r.x-.1,r.y+.1]),[h,d]=st(t,[r.x+.1,r.y-.1]);i.push({name:"path",type:"element",attributes:{d:`M${s},${o} L${a},${c} M${l},${u} L${h},${d}`,stroke:Mi.schematic.grid,"stroke-width":(.02*Math.abs(t.a)).toString(),"stroke-opacity":"0.7"}});let[_,g]=st(t,[r.x+.15,r.y-.15]);i.push({name:"text",type:"element",attributes:{x:_.toString(),y:g.toString(),fill:Mi.schematic.grid,"font-size":(.1*Math.abs(t.a)).toString(),"fill-opacity":"0.7","text-anchor":"start","font-family":"sans-serif","dominant-baseline":"middle"},children:[{type:"text",value:r.label||`(${r.x},${r.y})`,name:"",attributes:{},children:[]}]})}return{name:"g",value:"",type:"element",attributes:{class:"labeled-points"},children:i}}function QRt(n){return{left:180,top:90,bottom:-90,right:0}[n]??0}function t8t(n,e,t){let i=t+hl*2+F_*n.text.length+L_,r=D_(n.anchor_side);return n.anchor_position??{x:n.center.x-r.x*i*e/2,y:n.center.y-r.y*i*e/2}}function e8t(n,e=.5){let t=Number.POSITIVE_INFINITY,i=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY,o=.2;for(let c of n)if(c.type==="schematic_component")a(c.center,c.size,0);else if(c.type==="schematic_port")a(c.center,{width:o,height:o},0);else if(c.type==="schematic_debug_object")c.shape==="rect"?a(c.center,c.size,0):c.shape==="line"&&(a(c.start,{width:.1,height:.1},0),a(c.end,{width:.1,height:.1},0));else if(c.type==="schematic_net_label"){let l=z_("net_label"),u=Xw(c.text||""),d=(u+hl*2+F_*(c.text?.length||0)+L_)*l,_=1.2*l,g=QRt(c.anchor_side)/180*Math.PI,x=t8t(c,l,u),v=D_(c.anchor_side),P={x:x.x+v.x*d/2,y:x.y+v.y*d/2};a(P,{width:d,height:_},g)}else if(c.type==="schematic_trace")for(let l of c.edges)a(l.from,{width:.1,height:.1},0),a(l.to,{width:.1,height:.1},0);else if(c.type==="schematic_text"){let u=z_("reference_designator",c.font_size)??.18,d=(c.text??"").length*u,_=u;a(c.position,{width:d,height:_},c.rotation??0)}else if(c.type==="schematic_voltage_probe")a(c.position,{width:.2,height:.4},0);else if(c.type==="schematic_box")a({x:c.x+c.width/2,y:c.y+c.height/2},{width:c.width,height:c.height},0);else if(c.type==="schematic_table"){let{column_widths:l,row_heights:u}=ret(c,n),h=l.reduce((w,T)=>w+T,0),d=u.reduce((w,T)=>w+T,0),_=c.anchor??"center",g=c.anchor_position.x,x=c.anchor_position.y;_.includes("center")?g-=h/2:_.includes("right")&&(g-=h),_.includes("center")?x+=d/2:_.includes("bottom")&&(x+=d);let v=g+h/2,P=x-d/2;a({x:v,y:P},{width:h,height:d},0)}else c.type==="schematic_line"?(a({x:c.x1,y:c.y1},{width:.02,height:.02},0),a({x:c.x2,y:c.y2},{width:.02,height:.02},0)):c.type==="schematic_circle"?a(c.center,{width:c.radius*2,height:c.radius*2},0):c.type==="schematic_rect"?a(c.center,{width:c.width,height:c.height},c.rotation):c.type==="schematic_arc"&&a(c.center,{width:c.radius*2,height:c.radius*2},0);return t-=e,i-=e,r+=e,s+=e,{minX:t,minY:i,maxX:r,maxY:s};function a(c,l,u){let h=[{x:-l.width/2,y:-l.height/2},{x:l.width/2,y:-l.height/2},{x:l.width/2,y:l.height/2},{x:-l.width/2,y:l.height/2}];for(let d of h){let _=d.x*Math.cos(u)-d.y*Math.sin(u)+c.x,g=d.x*Math.sin(u)+d.y*Math.cos(u)+c.y;t=Math.min(t,_),i=Math.min(i,g),r=Math.max(r,_),s=Math.max(s,g)}}}function r8t(n,e,t,i){let r=e.x-n.x,s=e.y-n.y,o=Math.sqrt((t.x-n.x)**2+(t.y-n.y)**2),c=Math.sqrt((i.x-e.x)**2+(i.y-e.y)**2)/o,l=yn(r,s),u=ki(c,c);return Fe(l,u)}function h8t(n){let{component:e}=n;if(e.is_box_with_pins===!1)return[];let t=e.symbol_name?o8t(n):p8t(n);return[{type:"element",name:"g",attributes:{"data-circuit-json-type":"schematic_component","data-schematic-component-id":e.schematic_component_id},children:t,value:""}]}function d8t({probe:n,transform:e,colorMap:t}){let[i,r]=st(e,[n.position.x,n.position.y]),s=n.color??t.schematic.reference,o=Math.abs(e.a)*.6,a=Math.abs(e.a)*.28,c=i+o*Math.cos(-50*Math.PI/180),l=r+o*Math.sin(-50*Math.PI/180),u=i,h=r,d=[`M ${c},${l}`,`L ${u},${h}`,`M ${u},${h}`,`L ${u-a*Math.cos(100*Math.PI/180)},${h-a*Math.sin(100*Math.PI/180)}`,`L ${u-a*Math.cos(160*Math.PI/180)},${h-a*Math.sin(160*Math.PI/180)}`,"Z"].join(" "),_=(c+8-(c-c)).toString(),g=[];if(n.name&&n.voltage!==void 0)g.push({type:"element",name:"tspan",value:"",attributes:{x:_},children:[{type:"text",value:n.name,name:"",attributes:{},children:[]}]}),g.push({type:"element",name:"tspan",value:"",attributes:{x:_,dy:"1.2em"},children:[{type:"text",value:`${n.voltage}V`,name:"",attributes:{},children:[]}]});else{let x=[];n.name&&x.push(n.name),n.voltage!==void 0&&x.push(`${n.voltage}V`),g.push({type:"text",value:x.join(" "),name:"",attributes:{},children:[]})}return[{name:"path",type:"element",attributes:{d,stroke:s,fill:s,"stroke-width":`${Ui(e)}px`},value:"",children:[]},{type:"element",name:"text",value:"",attributes:{x:_,y:l.toString(),fill:s,"text-anchor":"start","dominant-baseline":"middle","font-family":"sans-serif","font-size":`${Ya(e,"reference_designator")}px`,"font-weight":"bold","data-schematic-voltage-probe-id":n.schematic_voltage_probe_id},children:g}]}function f8t({debugObject:n,transform:e}){if(n.shape==="rect"){let[t,i]=st(e,[n.center.x-n.size.width/2,n.center.y-n.size.height/2]),[r,s]=st(e,[n.center.x+n.size.width/2,n.center.y+n.size.height/2]);[i,s]=[Math.min(i,s),Math.max(i,s)];let o=Math.abs(r-t),a=Math.abs(s-i),[c,l]=st(e,[n.center.x,n.center.y]);return[{name:"rect",type:"element",value:"",attributes:{x:t.toString(),y:i.toString(),width:o.toString(),height:a.toString(),fill:"none",stroke:"red","stroke-width":(.02*Math.abs(e.a)).toString(),"stroke-dasharray":"5,5"},children:n.label?[{name:"text",type:"element",value:"",attributes:{x:c.toString(),y:(l-10).toString(),"text-anchor":"middle","font-size":(.2*Math.abs(e.a)).toString(),fill:"red"},children:[{type:"text",value:n.label,name:"",attributes:{},children:[]}]}]:[]}]}if(n.shape==="line"){let[t,i]=st(e,[n.start.x,n.start.y]),[r,s]=st(e,[n.end.x,n.end.y]),o=(t+r)/2,a=(i+s)/2;return[{name:"line",type:"element",value:"",attributes:{x1:t.toString(),y1:i.toString(),x2:r.toString(),y2:s.toString(),stroke:"red","stroke-width":(.02*Math.abs(e.a)).toString(),"stroke-dasharray":"5,5"},children:n.label?[{name:"text",type:"element",value:"",attributes:{x:o.toString(),y:(a-10).toString(),"text-anchor":"middle","font-size":(.2*Math.abs(e.a)).toString(),fill:"red"},children:[{type:"text",value:n.label,name:"",attributes:{},children:[]}]}]:[]}]}return[]}function m8t({trace:n,transform:e,colorMap:t}){let i=n.edges;if(i.length===0)return[];let r=[],s=[],o="";for(let a=0;a<i.length;a++){let c=i[a];if(c.is_crossing)continue;let[l,u]=st(e,[c.from.x,c.from.y]),[h,d]=st(e,[c.to.x,c.to.y]);a===0||i[a-1]?.is_crossing?o+=`M ${l} ${u} L ${h} ${d}`:o+=` L ${h} ${d}`}o&&(r.push({name:"path",type:"element",attributes:{d:o,class:"trace-invisible-hover-outline",stroke:t.schematic.wire,fill:"none","stroke-width":`${Ui(e)*8}px`,"stroke-linecap":"round",opacity:"0","stroke-linejoin":"round"},value:"",children:[]}),r.push({name:"path",type:"element",attributes:{d:o,stroke:t.schematic.wire,fill:"none","stroke-width":`${Ui(e)}px`,"stroke-linecap":"round","stroke-linejoin":"round"},value:"",children:[]}));for(let a of i){if(!a.is_crossing)continue;let[c,l]=st(e,[a.from.x,a.from.y]),[u,h]=st(e,[a.to.x,a.to.y]),d=(c+u)/2,_=(l+h)/2,g=u-c,x=h-l,v=Math.sqrt(g*g+x*x),P=v*.7,w=-x/v*P,T=g/v*P,k=d+w,C=_-Math.abs(T);s.push({name:"path",type:"element",attributes:{class:"trace-crossing-outline",d:`M ${c} ${l} Q ${k} ${C} ${u} ${h}`,stroke:t.schematic.background,fill:"none","stroke-width":`${Ui(e)*1.5}px`,"stroke-linecap":"butt"},value:"",children:[]}),s.push({name:"path",type:"element",attributes:{d:`M ${c} ${l} Q ${k} ${C} ${u} ${h}`,stroke:t.schematic.wire,fill:"none","stroke-width":`${Ui(e)}px`,"stroke-linecap":"round"},value:"",children:[]})}if(n.junctions)for(let a of n.junctions){let[c,l]=st(e,[a.x,a.y]);s.push({name:"circle",type:"element",attributes:{cx:c.toString(),cy:l.toString(),r:(Math.abs(e.a)*.03).toString(),class:"trace-junction",fill:t.schematic.junction},value:"",children:[]})}return[{name:"g",type:"element",value:"",attributes:{class:"trace","data-layer":"base","data-circuit-json-type":"schematic_trace","data-schematic-trace-id":n.schematic_trace_id,...n.subcircuit_connectivity_map_key&&{"data-subcircuit-connectivity-map-key":n.subcircuit_connectivity_map_key}},children:r},{name:"g",type:"element",value:"",attributes:{class:"trace-overlays","data-layer":"overlay","data-circuit-json-type":"schematic_trace","data-schematic-trace-id":n.schematic_trace_id,...n.subcircuit_connectivity_map_key&&{"data-subcircuit-connectivity-map-key":n.subcircuit_connectivity_map_key}},children:s}]}function S8t({schLine:n,transform:e,colorMap:t}){let i=st(e,{x:n.x1,y:n.y1}),r=st(e,{x:n.x2,y:n.y2}),s=n.stroke_width??.02,o=Math.abs(e.a)*s;return[{name:"line",type:"element",attributes:{x1:i.x.toString(),y1:i.y.toString(),x2:r.x.toString(),y2:r.y.toString(),stroke:n.color,"stroke-width":o.toString(),...n.is_dashed&&{"stroke-dasharray":(o*3).toString()},"data-schematic-line-id":n.schematic_line_id,...n.schematic_component_id&&{"data-schematic-component-id":n.schematic_component_id}},children:[],value:""}]}function w8t({schCircle:n,transform:e,colorMap:t}){let i=st(e,n.center),r=Math.abs(e.a)*n.radius,s=n.stroke_width??.02,o=Math.abs(e.a)*s;return[{name:"circle",type:"element",attributes:{cx:i.x.toString(),cy:i.y.toString(),r:r.toString(),fill:n.is_filled?n.fill_color??n.color:"none",stroke:n.color,"stroke-width":o.toString(),...n.is_dashed&&{"stroke-dasharray":(o*3).toString()},"data-schematic-circle-id":n.schematic_circle_id,...n.schematic_component_id&&{"data-schematic-component-id":n.schematic_component_id}},children:[],value:""}]}function P8t({schRect:n,transform:e,colorMap:t}){let i=st(e,n.center),r=Math.abs(e.a)*n.width,s=Math.abs(e.d)*n.height,o=n.stroke_width??.02,a=Math.abs(e.a)*o,c=i.x-r/2,l=i.y-s/2;return[{name:"rect",type:"element",attributes:{x:c.toString(),y:l.toString(),width:r.toString(),height:s.toString(),fill:n.is_filled?n.fill_color??n.color:"none",stroke:n.color,"stroke-width":a.toString(),...n.is_dashed&&{"stroke-dasharray":(a*3).toString()},...n.rotation!==0&&{transform:`rotate(${n.rotation} ${i.x} ${i.y})`},"data-schematic-rect-id":n.schematic_rect_id,...n.schematic_component_id&&{"data-schematic-component-id":n.schematic_component_id}},children:[],value:""}]}function k8t({schArc:n,transform:e,colorMap:t}){let i=st(e,n.center),r=Math.abs(e.a)*n.radius,s=n.stroke_width??.02,o=Math.abs(e.a)*s,a=n.start_angle_degrees*Math.PI/180,c=n.end_angle_degrees*Math.PI/180,l=i.x+r*Math.cos(a),u=i.y+r*Math.sin(a),h=i.x+r*Math.cos(c),d=i.y+r*Math.sin(c),_=n.end_angle_degrees-n.start_angle_degrees;n.direction==="clockwise"&&(_=-_),_<0&&(_+=360);let g=_>180?1:0,x=n.direction==="clockwise"?1:0;return[{name:"path",type:"element",attributes:{d:`M ${l} ${u} A ${r} ${r} 0 ${g} ${x} ${h} ${d}`,fill:"none",stroke:n.color,"stroke-width":o.toString(),...n.is_dashed&&{"stroke-dasharray":(o*3).toString()},"data-schematic-arc-id":n.schematic_arc_id,...n.schematic_component_id&&{"data-schematic-component-id":n.schematic_component_id}},children:[],value:""}]}function T8t(n){let e=[],t=i=>String(i).replace(/"/g,'\\"');for(let i of n){let s=`[data-subcircuit-connectivity-map-key="${t(i)}"]`,o=`g.trace${s}`,a=`g.trace-overlays${s}`,c=`:is(${o}, ${a}):hover`,l=`:is(${o}, ${a})`;e.push(`svg:has(${c}) ${l} { filter: invert(1); }`),e.push(`svg:has(${c}) ${a} .trace-crossing-outline { opacity: 0; }`)}return e.join(`
97
- `)}function VA(n,e){let t=e8t(n),i=t.maxX-t.minX,r=t.maxY-t.minY,s=e?.width??1200,o=e?.height??600,a=e?.colorOverrides,c={...Mi,schematic:{...Mi.schematic,...a?.schematic??{}}},l=i/r,u=s/o,h;if(l>u){let tt=s/l;h={x:0,y:(o-tt)/2}}else{let tt=o*l;h={x:(s-tt)/2,y:0}}let d=mtt([{x:t.minX,y:t.maxY},{x:t.maxX,y:t.maxY},{x:t.maxX,y:t.minY}],[{x:h.x,y:h.y},{x:s-h.x,y:h.y},{x:s-h.x,y:o-h.y}]),_=[];if(_.push({name:"rect",type:"element",attributes:{class:"boundary",x:"0",y:"0",width:s.toString(),height:o.toString()},children:[],value:""}),e?.grid){let tt=typeof e.grid=="object"?e.grid:{};_.push(qRt({bounds:t,transform:d,...tt}))}let g=[],x=[],v=[],P=new Set,w=[],T=[],k=[],C=[],M=[],I=[],E=[],A=[],R=[],B=[];for(let tt of n)tt.type==="schematic_debug_object"?g.push(...f8t({debugObject:tt,transform:d})):tt.type==="schematic_component"?(x.push(...h8t({component:tt,transform:d,circuitJson:n,colorMap:c})),I.push(...aet({component:tt,transform:d,circuitJson:n}))):tt.type==="schematic_box"?C.push(...g8t({schematicBox:tt,transform:d,colorMap:c})):tt.type==="schematic_trace"?(v.push(...m8t({trace:tt,transform:d,colorMap:c})),P.add(tt.subcircuit_connectivity_map_key)):tt.type==="schematic_net_label"?w.push(...y8t({schNetLabel:tt,realToScreenTransform:d,colorMap:c})):tt.type==="schematic_text"&&!tt.schematic_component_id?T.push(oet({elm:tt,transform:d,colorMap:c})):tt.type==="schematic_voltage_probe"?k.push(...d8t({probe:tt,transform:d,colorMap:c})):tt.type==="schematic_table"?M.push(...x8t({schematicTable:tt,transform:d,colorMap:c,circuitJson:n})):tt.type==="schematic_line"?E.push(...S8t({schLine:tt,transform:d,colorMap:c})):tt.type==="schematic_circle"?A.push(...w8t({schCircle:tt,transform:d,colorMap:c})):tt.type==="schematic_rect"?R.push(...P8t({schRect:tt,transform:d,colorMap:c})):tt.type==="schematic_arc"&&B.push(...k8t({schArc:tt,transform:d,colorMap:c}));let j=v.filter(tt=>tt.attributes?.["data-layer"]!=="overlay"),U=v.filter(tt=>tt.attributes?.["data-layer"]==="overlay");_.push(...g,...j,...U,...E,...A,...R,...B,...x,...I,...w,...T,...C,...k,...M),e?.labeledPoints&&_.push(ZRt({points:e.labeledPoints,transform:d}));let V=fl(n),H=ml;if(e?.showErrorsInTextOverlay){let tt=$_(n);tt&&_.push(tt)}let et={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:s.toString(),height:o.toString(),style:`background-color: ${c.schematic.background}`,"data-real-to-screen-transform":htt(d),...V&&{"data-software-used-string":V},...e?.includeVersion&&{"data-circuit-to-svg-version":H}},children:[{name:"style",type:"element",children:[{type:"text",value:`
96
+ `,name:"",attributes:{},children:[]}],value:"",attributes:{}},{name:"rect",type:"element",attributes:{fill:"#fff",x:"0",y:"0",width:l.toString(),height:u.toString()},value:"",children:[]},MRt(v,t,i,r,s),...w].filter(I=>I!==null);if(e?.showErrorsInTextOverlay){let I=$_(n);I&&C.push(I)}let M={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:l.toString(),height:u.toString(),...T&&{"data-software-used-string":T},...e?.includeVersion&&{"data-circuit-to-svg-version":k}},value:"",children:C};return(0,Ktt.stringify)(M)}function TRt(n,e,t){let i=Ee(t).source_component.list();switch(n.type){case"pcb_board":return mRt(n,e.transform);case"pcb_component":{let r=i.find(a=>a.source_component_id===n.source_component_id),o=Ee(t).pcb_port.list().filter(a=>a.pcb_component_id===n.pcb_component_id)[0];if(r&&o){let a=r.are_pins_interchangeable,c=yRt({elm:n,portPosition:{x:o.x,y:o.y},name:r.name,arePinsInterchangeable:a},e);return c?[c]:[]}return[]}case"pcb_smtpad":return PRt(n,e);case"pcb_hole":return SRt(n,e);case"pcb_plated_hole":return wRt(n,e);default:return[]}}function MRt(n,e,t,i,r){let[s,o]=st(n,[e,t]),[a,c]=st(n,[i,r]),l=Math.abs(a-s),u=Math.abs(c-o),h=Math.min(s,a),d=Math.min(o,c);return{name:"rect",type:"element",value:"",children:[],attributes:{class:"assembly-boundary",x:h.toString(),y:d.toString(),width:l.toString(),height:u.toString()}}}function IRt(n,e){let{transform:t,soup:i}=e,{width:r,height:s,center:o,outline:a}=n,l=i.find(_=>_.type==="source_board"&&_.title)?.title,u;if(a&&Array.isArray(a)&&a.length>=3)u=a.map((_,g)=>{let[x,v]=st(t,[_.x,_.y]);return g===0?`M ${x} ${v}`:`L ${x} ${v}`}).join(" ");else{let _=r/2,g=s/2,x=st(t,[o.x-_,o.y-g]),v=st(t,[o.x+_,o.y-g]),P=st(t,[o.x+_,o.y+g]),w=st(t,[o.x-_,o.y+g]);u=`M ${x[0]} ${x[1]} L ${v[0]} ${v[1]} L ${P[0]} ${P[1]} L ${w[0]} ${w[1]}`}u+=" Z";let h=Ee(i).pcb_cutout.list();for(let _ of h)if(_.shape==="rect"){let{x:g,y:x,width:v,height:P}=_.center?(()=>{let{x:E,y:A}=_.center,{width:R,height:B}=_;return{x:E,y:A,width:R,height:B}})():{x:0,y:0,width:0,height:0},w=v/2,T=P/2,[k,C,M,I]=[st(t,[g-w,x-T]),st(t,[g+w,x-T]),st(t,[g+w,x+T]),st(t,[g-w,x+T])];u+=` M ${k[0]} ${k[1]} L ${C[0]} ${C[1]} L ${M[0]} ${M[1]} L ${I[0]} ${I[1]} Z`}else _.shape;let d=[{name:"path",type:"element",value:"",children:[],attributes:{class:"pinout-board",d:u,fill:ERt,stroke:CRt,"fill-rule":"evenodd","stroke-opacity":"0.8","stroke-width":(.2*Math.abs(t.a)).toString()}}];if(l){let _=e.svgWidth/2;d.push({name:"text",type:"element",value:"",children:[{name:"",type:"text",value:l,attributes:{},children:[]}],attributes:{x:_.toString(),y:30 .toString(),"text-anchor":"middle","font-size":"18px","font-weight":"bold","font-family":"Arial, sans-serif",fill:"black",class:"pinout-board-title"}})}return d}function RRt(n,e){let{transform:t,soup:i}=e,{center:r,width:s,height:o,rotation:a=0,source_component_id:c}=n,l=Ee(i).source_component.get(c);if(!r||typeof s!="number"||typeof o!="number"||s===0||o===0)return[];let[u,h]=st(t,[r.x,r.y]),d=s*Math.abs(t.a),_=o*Math.abs(t.d),g=`translate(${u}, ${h})`,x=[{name:"rect",type:"element",attributes:{class:"pinout-component-box",x:(-d/2).toString(),y:(-_/2).toString(),width:d.toString(),height:_.toString(),fill:NRt,transform:`rotate(${a}deg)`},value:"",children:[]}];if(l?.name){let v=Math.min(d,_)*.4;x.push({name:"text",type:"element",attributes:{x:"0",y:"0",fill:ARt,"font-size":`${v}px`,"font-family":"sans-serif","text-anchor":"middle","dominant-baseline":"middle"},children:[{type:"text",value:l.name,name:"",attributes:{},children:[]}],value:""})}return[{name:"g",type:"element",attributes:{transform:g},children:x,value:""}]}function ORt(n,e){let{transform:t}=e,[i,r]=st(t,[n.x,n.y]);if(n.hole_shape==="circle"||n.hole_shape==="square"){let s=n.hole_diameter*Math.abs(t.a),o=s/2;return n.hole_shape==="circle"?[{name:"circle",type:"element",attributes:{class:"pinout-hole",cx:i.toString(),cy:r.toString(),r:o.toString(),fill:jA},children:[],value:""}]:[{name:"rect",type:"element",attributes:{class:"pinout-hole",x:(i-o).toString(),y:(r-o).toString(),width:s.toString(),height:s.toString(),fill:jA},children:[],value:""}]}if(n.hole_shape==="oval"){let s=n.hole_width*Math.abs(t.a),o=n.hole_height*Math.abs(t.a),a=s/2,c=o/2;return[{name:"ellipse",type:"element",attributes:{class:"pinout-hole",cx:i.toString(),cy:r.toString(),rx:a.toString(),ry:c.toString(),fill:jA},children:[],value:""}]}return[]}function LRt(n,e){let{transform:t}=e,[i,r]=st(t,[n.x,n.y]);if(n.shape==="pill"){let s=n.outer_width*Math.abs(t.a),o=n.outer_height*Math.abs(t.a),a=n.hole_width*Math.abs(t.a),c=n.hole_height*Math.abs(t.a),l=s/2,u=o-s,h=a/2;return[{name:"g",type:"element",children:[{name:"path",type:"element",attributes:{class:"pinout-hole-outer",fill:N1,d:`M${i-l},${r-u/2} v${u} a${l},${l} 0 0 0 ${s},0 v-${u} a${l},${l} 0 0 0 -${s},0 z`},value:"",children:[]},{name:"path",type:"element",attributes:{class:"pinout-hole-inner",fill:A1,d:`M${i-h},${r-(c-a)/2} v${c-a} a${h},${h} 0 0 0 ${a},0 v-${c-a} a${h},${h} 0 0 0 -${a},0 z`},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="circle"){let s=n.outer_diameter*Math.abs(t.a),o=n.outer_diameter*Math.abs(t.a),a=n.hole_diameter*Math.abs(t.a),c=n.hole_diameter*Math.abs(t.a),l=Math.min(s,o)/2,u=Math.min(a,c)/2;return[{name:"g",type:"element",children:[{name:"circle",type:"element",attributes:{class:"pinout-hole-outer",fill:N1,cx:i.toString(),cy:r.toString(),r:l.toString()},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"pinout-hole-inner",fill:A1,cx:i.toString(),cy:r.toString(),r:u.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="circular_hole_with_rect_pad"){let s=n.hole_diameter*Math.abs(t.a),o=n.rect_pad_width*Math.abs(t.a),a=n.rect_pad_height*Math.abs(t.a),c=s/2;return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"pinout-hole-outer-pad",fill:N1,x:(i-o/2).toString(),y:(r-a/2).toString(),width:o.toString(),height:a.toString()},value:"",children:[]},{name:"circle",type:"element",attributes:{class:"pinout-hole-inner",fill:A1,cx:i.toString(),cy:r.toString(),r:c.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="pill_hole_with_rect_pad"){let s=n.rect_pad_width*Math.abs(t.a),o=n.rect_pad_height*Math.abs(t.a),a=n.hole_height*Math.abs(t.a),c=n.hole_width*Math.abs(t.a),l=Math.min(a,c)/2;return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"pinout-hole-outer-pad",fill:N1,x:(i-s/2).toString(),y:(r-o/2).toString(),width:s.toString(),height:o.toString()},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pinout-hole-inner",fill:A1,x:(i-c/2).toString(),y:(r-a/2).toString(),width:c.toString(),height:a.toString(),rx:l.toString(),ry:l.toString()},value:"",children:[]}],value:"",attributes:{}}]}if(n.shape==="rotated_pill_hole_with_rect_pad"){let s=n.rect_pad_width*Math.abs(t.a),o=n.rect_pad_height*Math.abs(t.a),a=n.hole_height*Math.abs(t.a),c=n.hole_width*Math.abs(t.a),l=Math.min(a,c)/2;return[{name:"g",type:"element",children:[{name:"rect",type:"element",attributes:{class:"pinout-hole-outer-pad",fill:N1,x:(-s/2).toString(),y:(-o/2).toString(),width:s.toString(),height:o.toString(),transform:`translate(${i} ${r}) rotate(${-n.rect_ccw_rotation})`},value:"",children:[]},{name:"rect",type:"element",attributes:{class:"pinout-hole-inner",fill:A1,x:(-c/2).toString(),y:(-a/2).toString(),width:c.toString(),height:a.toString(),rx:l.toString(),ry:l.toString(),transform:`translate(${i} ${r}) rotate(${-n.hole_ccw_rotation})`},value:"",children:[]}],value:"",attributes:{}}]}return[]}function FRt(n,e){let{transform:t}=e;if(n.shape==="rect"||n.shape==="rotated_rect"){let i=n.width*Math.abs(t.a),r=n.height*Math.abs(t.d),[s,o]=st(t,[n.x,n.y]);return n.shape==="rotated_rect"&&n.ccw_rotation?[{name:"rect",type:"element",attributes:{class:"pinout-pad",fill:R1,x:(-i/2).toString(),y:(-r/2).toString(),width:i.toString(),height:r.toString(),transform:`translate(${s} ${o}) rotate(${-n.ccw_rotation})`,"data-layer":n.layer},value:"",children:[]}]:[{name:"rect",type:"element",attributes:{class:"pinout-pad",fill:R1,x:(s-i/2).toString(),y:(o-r/2).toString(),width:i.toString(),height:r.toString(),"data-layer":n.layer},value:"",children:[]}]}if(n.shape==="pill"){let i=n.width*Math.abs(t.a),r=n.height*Math.abs(t.d),s=n.radius*Math.abs(t.a),[o,a]=st(t,[n.x,n.y]);return[{name:"rect",type:"element",attributes:{class:"pinout-pad",fill:R1,x:(o-i/2).toString(),y:(a-r/2).toString(),width:i.toString(),height:r.toString(),rx:s.toString(),ry:s.toString(),"data-layer":n.layer},value:"",children:[]}]}if(n.shape==="circle"){let i=n.radius*Math.abs(t.a),[r,s]=st(t,[n.x,n.y]);return[{name:"circle",type:"element",attributes:{class:"pinout-pad",fill:R1,cx:r.toString(),cy:s.toString(),r:i.toString(),"data-layer":n.layer},value:"",children:[]}]}if(n.shape==="polygon"){let i=(n.points??[]).map(r=>st(t,[r.x,r.y]));return[{name:"polygon",type:"element",attributes:{class:"pinout-pad",fill:R1,points:i.map(r=>r.join(",")).join(" "),"data-layer":n.layer},value:"",children:[]}]}return[]}function BA(n){let{rectX:e,rectY:t,rectWidth:i,rectHeight:r,textX:s,textY:o,text:a,fontSize:c,labelBackground:l,labelColor:u,rx:h=4,ry:d=4,fontFamily:_="Arial, sans-serif",fontWeight:g="bold",textAnchor:x="middle",dominantBaseline:v="middle"}=n;return[{name:"rect",type:"element",attributes:{x:e.toString(),y:t.toString(),width:i.toString(),height:r.toString(),fill:l,rx:typeof h=="number"?h.toString():h,ry:typeof d=="number"?d.toString():d,stroke:"none"},children:[],value:""},{name:"text",type:"element",attributes:{x:s.toString(),y:o.toString(),fill:u,"font-size":`${c}px`,"font-family":_,"font-weight":g,"text-anchor":x,"dominant-baseline":v},children:[{type:"text",value:a,name:"",attributes:{},children:[]}],value:""}]}function jRt(n,e){let t=e.label_positions.get(n.pcb_port_id);if(!t)return[];let{text:i,aliases:r,elbow_end:s,label_pos:o,edge:a}=t,[c,l]=st(e.transform,[n.x,n.y]),u=a==="left"?"x-":a==="right"?"x+":a==="top"?"y-":"y+",h=a==="left"?"x+":a==="right"?"x-":a==="top"?"y+":"y-",d=qc({x:c,y:l,facingDirection:u},{x:s.x,y:s.y,facingDirection:h},{}),_=/^pin(\d+)$/i.exec(i),g=[{text:_?_[1]:i,bg:_?$Rt:Ott,color:_?DRt:Rtt},...r.map(H=>({text:H,bg:Ott,color:Rtt}))],x=Math.abs(e.transform.a),v=e.styleScale??1,w=1.6*v*x,T=Math.max(.08,.25*v),C=.3*v*x,M=T*x,I={x:o.x+(a==="left"?-M/2:M/2),y:o.y},E=[...d,I].map(H=>`${H.x},${H.y}`).join(" "),A=w*(11/21),R=(w-A)/2,B=R,j=g.map(({text:H,bg:et,color:tt})=>{let mt=H??"",Q=mt.length*A*.6+2*R;return{text:mt,rectWidth:Q,bg:et,color:tt}}),U=o.y,V=[{name:"polyline",type:"element",attributes:{points:E,stroke:zRt,"stroke-width":(T*x).toString(),fill:"none"},children:[],value:""}];if(a==="left"){let H=o.x;for(let{text:et,rectWidth:tt,bg:mt,color:G}of j){let Q=H-tt,nt=Q+tt/2;V.push(...BA({rectX:Q,rectY:U-w/2,rectWidth:tt,rectHeight:w,textX:nt,textY:U,text:et,fontSize:A,labelBackground:mt,labelColor:G,rx:C,ry:C})),H=Q-B}}else if(a==="right"){let H=o.x;for(let{text:et,rectWidth:tt,bg:mt,color:G}of j){let Q=H,nt=Q+tt/2;V.push(...BA({rectX:Q,rectY:U-w/2,rectWidth:tt,rectHeight:w,textX:nt,textY:U,text:et,fontSize:A,labelBackground:mt,labelColor:G,rx:C,ry:C})),H=Q+tt+B}}else{let H=j.reduce((tt,mt)=>tt+mt.rectWidth,0)+B*Math.max(0,j.length-1),et=o.x-H/2;for(let{text:tt,rectWidth:mt,bg:G,color:Q}of j){let nt=et,pt=nt+mt/2;V.push(...BA({rectX:nt,rectY:U-w/2,rectWidth:mt,rectHeight:w,textX:pt,textY:U,text:tt,fontSize:A,labelBackground:G,labelColor:Q,rx:C,ry:C})),et=nt+mt+B}}return V}function Ltt(n,e,{transform:t,soup:i,board_bounds:r,svgHeight:s,styleScale:o},a){let c=e.map(V=>V.pcb_port.x),l={};for(let V of c){let H=V.toFixed(1);l[H]=(l[H]||0)+1}let u;if(Object.keys(l).length>1&&e.length>2){let V=Object.entries(l).sort((pt,ht)=>ht[1]-pt[1]),H=parseFloat(V[0][0]),et=e.filter(pt=>Math.abs(pt.pcb_port.x-H)<.2),tt=e.filter(pt=>Math.abs(pt.pcb_port.x-H)>=.2),mt=pt=>({pcb_port:pt.pcb_port,y:st(t,[pt.pcb_port.x,pt.pcb_port.y])[1],aliases:pt.aliases});et.sort((pt,ht)=>ht.pcb_port.y-pt.pcb_port.y),tt.sort((pt,ht)=>ht.pcb_port.y-pt.pcb_port.y);let G=et.length>0?Math.max(...et.map(pt=>pt.pcb_port.y)):-1/0;u=((tt.length>0?Math.max(...tt.map(pt=>pt.pcb_port.y)):-1/0)>G?[...tt,...et]:[...et,...tt]).map(mt)}else u=e.map(V=>({pcb_port:V.pcb_port,y:st(t,[V.pcb_port.x,V.pcb_port.y])[1],aliases:V.aliases})).sort((V,H)=>V.y-H.y);if(u.length===0)return;let h=st(t,[n==="left"?r.minX:r.maxX,0])[0],d=u.length,_={};for(let V of e){let H=V.pcb_port.x.toFixed(1);_[H]=(_[H]||0)+1}let g=new Set;if(Object.keys(_).length>1&&e.length>2){let V=Object.entries(_).sort((tt,mt)=>mt[1]-tt[1]),H=parseFloat(V[0][0]),et=e.filter(tt=>Math.abs(tt.pcb_port.x-H)<.2);g=new Set(et.map(tt=>tt.pcb_port.pcb_port_id))}let x=u.map((V,H)=>g.has(V.pcb_port.pcb_port_id)?H:-1).filter(V=>V!==-1),v=(d-1)/2,P=Math.abs(t.a),w=Qtt*o*P,k=Math.max(.2*P,.3*o*P),C=XRt*o*P,M=(tet+d*eet)*o*P,E=M+v*(XA*o*P)+net*o*P,A=d-x.length,R=x.length===0?d:A,B=R*w+Math.max(0,R-1)*k,j;if(x.length>0&&A>0){let V=x.map(nt=>u[nt].y),H=Math.min(...V),et=Math.max(...V),tt=H-w/2,mt=et+w/2;u.map((nt,pt)=>pt).filter(nt=>!x.includes(nt))[0]<x[0]?j=tt-(k*2+C)-B+w/2:j=mt+(k*2+C)+w/2}else j=(s-B)/2+w/2;let U=x.length===d;u.forEach(({pcb_port:V,aliases:H},et)=>{let tt;if(x.length>0)if(x.includes(et))tt=v;else{let wt=Math.min(...x),Et=Math.max(...x),ot;et<wt?ot=wt-et:ot=et-Et,tt=v-ot}else{let wt=Math.abs(et-v);tt=v-wt}let mt=M+tt*(XA*o*P),G=n==="left"?-1:1,Q=x.includes(et),nt=U||x.length>0&&Q?u[et].y:j,pt={x:h+G*mt,y:nt},ht={x:h+G*E,y:nt};a.set(V.pcb_port_id,{text:H[0],aliases:H.slice(1),elbow_end:pt,label_pos:ht,edge:n}),x.length>0&&Q||(j+=w+k)})}function VRt(n,e){let t=Ee(e).source_port.get(n.source_port_id);if(!t)return null;let i=t.port_hints?.filter(o=>!/^\d+$/.test(o)&&!["left","right","top","bottom"].includes(o))??[],r=i[0];if(r||(r=t.name),!r)return null;let s=i.filter(o=>o!==r);return{text:r,aliases:s}}function GRt(n,e){let t={left:n.x-e.minX,right:e.maxX-n.x,top:e.maxY-n.y,bottom:n.y-e.minY},i="left",r=t.left;return t.right<r&&(r=t.right,i="right"),t.top<r&&(r=t.top,i="top"),t.bottom<r&&(r=t.bottom,i="bottom"),i}function HRt(n,e){let t=Number.POSITIVE_INFINITY,i=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let Z of n)if(Z.type==="pcb_board")if("outline"in Z&&Z.outline&&Array.isArray(Z.outline)&&Z.outline.length>0)for(let at of Z.outline)t=Math.min(t,at.x),i=Math.min(i,at.y),r=Math.max(r,at.x),s=Math.max(s,at.y);else{let at=Z.center,Mt=Z.width||0,Ft=Z.height||0;t=Math.min(t,at.x-Mt/2),i=Math.min(i,at.y-Ft/2),r=Math.max(r,at.x+Mt/2),s=Math.max(s,at.y+Ft/2)}let o=2,a=e?.width??1200,c=e?.height??768,l=n.find(Z=>Z.type==="source_board"&&!!Z.title)?.title,u={minX:t,minY:i,maxX:r,maxY:s},h=n.filter(Z=>Z.type==="pcb_port"&&Z.is_board_pinout),d=[];for(let Z of h){let at=VRt(Z,n);if(!at)continue;let Mt=GRt({x:Z.x,y:Z.y},u);d.push({pcb_port:Z,aliases:[at.text,...at.aliases],edge:Mt})}let _=d.filter(Z=>Z.edge==="left"),g=d.filter(Z=>Z.edge==="right"),x=d.filter(Z=>Z.edge==="top"),v=d.filter(Z=>Z.edge==="bottom"),P=(t+r)/2;x.length>0&&(x.filter(at=>at.pcb_port.x<P).length>x.length/2?_.push(...x):g.push(...x)),v.length>0&&(v.filter(at=>at.pcb_port.x<P).length>v.length/2?_.push(...v):g.push(...v));let T=n.filter(Z=>Z.type==="pcb_smtpad").map(Z=>{if(typeof Z.height=="number")return Z.height;if(typeof Z.radius=="number")return Z.radius*2}).filter(Z=>Number.isFinite(Z)),k=T.length?T.reduce((Z,at)=>Z+at,0)/T.length:void 0,M=k?Math.max(.5,Math.min(1,k/1)):1,I=Qtt*M;function E(Z){let at=[...Z.aliases??[]];if(at.length===0)return at;let Mt=/^pin(\d+)$/i.exec(at[0]);return Mt&&(at[0]=Mt[1]),at}function A(Z){if(Z.length===0)return 0;let at=I,Mt=at*BRt,Ft=(at-Mt)/2,Ot=Ft;return Z.map(Kt=>(Kt??"").length*Mt*YRt+2*Ft).reduce((Kt,le)=>Kt+le,0)+Ot*Math.max(0,Z.length-1)}function R(Z){if(Z<=0)return 0;let at=(Z-1)/2;return(tet+Z*eet)*M+at*(XA*M)+net*M}let B=Math.max(0,..._.map(Z=>A(E(Z)))),j=Math.max(0,...g.map(Z=>A(E(Z)))),U=R(_.length)+B,V=R(g.length)+j,H=t-U,tt=r+V-H+2*o,mt=s-i+2*o,G=a/tt,Q=c/mt,nt=Math.min(G,Q),pt=(a-tt*nt)/2,ht=(c-mt*nt)/2,wt=Fe(yn(pt-H*nt+o*nt,c-ht+i*nt-o*nt),Ti(nt,-nt)),Et=URt({left_labels:_,right_labels:g,transform:wt,soup:n,board_bounds:u,svgWidth:a,svgHeight:c,styleScale:M}),ot={transform:wt,soup:n,board_bounds:u,styleScale:M,label_positions:Et,svgWidth:a,svgHeight:c},X=n.sort((Z,at)=>(Ftt.indexOf(Z.type)??9999)-(Ftt.indexOf(at.type)??9999)).flatMap(Z=>WRt(Z,ot,n)),W=fl(n),rt=ml,ut=[{name:"rect",type:"element",attributes:{fill:"rgb(255, 255, 255)",x:"0",y:"0",width:a.toString(),height:c.toString()},value:"",children:[]},...X].filter(Z=>Z!==null);if(e?.showErrorsInTextOverlay){let Z=$_(n);Z&&ut.push(Z)}let yt={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:a.toString(),height:c.toString(),...W&&{"data-software-used-string":W},...e?.includeVersion&&{"data-circuit-to-svg-version":rt}},value:"",children:ut};return(0,Jtt.stringify)(yt)}function WRt(n,e,t){switch(n.type){case"pcb_board":return IRt(n,e);case"pcb_component":return RRt(n,e);case"pcb_smtpad":return FRt(n,e);case"pcb_hole":return ORt(n,e);case"pcb_plated_hole":return LRt(n,e);case"pcb_port":return n.is_board_pinout?jRt(n,e):[];default:return[]}}function qRt(n){let{minX:e,minY:t,maxX:i,maxY:r}=n.bounds,s=n.cellSize??1,o=n.labelCells??!1,a=[],c=(l,u)=>{let[h,d]=st(n.transform,[l,u]);return{x:h,y:d}};for(let l=Math.floor(e);l<=Math.ceil(i);l+=s){let u=c(l,t),h=c(l,r);a.push({name:"line",type:"element",attributes:{x1:u.x.toString(),y1:u.y.toString(),x2:h.x.toString(),y2:h.y.toString(),stroke:Ei.schematic.grid,"stroke-width":(.01*Math.abs(n.transform.a)).toString(),"stroke-opacity":"0.5"}})}for(let l=Math.floor(t);l<=Math.ceil(r);l+=s){let u=c(e,l),h=c(i,l);a.push({name:"line",type:"element",attributes:{x1:u.x.toString(),y1:u.y.toString(),x2:h.x.toString(),y2:h.y.toString(),stroke:Ei.schematic.grid,"stroke-width":(.01*Math.abs(n.transform.a)).toString(),"stroke-opacity":"0.5"}})}if(o){let l=(u,h)=>s<=.1?`${u.toFixed(1)},${h.toFixed(1)}`:`${u},${h}`;for(let u=Math.floor(e);u<=Math.ceil(i);u+=s)for(let h=Math.floor(t);h<=Math.ceil(r);h+=s){let d=c(u,h);a.push({name:"text",type:"element",attributes:{x:(d.x-2.5).toString(),y:(d.y-5).toString(),fill:Ei.schematic.grid,"font-size":(s/5*Math.abs(n.transform.a)).toString(),"fill-opacity":"0.5","text-anchor":"middle","dominant-baseline":"middle","font-family":"sans-serif"},children:[{type:"text",value:l(u,h),name:"",attributes:{},children:[]}]})}}return{name:"g",value:"",type:"element",attributes:{class:"grid"},children:a}}function ZRt(n){let{points:e,transform:t}=n,i=[];for(let r of e){let[s,o]=st(t,[r.x-.1,r.y-.1]),[a,c]=st(t,[r.x+.1,r.y+.1]),[l,u]=st(t,[r.x-.1,r.y+.1]),[h,d]=st(t,[r.x+.1,r.y-.1]);i.push({name:"path",type:"element",attributes:{d:`M${s},${o} L${a},${c} M${l},${u} L${h},${d}`,stroke:Ei.schematic.grid,"stroke-width":(.02*Math.abs(t.a)).toString(),"stroke-opacity":"0.7"}});let[_,g]=st(t,[r.x+.15,r.y-.15]);i.push({name:"text",type:"element",attributes:{x:_.toString(),y:g.toString(),fill:Ei.schematic.grid,"font-size":(.1*Math.abs(t.a)).toString(),"fill-opacity":"0.7","text-anchor":"start","font-family":"sans-serif","dominant-baseline":"middle"},children:[{type:"text",value:r.label||`(${r.x},${r.y})`,name:"",attributes:{},children:[]}]})}return{name:"g",value:"",type:"element",attributes:{class:"labeled-points"},children:i}}function QRt(n){return{left:180,top:90,bottom:-90,right:0}[n]??0}function t8t(n,e,t){let i=t+hl*2+F_*n.text.length+L_,r=D_(n.anchor_side);return n.anchor_position??{x:n.center.x-r.x*i*e/2,y:n.center.y-r.y*i*e/2}}function e8t(n,e=.5){let t=Number.POSITIVE_INFINITY,i=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY,o=.2;for(let c of n)if(c.type==="schematic_component")a(c.center,c.size,0);else if(c.type==="schematic_port")a(c.center,{width:o,height:o},0);else if(c.type==="schematic_debug_object")c.shape==="rect"?a(c.center,c.size,0):c.shape==="line"&&(a(c.start,{width:.1,height:.1},0),a(c.end,{width:.1,height:.1},0));else if(c.type==="schematic_net_label"){let l=z_("net_label"),u=Xw(c.text||""),d=(u+hl*2+F_*(c.text?.length||0)+L_)*l,_=1.2*l,g=QRt(c.anchor_side)/180*Math.PI,x=t8t(c,l,u),v=D_(c.anchor_side),P={x:x.x+v.x*d/2,y:x.y+v.y*d/2};a(P,{width:d,height:_},g)}else if(c.type==="schematic_trace")for(let l of c.edges)a(l.from,{width:.1,height:.1},0),a(l.to,{width:.1,height:.1},0);else if(c.type==="schematic_text"){let u=z_("reference_designator",c.font_size)??.18,d=(c.text??"").length*u,_=u;a(c.position,{width:d,height:_},c.rotation??0)}else if(c.type==="schematic_voltage_probe")a(c.position,{width:.2,height:.4},0);else if(c.type==="schematic_box")a({x:c.x+c.width/2,y:c.y+c.height/2},{width:c.width,height:c.height},0);else if(c.type==="schematic_table"){let{column_widths:l,row_heights:u}=ret(c,n),h=l.reduce((w,T)=>w+T,0),d=u.reduce((w,T)=>w+T,0),_=c.anchor??"center",g=c.anchor_position.x,x=c.anchor_position.y;_.includes("center")?g-=h/2:_.includes("right")&&(g-=h),_.includes("center")?x+=d/2:_.includes("bottom")&&(x+=d);let v=g+h/2,P=x-d/2;a({x:v,y:P},{width:h,height:d},0)}else c.type==="schematic_line"?(a({x:c.x1,y:c.y1},{width:.02,height:.02},0),a({x:c.x2,y:c.y2},{width:.02,height:.02},0)):c.type==="schematic_circle"?a(c.center,{width:c.radius*2,height:c.radius*2},0):c.type==="schematic_rect"?a(c.center,{width:c.width,height:c.height},c.rotation):c.type==="schematic_arc"&&a(c.center,{width:c.radius*2,height:c.radius*2},0);return t-=e,i-=e,r+=e,s+=e,{minX:t,minY:i,maxX:r,maxY:s};function a(c,l,u){let h=[{x:-l.width/2,y:-l.height/2},{x:l.width/2,y:-l.height/2},{x:l.width/2,y:l.height/2},{x:-l.width/2,y:l.height/2}];for(let d of h){let _=d.x*Math.cos(u)-d.y*Math.sin(u)+c.x,g=d.x*Math.sin(u)+d.y*Math.cos(u)+c.y;t=Math.min(t,_),i=Math.min(i,g),r=Math.max(r,_),s=Math.max(s,g)}}}function r8t(n,e,t,i){let r=e.x-n.x,s=e.y-n.y,o=Math.sqrt((t.x-n.x)**2+(t.y-n.y)**2),c=Math.sqrt((i.x-e.x)**2+(i.y-e.y)**2)/o,l=yn(r,s),u=Ti(c,c);return Fe(l,u)}function h8t(n){let{component:e}=n;if(e.is_box_with_pins===!1)return[];let t=e.symbol_name?o8t(n):p8t(n);return[{type:"element",name:"g",attributes:{"data-circuit-json-type":"schematic_component","data-schematic-component-id":e.schematic_component_id},children:t,value:""}]}function d8t({probe:n,transform:e,colorMap:t}){let[i,r]=st(e,[n.position.x,n.position.y]),s=n.color??t.schematic.reference,o=Math.abs(e.a)*.6,a=Math.abs(e.a)*.28,c=i+o*Math.cos(-50*Math.PI/180),l=r+o*Math.sin(-50*Math.PI/180),u=i,h=r,d=[`M ${c},${l}`,`L ${u},${h}`,`M ${u},${h}`,`L ${u-a*Math.cos(100*Math.PI/180)},${h-a*Math.sin(100*Math.PI/180)}`,`L ${u-a*Math.cos(160*Math.PI/180)},${h-a*Math.sin(160*Math.PI/180)}`,"Z"].join(" "),_=(c+8-(c-c)).toString(),g=[];if(n.name&&n.voltage!==void 0)g.push({type:"element",name:"tspan",value:"",attributes:{x:_},children:[{type:"text",value:n.name,name:"",attributes:{},children:[]}]}),g.push({type:"element",name:"tspan",value:"",attributes:{x:_,dy:"1.2em"},children:[{type:"text",value:`${n.voltage}V`,name:"",attributes:{},children:[]}]});else{let x=[];n.name&&x.push(n.name),n.voltage!==void 0&&x.push(`${n.voltage}V`),g.push({type:"text",value:x.join(" "),name:"",attributes:{},children:[]})}return[{name:"path",type:"element",attributes:{d,stroke:s,fill:s,"stroke-width":`${Ui(e)}px`},value:"",children:[]},{type:"element",name:"text",value:"",attributes:{x:_,y:l.toString(),fill:s,"text-anchor":"start","dominant-baseline":"middle","font-family":"sans-serif","font-size":`${Ya(e,"reference_designator")}px`,"font-weight":"bold","data-schematic-voltage-probe-id":n.schematic_voltage_probe_id},children:g}]}function f8t({debugObject:n,transform:e}){if(n.shape==="rect"){let[t,i]=st(e,[n.center.x-n.size.width/2,n.center.y-n.size.height/2]),[r,s]=st(e,[n.center.x+n.size.width/2,n.center.y+n.size.height/2]);[i,s]=[Math.min(i,s),Math.max(i,s)];let o=Math.abs(r-t),a=Math.abs(s-i),[c,l]=st(e,[n.center.x,n.center.y]);return[{name:"rect",type:"element",value:"",attributes:{x:t.toString(),y:i.toString(),width:o.toString(),height:a.toString(),fill:"none",stroke:"red","stroke-width":(.02*Math.abs(e.a)).toString(),"stroke-dasharray":"5,5"},children:n.label?[{name:"text",type:"element",value:"",attributes:{x:c.toString(),y:(l-10).toString(),"text-anchor":"middle","font-size":(.2*Math.abs(e.a)).toString(),fill:"red"},children:[{type:"text",value:n.label,name:"",attributes:{},children:[]}]}]:[]}]}if(n.shape==="line"){let[t,i]=st(e,[n.start.x,n.start.y]),[r,s]=st(e,[n.end.x,n.end.y]),o=(t+r)/2,a=(i+s)/2;return[{name:"line",type:"element",value:"",attributes:{x1:t.toString(),y1:i.toString(),x2:r.toString(),y2:s.toString(),stroke:"red","stroke-width":(.02*Math.abs(e.a)).toString(),"stroke-dasharray":"5,5"},children:n.label?[{name:"text",type:"element",value:"",attributes:{x:o.toString(),y:(a-10).toString(),"text-anchor":"middle","font-size":(.2*Math.abs(e.a)).toString(),fill:"red"},children:[{type:"text",value:n.label,name:"",attributes:{},children:[]}]}]:[]}]}return[]}function m8t({trace:n,transform:e,colorMap:t}){let i=n.edges;if(i.length===0)return[];let r=[],s=[],o="";for(let a=0;a<i.length;a++){let c=i[a];if(c.is_crossing)continue;let[l,u]=st(e,[c.from.x,c.from.y]),[h,d]=st(e,[c.to.x,c.to.y]);a===0||i[a-1]?.is_crossing?o+=`M ${l} ${u} L ${h} ${d}`:o+=` L ${h} ${d}`}o&&(r.push({name:"path",type:"element",attributes:{d:o,class:"trace-invisible-hover-outline",stroke:t.schematic.wire,fill:"none","stroke-width":`${Ui(e)*8}px`,"stroke-linecap":"round",opacity:"0","stroke-linejoin":"round"},value:"",children:[]}),r.push({name:"path",type:"element",attributes:{d:o,stroke:t.schematic.wire,fill:"none","stroke-width":`${Ui(e)}px`,"stroke-linecap":"round","stroke-linejoin":"round"},value:"",children:[]}));for(let a of i){if(!a.is_crossing)continue;let[c,l]=st(e,[a.from.x,a.from.y]),[u,h]=st(e,[a.to.x,a.to.y]),d=(c+u)/2,_=(l+h)/2,g=u-c,x=h-l,v=Math.sqrt(g*g+x*x),P=v*.7,w=-x/v*P,T=g/v*P,k=d+w,C=_-Math.abs(T);s.push({name:"path",type:"element",attributes:{class:"trace-crossing-outline",d:`M ${c} ${l} Q ${k} ${C} ${u} ${h}`,stroke:t.schematic.background,fill:"none","stroke-width":`${Ui(e)*1.5}px`,"stroke-linecap":"butt"},value:"",children:[]}),s.push({name:"path",type:"element",attributes:{d:`M ${c} ${l} Q ${k} ${C} ${u} ${h}`,stroke:t.schematic.wire,fill:"none","stroke-width":`${Ui(e)}px`,"stroke-linecap":"round"},value:"",children:[]})}if(n.junctions)for(let a of n.junctions){let[c,l]=st(e,[a.x,a.y]);s.push({name:"circle",type:"element",attributes:{cx:c.toString(),cy:l.toString(),r:(Math.abs(e.a)*.03).toString(),class:"trace-junction",fill:t.schematic.junction},value:"",children:[]})}return[{name:"g",type:"element",value:"",attributes:{class:"trace","data-layer":"base","data-circuit-json-type":"schematic_trace","data-schematic-trace-id":n.schematic_trace_id,...n.subcircuit_connectivity_map_key&&{"data-subcircuit-connectivity-map-key":n.subcircuit_connectivity_map_key}},children:r},{name:"g",type:"element",value:"",attributes:{class:"trace-overlays","data-layer":"overlay","data-circuit-json-type":"schematic_trace","data-schematic-trace-id":n.schematic_trace_id,...n.subcircuit_connectivity_map_key&&{"data-subcircuit-connectivity-map-key":n.subcircuit_connectivity_map_key}},children:s}]}function S8t({schLine:n,transform:e,colorMap:t}){let i=st(e,{x:n.x1,y:n.y1}),r=st(e,{x:n.x2,y:n.y2}),s=n.stroke_width??.02,o=Math.abs(e.a)*s;return[{name:"line",type:"element",attributes:{x1:i.x.toString(),y1:i.y.toString(),x2:r.x.toString(),y2:r.y.toString(),stroke:n.color,"stroke-width":o.toString(),...n.is_dashed&&{"stroke-dasharray":(o*3).toString()},"data-schematic-line-id":n.schematic_line_id,...n.schematic_component_id&&{"data-schematic-component-id":n.schematic_component_id}},children:[],value:""}]}function w8t({schCircle:n,transform:e,colorMap:t}){let i=st(e,n.center),r=Math.abs(e.a)*n.radius,s=n.stroke_width??.02,o=Math.abs(e.a)*s;return[{name:"circle",type:"element",attributes:{cx:i.x.toString(),cy:i.y.toString(),r:r.toString(),fill:n.is_filled?n.fill_color??n.color:"none",stroke:n.color,"stroke-width":o.toString(),...n.is_dashed&&{"stroke-dasharray":(o*3).toString()},"data-schematic-circle-id":n.schematic_circle_id,...n.schematic_component_id&&{"data-schematic-component-id":n.schematic_component_id}},children:[],value:""}]}function P8t({schRect:n,transform:e,colorMap:t}){let i=st(e,n.center),r=Math.abs(e.a)*n.width,s=Math.abs(e.d)*n.height,o=n.stroke_width??.02,a=Math.abs(e.a)*o,c=i.x-r/2,l=i.y-s/2;return[{name:"rect",type:"element",attributes:{x:c.toString(),y:l.toString(),width:r.toString(),height:s.toString(),fill:n.is_filled?n.fill_color??n.color:"none",stroke:n.color,"stroke-width":a.toString(),...n.is_dashed&&{"stroke-dasharray":(a*3).toString()},...n.rotation!==0&&{transform:`rotate(${n.rotation} ${i.x} ${i.y})`},"data-schematic-rect-id":n.schematic_rect_id,...n.schematic_component_id&&{"data-schematic-component-id":n.schematic_component_id}},children:[],value:""}]}function k8t({schArc:n,transform:e,colorMap:t}){let i=st(e,n.center),r=Math.abs(e.a)*n.radius,s=n.stroke_width??.02,o=Math.abs(e.a)*s,a=n.start_angle_degrees*Math.PI/180,c=n.end_angle_degrees*Math.PI/180,l=i.x+r*Math.cos(a),u=i.y+r*Math.sin(a),h=i.x+r*Math.cos(c),d=i.y+r*Math.sin(c),_=n.end_angle_degrees-n.start_angle_degrees;n.direction==="clockwise"&&(_=-_),_<0&&(_+=360);let g=_>180?1:0,x=n.direction==="clockwise"?1:0;return[{name:"path",type:"element",attributes:{d:`M ${l} ${u} A ${r} ${r} 0 ${g} ${x} ${h} ${d}`,fill:"none",stroke:n.color,"stroke-width":o.toString(),...n.is_dashed&&{"stroke-dasharray":(o*3).toString()},"data-schematic-arc-id":n.schematic_arc_id,...n.schematic_component_id&&{"data-schematic-component-id":n.schematic_component_id}},children:[],value:""}]}function T8t(n){let e=[],t=i=>String(i).replace(/"/g,'\\"');for(let i of n){let s=`[data-subcircuit-connectivity-map-key="${t(i)}"]`,o=`g.trace${s}`,a=`g.trace-overlays${s}`,c=`:is(${o}, ${a}):hover`,l=`:is(${o}, ${a})`;e.push(`svg:has(${c}) ${l} { filter: invert(1); }`),e.push(`svg:has(${c}) ${a} .trace-crossing-outline { opacity: 0; }`)}return e.join(`
97
+ `)}function VA(n,e){let t=e8t(n),i=t.maxX-t.minX,r=t.maxY-t.minY,s=e?.width??1200,o=e?.height??600,a=e?.colorOverrides,c={...Ei,schematic:{...Ei.schematic,...a?.schematic??{}}},l=i/r,u=s/o,h;if(l>u){let tt=s/l;h={x:0,y:(o-tt)/2}}else{let tt=o*l;h={x:(s-tt)/2,y:0}}let d=mtt([{x:t.minX,y:t.maxY},{x:t.maxX,y:t.maxY},{x:t.maxX,y:t.minY}],[{x:h.x,y:h.y},{x:s-h.x,y:h.y},{x:s-h.x,y:o-h.y}]),_=[];if(_.push({name:"rect",type:"element",attributes:{class:"boundary",x:"0",y:"0",width:s.toString(),height:o.toString()},children:[],value:""}),e?.grid){let tt=typeof e.grid=="object"?e.grid:{};_.push(qRt({bounds:t,transform:d,...tt}))}let g=[],x=[],v=[],P=new Set,w=[],T=[],k=[],C=[],M=[],I=[],E=[],A=[],R=[],B=[];for(let tt of n)tt.type==="schematic_debug_object"?g.push(...f8t({debugObject:tt,transform:d})):tt.type==="schematic_component"?(x.push(...h8t({component:tt,transform:d,circuitJson:n,colorMap:c})),I.push(...aet({component:tt,transform:d,circuitJson:n}))):tt.type==="schematic_box"?C.push(...g8t({schematicBox:tt,transform:d,colorMap:c})):tt.type==="schematic_trace"?(v.push(...m8t({trace:tt,transform:d,colorMap:c})),P.add(tt.subcircuit_connectivity_map_key)):tt.type==="schematic_net_label"?w.push(...y8t({schNetLabel:tt,realToScreenTransform:d,colorMap:c})):tt.type==="schematic_text"&&!tt.schematic_component_id?T.push(oet({elm:tt,transform:d,colorMap:c})):tt.type==="schematic_voltage_probe"?k.push(...d8t({probe:tt,transform:d,colorMap:c})):tt.type==="schematic_table"?M.push(...x8t({schematicTable:tt,transform:d,colorMap:c,circuitJson:n})):tt.type==="schematic_line"?E.push(...S8t({schLine:tt,transform:d,colorMap:c})):tt.type==="schematic_circle"?A.push(...w8t({schCircle:tt,transform:d,colorMap:c})):tt.type==="schematic_rect"?R.push(...P8t({schRect:tt,transform:d,colorMap:c})):tt.type==="schematic_arc"&&B.push(...k8t({schArc:tt,transform:d,colorMap:c}));let j=v.filter(tt=>tt.attributes?.["data-layer"]!=="overlay"),U=v.filter(tt=>tt.attributes?.["data-layer"]==="overlay");_.push(...g,...j,...U,...E,...A,...R,...B,...x,...I,...w,...T,...C,...k,...M),e?.labeledPoints&&_.push(ZRt({points:e.labeledPoints,transform:d}));let V=fl(n),H=ml;if(e?.showErrorsInTextOverlay){let tt=$_(n);tt&&_.push(tt)}let et={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:s.toString(),height:o.toString(),style:`background-color: ${c.schematic.background}`,"data-real-to-screen-transform":htt(d),...V&&{"data-software-used-string":V},...e?.includeVersion&&{"data-circuit-to-svg-version":H}},children:[{name:"style",type:"element",children:[{type:"text",value:`
98
98
  .boundary { fill: ${c.schematic.background}; }
99
99
  .schematic-boundary { fill: none; stroke: #fff; }
100
100
  .component { fill: none; stroke: ${c.schematic.component_outline}; }
@@ -118,10 +118,10 @@ $1`).replace(/>(\s*)(?=<!--\s*\/)/g,"> ")}});var ott=ue(Fw=>{"use strict";var i6
118
118
  .pin-number { fill: ${c.schematic.pin_number}; }
119
119
  .port-label { fill: ${c.schematic.reference}; }
120
120
  .component-name { fill: ${c.schematic.reference}; }
121
- `,name:"",attributes:{},children:[]}],value:"",attributes:{}},..._],value:""};return(0,iet.stringify)(et)}function GA(n){return n?.type==="simulation_transient_voltage_graph"}function HA(n){return n?.type==="simulation_experiment"}function uet(n){return n?.type==="simulation_voltage_probe"}function pet({circuitJson:n,simulation_experiment_id:e,simulation_transient_voltage_graph_ids:t,width:i=E8t,height:r=C8t,includeVersion:s}){let o=t?new Set(t):null,a=n.find(I=>HA(I)&&I.simulation_experiment_id===e),c=n.filter(I=>GA(I)&&I.simulation_experiment_id===e&&(!o||o.has(I.simulation_transient_voltage_graph_id)));if(c.length===0)throw new Error(`No simulation_transient_voltage_graph elements found for simulation_experiment_id "${e}"`);let l=I8t(c,n),u=l.flatMap(I=>I.points);if(u.length===0)throw new Error(`simulation_transient_voltage_graph elements for simulation_experiment_id "${e}" do not contain any datapoints`);let h=Btt(u.map(I=>I.timeMs)),d=Btt(u.map(I=>I.voltage),!0),_=Math.max(1,i-Dn.left-Dn.right),g=Math.max(1,r-Dn.top-Dn.bottom),x=Ytt(h.domainMin,h.domainMax,Dn.left,Dn.left+_),v=Ytt(d.domainMin,d.domainMax,Dn.top+g,Dn.top),P=W8t(e),w=fl(n),T=ml,k=H8t(a,i),C=[L8t(),F8t(i,r),z8t(P,_,g),$8t(_,g),D8t({timeAxis:h,voltageAxis:d,scaleX:x,scaleY:v,plotWidth:_,plotHeight:g}),G8t(l,P,x,v),j8t({timeAxis:h,voltageAxis:d,scaleX:x,scaleY:v,plotWidth:_,plotHeight:g}),X8t(l,i),...k?[k]:[]],M=kn("svg",{xmlns:"http://www.w3.org/2000/svg",width:i.toString(),height:r.toString(),viewBox:`0 0 ${me(i)} ${me(r)}`,"data-simulation-experiment-id":e,...a?.name&&{"data-simulation-experiment-name":a.name},...w&&{"data-software-used-string":w},...s&&{"data-circuit-to-svg-version":T}},C);return(0,cet.stringify)(M)}function I8t(n,e){let t=Array.isArray(Mi.palette)?Mi.palette:[],i=e.filter(uet),r=new Map,s=new Map;for(let o of i)o.name&&o.source_component_id&&r.set(o.source_component_id,o.name),o.color&&o.source_component_id&&s.set(o.source_component_id,o.color);return n.map((o,a)=>{let c=N8t(o),l=t.length>0?t[a%t.length]:jtt,u=o.source_component_id?s.get(o.source_component_id):void 0,h=o.color??u??l??jtt,d=o.source_component_id?r.get(o.source_component_id):void 0,_=d?`V(${d})`:o.name||(o.source_component_id?`Probe ${o.source_component_id}`:o.simulation_transient_voltage_graph_id);return{graph:o,points:c,color:h,label:_}}).filter(o=>o.points.length>0)}function N8t(n){let e=A8t(n),t=Math.min(e.length,n.voltage_levels.length),i=[];for(let r=0;r<t;r++){let s=Number(e[r]??Number.NaN),o=Number(n.voltage_levels[r]??Number.NaN);!Number.isFinite(s)||!Number.isFinite(o)||i.push({timeMs:s,voltage:o})}return i}function A8t(n){if(Array.isArray(n.timestamps_ms)&&n.timestamps_ms.length===n.voltage_levels.length)return n.timestamps_ms.map(r=>Number(r));let e=n.voltage_levels.length;if(e===0)return[];let t=[];for(let r=0;r<e;r++)t.push(n.start_time_ms+n.time_per_step*r);let i=t.length>0?t[t.length-1]:void 0;return i!==void 0&&Number.isFinite(n.end_time_ms)&&Number.isFinite(i)&&Math.abs(i-n.end_time_ms)>n.time_per_step/2&&t.push(n.end_time_ms),t}function Btt(n,e=!1){if(n.length===0)return{domainMin:0,domainMax:1,ticks:[0,1]};let t=Math.min(...n),i=Math.max(...n);if(t===i){let c=t===0?1:Math.abs(t)*.1||1;return{domainMin:t-c,domainMax:t+c,ticks:[t-c,t,t+c]}}let r=R8t(t,i),s=r.length>0?[...r]:[t,i],o=s[0],a=s[s.length-1];if(e&&s.length>1){let c=Math.abs(s[1]-s[0]),l=.1;t<o+c*l&&(o-=c,s.unshift(o)),i>a-c*l&&(a+=c,s.push(a))}return{domainMin:o,domainMax:a,ticks:s}}function R8t(n,e,t=6){let i=e-n;if(!Number.isFinite(i)||i<=Number.EPSILON)return[n,e];let r=O8t(i/Math.max(1,t-1)),s=Math.floor(n/r)*r,o=Math.ceil(e/r)*r,a=[];for(let c=s;c<=o+r/2;c+=r)a.push(Number.parseFloat(c.toPrecision(12)));return a}function O8t(n){if(!Number.isFinite(n)||n<=0)return 1;let e=Math.floor(Math.log10(n)),t=n/Math.pow(10,e),i;return t<=1?i=1:t<=2?i=2:t<=5?i=5:i=10,i*Math.pow(10,e)}function Ytt(n,e,t,i){if(!Number.isFinite(n)||!Number.isFinite(e)){let s=(t+i)/2;return()=>s}let r=e-n;if(Math.abs(r)<Number.EPSILON){let s=(t+i)/2;return()=>s}return s=>t+(s-n)/r*(i-t)}function L8t(){let n=`
121
+ `,name:"",attributes:{},children:[]}],value:"",attributes:{}},..._],value:""};return(0,iet.stringify)(et)}function GA(n){return n?.type==="simulation_transient_voltage_graph"}function HA(n){return n?.type==="simulation_experiment"}function uet(n){return n?.type==="simulation_voltage_probe"}function pet({circuitJson:n,simulation_experiment_id:e,simulation_transient_voltage_graph_ids:t,width:i=E8t,height:r=C8t,includeVersion:s}){let o=t?new Set(t):null,a=n.find(I=>HA(I)&&I.simulation_experiment_id===e),c=n.filter(I=>GA(I)&&I.simulation_experiment_id===e&&(!o||o.has(I.simulation_transient_voltage_graph_id)));if(c.length===0)throw new Error(`No simulation_transient_voltage_graph elements found for simulation_experiment_id "${e}"`);let l=I8t(c,n),u=l.flatMap(I=>I.points);if(u.length===0)throw new Error(`simulation_transient_voltage_graph elements for simulation_experiment_id "${e}" do not contain any datapoints`);let h=Btt(u.map(I=>I.timeMs)),d=Btt(u.map(I=>I.voltage),!0),_=Math.max(1,i-Dn.left-Dn.right),g=Math.max(1,r-Dn.top-Dn.bottom),x=Ytt(h.domainMin,h.domainMax,Dn.left,Dn.left+_),v=Ytt(d.domainMin,d.domainMax,Dn.top+g,Dn.top),P=W8t(e),w=fl(n),T=ml,k=H8t(a,i),C=[L8t(),F8t(i,r),z8t(P,_,g),$8t(_,g),D8t({timeAxis:h,voltageAxis:d,scaleX:x,scaleY:v,plotWidth:_,plotHeight:g}),G8t(l,P,x,v),j8t({timeAxis:h,voltageAxis:d,scaleX:x,scaleY:v,plotWidth:_,plotHeight:g}),X8t(l,i),...k?[k]:[]],M=kn("svg",{xmlns:"http://www.w3.org/2000/svg",width:i.toString(),height:r.toString(),viewBox:`0 0 ${me(i)} ${me(r)}`,"data-simulation-experiment-id":e,...a?.name&&{"data-simulation-experiment-name":a.name},...w&&{"data-software-used-string":w},...s&&{"data-circuit-to-svg-version":T}},C);return(0,cet.stringify)(M)}function I8t(n,e){let t=Array.isArray(Ei.palette)?Ei.palette:[],i=e.filter(uet),r=new Map,s=new Map;for(let o of i)o.name&&o.source_component_id&&r.set(o.source_component_id,o.name),o.color&&o.source_component_id&&s.set(o.source_component_id,o.color);return n.map((o,a)=>{let c=N8t(o),l=t.length>0?t[a%t.length]:jtt,u=o.source_component_id?s.get(o.source_component_id):void 0,h=o.color??u??l??jtt,d=o.source_component_id?r.get(o.source_component_id):void 0,_=d?`V(${d})`:o.name||(o.source_component_id?`Probe ${o.source_component_id}`:o.simulation_transient_voltage_graph_id);return{graph:o,points:c,color:h,label:_}}).filter(o=>o.points.length>0)}function N8t(n){let e=A8t(n),t=Math.min(e.length,n.voltage_levels.length),i=[];for(let r=0;r<t;r++){let s=Number(e[r]??Number.NaN),o=Number(n.voltage_levels[r]??Number.NaN);!Number.isFinite(s)||!Number.isFinite(o)||i.push({timeMs:s,voltage:o})}return i}function A8t(n){if(Array.isArray(n.timestamps_ms)&&n.timestamps_ms.length===n.voltage_levels.length)return n.timestamps_ms.map(r=>Number(r));let e=n.voltage_levels.length;if(e===0)return[];let t=[];for(let r=0;r<e;r++)t.push(n.start_time_ms+n.time_per_step*r);let i=t.length>0?t[t.length-1]:void 0;return i!==void 0&&Number.isFinite(n.end_time_ms)&&Number.isFinite(i)&&Math.abs(i-n.end_time_ms)>n.time_per_step/2&&t.push(n.end_time_ms),t}function Btt(n,e=!1){if(n.length===0)return{domainMin:0,domainMax:1,ticks:[0,1]};let t=Math.min(...n),i=Math.max(...n);if(t===i){let c=t===0?1:Math.abs(t)*.1||1;return{domainMin:t-c,domainMax:t+c,ticks:[t-c,t,t+c]}}let r=R8t(t,i),s=r.length>0?[...r]:[t,i],o=s[0],a=s[s.length-1];if(e&&s.length>1){let c=Math.abs(s[1]-s[0]),l=.1;t<o+c*l&&(o-=c,s.unshift(o)),i>a-c*l&&(a+=c,s.push(a))}return{domainMin:o,domainMax:a,ticks:s}}function R8t(n,e,t=6){let i=e-n;if(!Number.isFinite(i)||i<=Number.EPSILON)return[n,e];let r=O8t(i/Math.max(1,t-1)),s=Math.floor(n/r)*r,o=Math.ceil(e/r)*r,a=[];for(let c=s;c<=o+r/2;c+=r)a.push(Number.parseFloat(c.toPrecision(12)));return a}function O8t(n){if(!Number.isFinite(n)||n<=0)return 1;let e=Math.floor(Math.log10(n)),t=n/Math.pow(10,e),i;return t<=1?i=1:t<=2?i=2:t<=5?i=5:i=10,i*Math.pow(10,e)}function Ytt(n,e,t,i){if(!Number.isFinite(n)||!Number.isFinite(e)){let s=(t+i)/2;return()=>s}let r=e-n;if(Math.abs(r)<Number.EPSILON){let s=(t+i)/2;return()=>s}return s=>t+(s-n)/r*(i-t)}function L8t(){let n=`
122
122
  :root { color-scheme: light; }
123
123
  svg { font-family: 'Inter', 'Helvetica Neue', Arial, sans-serif; }
124
- .background { fill: ${Mi.schematic.background}; }
124
+ .background { fill: ${Ei.schematic.background}; }
125
125
  .plot-background { fill: #ffffff; }
126
126
  .grid-line { stroke: rgba(0, 0, 0, 0.08); stroke-width: 1; }
127
127
  .axis { stroke: rgba(0, 0, 0, 0.6); stroke-width: 1.5; }
@@ -133,8 +133,8 @@ svg { font-family: 'Inter', 'Helvetica Neue', Arial, sans-serif; }
133
133
  .simulation-line { fill: none; stroke-width: 2.5; }
134
134
  .simulation-point { stroke-width: 0; }
135
135
  .chart-title { fill: rgba(0, 0, 0, 0.85); font-size: 18px; font-weight: 600; }
136
- `;return kn("style",{},[Id(n)])}function F8t(n,e){return kn("rect",{class:"background",x:"0",y:"0",width:me(n),height:me(e)})}function z8t(n,e,t){return kn("defs",{},[kn("clipPath",{id:n},[kn("rect",{x:me(Dn.left),y:me(Dn.top),width:me(e),height:me(t)})])])}function $8t(n,e){return kn("rect",{class:"plot-background",x:me(Dn.left),y:me(Dn.top),width:me(n),height:me(e)})}function D8t({timeAxis:n,voltageAxis:e,scaleX:t,scaleY:i,plotWidth:r,plotHeight:s}){let o=Dn.top,a=Dn.top+s,c=Dn.left,l=Dn.left+r,u=[];for(let h of n.ticks){let d=me(t(h));u.push(kn("line",{class:"grid-line grid-line-x",x1:d,y1:me(o),x2:d,y2:me(a)}))}for(let h of e.ticks){let d=me(i(h));u.push(kn("line",{class:"grid-line grid-line-y",x1:me(c),y1:d,x2:me(l),y2:d}))}return kn("g",{class:"grid"},u)}function j8t({timeAxis:n,voltageAxis:e,scaleX:t,scaleY:i,plotWidth:r,plotHeight:s}){let o=Dn.top+s,a=Dn.left,c=Dn.left+r,l=[kn("line",{class:"axis axis-x",x1:me(a),y1:me(o),x2:me(c),y2:me(o)}),kn("line",{class:"axis axis-y",x1:me(a),y1:me(Dn.top),x2:me(a),y2:me(o)})];for(let u of n.ticks){let h=me(t(u));l.push(kn("line",{class:"axis-tick axis-tick-x",x1:h,y1:me(o),x2:h,y2:me(o+6)})),l.push(kn("text",{class:"axis-label axis-label-x",x:h,y:me(o+22),"text-anchor":"middle"},[Id(Xtt(u,n.ticks))]))}for(let u of e.ticks){let h=me(i(u));l.push(kn("line",{class:"axis-tick axis-tick-y",x1:me(a-6),y1:h,x2:me(a),y2:h})),l.push(kn("text",{class:"axis-label axis-label-y",x:me(a-10),y:h,"text-anchor":"end","dominant-baseline":"middle"},[Id(Xtt(u,e.ticks))]))}return l.push(kn("text",{class:"axis-title axis-title-x",x:me(a+r/2),y:me(o+48),"text-anchor":"middle"},[Id("Time (ms)")]),kn("text",{class:"axis-title axis-title-y",x:me(a-64),y:me(Dn.top+s/2),transform:`rotate(-90 ${me(a-64)} ${me(Dn.top+s/2)})`,"text-anchor":"middle"},[Id("Voltage (V)")])),kn("g",{class:"axes"},l)}function X8t(n,e){let t=Dn.top,i=n.map(r=>{let s=e-Dn.right+10,o=U8t(r.label),a=V8t(r,s,t,o),c=o.length*het;return t+=Math.max(c,Y8t),a});return kn("g",{class:"legend"},i)}function U8t(n){let e=n.split("_");if(e.length<=1)return[n];let t=[],i=e[0]??"";for(let r=1;r<e.length;r++){let s=e[r]??"",o=i+"_"+s;o.length>B8t?(t.push(i),i=s):i=o}return i&&t.push(i),t}function V8t(n,e,t,i){let r=i.map((s,o)=>kn("tspan",{x:"20",dy:o===0?"0":String(het)},[Id(s)]));return kn("g",{class:"legend-item",transform:`translate(${me(e)} ${me(t)})`},[kn("line",{class:"legend-line",x1:"0",y1:"0",x2:"16",y2:"0",stroke:n.color}),kn("text",{class:"legend-label",x:"20",y:"0","dominant-baseline":"middle"},r)])}function G8t(n,e,t,i){let s=[4,8],o=s.map(d=>me(d)).join(" "),c=s.reduce((d,_)=>d+_,0)/3,l=[];n.forEach((d,_)=>{if(d.points.length===0)return;let g=[];d.points.forEach((P,w)=>{let T=me(t(P.timeMs)),k=me(i(P.voltage));g.push(`${w===0?"M":"L"} ${T} ${k}`)});let x={class:"simulation-line",d:g.join(" "),stroke:d.color,"clip-path":`url(#${e})`,"data-simulation-transient-voltage-graph-id":d.graph.simulation_transient_voltage_graph_id};d.graph.source_component_id&&(x["data-source-component-id"]=d.graph.source_component_id),d.graph.subcircuit_connectivity_map_key&&(x["data-subcircuit-connectivity-map-key"]=d.graph.subcircuit_connectivity_map_key);let v=d.points.map(P=>{let w=me(t(P.timeMs)),T=me(i(P.voltage));return kn("circle",{class:"simulation-point",cx:w,cy:T,r:"2.5",fill:d.color,"clip-path":`url(#${e})`})});l.push({entry:d,graphIndex:_,pathAttributes:x,pointElements:v})});let u=[];for(let d=0;d<3;d++)l.forEach(_=>{let g=(_.graphIndex+d)%3,x=me(g*c);u.push(kn("path",{..._.pathAttributes,"stroke-dasharray":o,"stroke-dashoffset":x}))});let h=l.flatMap(d=>d.pointElements);return kn("g",{class:"data-series"},[...u,...h])}function H8t(n,e){return n?.name?kn("text",{class:"chart-title",x:me(e/2),y:me(Dn.top-40),"text-anchor":"middle"},[Id(n.name)]):null}function W8t(n){return`simulation-graph-${n.replace(/[^a-zA-Z0-9_-]+/g,"-")}`}function me(n){if(!Number.isFinite(n))return"0";let e=Number.parseFloat(n.toFixed(6));return Number.isInteger(e),e.toString()}function Xtt(n,e){if(e.length<=1)return me(n);let t=e[e.length-1]-e[0];if(!Number.isFinite(t)||t===0)return me(n);let i=t>=100?0:t>=10?1:t>=1?2:3,r=Math.pow(10,i);return(Math.round(n*r)/r).toFixed(i).replace(/\.0+$/,"").replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function kn(n,e,t=[]){return{name:n,type:"element",value:"",attributes:e,children:t}}function Id(n){return{name:"",type:"text",value:n,attributes:{},children:[]}}function K8t({circuitJson:n,simulation_experiment_id:e,simulation_transient_voltage_graph_ids:t,width:i=q8t,height:r=Z8t,schematicHeightRatio:s=det,schematicOptions:o,includeVersion:a,showErrorsInTextOverlay:c}){let l=n.filter(E=>!HA(E)&&!GA(E)),u=J8t(s),h=Math.max(1,r*u),d=Math.max(1,r-h),_=h+d,g=_===0?1:r/_,x=h*g,v=d*g,P=VA(l,{...o,width:i,height:x,includeVersion:!1,showErrorsInTextOverlay:c}),w=pet({circuitJson:n,simulation_experiment_id:e,simulation_transient_voltage_graph_ids:t,width:i,height:v,includeVersion:!1}),T=Vtt((0,L1.parseSync)(P)),k=Vtt((0,L1.parseSync)(w)),C=[];C.push(Utt(T,0,0,i,x)),C.push(Utt(k,0,x,i,v));let M=fl(l),I={name:"svg",type:"element",value:"",attributes:{xmlns:"http://www.w3.org/2000/svg",width:dl(i),height:dl(r),viewBox:`0 0 ${dl(i)} ${dl(r)}`,"data-simulation-experiment-id":e,...M&&{"data-software-used-string":M},...a&&{"data-circuit-to-svg-version":ml}},children:C};return(0,L1.stringify)(I)}function Utt(n,e,t,i,r){let s=fet(n);return s.attributes={...s.attributes,x:dl(e),y:dl(t),width:dl(i),height:dl(r)},delete s.attributes.xmlns,s}function Vtt(n){if(n.type!=="element")throw new Error("Expected SVG root element to be of type 'element'");return n}function fet(n){return{...n,attributes:{...n.attributes??{}},children:n.children?.map(fet)??[]}}function J8t(n){return Number.isFinite(n)?n<=0?0:n>=1?1:n:det}function dl(n){if(!Number.isFinite(n))return"0";let e=Number.parseFloat(n.toFixed(6));return Number.isInteger(e),e.toString()}function Q8t(n,e){let{transform:t,layer:i}=e;if(i&&n.layer!==i)return[];let[r,s]=st(t,[n.x,n.y]);if(n.shape==="rect"||n.shape==="rotated_rect"){let o=n.width*Math.abs(t.a),a=n.height*Math.abs(t.d);return n.shape==="rotated_rect"&&n.ccw_rotation?[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:jw(n.layer),x:(-o/2).toString(),y:(-a/2).toString(),width:o.toString(),height:a.toString(),transform:`translate(${r} ${s}) rotate(${-n.ccw_rotation})`,"data-type":"pcb_solder_paste","data-pcb-layer":n.layer}}]:[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:jw(n.layer),x:(r-o/2).toString(),y:(s-a/2).toString(),width:o.toString(),height:a.toString(),"data-type":"pcb_solder_paste","data-pcb-layer":n.layer}}]}if(n.shape==="pill"){let o=n.width*Math.abs(t.a),a=n.height*Math.abs(t.d),c=n.radius*Math.abs(t.a);return[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:jw(n.layer),x:(r-o/2).toString(),y:(s-a/2).toString(),width:o.toString(),height:a.toString(),rx:c.toString(),"data-type":"pcb_solder_paste","data-pcb-layer":n.layer}}]}if(n.shape==="circle"){let o=n.radius*Math.abs(t.a);return[{name:"circle",type:"element",attributes:{class:"pcb-solder-paste",fill:jw(n.layer),cx:r.toString(),cy:s.toString(),r:o.toString(),"data-type":"pcb_solder_paste","data-pcb-layer":n.layer}}]}}function tOt(n,e){let t=Number.POSITIVE_INFINITY,i=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY,o=n.filter(R=>R.type==="pcb_board"||R.type==="pcb_panel"||R.type==="pcb_solder_paste"&&R.layer===e.layer);for(let R of o)if(R.type==="pcb_board")R.outline&&Array.isArray(R.outline)&&R.outline.length>=3?A(R.outline):"center"in R&&"width"in R&&"height"in R&&E(R.center,R.width,R.height);else if(R.type==="pcb_panel"){let B=R,j=Y.parse(B.width),U=Y.parse(B.height);if(j!==void 0&&U!==void 0){let V=B.center??{x:j/2,y:U/2};E(V,j,U)}}else R.type==="pcb_solder_paste"&&"x"in R&&"y"in R&&E({x:R.x,y:R.y},0,0);let a=1,c=r-t+2*a,l=s-i+2*a,u=e.width??800,h=e.height??600,d=u/c,_=h/l,g=Math.min(d,_),x=(u-c*g)/2,v=(h-l*g)/2,P=Fe(yn(x-t*g+a*g,h-v+i*g-a*g),ki(g,-g)),w={transform:P,layer:e.layer,colorMap:Ti},T=o.sort((R,B)=>(Gtt.indexOf(B.type)??9999)-(Gtt.indexOf(R.type)??9999)).flatMap(R=>eOt({elm:R,ctx:w})),k=fl(n),C=ml,M=[{name:"style",type:"element",children:[{type:"text",value:""}]},{name:"rect",type:"element",attributes:{class:"boundary",x:"0",y:"0",fill:"#000",width:u.toString(),height:h.toString()}},nOt(P,t,i,r,s),...T].filter(R=>R!==null);if(e?.showErrorsInTextOverlay){let R=$_(n);R&&M.push(R)}let I={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:u.toString(),height:h.toString(),...k&&{"data-software-used-string":k},...e.includeVersion&&{"data-circuit-to-svg-version":C}},value:"",children:M};try{return(0,met.stringify)(I)}catch(R){throw console.error("Error stringifying SVG object:",R),R}function E(R,B,j){let U=B/2,V=j/2;t=Math.min(t,R.x-U),i=Math.min(i,R.y-V),r=Math.max(r,R.x+U),s=Math.max(s,R.y+V)}function A(R){for(let B of R)t=Math.min(t,B.x),i=Math.min(i,B.y),r=Math.max(r,B.x),s=Math.max(s,B.y)}}function eOt({elm:n,ctx:e}){let{transform:t}=e;switch(n.type){case"pcb_board":return Wtt(n,e);case"pcb_solder_paste":return Q8t(n,e);default:return[]}}function nOt(n,e,t,i,r){let[s,o]=st(n,[e,t]),[a,c]=st(n,[i,r]),l=Math.abs(a-s),u=Math.abs(c-o),h=Math.min(s,a),d=Math.min(o,c);return{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-boundary",fill:"none",stroke:"#fff","stroke-width":"0.3",x:h.toString(),y:d.toString(),width:l.toString(),height:u.toString()}}}var Htt,Ofe,Yfe,Ktt,Jtt,iet,xme,kme,L1,cet,met,f6t,m6t,Mi,x6t,v6t,S6t,P6t,T6t,Ti,Pfe,kfe,Tfe,Mfe,F6t,Y6t,X6t,H6t,Ttt,Mtt,Ls,Ett,qtt,O_,Bw,Ctt,Z6t,K6t,J6t,Q6t,sRt,oRt,cRt,ml,lRt,Itt,fRt,Yw,_Rt,z_,Ya,DA,E1,C1,I1,Att,ERt,CRt,NRt,ARt,jA,N1,A1,R1,Rtt,Ott,zRt,$Rt,DRt,Qtt,BRt,YRt,tet,eet,XA,net,XRt,URt,Ftt,ztt,Xw,ret,D_,hl,L_,F_,KRt,JRt,Ui,n8t,i8t,UA,set,s8t,o8t,O1,$tt,a8t,c8t,Dtt,l8t,u8t,oet,p8t,_8t,y8t,g8t,x8t,b8t,v8t,aet,M8t,E8t,C8t,Dn,jtt,B8t,het,Y8t,q8t,Z8t,det,Gtt,yet=qt(()=>{"use strict";St();Htt=Gt(os(),1);Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();er();Ofe=Gt(os(),1);Yt();Ae();er();Ae();Yt();Yt();Yt();Yfe=Gt(os(),1);Yt();Yt();Yt();Ktt=Gt(os(),1);Ae();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Jtt=Gt(os(),1);Yt();Yt();Ae();Ae();Yt();Yt();Yt();Yt();Yt();Ag();Yt();Ae();iet=Gt(os(),1);Yt();Yt();Yt();Yt();Ta();Ae();Ta();xme=Gt(os(),1);Yt();Yt();Yt();Ae();Ta();kme=Gt(os(),1);Yt();Yt();Ae();Yt();Ae();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Ta();Yt();Yt();Ae();Yt();Yt();Yt();Yt();Yt();L1=Gt(os(),1),cet=Gt(os(),1);St();met=Gt(os(),1);Yt();Yt();f6t="rgba(255,255,255,0.5)",m6t="rgba(255,255,255,0.2)";Mi={"3d_viewer":{background_bottom:"rgb(102, 102, 128)",background_top:"rgb(204, 204, 230)",board:"rgb(51, 43, 23)",copper:"rgb(179, 156, 0)",silkscreen_bottom:"rgb(230, 230, 230)",silkscreen_top:"rgb(230, 230, 230)",soldermask:"rgb(20, 51, 36)",solderpaste:"rgb(128, 128, 128)"},board:{anchor:"rgb(255, 38, 226)",aux_items:"rgb(255, 255, 255)",b_adhes:"rgb(0, 0, 132)",b_crtyd:"rgb(255, 38, 226)",b_fab:"rgb(88, 93, 132)",b_mask:"rgba(2, 255, 238, 0.400)",b_paste:"rgb(0, 194, 194)",b_silks:"rgb(232, 178, 167)",background:"rgb(0, 16, 35)",cmts_user:"rgb(89, 148, 220)",copper:{b:"rgb(77, 127, 196)",f:"rgb(200, 52, 52)",in1:"rgb(127, 200, 127)",in10:"rgb(237, 124, 51)",in11:"rgb(91, 195, 235)",in12:"rgb(247, 111, 142)",in13:"rgb(167, 165, 198)",in14:"rgb(40, 204, 217)",in15:"rgb(232, 178, 167)",in16:"rgb(242, 237, 161)",in17:"rgb(237, 124, 51)",in18:"rgb(91, 195, 235)",in19:"rgb(247, 111, 142)",in2:"rgb(206, 125, 44)",in20:"rgb(167, 165, 198)",in21:"rgb(40, 204, 217)",in22:"rgb(232, 178, 167)",in23:"rgb(242, 237, 161)",in24:"rgb(237, 124, 51)",in25:"rgb(91, 195, 235)",in26:"rgb(247, 111, 142)",in27:"rgb(167, 165, 198)",in28:"rgb(40, 204, 217)",in29:"rgb(232, 178, 167)",in3:"rgb(79, 203, 203)",in30:"rgb(242, 237, 161)",in4:"rgb(219, 98, 139)",in5:"rgb(167, 165, 198)",in6:"rgb(40, 204, 217)",in7:"rgb(232, 178, 167)",in8:"rgb(242, 237, 161)",in9:"rgb(141, 203, 129)"},cursor:"rgb(255, 255, 255)",drc:"rgb(194, 194, 194)",drc_error:"rgba(215, 91, 107, 0.800)",drc_exclusion:"rgb(255, 255, 255)",drc_warning:"rgba(255, 208, 66, 0.902)",dwgs_user:"rgb(194, 194, 194)",eco1_user:"rgb(180, 219, 210)",eco2_user:"rgb(216, 200, 82)",edge_cuts:"rgb(208, 210, 205)",f_adhes:"rgb(132, 0, 132)",f_crtyd:"rgb(255, 0, 245)",f_fab:"rgb(175, 175, 175)",f_mask:"rgba(216, 100, 255, 0.400)",f_paste:"rgba(180, 160, 154, 0.902)",f_silks:"rgb(242, 237, 161)",footprint_text_back:"rgb(0, 0, 132)",footprint_text_front:"rgb(194, 194, 194)",footprint_text_invisible:"rgb(132, 132, 132)",grid:"rgb(132, 132, 132)",grid_axes:"rgb(194, 194, 194)",margin:"rgb(255, 38, 226)",microvia:"rgb(0, 132, 132)",no_connect:"rgb(0, 0, 132)",pad_back:"rgb(77, 127, 196)",pad_front:"rgb(200, 52, 52)",pad_plated_hole:"rgb(194, 194, 0)",pad_through_hole:"rgb(227, 183, 46)",plated_hole:"rgb(26, 196, 210)",ratsnest:"rgba(245, 255, 213, 0.702)",select_overlay:"rgb(4, 255, 67)",through_via:"rgb(236, 236, 236)",user_1:"rgb(194, 194, 194)",user_2:"rgb(89, 148, 220)",user_3:"rgb(180, 219, 210)",user_4:"rgb(216, 200, 82)",user_5:"rgb(194, 194, 194)",user_6:"rgb(89, 148, 220)",user_7:"rgb(180, 219, 210)",user_8:"rgb(216, 200, 82)",user_9:"rgb(232, 178, 167)",via_blind_buried:"rgb(187, 151, 38)",via_hole:"rgb(227, 183, 46)",via_micro:"rgb(0, 132, 132)",via_through:"rgb(236, 236, 236)",worksheet:"rgb(200, 114, 171)"},gerbview:{axes:"rgb(0, 0, 132)",background:"rgb(0, 0, 0)",dcodes:"rgb(255, 255, 255)",grid:"rgb(132, 132, 132)",layers:["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)","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)","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)","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)"],negative_objects:"rgb(132, 132, 132)",worksheet:"rgb(0, 0, 132)"},meta:{filename:"kicad_2020",name:"KiCad 2020",version:2},palette:["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)"],schematic:{aux_items:"rgb(46, 46, 46)",background:"rgb(245, 241, 237)",brightened:"rgb(255, 0, 255)",bus:"rgb(0, 0, 132)",bus_junction:"rgb(0, 0, 132)",component_body:"rgb(255, 255, 194)",component_outline:"rgb(132, 0, 0)",cursor:"rgb(15, 15, 15)",erc_error:"rgba(230, 9, 13, 0.800)",erc_warning:"rgba(209, 146, 0, 0.800)",fields:"rgb(132, 0, 132)",grid:"rgb(181, 181, 181)",grid_axes:"rgb(0, 0, 132)",hidden:"rgb(194, 194, 194)",junction:"rgb(0, 150, 0)",label_global:"rgb(132, 0, 0)",label_background:"rgba(255, 255, 255, 0.6)",label_hier:"rgb(114, 86, 0)",label_local:"rgb(15, 15, 15)",net_name:"rgb(132, 132, 132)",no_connect:"rgb(0, 0, 132)",note:"rgb(0, 0, 194)",override_item_colors:!1,pin:"rgb(132, 0, 0)",pin_name:"rgb(0, 100, 100)",pin_number:"rgb(169, 0, 0)",reference:"rgb(0, 100, 100)",shadow:"rgba(102, 179, 255, 0.800)",sheet:"rgb(132, 0, 0)",sheet_background:"rgba(253, 255, 231, 0.000)",sheet_fields:"rgb(132, 0, 132)",sheet_filename:"rgb(114, 86, 0)",sheet_label:"rgb(0, 100, 100)",sheet_name:"rgb(0, 100, 100)",table:"rgb(102, 102, 102)",value:"rgb(0, 100, 100)",wire:"rgb(0, 150, 0)",wire_crossing:"rgb(30, 180, 30)",worksheet:"rgb(132, 0, 0)"}};x6t=Mi.board.user_2;v6t=Mi.board.user_2,S6t=Mi.board.user_2;P6t=Mi.board.user_2;T6t=Mi.board.user_2;Ti={copper:{top:"rgb(200, 52, 52)",inner1:"rgb(255, 140, 0)",inner2:"rgb(255, 215, 0)",inner3:"rgb(50, 205, 50)",inner4:"rgb(64, 224, 208)",inner5:"rgb(138, 43, 226)",inner6:"rgb(255, 105, 180)",bottom:"rgb(77, 127, 196)"},soldermaskWithCopperUnderneath:{top:"rgb(18, 82, 50)",bottom:"rgb(77, 127, 196)"},soldermask:{top:"rgb(12, 55, 33)",bottom:"rgb(52, 87, 136)"},substrate:"rgb(201, 162, 110)",drill:"#FF26E2",silkscreen:{top:"#f2eda1",bottom:"#5da9e9"},boardOutline:"rgba(255, 255, 255, 0.5)",courtyard:"#FF00FF",debugComponent:{fill:null,stroke:null}},Pfe=Ti.drill,kfe=Ti.silkscreen.top,Tfe=Ti.silkscreen.bottom,Mfe={...Ti.copper};F6t={bottom:"rgb(105, 105, 105)",top:"rgb(105, 105, 105)"};Y6t=(n,e)=>{let t=Ee(e).pcb_smtpad.get(n);if(t&&"x"in t&&"y"in t)return{x:t.x,y:t.y};let i=Ee(e).pcb_plated_hole.get(n);return i&&"x"in i&&"y"in i?{x:i.x,y:i.y}:null},X6t=(n,e,t,i)=>{let r=t.getIdsConnectedToNet(e),s=null,o=1/0;for(let a of r){let c=Y6t(a,i);if(c){let l=n.x-c.x,u=n.y-c.y,h=Math.sqrt(l*l+u*u);h>0&&h<o&&(o=h,s=c)}}return s};H6t="rgba(255, 255, 255, 0.5)",Ttt="pcb-grid-pattern";Mtt=.01,Ls=4,Ett=8,qtt=11,O_=1,Bw=5,Ctt=1.5,Z6t=15,K6t=10,J6t=.2,Q6t=50;sRt="rgba(100, 200, 255, 0.6)",oRt=.1;cRt={name:"circuit-to-svg",type:"module",version:"0.0.279",description:"Convert Circuit JSON to SVG",main:"dist/index.js",files:["dist"],scripts:{start:"cosmos",prepublish:"npm run build",build:"tsup-node ./lib/index.ts --format esm --dts --sourcemap --external tscircuit",format:"biome format . --write","format:check":"biome format .",cosmos:"cosmos","cosmos-export":"cosmos-export"},license:"ISC",devDependencies:{"@biomejs/biome":"^1.9.4","@types/bun":"^1.2.8","@vitejs/plugin-react":"5.0.0",biome:"^0.3.3","bun-match-svg":"^0.0.12",esbuild:"^0.20.2","performance-now":"^2.1.0","circuit-json":"^0.0.319",react:"19.1.0","react-cosmos":"7.0.0","react-cosmos-plugin-vite":"7.0.0","react-dom":"19.1.0",tscircuit:"^0.0.937",tsup:"^8.0.2",typescript:"^5.4.5","vite-tsconfig-paths":"^5.0.1"},dependencies:{"@types/node":"^22.5.5","bun-types":"^1.1.40","calculate-elbow":"0.0.12",svgson:"^5.3.1","transformation-matrix":"^2.16.1"}},ml=cRt.version,lRt={pcb_background:0,pcb_boundary:1,pcb_panel:5,pcb_board:10,pcb_cutout:15,pcb_hole:18,pcb_plated_hole_drill:19,pcb_plated_hole:20,pcb_trace_soldermask:25,pcb_trace:30,pcb_smtpad:30,pcb_copper_pour:35,pcb_via:36,pcb_soldermask:40,pcb_soldermask_opening:41,pcb_solder_paste:45,pcb_silkscreen_text:50,pcb_silkscreen_path:50,pcb_silkscreen_rect:50,pcb_silkscreen_circle:50,pcb_silkscreen_line:50,pcb_component:60,pcb_fabrication_note_text:70,pcb_fabrication_note_path:70,pcb_fabrication_note_rect:70,pcb_fabrication_note_dimension:70,pcb_note_dimension:70,pcb_note_text:70,pcb_note_rect:70,pcb_note_path:70,pcb_note_line:70,pcb_trace_error:80,pcb_rats_nest:85},Itt=100;fRt=Ztt,Yw={fill:"none",stroke:"rgb(0,0,0)",strokeOpacity:"0.8",strokeWidthFactor:.2};_Rt={pin_number:.15,negated_pin_number:.15*.8,reference_designator:.18,manufacturer_number:.18,net_label:.18,error:.05},z_=(n,e)=>e??_Rt[n],Ya=(n,e,t)=>Math.abs(n.a)*z_(e,t);DA="rgb(190, 190, 190)";E1="rgb(210, 210, 210)",C1="rgb(190, 190, 190)";I1="rgb(210, 210, 210)";Att=["pcb_component","pcb_smtpad","pcb_hole","pcb_plated_hole","pcb_board"];ERt="rgb(26, 115, 143)",CRt="rgba(0,0,0,0.9)";NRt="rgba(120, 120, 120, 0.6)",ARt="rgba(255, 255, 255, 0.9)";jA="rgb(50, 50, 50)";N1="rgb(218, 165, 32)",A1="rgb(40, 40, 40)";R1="rgb(218, 165, 32)";Rtt="rgb(255, 255, 255)",Ott="rgb(0, 0, 0)",zRt="rgba(0, 0, 0, 0.6)",$Rt="rgb(200, 200, 200)",DRt="rgb(0, 0, 0)";Qtt=1.6,BRt=11/21,YRt=.6,tet=.1,eet=.1,XA=3,net=.1,XRt=.8;URt=({left_labels:n,right_labels:e,transform:t,soup:i,board_bounds:r,svgWidth:s,svgHeight:o,styleScale:a})=>{let c=new Map,l={transform:t,soup:i,board_bounds:r};return Ltt("left",n,{...l,svgHeight:o,styleScale:a},c),Ltt("right",e,{...l,svgHeight:o,styleScale:a},c),c};Ftt=["pcb_board","pcb_smtpad","pcb_hole","pcb_plated_hole","pcb_component","pcb_port"];ztt={0:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},1:{width:13,height:27,ascent:22,descent:5,left:-3,right:9},2:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},3:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},4:{width:13,height:27,ascent:22,descent:5,left:0,right:12},5:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},6:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},7:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},8:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},9:{width:13,height:27,ascent:22,descent:5,left:-1,right:12}," ":{width:7,height:27,ascent:22,descent:5,left:0,right:0},"!":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},'"':{width:9,height:27,ascent:22,descent:5,left:-1,right:7},"#":{width:13,height:27,ascent:22,descent:5,left:0,right:13},$:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},"%":{width:21,height:27,ascent:22,descent:5,left:-1,right:20},"&":{width:16,height:27,ascent:22,descent:5,left:-1,right:15},"'":{width:5,height:27,ascent:22,descent:5,left:-1,right:3},"(":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},")":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},"*":{width:9,height:27,ascent:22,descent:5,left:-1,right:8},"+":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},",":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},"-":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},".":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},"/":{width:7,height:27,ascent:22,descent:5,left:0,right:7},":":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},";":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},"<":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},"=":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},">":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},"?":{width:13,height:27,ascent:22,descent:5,left:-1,right:12},"@":{width:24,height:27,ascent:22,descent:5,left:-1,right:23},A:{width:16,height:27,ascent:22,descent:5,left:0,right:16},B:{width:16,height:27,ascent:22,descent:5,left:-2,right:15},C:{width:17,height:27,ascent:22,descent:5,left:-1,right:16},D:{width:17,height:27,ascent:22,descent:5,left:-2,right:16},E:{width:16,height:27,ascent:22,descent:5,left:-2,right:15},F:{width:15,height:27,ascent:22,descent:5,left:-2,right:14},G:{width:19,height:27,ascent:22,descent:5,left:-1,right:17},H:{width:17,height:27,ascent:22,descent:5,left:-2,right:15},I:{width:7,height:27,ascent:22,descent:5,left:-2,right:5},J:{width:12,height:27,ascent:22,descent:5,left:-1,right:10},K:{width:16,height:27,ascent:22,descent:5,left:-2,right:16},L:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},M:{width:20,height:27,ascent:22,descent:5,left:-2,right:18},N:{width:17,height:27,ascent:22,descent:5,left:-2,right:15},O:{width:19,height:27,ascent:22,descent:5,left:-1,right:18},P:{width:16,height:27,ascent:22,descent:5,left:-2,right:15},Q:{width:19,height:27,ascent:22,descent:5,left:-1,right:18},R:{width:17,height:27,ascent:22,descent:5,left:-2,right:17},S:{width:16,height:27,ascent:22,descent:5,left:-1,right:15},T:{width:15,height:27,ascent:22,descent:5,left:-1,right:14},U:{width:17,height:27,ascent:22,descent:5,left:-2,right:15},V:{width:16,height:27,ascent:22,descent:5,left:0,right:16},W:{width:23,height:27,ascent:22,descent:5,left:0,right:22},X:{width:16,height:27,ascent:22,descent:5,left:0,right:16},Y:{width:16,height:27,ascent:22,descent:5,left:0,right:16},Z:{width:15,height:27,ascent:22,descent:5,left:0,right:14},"[":{width:7,height:27,ascent:22,descent:5,left:-2,right:6},"\\":{width:7,height:27,ascent:22,descent:5,left:0,right:7},"]":{width:7,height:27,ascent:22,descent:5,left:0,right:5},"^":{width:11,height:27,ascent:22,descent:5,left:-1,right:11},_:{width:13,height:27,ascent:22,descent:5,left:0,right:14},"`":{width:8,height:27,ascent:22,descent:5,left:-1,right:5},a:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},b:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},c:{width:12,height:27,ascent:22,descent:5,left:-1,right:12},d:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},e:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},f:{width:7,height:27,ascent:22,descent:5,left:0,right:8},g:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},h:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},i:{width:5,height:27,ascent:22,descent:5,left:-2,right:4},j:{width:5,height:27,ascent:22,descent:5,left:1,right:4},k:{width:12,height:27,ascent:22,descent:5,left:-2,right:12},l:{width:5,height:27,ascent:22,descent:5,left:-2,right:4},m:{width:20,height:27,ascent:22,descent:5,left:-2,right:18},n:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},o:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},p:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},q:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},r:{width:8,height:27,ascent:22,descent:5,left:-2,right:8},s:{width:12,height:27,ascent:22,descent:5,left:-1,right:11},t:{width:7,height:27,ascent:22,descent:5,left:0,right:6},u:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},v:{width:12,height:27,ascent:22,descent:5,left:0,right:12},w:{width:17,height:27,ascent:22,descent:5,left:0,right:17},x:{width:12,height:27,ascent:22,descent:5,left:0,right:12},y:{width:12,height:27,ascent:22,descent:5,left:0,right:12},z:{width:12,height:27,ascent:22,descent:5,left:0,right:11},"{":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},"|":{width:6,height:27,ascent:22,descent:5,left:-2,right:4},"}":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},"~":{width:14,height:27,ascent:22,descent:5,left:-1,right:13}},Xw=n=>{if(!n)return 0;let e=0;for(let t of n){let i=ztt[t];i?e+=i.width:e+=ztt["?"].width}return e/27},ret=(n,e)=>{if(n.column_widths&&n.column_widths.length>0&&n.row_heights&&n.row_heights.length>0){let u=h=>typeof h=="number"?h:h.endsWith("mm")?parseFloat(h):h.endsWith("in")?parseFloat(h)*25.4:parseFloat(h);return{column_widths:n.column_widths.map(u),row_heights:n.row_heights.map(u)}}let t=e.filter(u=>u.type==="schematic_table_cell"&&u.schematic_table_id===n.schematic_table_id);if(t.length===0)return{column_widths:[],row_heights:[]};let i=t.reduce((u,h)=>Math.max(u,h.end_column_index),-1)+1,r=t.reduce((u,h)=>Math.max(u,h.end_row_index),-1)+1,{cell_padding:s=.2}=n,o=new Array(i).fill(0),a=new Array(r).fill(0),c={},l={};for(let u of t){let h=z_("reference_designator",u.font_size),_=Xw(u.text??"")*h+2*s,g=h*1.2+2*s,x=`${u.start_row_index}-${u.start_column_index}`;c[x]=_,l[x]=g}for(let u=0;u<r;u++)for(let h=0;h<i;h++){let d=`${u}-${h}`;c[d]&&c[d]>o[h]&&(o[h]=c[d]),l[d]&&l[d]>a[u]&&(a[u]=l[d])}for(let u of t){if(u.start_column_index===u.end_column_index&&u.start_row_index===u.end_row_index)continue;let h=`${u.start_row_index}-${u.start_column_index}`,d=c[h],_=l[h];if(d===void 0||_===void 0)continue;let g=0;for(let v=u.start_column_index;v<=u.end_column_index;v++)g+=o[v];if(d>g){let P=(d-g)/(u.end_column_index-u.start_column_index+1);for(let w=u.start_column_index;w<=u.end_column_index;w++)o[w]+=P}let x=0;for(let v=u.start_row_index;v<=u.end_row_index;v++)x+=a[v];if(_>x){let P=(_-x)/(u.end_row_index-u.start_row_index+1);for(let w=u.start_row_index;w<=u.end_row_index;w++)a[w]+=P}}return{column_widths:o,row_heights:a}},D_=n=>{switch(n){case"top":return{x:0,y:-1};case"bottom":return{x:0,y:1};case"left":return{x:1,y:0};case"right":return{x:-1,y:0}}throw new Error(`Invalid side: ${n}`)},hl=.3,L_=.3,F_=.06,KRt={top_left:"start",top_right:"end",middle_left:"start",middle_right:"end",bottom_left:"start",bottom_right:"end",center:"middle",middle_top:"middle",middle_bottom:"middle"},JRt={top_left:"hanging",top_right:"hanging",bottom_left:"ideographic",bottom_right:"ideographic",center:"middle",middle_left:"middle",middle_right:"middle",middle_top:"hanging",middle_bottom:"ideographic"};Ui=n=>Math.abs(n.a)*.02,n8t=(n,e)=>{let t=n<0?n+2*Math.PI:n,i=e<0?e+2*Math.PI:e,r=Math.abs(t-i);return r>Math.PI&&(r=2*Math.PI-r),r},i8t=({schPorts:n,symbol:e,schComponent:t})=>{let i=n.map(a=>{let c=a.center.x-t.center.x,l=a.center.y-t.center.y;return{port:a,angle:Math.atan2(l,c)}}),r=e.ports.map(a=>{let c=a.x-e.center.x,l=a.y-e.center.y;return{port:a,angle:Math.atan2(l,c)}});i.sort((a,c)=>a.angle-c.angle),r.sort((a,c)=>a.angle-c.angle);let s=[],o=new Set;for(let a of i){let c=null;for(let l of r){if(o.has(l.port))continue;let u=n8t(a.angle,l.angle);(c===null||u<c.angleDiff)&&(c={symbolPort:l.port,angleDiff:u})}c&&c.angleDiff<Math.PI/4&&(s.push({schPort:a.port,symbolPort:c.symbolPort}),o.add(c.symbolPort))}return s};UA=({text:n,realCenter:e,realToScreenTransform:t})=>{let i=st(t,e);return{type:"element",name:"text",value:"",attributes:{x:i.x.toString(),y:i.y.toString(),fill:"red","text-anchor":"middle","dominant-baseline":"middle","font-family":"sans-serif","font-size":`${Ya(t,"error")}px`},children:[{type:"text",value:n,name:"",attributes:{},children:[]}]}},set=(n,e)=>{for(let t of n){if(t.type!=="source_trace")continue;let i=t;if(Array.isArray(i.connected_source_port_ids)&&i.connected_source_port_ids.includes(e))return!0}return!1},s8t={top_left:"start",top_right:"end",middle_left:"start",middle_right:"end",bottom_left:"start",bottom_right:"end",center:"middle",middle_top:"middle",middle_bottom:"middle"},o8t=({component:n,transform:e,circuitJson:t,colorMap:i})=>{let r=[],s=_i[n.symbol_name];if(!s)return[UA({text:`Symbol not found: ${n.symbol_name}`,realCenter:n.center,realToScreenTransform:e})];let o=Ee(t).schematic_port.list({schematic_component_id:n.schematic_component_id}),a=Ee(t).source_component.get(n.source_component_id),c=i8t({schPorts:o,symbol:s,schComponent:n});if(!c[0])return[UA({text:`Could not match ports for symbol ${n.symbol_name}`,realCenter:n.center,realToScreenTransform:e})];let l=r8t(c[1]?.symbolPort??s.center,c[1]?.schPort.center??n.center,c[0].symbolPort,c[0].schPort.center),u=s.primitives.filter(E=>E.type==="path"),h=s.primitives.filter(E=>E.type==="text"),d=s.primitives.filter(E=>E.type==="circle"),_=s.primitives.filter(E=>E.type==="box"),g=new Set;for(let E of c)set(t,E.schPort.source_port_id)&&g.add(E.symbolPort);let x={minX:Math.min(...u.flatMap(E=>E.points.map(A=>A.x))),maxX:Math.max(...u.flatMap(E=>E.points.map(A=>A.x))),minY:Math.min(...u.flatMap(E=>E.points.map(A=>A.y))),maxY:Math.max(...u.flatMap(E=>E.points.map(A=>A.y)))},[v,P]=st(Fe(e,l),[x.minX,x.minY]),[w,T]=st(Fe(e,l),[x.maxX,x.maxY]),k=Math.abs(T-P),C=Math.min(P,T),M=Math.abs(w-v),I=Math.min(v,w);r.push({name:"rect",type:"element",value:"",attributes:{class:"component-overlay",x:I.toString(),y:C.toString(),width:M.toString(),height:k.toString(),fill:"transparent"},children:[]});for(let E of u){let{points:A,color:R,closed:B,fill:j}=E;r.push({type:"element",name:"path",attributes:{d:A.map((U,V)=>{let[H,et]=st(Fe(e,l),[U.x,U.y]);return`${V===0?"M":"L"} ${H} ${et}`}).join(" ")+(B?" Z":""),stroke:i.schematic.component_outline,fill:"none","stroke-width":`${Ui(e)}px`,"stroke-linecap":"round"},value:"",children:[]})}for(let E of h){let A=st(Fe(e,l),E),R="";E.text==="{REF}"?R=a?.name??"":E.text==="{VAL}"&&(R=n.symbol_display_value??"");let U=Math.abs(x.maxY-x.minY)*.1,V=Math.abs(l.a),H=0;E.anchor.includes("bottom")?H=U*V:E.anchor.includes("top")&&(H=-U*V);let et=E.anchor.includes("bottom")?"auto":E.anchor.includes("top")?"hanging":"middle",tt=E.text==="{REF}";r.push({name:"text",type:"element",attributes:{x:A.x.toString(),y:(A.y+H).toString(),...tt?{stroke:i.schematic.background,"stroke-width":`${Ui(e)}px`,"paint-order":"stroke"}:{},fill:i.schematic.label_local,"font-family":"sans-serif","text-anchor":s8t[E.anchor],"dominant-baseline":et,"font-size":`${Ya(e,"reference_designator")}px`},value:"",children:[{type:"text",value:R,name:"",attributes:{},children:[]}]})}for(let E of _){let A=st(Fe(e,l),E),R=Fe(e,l).a;r.push({name:"rect",type:"element",attributes:{x:A.x.toString(),y:A.y.toString(),width:(E.width*R).toString(),height:(E.height*R).toString(),fill:"red"},value:"",children:[]})}for(let E of s.ports){if(g.has(E))continue;let A=st(Fe(e,l),E);r.push({type:"element",name:"circle",attributes:{cx:A.x.toString(),cy:A.y.toString(),r:`${Math.abs(e.a)*.02}px`,"stroke-width":`${Ui(e)}px`,fill:"none",stroke:i.schematic.component_outline},value:"",children:[]})}for(let E of d){let A=st(Fe(e,l),E),R=Math.abs(E.radius*e.a);r.push({type:"element",name:"circle",attributes:{cx:A.x.toString(),cy:A.y.toString(),r:`${R}px`,"stroke-width":`${Ui(e)}px`,fill:"none",stroke:i.schematic.component_outline},value:"",children:[]})}return r},O1=.02,$tt=(n,e,t,i,r)=>{let s=Math.PI/6,o={x:n.x-t*Math.cos(e-s),y:n.y-t*Math.sin(e-s)},a={x:n.x-t*Math.cos(e+s),y:n.y-t*Math.sin(e+s)};return{name:"polygon",type:"element",attributes:{points:`${n.x},${n.y} ${o.x},${o.y} ${a.x},${a.y}`,fill:"white",stroke:i,"stroke-width":`${r}px`},value:"",children:[]}},a8t=({schPort:n,schComponent:e,transform:t,circuitJson:i})=>{let r=[],s=Ee(i).source_port.get(n.source_port_id),o={x:n.center.x,y:n.center.y},a=n.distance_from_component_edge??.4;switch(n.side_of_component){case"left":o.x+=a;break;case"right":o.x-=a;break;case"top":o.y-=a;break;case"bottom":o.y+=a;break}let c=st(t,n.center),l=st(t,o),u=set(i,n.source_port_id),h={...n.center};if(!u)switch(n.side_of_component){case"left":h.x+=O1;break;case"right":h.x-=O1;break;case"top":h.y-=O1;break;case"bottom":h.y+=O1;break}let d=st(t,h);r.push({name:"line",type:"element",attributes:{class:"component-pin",x1:l.x.toString(),y1:l.y.toString(),x2:d.x.toString(),y2:d.y.toString(),"stroke-width":`${Ui(t)}px`},value:"",children:[]});let _=Math.abs(t.a)*O1,g=[];u||g.push({name:"circle",type:"element",attributes:{class:"component-pin",cx:c.x.toString(),cy:c.y.toString(),r:_.toString(),"stroke-width":`${Ui(t)}px`},value:"",children:[]}),g.push({name:"rect",type:"element",attributes:{x:(c.x-_).toString(),y:(c.y-_).toString(),width:(_*2).toString(),height:(_*2).toString(),opacity:"0"},value:"",children:[]}),r.push({name:"g",type:"element",value:"",attributes:{"data-schematic-port-id":n.source_port_id},children:g});let{has_input_arrow:x,has_output_arrow:v}=n;if((x||v)&&n.side_of_component){let P=Math.abs(t.a)*.1,w=Mi.schematic.component_outline,T=P*Math.cos(Math.PI/6),k=Ui(t)/3,C=0,M=0;n.side_of_component==="left"?(C=0,M=Math.PI):n.side_of_component==="right"?(C=Math.PI,M=0):n.side_of_component==="top"?(C=Math.PI/2,M=-Math.PI/2):n.side_of_component==="bottom"&&(C=-Math.PI/2,M=Math.PI/2);let I=x&&v,E={...l},A={...l};if(I){let R=T;n.side_of_component==="left"?A.x-=R:n.side_of_component==="right"?A.x+=R:n.side_of_component==="top"?A.y-=R:n.side_of_component==="bottom"&&(A.y+=R)}if(x&&r.push($tt(E,C,P,w,k)),v){let R={x:A.x+P*Math.cos(M),y:A.y+P*Math.sin(M)};r.push($tt(R,M,P,w,k))}}return r},c8t=n=>{let e=[],{schPort:t,schComponent:i,transform:r,circuitJson:s}=n,o={x:t.center.x,y:t.center.y};if(!t.side_of_component)return[];let a=D_(t.side_of_component),c=t.distance_from_component_edge??.4;o.x+=a.x*c/2,o.y+=a.y*c/2,t.side_of_component==="top"||t.side_of_component==="bottom"?o.x-=.02:o.y+=.02;let l=st(r,o);return e.push({name:"text",type:"element",attributes:{class:"pin-number",x:l.x.toString(),y:l.y.toString(),style:"font-family: sans-serif;",fill:Mi.schematic.pin_number,"text-anchor":"middle","dominant-baseline":"auto","font-size":`${Ya(r,"pin_number")}px`,transform:t.side_of_component==="top"||t.side_of_component==="bottom"?`rotate(-90 ${l.x} ${l.y})`:""},children:[{type:"text",value:t.pin_number?.toString()||"",name:"",attributes:{},children:[]}],value:""}),e},Dtt=.1,l8t=n=>{let e=[],{schPort:t,schComponent:i,transform:r,circuitJson:s}=n,o={x:t.center.x,y:t.center.y};if(!t.side_of_component)return[];let a=D_(t.side_of_component),c=t.distance_from_component_edge??.4;o.x+=a.x*(c+Dtt),o.y+=a.y*(c+Dtt);let l=st(r,o),u=t.display_pin_label??i.port_labels?.[`${t.pin_number}`];if(!u)return[];let h=u.startsWith("N_"),d=h?u.slice(2):u,_=Ya(r,h?"negated_pin_number":"pin_number");return e.push({name:"text",type:"element",attributes:{class:"pin-number",x:l.x.toString(),y:l.y.toString(),style:`font-family: sans-serif;${h?" text-decoration: overline;":""}`,fill:Mi.schematic.pin_number,"text-anchor":t.side_of_component==="left"||t.side_of_component==="bottom"?"start":"end","dominant-baseline":"middle","font-size":`${_}px`,transform:t.side_of_component==="top"||t.side_of_component==="bottom"?`rotate(-90 ${l.x} ${l.y})`:""},children:[{type:"text",value:d||"",name:"",attributes:{},children:[]}],value:""}),e},u8t=n=>{let e=[],{schPort:t,schComponent:i,transform:r,circuitJson:s}=n;return e.push(...a8t(n)),e.push(...c8t(n)),e.push(...l8t(n)),e},oet=({elm:n,transform:e,colorMap:t})=>{let i=st(e,n.position),r={center:"middle",center_right:"end",bottom_left:"start",bottom_center:"middle",bottom_right:"end",left:"start",right:"end",top:"middle",bottom:"middle",top_left:"start",top_center:"middle",top_right:"end",center_left:"start"},s={center:"middle",center_right:"middle",bottom_left:"ideographic",bottom_center:"ideographic",bottom_right:"ideographic",left:"middle",right:"middle",top:"hanging",bottom:"ideographic",top_left:"hanging",top_center:"hanging",top_right:"hanging",center_left:"middle"},o=n.text.split(`
137
- `),a=o.length===1?[{type:"text",value:n.text,name:n.schematic_text_id,attributes:{},children:[]}]:o.map((c,l)=>({type:"element",name:"tspan",value:"",attributes:{x:i.x.toString(),...l>0?{dy:"1em"}:{}},children:[{type:"text",value:c,name:l===0?n.schematic_text_id:"",attributes:{},children:[]}]}));return{type:"element",name:"text",value:"",attributes:{x:i.x.toString(),y:i.y.toString(),fill:n.color??t.schematic.sheet_label,"text-anchor":r[n.anchor],"dominant-baseline":s[n.anchor],"font-family":"sans-serif","font-size":`${Ya(e,"reference_designator",n.font_size)}px`,transform:`rotate(${n.rotation}, ${i.x}, ${i.y})`},children:a}},p8t=({component:n,transform:e,circuitJson:t,colorMap:i})=>{let r=[],s=st(e,{x:n.center.x-n.size.width/2,y:n.center.y+n.size.height/2}),o=st(e,{x:n.center.x+n.size.width/2,y:n.center.y-n.size.height/2}),a=o.x-s.x,c=o.y-s.y;r.push({name:"rect",type:"element",value:"",attributes:{class:"component chip",x:s.x.toString(),y:s.y.toString(),width:a.toString(),height:c.toString(),"stroke-width":`${Ui(e)}px`,fill:i.schematic.component_body,stroke:i.schematic.component_outline},children:[]}),r.push({name:"rect",type:"element",value:"",attributes:{class:"component-overlay",x:s.x.toString(),y:s.y.toString(),width:a.toString(),height:c.toString(),fill:"transparent"},children:[]});let l=Ee(t).schematic_text.list();for(let h of l)h.schematic_component_id===n.schematic_component_id&&r.push(oet({elm:h,transform:e,colorMap:i}));let u=Ee(t).schematic_port.list({schematic_component_id:n.schematic_component_id});for(let h of u)r.push(...u8t({schPort:h,schComponent:n,transform:e,circuitJson:t}));return r};_8t=({schNetLabel:n,realToScreenTransform:e,colorMap:t})=>{if(!n.text)return[];let i=n.text.startsWith("N_"),r=i?n.text.slice(2):n.text,s=[],o=_i[n.symbol_name];if(!o)return s.push(UA({text:`Symbol not found: ${n.symbol_name}`,realCenter:n.center,realToScreenTransform:e})),s;let a=o.primitives.filter(H=>H.type==="path"),c=o.primitives.filter(H=>H.type==="text"),l=o.primitives.filter(H=>H.type==="circle"),u=o.primitives.filter(H=>H.type==="box"),h={minX:Math.min(...a.flatMap(H=>H.points.map(et=>et.x))),maxX:Math.max(...a.flatMap(H=>H.points.map(et=>et.x))),minY:Math.min(...a.flatMap(H=>H.points.map(et=>et.y))),maxY:Math.max(...a.flatMap(H=>H.points.map(et=>et.y)))},d=z_("net_label"),g=Xw(r||"")+hl*2+F_*r.length+L_,x=D_(n.anchor_side),v=n.anchor_position??{x:n.center.x-x.x*g*d/2,y:n.center.y-x.y*g*d/2},w=ls(0/180*Math.PI),T={minX:Math.min(...o.primitives.flatMap(H=>H.type==="path"?H.points.map(et=>et.x):[])),maxX:Math.max(...o.primitives.flatMap(H=>H.type==="path"?H.points.map(et=>et.x):[])),minY:Math.min(...o.primitives.flatMap(H=>H.type==="path"?H.points.map(et=>et.y):[])),maxY:Math.max(...o.primitives.flatMap(H=>H.type==="path"?H.points.map(et=>et.y):[]))},k=o.ports?.[0]?{x:o.ports[0].x,y:o.ports[0].y}:{x:T.minX,y:(T.minY+T.maxY)/2},C=st(w,k),M=Fe(yn(v.x-C.x,v.y-C.y),w,ki(1)),[I,E]=st(Fe(e,M),[h.minX,h.minY]),[A,R]=st(Fe(e,M),[h.maxX,h.maxY]),B=Math.abs(R-E),j=Math.min(E,R),U=Math.abs(A-I),V=Math.min(I,A);s.push({name:"rect",type:"element",value:"",attributes:{class:"component-overlay",x:V.toString(),y:j.toString(),width:U.toString(),height:B.toString(),fill:"transparent"},children:[]});for(let H of a){let et=H.points.map((tt,mt)=>{let[G,Q]=st(Fe(e,M),[tt.x,tt.y]);return`${mt===0?"M":"L"} ${G} ${Q}`}).join(" ");s.push({name:"path",type:"element",attributes:{d:et+(H.closed?" Z":""),stroke:t.schematic.component_outline,fill:"none","stroke-width":`${Ui(e)}px`,"stroke-linecap":"round"},value:"",children:[]})}for(let H of c){let et=st(Fe(e,M),H),tt=H.text;tt==="{REF}"?tt=r||"":tt==="{VAL}"&&(tt="");let G=Math.abs(e.a)*.1,Q={x:et.x,y:et.y};s.push({name:"text",type:"element",attributes:{x:Q.x.toString(),y:Q.y.toString(),fill:t.schematic.label_local,"font-family":"sans-serif","text-anchor":KRt[H.anchor],"dominant-baseline":JRt[H.anchor],"font-size":`${Ya(e,"reference_designator")}px`,...i&&tt===r?{style:"text-decoration: overline;"}:{}},children:[{type:"text",value:tt,name:"",attributes:{},children:[]}],value:""})}for(let H of u){let et=st(Fe(e,M),H),tt=Fe(e,M).a;s.push({name:"rect",type:"element",attributes:{x:et.x.toString(),y:et.y.toString(),width:(H.width*tt).toString(),height:(H.height*tt).toString(),fill:"red"},value:"",children:[]})}for(let H of l){let et=st(Fe(e,M),H),tt=Fe(e,M).a;s.push({name:"circle",type:"element",attributes:{cx:et.x.toString(),cy:et.y.toString(),r:(H.radius*tt).toString(),fill:"none",stroke:t.schematic.component_outline,"stroke-width":`${Ui(e)}px`},value:"",children:[]})}return s},y8t=({schNetLabel:n,realToScreenTransform:e,colorMap:t})=>{if(!n.text)return[];let i=n.text;if(n.symbol_name)return _8t({schNetLabel:n,realToScreenTransform:e,colorMap:t});let r=[],s=Ya(e,"net_label"),o=z_("net_label"),a=Xw(i||""),c=st(e,n.center),l=D_(n.anchor_side),u={...l};u.y*=-1;let h=a+hl*2+F_*i.length+L_,d=n.anchor_position?st(e,n.anchor_position):{x:c.x-u.x*h*s/2,y:c.y-u.y*h*s/2},_=n.anchor_position??{x:n.center.x-l.x*h*o/2,y:n.center.y-l.y*h*o/2},g={left:0,top:-90,bottom:90,right:180}[n.anchor_side],x=[{x:0,y:0},{x:hl,y:.6},{x:hl*2+L_+F_*i.length+a,y:.6},{x:hl*2+L_+F_*i.length+a,y:-.6},{x:hl,y:-.6}].map(k=>st(Fe(e,yn(_.x,_.y),ki(o),ls(g/180*Math.PI)),k)),v=`
136
+ `;return kn("style",{},[Id(n)])}function F8t(n,e){return kn("rect",{class:"background",x:"0",y:"0",width:me(n),height:me(e)})}function z8t(n,e,t){return kn("defs",{},[kn("clipPath",{id:n},[kn("rect",{x:me(Dn.left),y:me(Dn.top),width:me(e),height:me(t)})])])}function $8t(n,e){return kn("rect",{class:"plot-background",x:me(Dn.left),y:me(Dn.top),width:me(n),height:me(e)})}function D8t({timeAxis:n,voltageAxis:e,scaleX:t,scaleY:i,plotWidth:r,plotHeight:s}){let o=Dn.top,a=Dn.top+s,c=Dn.left,l=Dn.left+r,u=[];for(let h of n.ticks){let d=me(t(h));u.push(kn("line",{class:"grid-line grid-line-x",x1:d,y1:me(o),x2:d,y2:me(a)}))}for(let h of e.ticks){let d=me(i(h));u.push(kn("line",{class:"grid-line grid-line-y",x1:me(c),y1:d,x2:me(l),y2:d}))}return kn("g",{class:"grid"},u)}function j8t({timeAxis:n,voltageAxis:e,scaleX:t,scaleY:i,plotWidth:r,plotHeight:s}){let o=Dn.top+s,a=Dn.left,c=Dn.left+r,l=[kn("line",{class:"axis axis-x",x1:me(a),y1:me(o),x2:me(c),y2:me(o)}),kn("line",{class:"axis axis-y",x1:me(a),y1:me(Dn.top),x2:me(a),y2:me(o)})];for(let u of n.ticks){let h=me(t(u));l.push(kn("line",{class:"axis-tick axis-tick-x",x1:h,y1:me(o),x2:h,y2:me(o+6)})),l.push(kn("text",{class:"axis-label axis-label-x",x:h,y:me(o+22),"text-anchor":"middle"},[Id(Xtt(u,n.ticks))]))}for(let u of e.ticks){let h=me(i(u));l.push(kn("line",{class:"axis-tick axis-tick-y",x1:me(a-6),y1:h,x2:me(a),y2:h})),l.push(kn("text",{class:"axis-label axis-label-y",x:me(a-10),y:h,"text-anchor":"end","dominant-baseline":"middle"},[Id(Xtt(u,e.ticks))]))}return l.push(kn("text",{class:"axis-title axis-title-x",x:me(a+r/2),y:me(o+48),"text-anchor":"middle"},[Id("Time (ms)")]),kn("text",{class:"axis-title axis-title-y",x:me(a-64),y:me(Dn.top+s/2),transform:`rotate(-90 ${me(a-64)} ${me(Dn.top+s/2)})`,"text-anchor":"middle"},[Id("Voltage (V)")])),kn("g",{class:"axes"},l)}function X8t(n,e){let t=Dn.top,i=n.map(r=>{let s=e-Dn.right+10,o=U8t(r.label),a=V8t(r,s,t,o),c=o.length*het;return t+=Math.max(c,Y8t),a});return kn("g",{class:"legend"},i)}function U8t(n){let e=n.split("_");if(e.length<=1)return[n];let t=[],i=e[0]??"";for(let r=1;r<e.length;r++){let s=e[r]??"",o=i+"_"+s;o.length>B8t?(t.push(i),i=s):i=o}return i&&t.push(i),t}function V8t(n,e,t,i){let r=i.map((s,o)=>kn("tspan",{x:"20",dy:o===0?"0":String(het)},[Id(s)]));return kn("g",{class:"legend-item",transform:`translate(${me(e)} ${me(t)})`},[kn("line",{class:"legend-line",x1:"0",y1:"0",x2:"16",y2:"0",stroke:n.color}),kn("text",{class:"legend-label",x:"20",y:"0","dominant-baseline":"middle"},r)])}function G8t(n,e,t,i){let s=[4,8],o=s.map(d=>me(d)).join(" "),c=s.reduce((d,_)=>d+_,0)/3,l=[];n.forEach((d,_)=>{if(d.points.length===0)return;let g=[];d.points.forEach((P,w)=>{let T=me(t(P.timeMs)),k=me(i(P.voltage));g.push(`${w===0?"M":"L"} ${T} ${k}`)});let x={class:"simulation-line",d:g.join(" "),stroke:d.color,"clip-path":`url(#${e})`,"data-simulation-transient-voltage-graph-id":d.graph.simulation_transient_voltage_graph_id};d.graph.source_component_id&&(x["data-source-component-id"]=d.graph.source_component_id),d.graph.subcircuit_connectivity_map_key&&(x["data-subcircuit-connectivity-map-key"]=d.graph.subcircuit_connectivity_map_key);let v=d.points.map(P=>{let w=me(t(P.timeMs)),T=me(i(P.voltage));return kn("circle",{class:"simulation-point",cx:w,cy:T,r:"2.5",fill:d.color,"clip-path":`url(#${e})`})});l.push({entry:d,graphIndex:_,pathAttributes:x,pointElements:v})});let u=[];for(let d=0;d<3;d++)l.forEach(_=>{let g=(_.graphIndex+d)%3,x=me(g*c);u.push(kn("path",{..._.pathAttributes,"stroke-dasharray":o,"stroke-dashoffset":x}))});let h=l.flatMap(d=>d.pointElements);return kn("g",{class:"data-series"},[...u,...h])}function H8t(n,e){return n?.name?kn("text",{class:"chart-title",x:me(e/2),y:me(Dn.top-40),"text-anchor":"middle"},[Id(n.name)]):null}function W8t(n){return`simulation-graph-${n.replace(/[^a-zA-Z0-9_-]+/g,"-")}`}function me(n){if(!Number.isFinite(n))return"0";let e=Number.parseFloat(n.toFixed(6));return Number.isInteger(e),e.toString()}function Xtt(n,e){if(e.length<=1)return me(n);let t=e[e.length-1]-e[0];if(!Number.isFinite(t)||t===0)return me(n);let i=t>=100?0:t>=10?1:t>=1?2:3,r=Math.pow(10,i);return(Math.round(n*r)/r).toFixed(i).replace(/\.0+$/,"").replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")}function kn(n,e,t=[]){return{name:n,type:"element",value:"",attributes:e,children:t}}function Id(n){return{name:"",type:"text",value:n,attributes:{},children:[]}}function K8t({circuitJson:n,simulation_experiment_id:e,simulation_transient_voltage_graph_ids:t,width:i=q8t,height:r=Z8t,schematicHeightRatio:s=det,schematicOptions:o,includeVersion:a,showErrorsInTextOverlay:c}){let l=n.filter(E=>!HA(E)&&!GA(E)),u=J8t(s),h=Math.max(1,r*u),d=Math.max(1,r-h),_=h+d,g=_===0?1:r/_,x=h*g,v=d*g,P=VA(l,{...o,width:i,height:x,includeVersion:!1,showErrorsInTextOverlay:c}),w=pet({circuitJson:n,simulation_experiment_id:e,simulation_transient_voltage_graph_ids:t,width:i,height:v,includeVersion:!1}),T=Vtt((0,L1.parseSync)(P)),k=Vtt((0,L1.parseSync)(w)),C=[];C.push(Utt(T,0,0,i,x)),C.push(Utt(k,0,x,i,v));let M=fl(l),I={name:"svg",type:"element",value:"",attributes:{xmlns:"http://www.w3.org/2000/svg",width:dl(i),height:dl(r),viewBox:`0 0 ${dl(i)} ${dl(r)}`,"data-simulation-experiment-id":e,...M&&{"data-software-used-string":M},...a&&{"data-circuit-to-svg-version":ml}},children:C};return(0,L1.stringify)(I)}function Utt(n,e,t,i,r){let s=fet(n);return s.attributes={...s.attributes,x:dl(e),y:dl(t),width:dl(i),height:dl(r)},delete s.attributes.xmlns,s}function Vtt(n){if(n.type!=="element")throw new Error("Expected SVG root element to be of type 'element'");return n}function fet(n){return{...n,attributes:{...n.attributes??{}},children:n.children?.map(fet)??[]}}function J8t(n){return Number.isFinite(n)?n<=0?0:n>=1?1:n:det}function dl(n){if(!Number.isFinite(n))return"0";let e=Number.parseFloat(n.toFixed(6));return Number.isInteger(e),e.toString()}function Q8t(n,e){let{transform:t,layer:i}=e;if(i&&n.layer!==i)return[];let[r,s]=st(t,[n.x,n.y]);if(n.shape==="rect"||n.shape==="rotated_rect"){let o=n.width*Math.abs(t.a),a=n.height*Math.abs(t.d);return n.shape==="rotated_rect"&&n.ccw_rotation?[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:jw(n.layer),x:(-o/2).toString(),y:(-a/2).toString(),width:o.toString(),height:a.toString(),transform:`translate(${r} ${s}) rotate(${-n.ccw_rotation})`,"data-type":"pcb_solder_paste","data-pcb-layer":n.layer}}]:[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:jw(n.layer),x:(r-o/2).toString(),y:(s-a/2).toString(),width:o.toString(),height:a.toString(),"data-type":"pcb_solder_paste","data-pcb-layer":n.layer}}]}if(n.shape==="pill"){let o=n.width*Math.abs(t.a),a=n.height*Math.abs(t.d),c=n.radius*Math.abs(t.a);return[{name:"rect",type:"element",attributes:{class:"pcb-solder-paste",fill:jw(n.layer),x:(r-o/2).toString(),y:(s-a/2).toString(),width:o.toString(),height:a.toString(),rx:c.toString(),"data-type":"pcb_solder_paste","data-pcb-layer":n.layer}}]}if(n.shape==="circle"){let o=n.radius*Math.abs(t.a);return[{name:"circle",type:"element",attributes:{class:"pcb-solder-paste",fill:jw(n.layer),cx:r.toString(),cy:s.toString(),r:o.toString(),"data-type":"pcb_solder_paste","data-pcb-layer":n.layer}}]}}function tOt(n,e){let t=Number.POSITIVE_INFINITY,i=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY,o=n.filter(R=>R.type==="pcb_board"||R.type==="pcb_panel"||R.type==="pcb_solder_paste"&&R.layer===e.layer);for(let R of o)if(R.type==="pcb_board")R.outline&&Array.isArray(R.outline)&&R.outline.length>=3?A(R.outline):"center"in R&&"width"in R&&"height"in R&&E(R.center,R.width,R.height);else if(R.type==="pcb_panel"){let B=R,j=Y.parse(B.width),U=Y.parse(B.height);if(j!==void 0&&U!==void 0){let V=B.center??{x:j/2,y:U/2};E(V,j,U)}}else R.type==="pcb_solder_paste"&&"x"in R&&"y"in R&&E({x:R.x,y:R.y},0,0);let a=1,c=r-t+2*a,l=s-i+2*a,u=e.width??800,h=e.height??600,d=u/c,_=h/l,g=Math.min(d,_),x=(u-c*g)/2,v=(h-l*g)/2,P=Fe(yn(x-t*g+a*g,h-v+i*g-a*g),Ti(g,-g)),w={transform:P,layer:e.layer,colorMap:Mi},T=o.sort((R,B)=>(Gtt.indexOf(B.type)??9999)-(Gtt.indexOf(R.type)??9999)).flatMap(R=>eOt({elm:R,ctx:w})),k=fl(n),C=ml,M=[{name:"style",type:"element",children:[{type:"text",value:""}]},{name:"rect",type:"element",attributes:{class:"boundary",x:"0",y:"0",fill:"#000",width:u.toString(),height:h.toString()}},nOt(P,t,i,r,s),...T].filter(R=>R!==null);if(e?.showErrorsInTextOverlay){let R=$_(n);R&&M.push(R)}let I={name:"svg",type:"element",attributes:{xmlns:"http://www.w3.org/2000/svg",width:u.toString(),height:h.toString(),...k&&{"data-software-used-string":k},...e.includeVersion&&{"data-circuit-to-svg-version":C}},value:"",children:M};try{return(0,met.stringify)(I)}catch(R){throw console.error("Error stringifying SVG object:",R),R}function E(R,B,j){let U=B/2,V=j/2;t=Math.min(t,R.x-U),i=Math.min(i,R.y-V),r=Math.max(r,R.x+U),s=Math.max(s,R.y+V)}function A(R){for(let B of R)t=Math.min(t,B.x),i=Math.min(i,B.y),r=Math.max(r,B.x),s=Math.max(s,B.y)}}function eOt({elm:n,ctx:e}){let{transform:t}=e;switch(n.type){case"pcb_board":return Wtt(n,e);case"pcb_solder_paste":return Q8t(n,e);default:return[]}}function nOt(n,e,t,i,r){let[s,o]=st(n,[e,t]),[a,c]=st(n,[i,r]),l=Math.abs(a-s),u=Math.abs(c-o),h=Math.min(s,a),d=Math.min(o,c);return{name:"rect",type:"element",value:"",children:[],attributes:{class:"pcb-boundary",fill:"none",stroke:"#fff","stroke-width":"0.3",x:h.toString(),y:d.toString(),width:l.toString(),height:u.toString()}}}var Htt,Ofe,Yfe,Ktt,Jtt,iet,xme,kme,L1,cet,met,f6t,m6t,Ei,x6t,v6t,S6t,P6t,T6t,Mi,Pfe,kfe,Tfe,Mfe,F6t,Y6t,X6t,H6t,Ttt,Mtt,Ls,Ett,qtt,O_,Bw,Ctt,Z6t,K6t,J6t,Q6t,sRt,oRt,cRt,ml,lRt,Itt,fRt,Yw,_Rt,z_,Ya,DA,E1,C1,I1,Att,ERt,CRt,NRt,ARt,jA,N1,A1,R1,Rtt,Ott,zRt,$Rt,DRt,Qtt,BRt,YRt,tet,eet,XA,net,XRt,URt,Ftt,ztt,Xw,ret,D_,hl,L_,F_,KRt,JRt,Ui,n8t,i8t,UA,set,s8t,o8t,O1,$tt,a8t,c8t,Dtt,l8t,u8t,oet,p8t,_8t,y8t,g8t,x8t,b8t,v8t,aet,M8t,E8t,C8t,Dn,jtt,B8t,het,Y8t,q8t,Z8t,det,Gtt,yet=qt(()=>{"use strict";St();Htt=Gt(os(),1);Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();er();Ofe=Gt(os(),1);Yt();Ae();er();Ae();Yt();Yt();Yt();Yfe=Gt(os(),1);Yt();Yt();Yt();Ktt=Gt(os(),1);Ae();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Jtt=Gt(os(),1);Yt();Yt();Ae();Ae();Yt();Yt();Yt();Yt();Yt();Ag();Yt();Ae();iet=Gt(os(),1);Yt();Yt();Yt();Yt();Ta();Ae();Ta();xme=Gt(os(),1);Yt();Yt();Yt();Ae();Ta();kme=Gt(os(),1);Yt();Yt();Ae();Yt();Ae();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Yt();Ta();Yt();Yt();Ae();Yt();Yt();Yt();Yt();Yt();L1=Gt(os(),1),cet=Gt(os(),1);St();met=Gt(os(),1);Yt();Yt();f6t="rgba(255,255,255,0.5)",m6t="rgba(255,255,255,0.2)";Ei={"3d_viewer":{background_bottom:"rgb(102, 102, 128)",background_top:"rgb(204, 204, 230)",board:"rgb(51, 43, 23)",copper:"rgb(179, 156, 0)",silkscreen_bottom:"rgb(230, 230, 230)",silkscreen_top:"rgb(230, 230, 230)",soldermask:"rgb(20, 51, 36)",solderpaste:"rgb(128, 128, 128)"},board:{anchor:"rgb(255, 38, 226)",aux_items:"rgb(255, 255, 255)",b_adhes:"rgb(0, 0, 132)",b_crtyd:"rgb(255, 38, 226)",b_fab:"rgb(88, 93, 132)",b_mask:"rgba(2, 255, 238, 0.400)",b_paste:"rgb(0, 194, 194)",b_silks:"rgb(232, 178, 167)",background:"rgb(0, 16, 35)",cmts_user:"rgb(89, 148, 220)",copper:{b:"rgb(77, 127, 196)",f:"rgb(200, 52, 52)",in1:"rgb(127, 200, 127)",in10:"rgb(237, 124, 51)",in11:"rgb(91, 195, 235)",in12:"rgb(247, 111, 142)",in13:"rgb(167, 165, 198)",in14:"rgb(40, 204, 217)",in15:"rgb(232, 178, 167)",in16:"rgb(242, 237, 161)",in17:"rgb(237, 124, 51)",in18:"rgb(91, 195, 235)",in19:"rgb(247, 111, 142)",in2:"rgb(206, 125, 44)",in20:"rgb(167, 165, 198)",in21:"rgb(40, 204, 217)",in22:"rgb(232, 178, 167)",in23:"rgb(242, 237, 161)",in24:"rgb(237, 124, 51)",in25:"rgb(91, 195, 235)",in26:"rgb(247, 111, 142)",in27:"rgb(167, 165, 198)",in28:"rgb(40, 204, 217)",in29:"rgb(232, 178, 167)",in3:"rgb(79, 203, 203)",in30:"rgb(242, 237, 161)",in4:"rgb(219, 98, 139)",in5:"rgb(167, 165, 198)",in6:"rgb(40, 204, 217)",in7:"rgb(232, 178, 167)",in8:"rgb(242, 237, 161)",in9:"rgb(141, 203, 129)"},cursor:"rgb(255, 255, 255)",drc:"rgb(194, 194, 194)",drc_error:"rgba(215, 91, 107, 0.800)",drc_exclusion:"rgb(255, 255, 255)",drc_warning:"rgba(255, 208, 66, 0.902)",dwgs_user:"rgb(194, 194, 194)",eco1_user:"rgb(180, 219, 210)",eco2_user:"rgb(216, 200, 82)",edge_cuts:"rgb(208, 210, 205)",f_adhes:"rgb(132, 0, 132)",f_crtyd:"rgb(255, 0, 245)",f_fab:"rgb(175, 175, 175)",f_mask:"rgba(216, 100, 255, 0.400)",f_paste:"rgba(180, 160, 154, 0.902)",f_silks:"rgb(242, 237, 161)",footprint_text_back:"rgb(0, 0, 132)",footprint_text_front:"rgb(194, 194, 194)",footprint_text_invisible:"rgb(132, 132, 132)",grid:"rgb(132, 132, 132)",grid_axes:"rgb(194, 194, 194)",margin:"rgb(255, 38, 226)",microvia:"rgb(0, 132, 132)",no_connect:"rgb(0, 0, 132)",pad_back:"rgb(77, 127, 196)",pad_front:"rgb(200, 52, 52)",pad_plated_hole:"rgb(194, 194, 0)",pad_through_hole:"rgb(227, 183, 46)",plated_hole:"rgb(26, 196, 210)",ratsnest:"rgba(245, 255, 213, 0.702)",select_overlay:"rgb(4, 255, 67)",through_via:"rgb(236, 236, 236)",user_1:"rgb(194, 194, 194)",user_2:"rgb(89, 148, 220)",user_3:"rgb(180, 219, 210)",user_4:"rgb(216, 200, 82)",user_5:"rgb(194, 194, 194)",user_6:"rgb(89, 148, 220)",user_7:"rgb(180, 219, 210)",user_8:"rgb(216, 200, 82)",user_9:"rgb(232, 178, 167)",via_blind_buried:"rgb(187, 151, 38)",via_hole:"rgb(227, 183, 46)",via_micro:"rgb(0, 132, 132)",via_through:"rgb(236, 236, 236)",worksheet:"rgb(200, 114, 171)"},gerbview:{axes:"rgb(0, 0, 132)",background:"rgb(0, 0, 0)",dcodes:"rgb(255, 255, 255)",grid:"rgb(132, 132, 132)",layers:["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)","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)","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)","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)"],negative_objects:"rgb(132, 132, 132)",worksheet:"rgb(0, 0, 132)"},meta:{filename:"kicad_2020",name:"KiCad 2020",version:2},palette:["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)"],schematic:{aux_items:"rgb(46, 46, 46)",background:"rgb(245, 241, 237)",brightened:"rgb(255, 0, 255)",bus:"rgb(0, 0, 132)",bus_junction:"rgb(0, 0, 132)",component_body:"rgb(255, 255, 194)",component_outline:"rgb(132, 0, 0)",cursor:"rgb(15, 15, 15)",erc_error:"rgba(230, 9, 13, 0.800)",erc_warning:"rgba(209, 146, 0, 0.800)",fields:"rgb(132, 0, 132)",grid:"rgb(181, 181, 181)",grid_axes:"rgb(0, 0, 132)",hidden:"rgb(194, 194, 194)",junction:"rgb(0, 150, 0)",label_global:"rgb(132, 0, 0)",label_background:"rgba(255, 255, 255, 0.6)",label_hier:"rgb(114, 86, 0)",label_local:"rgb(15, 15, 15)",net_name:"rgb(132, 132, 132)",no_connect:"rgb(0, 0, 132)",note:"rgb(0, 0, 194)",override_item_colors:!1,pin:"rgb(132, 0, 0)",pin_name:"rgb(0, 100, 100)",pin_number:"rgb(169, 0, 0)",reference:"rgb(0, 100, 100)",shadow:"rgba(102, 179, 255, 0.800)",sheet:"rgb(132, 0, 0)",sheet_background:"rgba(253, 255, 231, 0.000)",sheet_fields:"rgb(132, 0, 132)",sheet_filename:"rgb(114, 86, 0)",sheet_label:"rgb(0, 100, 100)",sheet_name:"rgb(0, 100, 100)",table:"rgb(102, 102, 102)",value:"rgb(0, 100, 100)",wire:"rgb(0, 150, 0)",wire_crossing:"rgb(30, 180, 30)",worksheet:"rgb(132, 0, 0)"}};x6t=Ei.board.user_2;v6t=Ei.board.user_2,S6t=Ei.board.user_2;P6t=Ei.board.user_2;T6t=Ei.board.user_2;Mi={copper:{top:"rgb(200, 52, 52)",inner1:"rgb(255, 140, 0)",inner2:"rgb(255, 215, 0)",inner3:"rgb(50, 205, 50)",inner4:"rgb(64, 224, 208)",inner5:"rgb(138, 43, 226)",inner6:"rgb(255, 105, 180)",bottom:"rgb(77, 127, 196)"},soldermaskWithCopperUnderneath:{top:"rgb(18, 82, 50)",bottom:"rgb(77, 127, 196)"},soldermask:{top:"rgb(12, 55, 33)",bottom:"rgb(52, 87, 136)"},substrate:"rgb(201, 162, 110)",drill:"#FF26E2",silkscreen:{top:"#f2eda1",bottom:"#5da9e9"},boardOutline:"rgba(255, 255, 255, 0.5)",courtyard:"#FF00FF",debugComponent:{fill:null,stroke:null}},Pfe=Mi.drill,kfe=Mi.silkscreen.top,Tfe=Mi.silkscreen.bottom,Mfe={...Mi.copper};F6t={bottom:"rgb(105, 105, 105)",top:"rgb(105, 105, 105)"};Y6t=(n,e)=>{let t=Ee(e).pcb_smtpad.get(n);if(t&&"x"in t&&"y"in t)return{x:t.x,y:t.y};let i=Ee(e).pcb_plated_hole.get(n);return i&&"x"in i&&"y"in i?{x:i.x,y:i.y}:null},X6t=(n,e,t,i)=>{let r=t.getIdsConnectedToNet(e),s=null,o=1/0;for(let a of r){let c=Y6t(a,i);if(c){let l=n.x-c.x,u=n.y-c.y,h=Math.sqrt(l*l+u*u);h>0&&h<o&&(o=h,s=c)}}return s};H6t="rgba(255, 255, 255, 0.5)",Ttt="pcb-grid-pattern";Mtt=.01,Ls=4,Ett=8,qtt=11,O_=1,Bw=5,Ctt=1.5,Z6t=15,K6t=10,J6t=.2,Q6t=50;sRt="rgba(100, 200, 255, 0.6)",oRt=.1;cRt={name:"circuit-to-svg",type:"module",version:"0.0.279",description:"Convert Circuit JSON to SVG",main:"dist/index.js",files:["dist"],scripts:{start:"cosmos",prepublish:"npm run build",build:"tsup-node ./lib/index.ts --format esm --dts --sourcemap --external tscircuit",format:"biome format . --write","format:check":"biome format .",cosmos:"cosmos","cosmos-export":"cosmos-export"},license:"ISC",devDependencies:{"@biomejs/biome":"^1.9.4","@types/bun":"^1.2.8","@vitejs/plugin-react":"5.0.0",biome:"^0.3.3","bun-match-svg":"^0.0.12",esbuild:"^0.20.2","performance-now":"^2.1.0","circuit-json":"^0.0.319",react:"19.1.0","react-cosmos":"7.0.0","react-cosmos-plugin-vite":"7.0.0","react-dom":"19.1.0",tscircuit:"^0.0.937",tsup:"^8.0.2",typescript:"^5.4.5","vite-tsconfig-paths":"^5.0.1"},dependencies:{"@types/node":"^22.5.5","bun-types":"^1.1.40","calculate-elbow":"0.0.12",svgson:"^5.3.1","transformation-matrix":"^2.16.1"}},ml=cRt.version,lRt={pcb_background:0,pcb_boundary:1,pcb_panel:5,pcb_board:10,pcb_cutout:15,pcb_hole:18,pcb_plated_hole_drill:19,pcb_plated_hole:20,pcb_trace_soldermask:25,pcb_trace:30,pcb_smtpad:30,pcb_copper_pour:35,pcb_via:36,pcb_soldermask:40,pcb_soldermask_opening:41,pcb_solder_paste:45,pcb_silkscreen_text:50,pcb_silkscreen_path:50,pcb_silkscreen_rect:50,pcb_silkscreen_circle:50,pcb_silkscreen_line:50,pcb_component:60,pcb_fabrication_note_text:70,pcb_fabrication_note_path:70,pcb_fabrication_note_rect:70,pcb_fabrication_note_dimension:70,pcb_note_dimension:70,pcb_note_text:70,pcb_note_rect:70,pcb_note_path:70,pcb_note_line:70,pcb_trace_error:80,pcb_rats_nest:85},Itt=100;fRt=Ztt,Yw={fill:"none",stroke:"rgb(0,0,0)",strokeOpacity:"0.8",strokeWidthFactor:.2};_Rt={pin_number:.15,negated_pin_number:.15*.8,reference_designator:.18,manufacturer_number:.18,net_label:.18,error:.05},z_=(n,e)=>e??_Rt[n],Ya=(n,e,t)=>Math.abs(n.a)*z_(e,t);DA="rgb(190, 190, 190)";E1="rgb(210, 210, 210)",C1="rgb(190, 190, 190)";I1="rgb(210, 210, 210)";Att=["pcb_component","pcb_smtpad","pcb_hole","pcb_plated_hole","pcb_board"];ERt="rgb(26, 115, 143)",CRt="rgba(0,0,0,0.9)";NRt="rgba(120, 120, 120, 0.6)",ARt="rgba(255, 255, 255, 0.9)";jA="rgb(50, 50, 50)";N1="rgb(218, 165, 32)",A1="rgb(40, 40, 40)";R1="rgb(218, 165, 32)";Rtt="rgb(255, 255, 255)",Ott="rgb(0, 0, 0)",zRt="rgba(0, 0, 0, 0.6)",$Rt="rgb(200, 200, 200)",DRt="rgb(0, 0, 0)";Qtt=1.6,BRt=11/21,YRt=.6,tet=.1,eet=.1,XA=3,net=.1,XRt=.8;URt=({left_labels:n,right_labels:e,transform:t,soup:i,board_bounds:r,svgWidth:s,svgHeight:o,styleScale:a})=>{let c=new Map,l={transform:t,soup:i,board_bounds:r};return Ltt("left",n,{...l,svgHeight:o,styleScale:a},c),Ltt("right",e,{...l,svgHeight:o,styleScale:a},c),c};Ftt=["pcb_board","pcb_smtpad","pcb_hole","pcb_plated_hole","pcb_component","pcb_port"];ztt={0:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},1:{width:13,height:27,ascent:22,descent:5,left:-3,right:9},2:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},3:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},4:{width:13,height:27,ascent:22,descent:5,left:0,right:12},5:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},6:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},7:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},8:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},9:{width:13,height:27,ascent:22,descent:5,left:-1,right:12}," ":{width:7,height:27,ascent:22,descent:5,left:0,right:0},"!":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},'"':{width:9,height:27,ascent:22,descent:5,left:-1,right:7},"#":{width:13,height:27,ascent:22,descent:5,left:0,right:13},$:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},"%":{width:21,height:27,ascent:22,descent:5,left:-1,right:20},"&":{width:16,height:27,ascent:22,descent:5,left:-1,right:15},"'":{width:5,height:27,ascent:22,descent:5,left:-1,right:3},"(":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},")":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},"*":{width:9,height:27,ascent:22,descent:5,left:-1,right:8},"+":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},",":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},"-":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},".":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},"/":{width:7,height:27,ascent:22,descent:5,left:0,right:7},":":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},";":{width:7,height:27,ascent:22,descent:5,left:-2,right:5},"<":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},"=":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},">":{width:14,height:27,ascent:22,descent:5,left:-1,right:13},"?":{width:13,height:27,ascent:22,descent:5,left:-1,right:12},"@":{width:24,height:27,ascent:22,descent:5,left:-1,right:23},A:{width:16,height:27,ascent:22,descent:5,left:0,right:16},B:{width:16,height:27,ascent:22,descent:5,left:-2,right:15},C:{width:17,height:27,ascent:22,descent:5,left:-1,right:16},D:{width:17,height:27,ascent:22,descent:5,left:-2,right:16},E:{width:16,height:27,ascent:22,descent:5,left:-2,right:15},F:{width:15,height:27,ascent:22,descent:5,left:-2,right:14},G:{width:19,height:27,ascent:22,descent:5,left:-1,right:17},H:{width:17,height:27,ascent:22,descent:5,left:-2,right:15},I:{width:7,height:27,ascent:22,descent:5,left:-2,right:5},J:{width:12,height:27,ascent:22,descent:5,left:-1,right:10},K:{width:16,height:27,ascent:22,descent:5,left:-2,right:16},L:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},M:{width:20,height:27,ascent:22,descent:5,left:-2,right:18},N:{width:17,height:27,ascent:22,descent:5,left:-2,right:15},O:{width:19,height:27,ascent:22,descent:5,left:-1,right:18},P:{width:16,height:27,ascent:22,descent:5,left:-2,right:15},Q:{width:19,height:27,ascent:22,descent:5,left:-1,right:18},R:{width:17,height:27,ascent:22,descent:5,left:-2,right:17},S:{width:16,height:27,ascent:22,descent:5,left:-1,right:15},T:{width:15,height:27,ascent:22,descent:5,left:-1,right:14},U:{width:17,height:27,ascent:22,descent:5,left:-2,right:15},V:{width:16,height:27,ascent:22,descent:5,left:0,right:16},W:{width:23,height:27,ascent:22,descent:5,left:0,right:22},X:{width:16,height:27,ascent:22,descent:5,left:0,right:16},Y:{width:16,height:27,ascent:22,descent:5,left:0,right:16},Z:{width:15,height:27,ascent:22,descent:5,left:0,right:14},"[":{width:7,height:27,ascent:22,descent:5,left:-2,right:6},"\\":{width:7,height:27,ascent:22,descent:5,left:0,right:7},"]":{width:7,height:27,ascent:22,descent:5,left:0,right:5},"^":{width:11,height:27,ascent:22,descent:5,left:-1,right:11},_:{width:13,height:27,ascent:22,descent:5,left:0,right:14},"`":{width:8,height:27,ascent:22,descent:5,left:-1,right:5},a:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},b:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},c:{width:12,height:27,ascent:22,descent:5,left:-1,right:12},d:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},e:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},f:{width:7,height:27,ascent:22,descent:5,left:0,right:8},g:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},h:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},i:{width:5,height:27,ascent:22,descent:5,left:-2,right:4},j:{width:5,height:27,ascent:22,descent:5,left:1,right:4},k:{width:12,height:27,ascent:22,descent:5,left:-2,right:12},l:{width:5,height:27,ascent:22,descent:5,left:-2,right:4},m:{width:20,height:27,ascent:22,descent:5,left:-2,right:18},n:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},o:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},p:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},q:{width:13,height:27,ascent:22,descent:5,left:-1,right:12},r:{width:8,height:27,ascent:22,descent:5,left:-2,right:8},s:{width:12,height:27,ascent:22,descent:5,left:-1,right:11},t:{width:7,height:27,ascent:22,descent:5,left:0,right:6},u:{width:13,height:27,ascent:22,descent:5,left:-2,right:12},v:{width:12,height:27,ascent:22,descent:5,left:0,right:12},w:{width:17,height:27,ascent:22,descent:5,left:0,right:17},x:{width:12,height:27,ascent:22,descent:5,left:0,right:12},y:{width:12,height:27,ascent:22,descent:5,left:0,right:12},z:{width:12,height:27,ascent:22,descent:5,left:0,right:11},"{":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},"|":{width:6,height:27,ascent:22,descent:5,left:-2,right:4},"}":{width:8,height:27,ascent:22,descent:5,left:-1,right:7},"~":{width:14,height:27,ascent:22,descent:5,left:-1,right:13}},Xw=n=>{if(!n)return 0;let e=0;for(let t of n){let i=ztt[t];i?e+=i.width:e+=ztt["?"].width}return e/27},ret=(n,e)=>{if(n.column_widths&&n.column_widths.length>0&&n.row_heights&&n.row_heights.length>0){let u=h=>typeof h=="number"?h:h.endsWith("mm")?parseFloat(h):h.endsWith("in")?parseFloat(h)*25.4:parseFloat(h);return{column_widths:n.column_widths.map(u),row_heights:n.row_heights.map(u)}}let t=e.filter(u=>u.type==="schematic_table_cell"&&u.schematic_table_id===n.schematic_table_id);if(t.length===0)return{column_widths:[],row_heights:[]};let i=t.reduce((u,h)=>Math.max(u,h.end_column_index),-1)+1,r=t.reduce((u,h)=>Math.max(u,h.end_row_index),-1)+1,{cell_padding:s=.2}=n,o=new Array(i).fill(0),a=new Array(r).fill(0),c={},l={};for(let u of t){let h=z_("reference_designator",u.font_size),_=Xw(u.text??"")*h+2*s,g=h*1.2+2*s,x=`${u.start_row_index}-${u.start_column_index}`;c[x]=_,l[x]=g}for(let u=0;u<r;u++)for(let h=0;h<i;h++){let d=`${u}-${h}`;c[d]&&c[d]>o[h]&&(o[h]=c[d]),l[d]&&l[d]>a[u]&&(a[u]=l[d])}for(let u of t){if(u.start_column_index===u.end_column_index&&u.start_row_index===u.end_row_index)continue;let h=`${u.start_row_index}-${u.start_column_index}`,d=c[h],_=l[h];if(d===void 0||_===void 0)continue;let g=0;for(let v=u.start_column_index;v<=u.end_column_index;v++)g+=o[v];if(d>g){let P=(d-g)/(u.end_column_index-u.start_column_index+1);for(let w=u.start_column_index;w<=u.end_column_index;w++)o[w]+=P}let x=0;for(let v=u.start_row_index;v<=u.end_row_index;v++)x+=a[v];if(_>x){let P=(_-x)/(u.end_row_index-u.start_row_index+1);for(let w=u.start_row_index;w<=u.end_row_index;w++)a[w]+=P}}return{column_widths:o,row_heights:a}},D_=n=>{switch(n){case"top":return{x:0,y:-1};case"bottom":return{x:0,y:1};case"left":return{x:1,y:0};case"right":return{x:-1,y:0}}throw new Error(`Invalid side: ${n}`)},hl=.3,L_=.3,F_=.06,KRt={top_left:"start",top_right:"end",middle_left:"start",middle_right:"end",bottom_left:"start",bottom_right:"end",center:"middle",middle_top:"middle",middle_bottom:"middle"},JRt={top_left:"hanging",top_right:"hanging",bottom_left:"ideographic",bottom_right:"ideographic",center:"middle",middle_left:"middle",middle_right:"middle",middle_top:"hanging",middle_bottom:"ideographic"};Ui=n=>Math.abs(n.a)*.02,n8t=(n,e)=>{let t=n<0?n+2*Math.PI:n,i=e<0?e+2*Math.PI:e,r=Math.abs(t-i);return r>Math.PI&&(r=2*Math.PI-r),r},i8t=({schPorts:n,symbol:e,schComponent:t})=>{let i=n.map(a=>{let c=a.center.x-t.center.x,l=a.center.y-t.center.y;return{port:a,angle:Math.atan2(l,c)}}),r=e.ports.map(a=>{let c=a.x-e.center.x,l=a.y-e.center.y;return{port:a,angle:Math.atan2(l,c)}});i.sort((a,c)=>a.angle-c.angle),r.sort((a,c)=>a.angle-c.angle);let s=[],o=new Set;for(let a of i){let c=null;for(let l of r){if(o.has(l.port))continue;let u=n8t(a.angle,l.angle);(c===null||u<c.angleDiff)&&(c={symbolPort:l.port,angleDiff:u})}c&&c.angleDiff<Math.PI/4&&(s.push({schPort:a.port,symbolPort:c.symbolPort}),o.add(c.symbolPort))}return s};UA=({text:n,realCenter:e,realToScreenTransform:t})=>{let i=st(t,e);return{type:"element",name:"text",value:"",attributes:{x:i.x.toString(),y:i.y.toString(),fill:"red","text-anchor":"middle","dominant-baseline":"middle","font-family":"sans-serif","font-size":`${Ya(t,"error")}px`},children:[{type:"text",value:n,name:"",attributes:{},children:[]}]}},set=(n,e)=>{for(let t of n){if(t.type!=="source_trace")continue;let i=t;if(Array.isArray(i.connected_source_port_ids)&&i.connected_source_port_ids.includes(e))return!0}return!1},s8t={top_left:"start",top_right:"end",middle_left:"start",middle_right:"end",bottom_left:"start",bottom_right:"end",center:"middle",middle_top:"middle",middle_bottom:"middle"},o8t=({component:n,transform:e,circuitJson:t,colorMap:i})=>{let r=[],s=_i[n.symbol_name];if(!s)return[UA({text:`Symbol not found: ${n.symbol_name}`,realCenter:n.center,realToScreenTransform:e})];let o=Ee(t).schematic_port.list({schematic_component_id:n.schematic_component_id}),a=Ee(t).source_component.get(n.source_component_id),c=i8t({schPorts:o,symbol:s,schComponent:n});if(!c[0])return[UA({text:`Could not match ports for symbol ${n.symbol_name}`,realCenter:n.center,realToScreenTransform:e})];let l=r8t(c[1]?.symbolPort??s.center,c[1]?.schPort.center??n.center,c[0].symbolPort,c[0].schPort.center),u=s.primitives.filter(E=>E.type==="path"),h=s.primitives.filter(E=>E.type==="text"),d=s.primitives.filter(E=>E.type==="circle"),_=s.primitives.filter(E=>E.type==="box"),g=new Set;for(let E of c)set(t,E.schPort.source_port_id)&&g.add(E.symbolPort);let x={minX:Math.min(...u.flatMap(E=>E.points.map(A=>A.x))),maxX:Math.max(...u.flatMap(E=>E.points.map(A=>A.x))),minY:Math.min(...u.flatMap(E=>E.points.map(A=>A.y))),maxY:Math.max(...u.flatMap(E=>E.points.map(A=>A.y)))},[v,P]=st(Fe(e,l),[x.minX,x.minY]),[w,T]=st(Fe(e,l),[x.maxX,x.maxY]),k=Math.abs(T-P),C=Math.min(P,T),M=Math.abs(w-v),I=Math.min(v,w);r.push({name:"rect",type:"element",value:"",attributes:{class:"component-overlay",x:I.toString(),y:C.toString(),width:M.toString(),height:k.toString(),fill:"transparent"},children:[]});for(let E of u){let{points:A,color:R,closed:B,fill:j}=E;r.push({type:"element",name:"path",attributes:{d:A.map((U,V)=>{let[H,et]=st(Fe(e,l),[U.x,U.y]);return`${V===0?"M":"L"} ${H} ${et}`}).join(" ")+(B?" Z":""),stroke:i.schematic.component_outline,fill:"none","stroke-width":`${Ui(e)}px`,"stroke-linecap":"round"},value:"",children:[]})}for(let E of h){let A=st(Fe(e,l),E),R="";E.text==="{REF}"?R=a?.name??"":E.text==="{VAL}"&&(R=n.symbol_display_value??"");let U=Math.abs(x.maxY-x.minY)*.1,V=Math.abs(l.a),H=0;E.anchor.includes("bottom")?H=U*V:E.anchor.includes("top")&&(H=-U*V);let et=E.anchor.includes("bottom")?"auto":E.anchor.includes("top")?"hanging":"middle",tt=E.text==="{REF}";r.push({name:"text",type:"element",attributes:{x:A.x.toString(),y:(A.y+H).toString(),...tt?{stroke:i.schematic.background,"stroke-width":`${Ui(e)}px`,"paint-order":"stroke"}:{},fill:i.schematic.label_local,"font-family":"sans-serif","text-anchor":s8t[E.anchor],"dominant-baseline":et,"font-size":`${Ya(e,"reference_designator")}px`},value:"",children:[{type:"text",value:R,name:"",attributes:{},children:[]}]})}for(let E of _){let A=st(Fe(e,l),E),R=Fe(e,l).a;r.push({name:"rect",type:"element",attributes:{x:A.x.toString(),y:A.y.toString(),width:(E.width*R).toString(),height:(E.height*R).toString(),fill:"red"},value:"",children:[]})}for(let E of s.ports){if(g.has(E))continue;let A=st(Fe(e,l),E);r.push({type:"element",name:"circle",attributes:{cx:A.x.toString(),cy:A.y.toString(),r:`${Math.abs(e.a)*.02}px`,"stroke-width":`${Ui(e)}px`,fill:"none",stroke:i.schematic.component_outline},value:"",children:[]})}for(let E of d){let A=st(Fe(e,l),E),R=Math.abs(E.radius*e.a);r.push({type:"element",name:"circle",attributes:{cx:A.x.toString(),cy:A.y.toString(),r:`${R}px`,"stroke-width":`${Ui(e)}px`,fill:"none",stroke:i.schematic.component_outline},value:"",children:[]})}return r},O1=.02,$tt=(n,e,t,i,r)=>{let s=Math.PI/6,o={x:n.x-t*Math.cos(e-s),y:n.y-t*Math.sin(e-s)},a={x:n.x-t*Math.cos(e+s),y:n.y-t*Math.sin(e+s)};return{name:"polygon",type:"element",attributes:{points:`${n.x},${n.y} ${o.x},${o.y} ${a.x},${a.y}`,fill:"white",stroke:i,"stroke-width":`${r}px`},value:"",children:[]}},a8t=({schPort:n,schComponent:e,transform:t,circuitJson:i})=>{let r=[],s=Ee(i).source_port.get(n.source_port_id),o={x:n.center.x,y:n.center.y},a=n.distance_from_component_edge??.4;switch(n.side_of_component){case"left":o.x+=a;break;case"right":o.x-=a;break;case"top":o.y-=a;break;case"bottom":o.y+=a;break}let c=st(t,n.center),l=st(t,o),u=set(i,n.source_port_id),h={...n.center};if(!u)switch(n.side_of_component){case"left":h.x+=O1;break;case"right":h.x-=O1;break;case"top":h.y-=O1;break;case"bottom":h.y+=O1;break}let d=st(t,h);r.push({name:"line",type:"element",attributes:{class:"component-pin",x1:l.x.toString(),y1:l.y.toString(),x2:d.x.toString(),y2:d.y.toString(),"stroke-width":`${Ui(t)}px`},value:"",children:[]});let _=Math.abs(t.a)*O1,g=[];u||g.push({name:"circle",type:"element",attributes:{class:"component-pin",cx:c.x.toString(),cy:c.y.toString(),r:_.toString(),"stroke-width":`${Ui(t)}px`},value:"",children:[]}),g.push({name:"rect",type:"element",attributes:{x:(c.x-_).toString(),y:(c.y-_).toString(),width:(_*2).toString(),height:(_*2).toString(),opacity:"0"},value:"",children:[]}),r.push({name:"g",type:"element",value:"",attributes:{"data-schematic-port-id":n.source_port_id},children:g});let{has_input_arrow:x,has_output_arrow:v}=n;if((x||v)&&n.side_of_component){let P=Math.abs(t.a)*.1,w=Ei.schematic.component_outline,T=P*Math.cos(Math.PI/6),k=Ui(t)/3,C=0,M=0;n.side_of_component==="left"?(C=0,M=Math.PI):n.side_of_component==="right"?(C=Math.PI,M=0):n.side_of_component==="top"?(C=Math.PI/2,M=-Math.PI/2):n.side_of_component==="bottom"&&(C=-Math.PI/2,M=Math.PI/2);let I=x&&v,E={...l},A={...l};if(I){let R=T;n.side_of_component==="left"?A.x-=R:n.side_of_component==="right"?A.x+=R:n.side_of_component==="top"?A.y-=R:n.side_of_component==="bottom"&&(A.y+=R)}if(x&&r.push($tt(E,C,P,w,k)),v){let R={x:A.x+P*Math.cos(M),y:A.y+P*Math.sin(M)};r.push($tt(R,M,P,w,k))}}return r},c8t=n=>{let e=[],{schPort:t,schComponent:i,transform:r,circuitJson:s}=n,o={x:t.center.x,y:t.center.y};if(!t.side_of_component)return[];let a=D_(t.side_of_component),c=t.distance_from_component_edge??.4;o.x+=a.x*c/2,o.y+=a.y*c/2,t.side_of_component==="top"||t.side_of_component==="bottom"?o.x-=.02:o.y+=.02;let l=st(r,o);return e.push({name:"text",type:"element",attributes:{class:"pin-number",x:l.x.toString(),y:l.y.toString(),style:"font-family: sans-serif;",fill:Ei.schematic.pin_number,"text-anchor":"middle","dominant-baseline":"auto","font-size":`${Ya(r,"pin_number")}px`,transform:t.side_of_component==="top"||t.side_of_component==="bottom"?`rotate(-90 ${l.x} ${l.y})`:""},children:[{type:"text",value:t.pin_number?.toString()||"",name:"",attributes:{},children:[]}],value:""}),e},Dtt=.1,l8t=n=>{let e=[],{schPort:t,schComponent:i,transform:r,circuitJson:s}=n,o={x:t.center.x,y:t.center.y};if(!t.side_of_component)return[];let a=D_(t.side_of_component),c=t.distance_from_component_edge??.4;o.x+=a.x*(c+Dtt),o.y+=a.y*(c+Dtt);let l=st(r,o),u=t.display_pin_label??i.port_labels?.[`${t.pin_number}`];if(!u)return[];let h=u.startsWith("N_"),d=h?u.slice(2):u,_=Ya(r,h?"negated_pin_number":"pin_number");return e.push({name:"text",type:"element",attributes:{class:"pin-number",x:l.x.toString(),y:l.y.toString(),style:`font-family: sans-serif;${h?" text-decoration: overline;":""}`,fill:Ei.schematic.pin_number,"text-anchor":t.side_of_component==="left"||t.side_of_component==="bottom"?"start":"end","dominant-baseline":"middle","font-size":`${_}px`,transform:t.side_of_component==="top"||t.side_of_component==="bottom"?`rotate(-90 ${l.x} ${l.y})`:""},children:[{type:"text",value:d||"",name:"",attributes:{},children:[]}],value:""}),e},u8t=n=>{let e=[],{schPort:t,schComponent:i,transform:r,circuitJson:s}=n;return e.push(...a8t(n)),e.push(...c8t(n)),e.push(...l8t(n)),e},oet=({elm:n,transform:e,colorMap:t})=>{let i=st(e,n.position),r={center:"middle",center_right:"end",bottom_left:"start",bottom_center:"middle",bottom_right:"end",left:"start",right:"end",top:"middle",bottom:"middle",top_left:"start",top_center:"middle",top_right:"end",center_left:"start"},s={center:"middle",center_right:"middle",bottom_left:"ideographic",bottom_center:"ideographic",bottom_right:"ideographic",left:"middle",right:"middle",top:"hanging",bottom:"ideographic",top_left:"hanging",top_center:"hanging",top_right:"hanging",center_left:"middle"},o=n.text.split(`
137
+ `),a=o.length===1?[{type:"text",value:n.text,name:n.schematic_text_id,attributes:{},children:[]}]:o.map((c,l)=>({type:"element",name:"tspan",value:"",attributes:{x:i.x.toString(),...l>0?{dy:"1em"}:{}},children:[{type:"text",value:c,name:l===0?n.schematic_text_id:"",attributes:{},children:[]}]}));return{type:"element",name:"text",value:"",attributes:{x:i.x.toString(),y:i.y.toString(),fill:n.color??t.schematic.sheet_label,"text-anchor":r[n.anchor],"dominant-baseline":s[n.anchor],"font-family":"sans-serif","font-size":`${Ya(e,"reference_designator",n.font_size)}px`,transform:`rotate(${n.rotation}, ${i.x}, ${i.y})`},children:a}},p8t=({component:n,transform:e,circuitJson:t,colorMap:i})=>{let r=[],s=st(e,{x:n.center.x-n.size.width/2,y:n.center.y+n.size.height/2}),o=st(e,{x:n.center.x+n.size.width/2,y:n.center.y-n.size.height/2}),a=o.x-s.x,c=o.y-s.y;r.push({name:"rect",type:"element",value:"",attributes:{class:"component chip",x:s.x.toString(),y:s.y.toString(),width:a.toString(),height:c.toString(),"stroke-width":`${Ui(e)}px`,fill:i.schematic.component_body,stroke:i.schematic.component_outline},children:[]}),r.push({name:"rect",type:"element",value:"",attributes:{class:"component-overlay",x:s.x.toString(),y:s.y.toString(),width:a.toString(),height:c.toString(),fill:"transparent"},children:[]});let l=Ee(t).schematic_text.list();for(let h of l)h.schematic_component_id===n.schematic_component_id&&r.push(oet({elm:h,transform:e,colorMap:i}));let u=Ee(t).schematic_port.list({schematic_component_id:n.schematic_component_id});for(let h of u)r.push(...u8t({schPort:h,schComponent:n,transform:e,circuitJson:t}));return r};_8t=({schNetLabel:n,realToScreenTransform:e,colorMap:t})=>{if(!n.text)return[];let i=n.text.startsWith("N_"),r=i?n.text.slice(2):n.text,s=[],o=_i[n.symbol_name];if(!o)return s.push(UA({text:`Symbol not found: ${n.symbol_name}`,realCenter:n.center,realToScreenTransform:e})),s;let a=o.primitives.filter(H=>H.type==="path"),c=o.primitives.filter(H=>H.type==="text"),l=o.primitives.filter(H=>H.type==="circle"),u=o.primitives.filter(H=>H.type==="box"),h={minX:Math.min(...a.flatMap(H=>H.points.map(et=>et.x))),maxX:Math.max(...a.flatMap(H=>H.points.map(et=>et.x))),minY:Math.min(...a.flatMap(H=>H.points.map(et=>et.y))),maxY:Math.max(...a.flatMap(H=>H.points.map(et=>et.y)))},d=z_("net_label"),g=Xw(r||"")+hl*2+F_*r.length+L_,x=D_(n.anchor_side),v=n.anchor_position??{x:n.center.x-x.x*g*d/2,y:n.center.y-x.y*g*d/2},w=ls(0/180*Math.PI),T={minX:Math.min(...o.primitives.flatMap(H=>H.type==="path"?H.points.map(et=>et.x):[])),maxX:Math.max(...o.primitives.flatMap(H=>H.type==="path"?H.points.map(et=>et.x):[])),minY:Math.min(...o.primitives.flatMap(H=>H.type==="path"?H.points.map(et=>et.y):[])),maxY:Math.max(...o.primitives.flatMap(H=>H.type==="path"?H.points.map(et=>et.y):[]))},k=o.ports?.[0]?{x:o.ports[0].x,y:o.ports[0].y}:{x:T.minX,y:(T.minY+T.maxY)/2},C=st(w,k),M=Fe(yn(v.x-C.x,v.y-C.y),w,Ti(1)),[I,E]=st(Fe(e,M),[h.minX,h.minY]),[A,R]=st(Fe(e,M),[h.maxX,h.maxY]),B=Math.abs(R-E),j=Math.min(E,R),U=Math.abs(A-I),V=Math.min(I,A);s.push({name:"rect",type:"element",value:"",attributes:{class:"component-overlay",x:V.toString(),y:j.toString(),width:U.toString(),height:B.toString(),fill:"transparent"},children:[]});for(let H of a){let et=H.points.map((tt,mt)=>{let[G,Q]=st(Fe(e,M),[tt.x,tt.y]);return`${mt===0?"M":"L"} ${G} ${Q}`}).join(" ");s.push({name:"path",type:"element",attributes:{d:et+(H.closed?" Z":""),stroke:t.schematic.component_outline,fill:"none","stroke-width":`${Ui(e)}px`,"stroke-linecap":"round"},value:"",children:[]})}for(let H of c){let et=st(Fe(e,M),H),tt=H.text;tt==="{REF}"?tt=r||"":tt==="{VAL}"&&(tt="");let G=Math.abs(e.a)*.1,Q={x:et.x,y:et.y};s.push({name:"text",type:"element",attributes:{x:Q.x.toString(),y:Q.y.toString(),fill:t.schematic.label_local,"font-family":"sans-serif","text-anchor":KRt[H.anchor],"dominant-baseline":JRt[H.anchor],"font-size":`${Ya(e,"reference_designator")}px`,...i&&tt===r?{style:"text-decoration: overline;"}:{}},children:[{type:"text",value:tt,name:"",attributes:{},children:[]}],value:""})}for(let H of u){let et=st(Fe(e,M),H),tt=Fe(e,M).a;s.push({name:"rect",type:"element",attributes:{x:et.x.toString(),y:et.y.toString(),width:(H.width*tt).toString(),height:(H.height*tt).toString(),fill:"red"},value:"",children:[]})}for(let H of l){let et=st(Fe(e,M),H),tt=Fe(e,M).a;s.push({name:"circle",type:"element",attributes:{cx:et.x.toString(),cy:et.y.toString(),r:(H.radius*tt).toString(),fill:"none",stroke:t.schematic.component_outline,"stroke-width":`${Ui(e)}px`},value:"",children:[]})}return s},y8t=({schNetLabel:n,realToScreenTransform:e,colorMap:t})=>{if(!n.text)return[];let i=n.text;if(n.symbol_name)return _8t({schNetLabel:n,realToScreenTransform:e,colorMap:t});let r=[],s=Ya(e,"net_label"),o=z_("net_label"),a=Xw(i||""),c=st(e,n.center),l=D_(n.anchor_side),u={...l};u.y*=-1;let h=a+hl*2+F_*i.length+L_,d=n.anchor_position?st(e,n.anchor_position):{x:c.x-u.x*h*s/2,y:c.y-u.y*h*s/2},_=n.anchor_position??{x:n.center.x-l.x*h*o/2,y:n.center.y-l.y*h*o/2},g={left:0,top:-90,bottom:90,right:180}[n.anchor_side],x=[{x:0,y:0},{x:hl,y:.6},{x:hl*2+L_+F_*i.length+a,y:.6},{x:hl*2+L_+F_*i.length+a,y:-.6},{x:hl,y:-.6}].map(k=>st(Fe(e,yn(_.x,_.y),Ti(o),ls(g/180*Math.PI)),k)),v=`
138
138
  M ${x[0].x},${x[0].y}
139
139
  L ${x[1].x},${x[1].y}
140
140
  L ${x[2].x},${x[2].y}
@@ -158,7 +158,7 @@ svg { font-family: 'Inter', 'Helvetica Neue', Arial, sans-serif; }
158
158
  fieldset[disabled]:not(fieldset[disabled] legend:first-of-type *)
159
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 Ms=Gt(qh(),1);var L5={};function F5(n,e){return n===Ms.default.falseFunc?Ms.default.falseFunc:t=>e.isTag(t)&&n(t)}function z5(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 O5(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 R5=(n,e,t,i,r)=>{let s=r(e,O5(t),i);return s===Ms.default.trueFunc?n:s===Ms.default.falseFunc?Ms.default.falseFunc:o=>s(o)&&n(o)},eS={is:R5,matches:R5,where:R5,not(n,e,t,i,r){let s=r(e,O5(t),i);return s===Ms.default.falseFunc?n:s===Ms.default.trueFunc?Ms.default.falseFunc:o=>!s(o)&&n(o)},has(n,e,t,i,r){let{adapter:s}=t,o=O5(t);o.relativeSelector=!0;let a=e.some(u=>u.some(gg))?[L5]:void 0,c=r(e,o,a);if(c===Ms.default.falseFunc)return Ms.default.falseFunc;let l=F5(c,s);if(a&&c!==Ms.default.trueFunc){let{shouldTestNextSiblings:u=!1}=c;return h=>{if(!n(h))return!1;a[0]=h;let d=s.getChildren(h),_=u?[...d,...z5(h,s)]:d;return s.existsOne(l,_)}}return u=>n(u)&&s.existsOne(l,s.getChildren(u))}};function TG(n,e,t,i,r){var s;let{name:o,data:a}=e;if(Array.isArray(a)){if(!(o in eS))throw new Error(`Unknown pseudo-class :${o}(${a})`);return eS[o](n,a,t,i,r)}let c=(s=t.pseudos)===null||s===void 0?void 0:s[o],l=typeof c=="string"?c:A5[o];if(typeof l=="string"){if(a!=null)throw new Error(`Pseudo ${o} doesn't have any arguments`);let u=yg(l);return eS.is(n,u,t,i,r)}if(typeof c=="function")return N5(c,o,a,1),u=>c(u,a)&&n(u);if(o in bg)return bg[o](n,a,t,i);if(o in tS){let u=tS[o];return N5(u,o,a,2),h=>u(h,t,a)&&n(h)}throw new Error(`Unknown pseudo-class :${o}`)}function $5(n,e){let t=e.getParent(n);return t&&e.isTag(t)?t:null}function MG(n,e,t,i,r){let{adapter:s,equals:o}=t;switch(e.type){case de.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case de.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case de.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()),SG[e.action](n,e,t)}case de.Pseudo:return TG(n,e,t,i,r);case de.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 de.Descendant:{if(t.cacheResults===!1||typeof WeakSet>"u")return function(l){let u=l;for(;u=$5(u,s);)if(n(u))return!0;return!1};let a=new WeakSet;return function(l){let u=l;for(;u=$5(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=$5(l,s));return!1};case de.Parent:return function(c){return s.getChildren(c).some(l=>s.isTag(l)&&n(l))};case de.Child:return function(c){let l=s.getParent(c);return l!=null&&s.isTag(l)&&n(l)};case de.Sibling:return function(c){let l=s.getSiblings(c);for(let u=0;u<l.length;u++){let h=l[u];if(o(c,h))break;if(s.isTag(h)&&n(h))return!0}return!1};case de.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 h=0;h<l.length;h++){let d=l[h];if(o(c,d))break;s.isTag(d)&&(u=d)}return!!u&&n(u)};case de.Universal:{if(e.namespace!=null&&e.namespace!=="*")throw new Error("Namespaced universal selectors are not yet supported by css-select");return n}}}function EG(n,e,t){let i=nS(n,e,t);return F5(i,e.adapter)}function nS(n,e,t){let i=typeof n=="string"?yg(n):n;return iS(i,e,t)}function CG(n){return n.type===de.Pseudo&&(n.name==="scope"||Array.isArray(n.data)&&n.data.some(e=>e.some(CG)))}var _3t={type:de.Descendant},y3t={type:"_flexibleDescendant"},g3t={type:de.Pseudo,name:"scope",data:null};function x3t(n,{adapter:e},t){let i=!!t?.every(r=>{let s=e.isTag(r)&&e.getParent(r);return r===L5||s&&e.isTag(s)});for(let r of n){if(!(r.length>0&&gg(r[0])&&r[0].type!==de.Descendant))if(i&&!r.some(CG))r.unshift(_3t);else continue;r.unshift(g3t)}}function iS(n,e,t){var i;n.forEach(E5),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)x3t(n,e,s);else if(n.some(c=>c.length>0&&gg(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!==de.Pseudo||l.name!=="scope"||(r&&u.type===de.Descendant?c[1]=y3t:(u.type===de.Adjacent||u.type===de.Sibling)&&(o=!0))}return b3t(c,e,s)}).reduce(v3t,Ca.default.falseFunc);return a.shouldTestNextSiblings=o,a}function b3t(n,e,t){var i;return n.reduce((r,s)=>r===Ca.default.falseFunc?Ca.default.falseFunc:MG(r,s,e,t,iS),(i=e.rootFunc)!==null&&i!==void 0?i:Ca.default.trueFunc)}function v3t(n,e){return e===Ca.default.falseFunc||n===Ca.default.trueFunc?n:n===Ca.default.falseFunc||e===Ca.default.trueFunc?e:function(i){return n(i)||e(i)}}var IG=(n,e)=>n===e,S3t={adapter:J2,equals:IG};function NG(n){var e,t,i,r;let s=n??S3t;return(e=s.adapter)!==null&&e!==void 0||(s.adapter=J2),(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:IG),s}function j5(n){return function(t,i,r){let s=NG(i);return n(t,s,r)}}var pte=j5(EG),hte=j5(nS),dte=j5(iS);function AG(n){return function(t,i,r){let s=NG(r);typeof t!="function"&&(t=nS(t,s,i));let o=w3t(i,s.adapter,t.shouldTestNextSiblings);return n(t,o,s)}}function w3t(n,e,t=!1){return t&&(n=P3t(n,e)),Array.isArray(n)?e.removeSubsets(n):e.getChildren(n)}function P3t(n,e){let t=Array.isArray(n)?n.slice(0):[n],i=t.length;for(let r=0;r<i;r++){let s=z5(t[r],e);t.push(...s)}return t}var B5=AG((n,e,t)=>n===D5.default.falseFunc||!e||e.length===0?[]:t.adapter.findAll(n,e)),rS=AG((n,e,t)=>n===D5.default.falseFunc||!e||e.length===0?null:t.adapter.findOne(n,e));J();St();J();var uH=Gt(En(),1);St();var dH=Gt(En(),1),mH=Gt(En(),1);St();ii();W5();var q5=(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(h=>h.type===l&&h[c]===o[c]);return u?n.find(h=>h.type===s&&h[`${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&&(Yh[s]??Bh).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(h=>h.type==="source_component"&&h.name===a);if(!l)return null;let u=n.find(h=>h.type==="source_port"&&h.source_component_id===l.source_component_id&&(h.name===c||(h.port_hints??[]).includes(c)));if(!u)return null;if(s==="source_port")return u;if(s==="pcb_port")return n.find(h=>h.type==="pcb_port"&&h.source_port_id===u.source_port_id);if(s==="schematic_port")return n.find(h=>h.type==="schematic_port"&&h.source_port_id===u.source_port_id)}}}})};q5.unparsed=q5;var GG=q5;var _ne=Gt(WG(),1);er();function io(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 kg(n,e){let t=io(n),i=io(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=Vn(n.center.x,i.minX,i.maxX),o.y=Vn(n.center.y,i.minY,i.maxY),a.x=Vn(e.center.x,t.minX,t.maxX),a.y=Vn(e.center.y,t.minY,t.maxY),{distance:Math.hypot(o.x-a.x,o.y-a.y),pointA:o,pointB:a})}function Ao(n,e){return kg(n,e)}function t4(n,e){let t=io(n),i=io(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 Vn(n,e,t){return Math.max(e,Math.min(t,n))}function Tg(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}=kg(s,o);a<t&&(t=a,i=c,r=l)}return{pointA:i,pointB:r,distance:t}}er();er();var eH="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var nH=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=eH[t[n]&63];return e};er();var nd=(n,e)=>Math.abs(n.x-e.x)+Math.abs(n.y-e.y),iH=(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)}},cH=(n,e,t)=>Math.abs(n.x-e.x)*Math.abs(t.dx)+Math.abs(n.y-e.y)*Math.abs(t.dy),lH=(n,e=.1)=>`${Math.round(n.x/e)},${Math.round(n.y/e)}`,rH=(n,e)=>Math.abs(n-e)<1e-4,pH=(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=rH(s.y,o.y),l=rH(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 h={type:"rect",layers:[s.layer,o.layer],center:{x:s.x,y:s.y},connectedTo:[e],width:t,height:t};i.push(h)}}return i},hH=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,h=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<h&&r<l.bottom&&(g=l.bottom-r):s===0&&o===-1&&i>u&&i<h&&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 I3t(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 h={start:e[u],end:e[u+1]};if(h.start.layer===r.start.layer&&h.start.layer===r.start.layer){let d=N3t(h,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 N3t(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 sH(t,n)&&sH(t,e)?t:null}function sH(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 A3t(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 fne=(0,dH.default)("autorouter:shortenPathWithShortcuts");function R3t(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,h=l.start.y===l.end.y,d=o&&u,_=a&&h;if(_&&d||!(d||_))continue;let x=!1,v=Math.min(r.start.x,r.end.x),P=Math.max(r.start.x,r.end.x),w=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),C=Math.max(r.start.y,r.end.y),M=Math.min(l.start.y,l.end.y),I=Math.max(l.start.y,l.end.y);if(_?x=v<=T&&P>=w:d&&(x=k<=I&&C>=M),!x)continue;let E=[],A=t[t.length-1],R=n[c+2];if(!R)continue;_&&w<P&&R.x===w&&E.push({x:w,y:r.start.y,layer:r.start.layer}),_&&T>v&&R.x===T&&E.push({x:T,y:r.start.y,layer:r.start.layer}),d&&M<C&&R.y===M&&E.push({x:r.start.x,y:M,layer:r.start.layer}),d&&I>k&&R.y===I&&E.push({x:r.start.x,y:I,layer:r.start.layer});let B=null;for(let j of E)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 ed=(0,uH.default)("autorouting-dataset:astar"),fH=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??ed.enabled,this.isRemovePathLoopsEnabled=n.isRemovePathLoopsEnabled??!1,this.isShortenPathWithShortcutsEnabled=n.isShortenPathWithShortcutsEnabled??!1,this.debug&&(ed.enabled=!0),ed.enabled&&(this.debugSolutions={},this.debugMessage="")}getNeighbors(n){return[]}isSameNode(n,e){return nd(n,e)<this.GRID_STEP}computeG(n,e){return n.g+nd(n,e)}computeH(n){return nd(n,this.goalPoint)}getNodeName(n){return lH(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),h=c+u*this.GREEDY_MULTIPLIER,d={...a,g:c,h:u,f:h,obstacleHit:a.obstacleHit??void 0,manDistFromParent:nd(r,a),nodesInPath:r.nodesInPath+1,parent:r,enterMarginCost:a.enterMarginCost,travelMarginCostFactor:a.travelMarginCostFactor};n.push(d),o.push(d)}}return ed.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 ed.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations
160
160
  `),this.isRemovePathLoopsEnabled&&(r=I3t(r)),this.isShortenPathWithShortcutsEnabled&&(r=R3t(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 ed.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations (failed)
161
- `),{solved:!1,connectionName:n.name}}createObstacleList({dominantLayer:n,connection:e,obstaclesFromTraces:t}){return new hH(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),ed.enabled&&this.drawDebugTraceObstacles(e),r.solved&&e.push(...pH(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:A3t(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})}}},O3t=(0,mH.default)("autorouting-dataset:infinite-grid-ijump-astar:get-distance-to-overcome-obstacle");function e4({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 h=e.dy===0,d=h?i.height:i.width;if((h?u.height:u.width)>d)return O3t("next obstacle on path is bigger, not trying to overcome it"),l;let g=e4({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 L3t=class extends fH{constructor(){super(...arguments);f(this,"MAX_ITERATIONS",200)}getNeighbors(e){let t=this.obstacles,i=this.goalPoint,r;e.parent?r=iH(e.parent,e):r=iH(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=e4({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=cH(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 F3t(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,P=d*1.1,w=Math.abs(r*c)+Math.abs(d*l);o.push({center:{x:t.x+x,y:t.y+v},width:P,height:w})}}else{let d=r/e;for(let _=0;_<e;_++){let g=(_-e/2+.5)*d,x=-g*l,v=g*c,P=Math.abs(i*c)+Math.abs(d*l),w=d*1.1;o.push({center:{x:t.x+x,y:t.y+v},width:P,height:w})}}return o}var uS=["top","inner1","inner2","bottom"],_H=(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=F3t(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:uS,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:uS,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:uS,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:uS,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=pH(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 oH(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 _H(i).map(r=>({...r,connectedTo:[t]}))}var yH=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=oH({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=oH({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=Tg(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]}},z3t=(n,e={})=>{let t={minTraceWidth:.1};t.layerCount=e.layerCount??1,t.obstacles=_H(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=GG(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 lS(n);s=yH({connection:s,pcbConnMap:o})}t.connections.push(s),$3t(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},$3t=(n,e,t)=>{for(let i of e)for(let r of n)D3t(i,r)&&r.connectedTo.push(t)};function D3t(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 aH(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 n4={1:["top"],2:["top","bottom"],4:["top","inner1","inner2","bottom"]},j3t=n=>n4[n];function gH(n,e){let i=n4[n].indexOf(e);if(i===-1)throw new Error(`Invalid layer for getLayerIndex (for layerCount === ${n}): "${e}"`);return i}function B3t(n,e){let i=n4[n][e];if(!i)throw new Error(`Invalid index for indexToLayer (for layerCount === ${n}): "${e}"`);return i}var Y3t=class extends hH{constructor(e,t){super([]);f(this,"obstacles");f(this,"GRID_STEP",.1);f(this,"layerCount");this.layerCount=e;let i=j3t(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:gH(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,h=null;if(l!==0){let d=o+l;return this.isObstacleAt(r,s,d,i)?(u=1,h=this.getObstacleAt(r,s,d,i)):u=1,{dx:a,dy:c,dl:l,wallDistance:u,obstacle:h}}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,P=null;a===1&&c===0?s>v&&s<x&&r<d.left&&(P=d.left-r):a===-1&&c===0?s>v&&s<x&&r>d.right&&(P=r-d.right):a===0&&c===1?r>_&&r<g&&s<d.bottom&&(P=d.bottom-s):a===0&&c===-1&&r>_&&r<g&&s>d.top&&(P=s-d.top),P!==null&&P<u&&(u=P,h=d)}return{dx:a,dy:c,dl:0,wallDistance:u,obstacle:h}}}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}},pS=class extends fH{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 lS,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?yH({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_${nH(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 Y3t(this.layerCount,this.allObstacles.filter(s=>!s.connectedTo.includes(r)).concat(i??[]))}computeG(e,t){let i=e.g+nd(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 gH(this.layerCount,e)}indexToLayer(e){return B3t(this.layerCount,e)}getNodeName(e){return`${lH(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=nd(e,i);if(r<=this.OBSTACLE_MARGIN)return this.getNeighborsSurroundingGoal(e);let s;e.parent?s=aH(e.parent,e):s=aH(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=nd(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(h=>h.dx===s.dx*-1&&h.dy===s.dy*-1&&h.dl===s.dl*-1?!1:!(h.dx===s.dx&&h.dy===s.dy&&h.dl===s.dl&&e.parent?.obstacleHit)).map(h=>t.getOrthoDirectionCollisionInfo(e,h,{margin:this.OBSTACLE_MARGIN})).filter(h=>!(h.wallDistance<this.OBSTACLE_MARGIN)),u=[];for(let h of l){let d=h.dx===0&&h.dy===0&&h.dl===1,_=h.dx===0&&h.dy===0&&h.dl===-1;if((d||_)&&![e.l,e.l+h.dl].every(w=>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:w}).length===0))continue;if(d){e.l<this.layerCount-1&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}if(_){e.l>0&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}let g=null;e?.obstacleHit&&(g=e4({node:e,travelDir:h,wallDir:{...s,wallDistance:this.OBSTACLE_MARGIN},obstacle:e.obstacleHit,obstacles:t,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let x=cH(e,i,h),v=(h.dx===0||Math.sign(i.x-e.x)===h.dx)&&(h.dy===0||Math.sign(i.y-e.y)===h.dy);if(x<h.wallDistance&&x>0&&v){let P=e.l===i.l,w=0;!P&&Math.abs(x-r)<this.GRID_STEP&&(w=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin),u.push({...h,travelDistance:x-w,enterMarginCost:0,travelMarginCostFactor:1})}else if(g!==null&&g<h.wallDistance){for(let{margin:P,enterCost:w,travelCostFactor:T}of this.marginsWithCosts)g-this.OBSTACLE_MARGIN+P*2<h.wallDistance&&u.push({...h,travelDistance:g-this.OBSTACLE_MARGIN+P,enterMarginCost:w,travelMarginCostFactor:T});if(h.wallDistance===1/0)u.push({...h,travelDistance:x,enterMarginCost:0,travelMarginCostFactor:1});else if(h.wallDistance>this.largestMargin)for(let{margin:P,enterCost:w,travelCostFactor:T}of this.marginsWithCosts)h.wallDistance>this.largestMargin+P&&u.push({...h,travelDistance:h.wallDistance-P,enterMarginCost:w,travelMarginCostFactor:T})}else if(h.wallDistance!==1/0)for(let{margin:P,enterCost:w,travelCostFactor:T}of this.marginsWithCosts)h.wallDistance>P&&u.push({...h,travelDistance:h.wallDistance-P,enterMarginCost:w,travelMarginCostFactor:T})}return u.map(h=>({x:e.x+h.dx*h.travelDistance,y:e.y+h.dy*h.travelDistance,l:e.l+h.dl,obstacleHit:h.obstacle,travelMarginCostFactor:h.travelMarginCostFactor,enterMarginCost:h.enterMarginCost}))}};function xH(n){let e=z3t(n),t=new L3t({input:e});return{solution:t.solveAndMapToTraces(),debugSolutions:t.debugSolutions,debugMessage:t.debugMessage}}J();J();St();J();J();St();St();J();J();St();J();J();J();J();St();J();J();J();St();J();J();St();J();J();J();J();J();J();J();J();J();J();St();J();St();J();St();J();J();St();St();J();St();J();J();St();J();J();J();St();J();St();J();St();J();St();J();St();J();St();J();St();J();J();J();J();J();J();J();J();St();J();St();J();J();St();J();St();J();J();J();St();J();St();St();J();J();J();St();J();J();J();St();J();St();J();St();J();St();J();St();J();St();J();St();J();St();J();J();St();J();St();J();St();J();J();St();St();J();J();St();St();J();J();St();J();St();J();St();J();St();J();St();J();St();J();J();St();J();St();J();St();J();St();J();St();J();St();J();St();J();St();St();J();St();J();St();J();J();St();J();St();J();St();J();St();J();St();J();J();var Ct=n=>{};Ct("extra props b");Ct("missing props b");Ct(!0);Ct("property a has mismatched types");var X3t=p.enum(["up","down","left","right"]),Ane=p.enum(["top-to-bottom","left-to-right","bottom-to-top","right-to-left"]);Ct(!0);Ct(!0);var ro=p.array(p.string().or(p.number()));Ct(!0);var fS=p.object({x:Y,y:Y,z:Y}),U3t=p.object({x:p.union([p.number(),p.string()]),y:p.union([p.number(),p.string()]),z:p.union([p.number(),p.string()])}),Uc=p.object({rotationOffset:p.number().or(U3t).optional(),positionOffset:fS.optional(),size:fS.optional(),modelUnitToMmScale:Y.optional(),zOffsetFromSurface:Y.optional()});Ct(!0);var V3t=Uc.extend({stlUrl:p.string()}),G3t=Uc.extend({objUrl:p.string(),mtlUrl:p.string().optional()}),H3t=Uc.extend({gltfUrl:p.string()}),W3t=Uc.extend({glbUrl:p.string()}),q3t=Uc.extend({stepUrl:p.string()}),Z3t=Uc.extend({wrlUrl:p.string()}),K3t=Uc.extend({jscad:p.record(p.any())}),MH=p.union([p.null(),p.string(),p.custom(n=>n&&typeof n=="object"&&"type"in n&&"props"in n),V3t,G3t,H3t,W3t,q3t,Z3t,K3t]);Ct(!0);var J3t=p.custom(n=>!0),s4=p.object({silkscreenFontSize:Y.optional(),viaPadDiameter:Y.optional(),viaHoleDiameter:Y.optional(),silkscreenTextPosition:p.union([p.enum(["centered","outside","none"]),p.object({offsetX:p.number(),offsetY:p.number()})]).optional(),silkscreenTextVisibility:p.enum(["hidden","visible","inherit"]).optional()});Ct(!0);var Q3t=p.custom(n=>!0),je=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbRotation:Qe.optional(),pcbPositionAnchor:p.string().optional(),pcbPositionMode:p.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),layer:pe.optional(),pcbMarginTop:Y.optional(),pcbMarginRight:Y.optional(),pcbMarginBottom:Y.optional(),pcbMarginLeft:Y.optional(),pcbMarginX:Y.optional(),pcbMarginY:Y.optional(),pcbStyle:s4.optional(),pcbRelative:p.boolean().optional(),relative:p.boolean().optional()});Ct(!0);var mS=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbRotation:Qe.optional(),pcbPositionAnchor:p.string().optional(),pcbPositionMode:p.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),pcbMarginTop:Y.optional(),pcbMarginRight:Y.optional(),pcbMarginBottom:Y.optional(),pcbMarginLeft:Y.optional(),pcbMarginX:Y.optional(),pcbMarginY:Y.optional(),pcbStyle:s4.optional(),schMarginTop:Y.optional(),schMarginRight:Y.optional(),schMarginBottom:Y.optional(),schMarginLeft:Y.optional(),schMarginX:Y.optional(),schMarginY:Y.optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Qe.optional(),layer:pe.optional(),footprint:J3t.optional(),symbol:Q3t.optional(),relative:p.boolean().optional(),schRelative:p.boolean().optional(),pcbRelative:p.boolean().optional()});Ct(!0);var tMt=p.object({supplierPartNumbers:p.record(Nm,p.array(p.string())).optional()});Ct(!0);var eMt=p.object({providesPower:p.boolean().optional(),requiresPower:p.boolean().optional(),providesGround:p.boolean().optional(),requiresGround:p.boolean().optional(),providesVoltage:p.union([p.string(),p.number()]).optional(),requiresVoltage:p.union([p.string(),p.number()]).optional(),doNotConnect:p.boolean().optional(),includeInBoardPinout:p.boolean().optional(),highlightColor:p.string().optional(),mustBeConnected:p.boolean().optional()});Ct(!0);var ri=mS.merge(tMt).extend({key:p.any().optional(),name:p.string(),cadModel:MH.optional(),children:p.any().optional(),symbolName:p.string().optional(),doNotPlace:p.boolean().optional(),obstructsWithinBounds:p.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:p.boolean().optional().describe("Whether to show this component's CAD model as translucent in the 3D viewer."),pinAttributes:p.record(p.string(),eMt).optional()});Ct(!0);var o4=["pin1","left","pin2","right"],_S=["pin1","left","anode","pos","pin2","right","cathode","neg"],Vne=Y.or(p.enum(["2x","3x","4x"]));var Vc=p.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 hS=p.object({pins:p.array(p.union([p.number(),p.string()])),direction:p.union([p.literal("top-to-bottom"),p.literal("left-to-right"),p.literal("bottom-to-top"),p.literal("right-to-left")])}),Eg=p.object({leftSize:p.number().optional().describe("@deprecated, use leftPinCount"),topSize:p.number().optional().describe("@deprecated, use topPinCount"),rightSize:p.number().optional().describe("@deprecated, use rightPinCount"),bottomSize:p.number().optional().describe("@deprecated, use bottomPinCount"),leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftSide:hS.optional(),rightSide:hS.optional(),topSide:hS.optional(),bottomSide:hS.optional()}),a4=Eg;Ct(!0);var Cg=p.record(p.object({marginLeft:Y.optional(),marginRight:Y.optional(),marginTop:Y.optional(),marginBottom:Y.optional(),leftMargin:Y.optional(),rightMargin:Y.optional(),topMargin:Y.optional(),bottomMargin:Y.optional()}));Ct(!0);var Cs=p.string().regex(/^[A-Za-z0-9_]+$/),t_=p.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),Ro=p.object({x:Y,y:Y}),Ig=p.object({edit_event_id:p.string(),in_progress:p.boolean().optional(),created_at:p.number()});Ct(!0);var nMt=Ig.extend({pcb_edit_event_type:p.literal("edit_component_location").describe("deprecated"),edit_event_type:p.literal("edit_pcb_component_location"),pcb_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var iMt=Ig.extend({pcb_edit_event_type:p.literal("edit_trace_hint").describe("deprecated"),edit_event_type:p.literal("edit_pcb_trace_hint").optional(),pcb_port_id:p.string(),pcb_trace_hint_id:p.string().optional(),route:p.array(p.object({x:p.number(),y:p.number(),via:p.boolean().optional()}))});Ct(!0);var rMt=Ig.extend({edit_event_type:p.literal("edit_schematic_component_location"),schematic_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var cie=Ig.extend({edit_event_type:p.literal("edit_pcb_group_location"),pcb_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var uie=Ig.extend({edit_event_type:p.literal("edit_schematic_group_location"),schematic_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var hie=p.union([nMt,iMt,rMt]);Ct(!0);var sMt=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Zt});Ct(!0);var oMt=p.object({pcb_port_selector:p.string(),offsets:p.array(Ji)});Ct(!0);var aMt=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Zt});Ct(!0);var cMt=p.object({pcb_placements:p.array(sMt).optional(),manual_trace_hints:p.array(oMt).optional(),schematic_placements:p.array(aMt).optional()});Ct(!0);var e_=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),id=n=>p.record(p.enum(n),e_),Mg=p.object({layoutMode:p.enum(["grid","flex","match-adapt","relative","none"]).optional(),position:p.enum(["absolute","relative"]).optional(),grid:p.boolean().optional(),gridCols:p.number().or(p.string()).optional(),gridRows:p.number().or(p.string()).optional(),gridTemplateRows:p.string().optional(),gridTemplateColumns:p.string().optional(),gridTemplate:p.string().optional(),gridGap:p.number().or(p.string()).optional(),gridRowGap:p.number().or(p.string()).optional(),gridColumnGap:p.number().or(p.string()).optional(),flex:p.boolean().or(p.string()).optional(),flexDirection:p.enum(["row","column"]).optional(),alignItems:p.enum(["start","center","end","stretch"]).optional(),justifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),flexRow:p.boolean().optional(),flexColumn:p.boolean().optional(),gap:p.number().or(p.string()).optional(),pack:p.boolean().optional().describe("Pack the contents of this group using a packing strategy"),packOrderStrategy:p.enum(["largest_to_smallest","first_to_last","highest_to_lowest_pin_count"]).optional(),packPlacementStrategy:p.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:p.boolean().optional(),matchAdaptTemplate:p.any().optional()});Ct(!0);var bH=p.object({strokeWidth:D.optional(),dashed:p.boolean().optional(),solid:p.boolean().optional()}),lMt=p.custom(n=>typeof n=="string"),uMt=p.object({serverUrl:p.string().optional(),inputFormat:p.enum(["simplified","circuit-json"]).optional(),serverMode:p.enum(["job","solve-endpoint"]).optional(),serverCacheEnabled:p.boolean().optional(),cache:p.custom(n=>!0).optional(),traceClearance:D.optional(),groupMode:p.enum(["sequential_trace","subcircuit","sequential-trace"]).optional(),algorithmFn:p.custom(n=>typeof n=="function"||n===void 0).optional(),preset:p.enum(["sequential_trace","subcircuit","auto","auto_local","auto_cloud","freerouting","laser_prefab","sequential-trace","auto-local","auto-cloud"]).optional(),local:p.boolean().optional()}),pMt=p.union([p.literal("sequential_trace"),p.literal("subcircuit"),p.literal("auto"),p.literal("auto_local"),p.literal("auto_cloud"),p.literal("freerouting"),p.literal("laser_prefab"),p.literal("sequential-trace"),p.literal("auto-local"),p.literal("auto-cloud")]),hMt=p.string(),EH=p.union([uMt,pMt,hMt]),c4=mS.extend({name:p.string().optional(),children:p.any().optional(),schTitle:p.string().optional(),key:p.any().optional(),showAsSchematicBox:p.boolean().optional(),connections:p.record(p.string(),e_.optional()).optional(),schPinArrangement:a4.optional(),schPinSpacing:D.optional(),schPinStyle:Cg.optional(),...Mg.shape,grid:Mg.shape.grid.describe("@deprecated use pcbGrid"),flex:Mg.shape.flex.describe("@deprecated use pcbFlex"),pcbGrid:p.boolean().optional(),pcbGridCols:p.number().or(p.string()).optional(),pcbGridRows:p.number().or(p.string()).optional(),pcbGridTemplateRows:p.string().optional(),pcbGridTemplateColumns:p.string().optional(),pcbGridTemplate:p.string().optional(),pcbGridGap:p.number().or(p.string()).optional(),pcbGridRowGap:p.number().or(p.string()).optional(),pcbGridColumnGap:p.number().or(p.string()).optional(),pcbFlex:p.boolean().or(p.string()).optional(),pcbFlexGap:p.number().or(p.string()).optional(),pcbFlexDirection:p.enum(["row","column"]).optional(),pcbAlignItems:p.enum(["start","center","end","stretch"]).optional(),pcbJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),pcbFlexRow:p.boolean().optional(),pcbFlexColumn:p.boolean().optional(),pcbGap:p.number().or(p.string()).optional(),pcbPack:p.boolean().optional(),pcbPackGap:p.number().or(p.string()).optional(),schGrid:p.boolean().optional(),schGridCols:p.number().or(p.string()).optional(),schGridRows:p.number().or(p.string()).optional(),schGridTemplateRows:p.string().optional(),schGridTemplateColumns:p.string().optional(),schGridTemplate:p.string().optional(),schGridGap:p.number().or(p.string()).optional(),schGridRowGap:p.number().or(p.string()).optional(),schGridColumnGap:p.number().or(p.string()).optional(),schFlex:p.boolean().or(p.string()).optional(),schFlexGap:p.number().or(p.string()).optional(),schFlexDirection:p.enum(["row","column"]).optional(),schAlignItems:p.enum(["start","center","end","stretch"]).optional(),schJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),schFlexRow:p.boolean().optional(),schFlexColumn:p.boolean().optional(),schGap:p.number().or(p.string()).optional(),schPack:p.boolean().optional(),schMatchAdapt:p.boolean().optional(),pcbWidth:D.optional(),pcbHeight:D.optional(),minTraceWidth:D.optional(),schWidth:D.optional(),schHeight:D.optional(),pcbLayout:Mg.optional(),schLayout:Mg.optional(),cellBorder:bH.nullable().optional(),border:bH.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:lMt.optional()}),CH=p.custom(n=>"findPart"in n),l4=c4.extend({manualEdits:cMt.optional(),schAutoLayoutEnabled:p.boolean().optional(),schTraceAutoLabelEnabled:p.boolean().optional(),schMaxTraceDistance:Y.optional(),routingDisabled:p.boolean().optional(),defaultTraceWidth:D.optional(),minTraceWidth:D.optional(),partsEngine:CH.optional(),pcbRouteCache:p.custom(n=>!0).optional(),autorouter:EH.optional(),square:p.boolean().optional(),emptyArea:p.string().optional(),filledArea:p.string().optional(),width:Y.optional(),height:Y.optional(),outline:p.array(Ro).optional(),outlineOffsetX:Y.optional(),outlineOffsetY:Y.optional(),circuitJson:p.array(p.any()).optional()}),dMt=l4.extend({subcircuit:p.literal(!0)}),IH=p.discriminatedUnion("subcircuit",[c4.extend({subcircuit:p.literal(!1).optional()}),dMt]);Ct(!0);Ct(!0);Ct(!0);Ct(!0);var Qm=p.custom(n=>typeof n=="string"),u4=l4.omit({connections:!0}).extend({material:p.enum(["fr4","fr1"]).default("fr4"),layers:p.union([p.literal(1),p.literal(2),p.literal(4),p.literal(6),p.literal(8)]).default(2),borderRadius:Y.optional(),thickness:Y.optional(),boardAnchorPosition:Ro.optional(),boardAnchorAlignment:t_.optional(),title:p.string().optional(),solderMaskColor:Qm.optional(),topSolderMaskColor:Qm.optional(),bottomSolderMaskColor:Qm.optional(),silkscreenColor:Qm.optional(),topSilkscreenColor:Qm.optional(),bottomSilkscreenColor:Qm.optional(),doubleSidedAssembly:p.boolean().optional().default(!1),schematicDisabled:p.boolean().optional()});Ct(!0);var NH=c4.omit({width:!0,height:!0,children:!0}).extend({width:Y,height:Y,children:p.any().optional(),noSolderMask:p.boolean().optional(),panelizationMethod:p.enum(["tab-routing","none"]).optional(),boardGap:Y.optional(),tabWidth:Y.optional(),tabLength:Y.optional(),mouseBites:p.boolean().optional()});Ct(!0);var wie=l4.extend({padding:Y.optional(),paddingLeft:Y.optional(),paddingRight:Y.optional(),paddingTop:Y.optional(),paddingBottom:Y.optional()});Ct(!0);var fMt=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),mMt=p.custom().pipe(p.record(p.string(),fMt)),_Mt=p.record(Cs,Cs.or(p.array(Cs).readonly()).or(p.array(Cs)));Ct(!0);var yMt=p.object({manufacturerPartNumber:p.string().optional(),supplierPartNumber:p.record(Nm,p.array(p.string())).optional()}),n_=ri.extend({manufacturerPartNumber:p.string().optional(),pinLabels:_Mt.optional(),showPinAliases:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),externallyConnectedPins:p.array(p.array(p.string())).optional(),schPinArrangement:Eg.optional(),schPortArrangement:Eg.optional(),pinCompatibleVariants:p.array(yMt).optional(),schPinStyle:Cg.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),noSchematicRepresentation:p.boolean().optional(),connections:mMt.optional()});Ct(!0);var AH=n_;Ct(!0);var p4=ri.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(Cs),Cs.or(p.array(Cs))).optional(),schPinStyle:Cg.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),schDirection:p.enum(["left","right"]).optional(),schPinArrangement:a4.optional(),schPortArrangement:Eg.optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),pinCount:p.union([p.literal(2),p.literal(3)]).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),connections:p.custom().pipe(p.record(p.string(),e_)).optional()});Ct(!0);var RH=p4.extend({bridgedPins:p.array(p.array(p.string())).optional(),bridged:p.boolean().optional()});Ct(!0);var Nie=ri.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(Cs),Cs.or(p.array(Cs))).optional(),schPinStyle:Cg.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),schDirection:p.enum(["left","right"]).optional(),schPortArrangement:Eg.optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),standard:p.enum(["usb_c","m2"]).optional()});Ct(!0);var Rie=ri.extend({standard:p.enum(["TSC0001_36P_XALT_2025_11"]).optional()});Ct(!0);var OH=ri.extend({currentRating:p.union([p.number(),p.string()]),voltageRating:p.union([p.number(),p.string()]).optional(),schShowRatings:p.boolean().optional(),schOrientation:Vc.optional(),connections:p.record(p.string(),p.union([p.string(),p.array(p.string()).readonly(),p.array(p.string())])).optional()}),dS=p.custom().transform(n=>{if(n!==void 0)return Y.parse(n)}),LH=p.discriminatedUnion("shape",[je.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circle"),holeDiameter:Y,outerDiameter:Y,padDiameter:Y.optional().describe("Diameter of the copper pad"),portHints:ro.optional(),solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}),je.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("oval"),outerWidth:Y,outerHeight:Y,holeWidth:dS,holeHeight:dS,innerWidth:Y.optional().describe("DEPRECATED use holeWidth"),innerHeight:Y.optional().describe("DEPRECATED use holeHeight"),portHints:ro.optional(),solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}),je.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill"),rectPad:p.boolean().optional(),outerWidth:Y,outerHeight:Y,holeWidth:dS,holeHeight:dS,innerWidth:Y.optional().describe("DEPRECATED use holeWidth"),innerHeight:Y.optional().describe("DEPRECATED use holeHeight"),portHints:ro.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional(),solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}),je.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circular_hole_with_rect_pad"),holeDiameter:Y,rectPadWidth:Y,rectPadHeight:Y,rectBorderRadius:Y.optional(),holeShape:p.literal("circle").optional(),padShape:p.literal("rect").optional(),portHints:ro.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional(),solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}),je.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill_hole_with_rect_pad"),holeShape:p.literal("pill"),padShape:p.literal("rect"),holeWidth:Y,holeHeight:Y,rectPadWidth:Y,rectPadHeight:Y,portHints:ro.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional(),solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}),je.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("hole_with_polygon_pad"),holeShape:p.enum(["circle","oval","pill","rotated_pill"]),holeDiameter:Y.optional(),holeWidth:Y.optional(),holeHeight:Y.optional(),padOutline:p.array(Ro),holeOffsetX:Y,holeOffsetY:Y,portHints:ro.optional(),solderMaskMargin:Y.optional(),coveredWithSolderMask:p.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 gMt=["pin1","pin2","pos","neg"],FH=ri.extend({resistance:zc,pullupFor:p.string().optional(),pullupTo:p.string().optional(),pulldownFor:p.string().optional(),pulldownTo:p.string().optional(),schOrientation:Vc.optional(),connections:id(gMt).optional()}),zH=o4;Ct(!0);var $H=ri.extend({maxResistance:zc,pinVariant:p.enum(["two_pin","three_pin"]).optional()});Ct(!0);var xMt=o4,DH=ri.extend({frequency:Fr,loadCapacitance:va,manufacturerPartNumber:p.string().optional(),mpn:p.string().optional(),pinVariant:p.enum(["two_pin","four_pin"]).optional(),schOrientation:Vc.optional(),connections:id(xMt).optional()});Ct(!0);var jH=ri.extend({frequency:Fr,loadCapacitance:va,pinVariant:p.enum(["no_ground","ground_pin","two_ground_pins"]).optional()});Ct(!0);var Hie=u4.extend({leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftPins:p.array(p.string()).optional(),rightPins:p.array(p.string()).optional(),topPins:p.array(p.string()).optional(),bottomPins:p.array(p.string()).optional(),pinPitch:Y.optional(),innerHoles:p.boolean().optional()});Ct(!0);var bMt=["pin1","pin2","pos","neg","anode","cathode"],BH=ri.extend({capacitance:va,maxVoltageRating:lr.optional(),schShowRatings:p.boolean().optional().default(!1),polarized:p.boolean().optional().default(!1),decouplingFor:p.string().optional(),decouplingTo:p.string().optional(),bypassFor:p.string().optional(),bypassTo:p.string().optional(),maxDecouplingTraceLength:p.number().optional(),schOrientation:Vc.optional(),connections:id(bMt).optional()}),YH=_S;Ct(!0);var Kie=p.object({name:p.string(),connectsTo:p.string().or(p.array(p.string())).optional(),highlightColor:p.string().optional(),isPowerNet:p.boolean().optional(),isGroundNet:p.boolean().optional()});Ct(!0);var Qie=p.object({name:p.string().optional(),pcbOnly:p.boolean().optional(),schOnly:p.boolean().optional()});Ct(!0);var vMt=p.object({pcb:p.literal(!0).optional(),xDist:Y,left:p.string(),right:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});Ct(!0);var SMt=p.object({pcb:p.literal(!0).optional(),yDist:Y,top:p.string(),bottom:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});Ct(!0);var wMt=p.object({pcb:p.literal(!0).optional(),sameY:p.literal(!0).optional(),for:p.array(p.string())});Ct(!0);var PMt=p.object({pcb:p.literal(!0).optional(),sameX:p.literal(!0).optional(),for:p.array(p.string())});Ct(!0);var XH=p.union([vMt,SMt,wMt,PMt]);Ct(!0);var kMt=je.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y});Ct(!0);var TMt=je.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:Y});Ct(!0);var MMt=je.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Ro)});Ct(!0);var UH=p.discriminatedUnion("shape",[kMt,TMt,MMt]),EMt=je.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y,rectBorderRadius:Y.optional(),cornerRadius:Y.optional(),portHints:ro.optional(),coveredWithSolderMask:p.boolean().optional(),solderMaskMargin:Y.optional()});Ct(!0);var CMt=je.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rotated_rect"),width:Y,height:Y,ccwRotation:p.number(),cornerRadius:Y.optional(),portHints:ro.optional(),coveredWithSolderMask:p.boolean().optional(),solderMaskMargin:Y.optional()});Ct(!0);var IMt=je.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:Y,portHints:ro.optional(),coveredWithSolderMask:p.boolean().optional(),solderMaskMargin:Y.optional()});Ct(!0);var NMt=je.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("pill"),width:Y,height:Y,radius:Y,portHints:ro.optional(),coveredWithSolderMask:p.boolean().optional(),solderMaskMargin:Y.optional()});Ct(!0);var AMt=je.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Ro),portHints:ro.optional(),coveredWithSolderMask:p.boolean().optional(),solderMaskMargin:Y.optional()});Ct(!0);var VH=p.discriminatedUnion("shape",[IMt,EMt,CMt,NMt,AMt]);Ct(!0);var RMt=je.omit({pcbRotation:!0}).extend({shape:p.literal("rect"),width:Y,height:Y});Ct(!0);var OMt=je.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:Y});Ct(!0);var rre=p.union([OMt,RMt]);Ct(!0);var LMt=je.extend({name:p.string().optional(),shape:p.literal("circle").optional(),diameter:Y.optional(),radius:Y.optional(),solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}).transform(n=>({...n,diameter:n.diameter??2*n.radius,radius:n.radius??n.diameter/2})),FMt=je.extend({name:p.string().optional(),shape:p.literal("pill"),width:Y,height:Y,solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}),zMt=je.extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y,solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}),GH=p.union([LMt,FMt,zMt]);Ct(!0);var i4=p.union([p.string(),p.custom(n=>!!n.getPortSelector)]),vH=p.object({key:p.string().optional(),thickness:Y.optional(),width:Y.optional().describe("Alias for trace thickness"),schematicRouteHints:p.array(Ro).optional(),pcbRouteHints:p.array(Ji).optional(),pcbPathRelativeTo:p.string().optional(),pcbPath:p.array(p.union([Ro,p.string()])).optional(),pcbStraightLine:p.boolean().optional().describe("Draw a straight pcb trace between the connected points"),schDisplayLabel:p.string().optional(),schStroke:p.string().optional(),highlightColor:p.string().optional(),maxLength:Y.optional()}),HH=p.union([vH.extend({path:p.array(i4)}),vH.extend({from:i4,to:i4})]),WH=p.object({children:p.any().optional(),originalLayer:pe.default("top").optional(),circuitJson:p.array(p.any()).optional()});Ct(!0);var qH=p.object({originalFacingDirection:p.enum(["up","down","left","right"]).default("right").optional()});Ct(!0);var $Mt=p.number().or(p.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"),ZH=ri.extend({capacity:$Mt.optional(),voltage:lr.optional(),standard:p.enum(["AA","AAA","9V","CR2032","18650","C"]).optional(),schOrientation:Vc.optional()});Ct(!0);var DMt=p.enum(["vertical","horizontal"]).describe("vertical means pins go 1->2 downward and horizontal means pins go 1->2 rightward");Ct(!0);var KH=ri.extend({pinCount:p.number(),pitch:Y.optional(),schFacingDirection:p.enum(["up","down","left","right"]).optional(),gender:p.enum(["male","female","unpopulated"]).optional().default("male"),showSilkscreenPinLabels:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),doubleRow:p.boolean().optional(),rightAngle:p.boolean().optional(),pcbOrientation:DMt.optional(),holeDiameter:Y.optional(),platedDiameter:Y.optional(),pinLabels:p.record(p.string(),Cs).or(p.array(Cs)).optional(),connections:p.custom().pipe(p.record(p.string(),e_)).optional(),facingDirection:p.enum(["left","right"]).optional(),schPinArrangement:a4.optional(),schPinStyle:Cg.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional()});Ct(!0);var gre=p.object({net:p.string().optional(),connection:p.string().optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Qe.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});Ct(!0);var JH=p.object({net:p.string().optional(),connection:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Qe.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});Ct(!0);var QH=n_.extend({});Ct(!0);Ct(!0);var jMt=p.custom(n=>typeof n=="string"),tW=p.object({simulationType:p.literal("spice_transient_analysis").default("spice_transient_analysis"),duration:ur.optional(),timePerStep:ur.optional(),spiceEngine:jMt.optional()});Ct(!0);var BMt=["pin1","pin2","pin3","emitter","collector","base","gate","source","drain"],eW=ri.extend({type:p.enum(["npn","pnp","bjt","jfet","mosfet","igbt"]),connections:id(BMt).optional()});Ct(!0);var nW=ri.extend({channelType:p.enum(["n","p"]),mosfetMode:p.enum(["enhancement","depletion"])});Ct(!0);var YMt=o4,iW=ri.extend({inductance:Yx,maxCurrentRating:p.union([p.string(),p.number()]).optional(),schOrientation:Vc.optional(),connections:id(YMt).optional()});Ct(!0);var XMt=p.enum(["anode","cathode","pin1","pin2","pos","neg"]),UMt=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),VMt=p.record(XMt,UMt),GMt=p.enum(["standard","schottky","zener","avalanche","photo","tvs"]),rW=ri.extend({connections:VMt.optional(),variant:GMt.optional().default("standard"),standard:p.boolean().optional(),schottky:p.boolean().optional(),zener:p.boolean().optional(),avalanche:p.boolean().optional(),photo:p.boolean().optional(),tvs:p.boolean().optional(),schOrientation:Vc.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:p.ZodIssueCode.custom,message:"Exactly one diode variant must be enabled",path:[]}),p.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}),sW=_S;Ct(!0);var oW=ri.extend({color:p.string().optional(),wavelength:p.string().optional(),schDisplayValue:p.string().optional(),schOrientation:Vc.optional(),connections:id(_S).optional(),laser:p.boolean().optional()}),aW=_S,cW=ri.extend({type:p.enum(["spst","spdt","dpst","dpdt"]).optional(),isNormallyClosed:p.boolean().optional().default(!1),spst:p.boolean().optional(),spdt:p.boolean().optional(),dpst:p.boolean().optional(),dpdt:p.boolean().optional(),simSwitchFrequency:Fr.optional(),simCloseAt:ur.optional(),simOpenAt:ur.optional(),simStartClosed:p.boolean().optional(),simStartOpen:p.boolean().optional(),connections:p.custom().pipe(p.record(p.string(),e_)).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 lW=je.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional()});Ct(!0);var uW=je.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional(),cornerRadius:Y.optional()}),pW=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Ji),strokeWidth:D.optional(),color:p.string().optional()}),SH=p.union([p.string(),Ro]),hW=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:SH,to:SH,text:p.string().optional(),offset:Y.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional(),arrowSize:Y.optional(),units:p.enum(["in","mm"]).optional(),outerEdgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional(),innerEdgeToEdge:p.literal(!0).optional()});Ct(!0);var Bre=p.object({layer:p.string().optional(),thickness:Y.optional(),route:p.array(Ji)}),dW=mS.extend({name:p.string().optional(),fromLayer:pe,toLayer:pe,holeDiameter:Y.optional(),outerDiameter:Y.optional(),connectsTo:p.string().or(p.array(p.string())).optional(),netIsAssignable:p.boolean().optional()});Ct(!0);var HMt=p.object({pin1:e_}).strict(),fW=ri.extend({connections:HMt.optional(),footprintVariant:p.enum(["pad","through_hole"]).optional(),padShape:p.enum(["rect","circle"]).optional().default("circle"),padDiameter:Y.optional(),holeDiameter:Y.optional(),width:Y.optional(),height:Y.optional()}).refine(n=>n.footprintVariant!=="through_hole"||n.holeDiameter!==void 0,{message:"holeDiameter is required for through_hole testpoints"});Ct(!0);var mW=je.omit({pcbRotation:!0,layer:!0}).extend({connection:p.string()});Ct(!0);var _W=p.union([je.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:Y}),je.extend({shape:p.literal("rect"),width:Y,height:Y})]),Kre=je.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),tse=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({outline:p.array(Ro),strokeWidth:D.optional(),isClosed:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),yW=p.object({name:p.string().optional(),layer:pe,connectsTo:p.string(),padMargin:Y.optional(),traceMargin:Y.optional(),clearance:Y.optional(),boardEdgeMargin:Y.optional(),cutoutMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional().default(!0)});Ct(!0);var gW=p.object({originalLayer:pe.default("top").optional(),children:p.any().optional()});Ct(!0);var WMt=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbZ:Y.optional()}),qMt=Uc.extend({modelUrl:p.string(),stepUrl:p.string().optional()}),ZMt=qMt.merge(WMt);Ct(!0);var xW=p.union([p.null(),p.string(),ZMt]),bW=ri.extend({voltage:lr}),KMt=["pin1","pin2","pos","neg"],JMt=p.union([p.string(),p.number()]).transform(n=>typeof n=="string"?n.endsWith("%")?parseFloat(n.slice(0,-1))/100:parseFloat(n):n).pipe(p.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),vW=ri.extend({voltage:lr.optional(),frequency:Fr.optional(),peakToPeakVoltage:lr.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Qe.optional(),dutyCycle:JMt.optional(),connections:id(KMt).optional()});Ct(!0);var SW=ri.omit({name:!0}).extend({name:p.string().optional(),connectsTo:p.string(),referenceTo:p.string().optional(),color:p.string().optional()});Ct(!0);var wW=p.object({center:Zt,radius:Y,startAngleDegrees:Qe,endAngleDegrees:Qe,direction:p.enum(["clockwise","counterclockwise"]).default("counterclockwise"),strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),PW=p.object({schX:Y.optional(),schY:Y.optional(),width:Y.optional(),height:Y.optional(),overlay:p.array(p.string()).optional(),padding:Y.optional(),paddingLeft:Y.optional(),paddingRight:Y.optional(),paddingTop:Y.optional(),paddingBottom:Y.optional(),title:p.string().optional(),titleAlignment:t_.default("top_left"),titleColor:p.string().optional(),titleFontSize:Y.optional(),titleInside:p.boolean().default(!1),strokeStyle:p.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."}),kW=p.object({center:Zt,radius:Y,strokeWidth:Y.optional(),color:p.string().optional(),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),TW=p.object({schX:Y.optional(),schY:Y.optional(),width:Y,height:Y,rotation:Qe.default(0),strokeWidth:Y.optional(),color:p.string().optional(),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1),cornerRadius:Y.optional()}),MW=p.object({x1:Y,y1:Y,x2:Y,y2:Y,strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),QMt=p.enum(["center","left","right","top","bottom"]),EW=p.object({schX:Y.optional(),schY:Y.optional(),text:p.string(),fontSize:p.number().default(1),anchor:p.union([QMt.describe("legacy"),t_]).default("center"),color:p.string().default("#000000"),schRotation:Qe.default(0)}),kse=p.object({points:p.array(Zt),isFilled:p.boolean().optional().default(!1),fillColor:p.enum(["red","blue"]).optional()}),CW=p.object({schX:Y.optional(),schY:Y.optional(),children:p.any().optional(),cellPadding:Y.optional(),borderWidth:Y.optional(),anchor:t_.optional(),fontSize:Y.optional()});Ct(!0);var IW=p.object({children:p.any().optional(),height:Y.optional()});Ct(!0);var NW=p.object({children:p.string().optional(),horizontalAlign:p.enum(["left","center","right"]).optional(),verticalAlign:p.enum(["top","middle","bottom"]).optional(),fontSize:Y.optional(),rowSpan:p.number().optional(),colSpan:p.number().optional(),width:Y.optional(),text:p.string().optional()});Ct(!0);var Ose=je.extend({text:p.string(),anchorAlignment:t_.default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),layers:p.array(pe).optional()}),AW=je.extend({text:p.string(),anchorAlignment:t_.default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),isKnockout:p.boolean().optional(),knockoutPadding:D.optional(),knockoutPaddingLeft:D.optional(),knockoutPaddingRight:D.optional(),knockoutPaddingTop:D.optional(),knockoutPaddingBottom:D.optional(),layers:p.array(pe).optional()}),RW=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Ji),strokeWidth:D.optional()}),OW=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({strokeWidth:Y,x1:Y,y1:Y,x2:Y,y2:Y}),LW=je.omit({pcbRotation:!0}).extend({filled:p.boolean().default(!0).optional(),stroke:p.enum(["dashed","solid","none"]).optional(),strokeWidth:Y.optional(),width:Y,height:Y,cornerRadius:Y.optional()}),FW=je.omit({pcbRotation:!0}).extend({isFilled:p.boolean().optional(),isOutline:p.boolean().optional(),strokeWidth:Y.optional(),radius:Y}),wH=p.object({x:Y,y:Y,via:p.boolean().optional(),toLayer:pe.optional()}),zW=p.object({for:p.string().optional().describe("Selector for the port you're targeting, not required if you're inside a trace"),order:p.number().optional(),offset:Ji.or(wH).optional(),offsets:p.array(Ji).or(p.array(wH)).optional(),traceWidth:p.number().optional()}),Hse=mS.extend({name:p.string(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),direction:X3t,connectsTo:p.string().or(p.array(p.string())).optional()}),$W=je.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional()});Ct(!0);var DW=je.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional(),cornerRadius:Y.optional()});Ct(!0);var jW=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Ji),strokeWidth:D.optional(),color:p.string().optional()});Ct(!0);var BW=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({x1:Y,y1:Y,x2:Y,y2:Y,strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional()});Ct(!0);var PH=p.union([p.string(),Ro]),YW=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:PH,to:PH,text:p.string().optional(),offset:Y.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional(),arrowSize:Y.optional(),units:p.enum(["in","mm"]).optional(),outerEdgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional(),innerEdgeToEdge:p.literal(!0).optional()});Ct(!0);var XW=p.array(p.any()).describe("Circuit JSON"),r4=p.object({footprintCircuitJson:p.array(p.any()),cadModel:MH.optional()}),kH=p.function().args(p.string()).returns(p.promise(r4)).or(p.function().args(p.string(),p.object({resolvedPcbStyle:s4.optional()}).optional()).returns(p.promise(r4))).describe("A function that takes a path and returns Circuit JSON"),tEt=p.object({loadFromUrl:p.function().args(p.string()).returns(p.promise(r4)).describe("A function that takes a footprint file URL and returns Circuit JSON")}),eEt=p.object({engineVersionString:p.string().optional(),simulationResultCircuitJson:XW}),nEt=p.object({simulate:p.function().args(p.string()).returns(p.promise(eEt)).describe("A function that takes a SPICE string and returns a simulation result")}),iEt=p.custom(n=>typeof n=="string"),TH=p.object({run:p.function().args().returns(p.promise(p.unknown())).describe("Run the autorouter"),getOutputSimpleRouteJson:p.function().args().returns(p.promise(p.any())).describe("Get the resulting SimpleRouteJson")}),rEt=p.object({createAutorouter:p.function().args(p.any(),p.any().optional()).returns(p.union([TH,p.promise(TH)])).describe("Create an autorouter instance")}),sEt=p.object({partsEngine:CH.optional(),autorouter:EH.optional(),autorouterMap:p.record(p.string(),rEt).optional(),registryApiUrl:p.string().optional(),cloudAutorouterUrl:p.string().optional(),projectName:p.string().optional(),projectBaseUrl:p.string().optional(),version:p.string().optional(),url:p.string().optional(),printBoardInformationToSilkscreen:p.boolean().optional(),includeBoardFiles:p.array(p.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:p.string().describe('The directory where snapshots are stored for "tsci snapshot", defaults to "tests/__snapshots__"').optional(),defaultSpiceEngine:iEt.optional(),localCacheEngine:p.any().optional(),pcbDisabled:p.boolean().optional(),schematicDisabled:p.boolean().optional(),partsEngineDisabled:p.boolean().optional(),spiceEngineMap:p.record(p.string(),nEt).optional(),footprintLibraryMap:p.record(p.string(),p.union([kH,p.record(p.string(),p.union([XW,kH]))])).optional(),footprintFileParserMap:p.record(p.string(),tEt).optional(),resolveProjectStaticFileImportUrl:p.function().args(p.string()).returns(p.promise(p.string())).describe("A function that returns a string URL for static files for the project").optional()});Ct(!0);var oEt=sEt,soe=oEt.pick({projectName:!0,projectBaseUrl:!0,version:!0,url:!0,printBoardInformationToSilkscreen:!0,includeBoardFiles:!0,snapshotsDir:!0,defaultSpiceEngine:!0});Ct(!0);St();J();St();St();St();Ta();J();var Va=Gt(Zs(),1);Ta();J();function Gc(){return new h4}var h4=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 yS(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 yS(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}},yS=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 Ia=class{constructor(e=""){f(this,"_name");f(this,"_value",0);f(this,"_context",null);f(this,"_id",aEt++);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 $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])}toJSON(){return{name:this._name,value:this._value}}toString(){return this._context+"["+this._name+":"+this._value+"]"}},aEt=0;var $n=class n{constructor(){f(this,"_terms");f(this,"_constant");let e=cEt(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 cEt(n){let e=0,t=()=>0,i=Gc();for(let r=0,s=n.length;r<s;++r){let o=n[r];if(typeof o=="number")e+=o;else if(o instanceof Ia)i.setDefault(o,t).second+=1;else if(o instanceof $n){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 Ia)i.setDefault(c,t).second+=a;else if(c instanceof $n){e+=c.constant()*a;let l=c.terms();for(let u=0,h=l.size();u<h;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 so=class so{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(so.required,e))}};f(so,"required",so.create(1e3,1e3,1e3)),f(so,"strong",so.create(1,0,0)),f(so,"medium",so.create(0,1,0)),f(so,"weak",so.create(0,0,1));var Rn=so;var si;(function(n){n[n.Le=0]="Le",n[n.Ge=1]="Ge",n[n.Eq=2]="Eq"})(si||(si={}));var wi=class{constructor(e,t,i,r=Rn.required){f(this,"_expression");f(this,"_operator");f(this,"_strength");f(this,"_id",lEt++);this._operator=t,this._strength=Rn.clip(r),i===void 0&&e instanceof $n?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()+")"}},lEt=0;var i_=class{constructor(){f(this,"maxIterations",1e3);f(this,"_cnMap",uEt());f(this,"_rowMap",pEt());f(this,"_varMap",hEt());f(this,"_editMap",dEt());f(this,"_infeasibleRows",[]);f(this,"_objective",new bS);f(this,"_artificial",null);f(this,"_idTick",0)}createConstraint(e,t,i,r=Rn.required){let s=new wi(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()===nn.Invalid&&r.allDummies())if(gS(r.constant()))o=s.marker;else throw new Error("unsatisfiable constraint");if(o.type()===nn.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()===nn.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=Rn.clip(t),t===Rn.required)throw new Error("bad required strength");let r=new $n(e),s=new wi(r,si.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,h=r.size();u<h;++u){let d=r.itemAt(u),_=d.second,g=_.coefficientFor(a);g!==0&&_.add(o*g)<0&&d.first.type()!==nn.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(nn.External);return this._varMap.setDefault(e,t).second}_createRow(e){let t=e.expression(),i=new bS(t.constant()),r=t.terms();for(let c=0,l=r.size();c<l;++c){let u=r.itemAt(c);if(!gS(u.second)){let h=this._getVarSymbol(u.first),d=this._rowMap.find(h);d!==void 0?i.insertRow(d.second,u.second):i.insertSymbol(h,u.second)}}let s=this._objective,o=e.strength(),a={marker:Hc,other:Hc};switch(e.op()){case si.Le:case si.Ge:{let c=e.op()===si.Le?1:-1,l=this._makeSymbol(nn.Slack);if(a.marker=l,i.insertSymbol(l,c),o<Rn.required){let u=this._makeSymbol(nn.Error);a.other=u,i.insertSymbol(u,-c),s.insertSymbol(u,o)}break}case si.Eq:{if(o<Rn.required){let c=this._makeSymbol(nn.Error),l=this._makeSymbol(nn.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(nn.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()===nn.External)return a.first}let r=t.marker.type();return(r===nn.Slack||r===nn.Error)&&e.coefficientFor(t.marker)<0?t.marker:(r=t.other.type(),(r===nn.Slack||r===nn.Error)&&e.coefficientFor(t.other)<0?t.other:Hc)}_addWithArtificialVariable(e){let t=this._makeSymbol(nn.Slack);this._rowMap.insert(t,e.copy()),this._artificial=e.copy(),this._optimize(this._artificial);let i=gS(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()===nn.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()!==nn.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()===nn.Invalid)return;let r=this._getLeavingSymbol(i);if(r.type()===nn.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()===nn.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()!==nn.Dummy)return o}return Hc}_getDualEnteringSymbol(e){let t=Number.MAX_VALUE,i=Hc,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()!==nn.Dummy){let h=this._objective.coefficientFor(c)/l;h<t&&(t=h,i=c)}}return i}_getLeavingSymbol(e){let t=Number.MAX_VALUE,i=Hc,r=this._rowMap;for(let s=0,o=r.size();s<o;++s){let a=r.itemAt(s),c=a.first;if(c.type()!==nn.External){let l=a.second,u=l.coefficientFor(e);if(u<0){let h=-l.constant()/u;h<t&&(t=h,i=c)}}}return i}_getMarkerLeavingSymbol(e){let t=Number.MAX_VALUE,i=t,r=t,s=Hc,o=s,a=s,c=s,l=this._rowMap;for(let u=0,h=l.size();u<h;++u){let d=l.itemAt(u),_=d.second,g=_.coefficientFor(e);if(g===0)continue;let x=d.first;if(x.type()===nn.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()===nn.Error&&this._removeMarkerEffects(t.marker,e.strength()),t.other.type()===nn.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===nn.Slack||o===nn.Error)return s.first}return Hc}_makeSymbol(e){return new xS(e,this._idTick++)}};function gS(n){let e=1e-8;return n<0?-n<e:n<e}function uEt(){return Gc()}function pEt(){return Gc()}function hEt(){return Gc()}function dEt(){return Gc()}var nn;(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"})(nn||(nn={}));var xS=class{constructor(e,t){f(this,"_id");f(this,"_type");this._id=t,this._type=e}id(){return this._id}type(){return this._type}},Hc=new xS(nn.Invalid,-1),bS=class n{constructor(e=0){f(this,"_cellMap",Gc());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()!==nn.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);gS(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 snt=Gt(En(),1);J();St();St();er();var y4={};vh(y4,{areBoundsCompletelyInsidePolygon:()=>_4,areBoundsOverlappingPolygon:()=>m4,boundsAreaOverlap:()=>nq,boundsDistance:()=>iq,boundsIntersection:()=>rq,clamp:()=>Vn,computeDistanceBetweenBoxes:()=>Ao,computeGapBetweenBoxes:()=>t4,computeManhattanDistanceBetweenBoxes:()=>kg,distSq:()=>qW,distance:()=>Fi,doBoundsOverlap:()=>Wc,doSegmentsIntersect:()=>Pi,doesLineIntersectLine:()=>Na,doesSegmentIntersectRect:()=>d4,findNearestPointsBetweenBoxSets:()=>Tg,getBoundingBox:()=>io,getBoundsFromPoints:()=>Oo,getSegmentIntersection:()=>od,getUnitVectorFromDirection:()=>kS,getUnitVectorFromPointAToB:()=>PS,grid:()=>sq,isPointInsidePolygon:()=>wS,isRectCompletelyInsidePolygon:()=>tq,isRectOverlappingPolygon:()=>QW,midpoint:()=>WW,normalizeDegrees:()=>ad,onSegment:()=>sd,orientation:()=>rd,pointToBoundsDistance:()=>HW,pointToBoxDistance:()=>GW,pointToSegmentClosestPoint:()=>VW,pointToSegmentDistance:()=>yi,range:()=>eq,segmentToBoundsMinDistance:()=>Ng,segmentToBoxMinDistance:()=>vS,segmentToCircleMinDistance:()=>SS,segmentToSegmentMinDistance:()=>r_});function Na([n,e],[t,i],{lineThickness:r=0}={}){return r===0?Pi(n,e,t,i):fEt(n,e,t,i)<=r}function Pi(n,e,t,i){let r=rd(n,e,t),s=rd(n,e,i),o=rd(t,i,n),a=rd(t,i,e);return!!(r!==s&&o!==a||r===0&&sd(n,t,e)||s===0&&sd(n,i,e)||o===0&&sd(t,n,i)||a===0&&sd(t,e,i))}function rd(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 sd(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 fEt(n,e,t,i){if(n.x===e.x&&n.y===e.y)return yi(n,t,i);if(t.x===i.x&&t.y===i.y)return yi(t,n,e);if(Pi(n,e,t,i))return 0;let r=[yi(n,t,i),yi(e,t,i),yi(t,n,e),yi(i,n,e)];return Math.min(...r)}function yi(n,e,t){let i=(t.x-e.x)**2+(t.y-e.y)**2;if(i===0)return Fi(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 Fi(n,s)}function Fi(n,e){let t=n.x-e.x,i=n.y-e.y;return Math.sqrt(t*t+i*i)}function od(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 h=(l*o-c*a)/u,d=(r*l-s*c)/u,_=1e-9;if(h>=-_&&h<=1+_&&d>=-_&&d<=1+_){let g=n.x+h*r,x=n.y+h*s;return{x:g,y:x}}return null}function d4(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 Pi(n,e,r,s)||Pi(n,e,s,a)||Pi(n,e,a,o)||Pi(n,e,o,r)}function r_(n,e,t,i){if(n.x===e.x&&n.y===e.y)return yi(n,t,i);if(t.x===i.x&&t.y===i.y)return yi(t,n,e);if(Pi(n,e,t,i))return 0;let r=[yi(n,t,i),yi(e,t,i),yi(t,n,e),yi(i,n,e)];return Math.min(...r)}function Ng(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(Pi(n,e,i,r)||Pi(n,e,r,o)||Pi(n,e,o,s)||Pi(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=[yi(i,n,e),yi(r,n,e),yi(s,n,e),yi(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=Vn(n.x,t.minX,t.maxX),l=Vn(n.y,t.minY,t.maxY);a.push(Fi(n,{x:c,y:l}))}if(e.x<t.minX||e.x>t.maxX||e.y<t.minY||e.y>t.maxY){let c=Vn(e.x,t.minX,t.maxX),l=Vn(e.y,t.minY,t.maxY);a.push(Fi(e,{x:c,y:l}))}return Math.min(...a)}function vS(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 Ng(n,e,s)}function SS(n,e,t){let i={x:t.x,y:t.y};if(n.x===e.x&&n.y===e.y)return Math.max(0,Fi(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=Fi(c,i);return Math.max(0,l-t.radius)}function VW(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 ad(n){return(n%360+360)%360}function GW(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=Vn(n.x,r,s),l=Vn(n.y,o,a);return Fi(n,{x:c,y:l})}function HW(n,e){if(n.x>=e.minX&&n.x<=e.maxX&&n.y>=e.minY&&n.y<=e.maxY)return 0;let t=Vn(n.x,e.minX,e.maxX),i=Vn(n.y,e.minY,e.maxY);return Fi(n,{x:t,y:i})}function WW(n,e){return{x:(n.x+e.x)/2,y:(n.y+e.y)/2}}function qW(n,e){let t=n.x-e.x,i=n.y-e.y;return t*t+i*i}var ZW=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}},f4=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}],KW=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},mEt=(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)},_Et=(n,e)=>n.x>=e.minX&&n.x<=e.maxX&&n.y>=e.minY&&n.y<=e.maxY,wS=(n,e)=>{if(e.length<3)return!1;let t=KW(e);for(let[r,s]of t)if(mEt(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},JW=(n,e)=>{let t=f4(n),i=[[t[0],t[1]],[t[1],t[2]],[t[2],t[3]],[t[3],t[0]]],r=KW(e);for(let[s,o]of r)for(let[a,c]of i)if(Pi(s,o,a,c))return!0;return!1},m4=(n,e)=>e.length<3?!1:e.some(i=>_Et(i,n))||f4(n).some(i=>wS(i,e))?!0:JW(n,e),_4=(n,e)=>e.length<3||!f4(n).every(i=>wS(i,e))?!1:!JW(n,e),QW=(n,e)=>m4(ZW(n),e),tq=(n,e)=>_4(ZW(n),e);function eq(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 nq=(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 iq=(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 rq=(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 Wc=(n,e)=>!(n.maxX<e.minX||e.maxX<n.minX||n.maxY<e.minY||e.maxY<n.minY);var Oo=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 PS=(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}},kS=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 sq({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,h=i??1,d=r??e*u,_=s??n*h,g=l?-d/2:0,x=l?-_/2:0,v=r?r/e:u,P=s?s/n:h,w=[];for(let T=0;T<n;T++)for(let k=0;k<e;k++){let C=T*e+k,M=o+g+k*v+v/2,I=a+T*P+P/2,E=c==="cartesian"?a+x+(n-1-T)*P+P/2:a+x+T*P+P/2;w.push({index:C,center:{x:M,y:E},topLeft:{x:M-v/2,y:E+P/2},bottomRight:{x:M+v/2,y:E-P/2},row:T,col:k})}return w}St();Ag();var oq={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"}};St();er();Ae();var o9=Gt(Zs(),1);St();var hnt=Gt(En(),1);var W4={};vh(W4,{AssignableViaAutoroutingPipelineSolver:()=>aIt,AutoroutingPipelineSolver:()=>CZ,CapacityMeshSolver:()=>eIt,InMemoryCache:()=>pZ,LocalStorageCache:()=>hZ,calculateOptimalCapacityDepth:()=>U4,convertSrjToGraphicsObject:()=>Vg,getGlobalInMemoryCache:()=>__,getGlobalLocalStorageCache:()=>dZ,getTunedTotalCapacity1:()=>ao,setupGlobalCaches:()=>Ug});var uZ=Gt(CS(),1),wZ=Gt(CS(),1),TZ=Gt(CS(),1);var hd=(...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},an=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 bq(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 Kc(n,e,t){return Math.max(e,Math.min(t,n))}function zi(n,e,t,i){let r=IS(n,e,t),s=IS(n,e,i),o=IS(t,i,n),a=IS(t,i,e);return r!==s&&o!==a||!(r!==0||!NS(n,t,e))||!(s!==0||!NS(n,i,e))||!(o!==0||!NS(t,n,i))||!(a!==0||!NS(t,e,i))}function IS(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 NS(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 fr(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 Hq(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 h=(l*o-c*a)/u,d=(r*l-s*c)/u,_=1e-9;return h>=-1e-9&&h<=1+_&&d>=-1e-9&&d<=1+_?{x:n.x+h*r,y:n.y+h*s}:null}function vq(n,e){return{x:(n.x+e.x)/2,y:(n.y+e.y)/2}}var Wq=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}},X4=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}],qq=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},CEt=(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)},Zq=(n,e)=>{if(e.length<3)return!1;let t=qq(e);for(let[r,s]of t)if(CEt(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},Kq=(n,e)=>{let t=X4(n),i=[[t[0],t[1]],[t[1],t[2]],[t[2],t[3]],[t[3],t[0]]],r=qq(e);for(let[s,o]of r)for(let[a,c]of i)if(zi(s,o,a,c))return!0;return!1},A4=(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))||!!X4(t).some(r=>Zq(r,i))||Kq(t,i)))(Wq(n),e),Jq=(n,e)=>((t,i)=>!(i.length<3)&&!!X4(t).every(r=>Zq(r,i))&&!Kq(t,i))(Wq(n),e);function R4(n,e,t,i){if(n.x===e.x&&n.y===e.y)return fr(n,t,i);if(t.x===i.x&&t.y===i.y)return fr(t,n,e);if(zi(n,e,t,i))return 0;let r=[fr(n,t,i),fr(e,t,i),fr(t,n,e),fr(i,n,e)];return Math.min(...r)}function Qq(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},h={x:a.maxX,y:a.maxY};if(zi(s,o,c,l)||zi(s,o,l,h)||zi(s,o,h,u)||zi(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=[fr(c,s,o),fr(l,s,o),fr(u,s,o),fr(h,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 _=Kc(s.x,a.minX,a.maxX),g=Kc(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 _=Kc(o.x,a.minX,a.maxX),g=Kc(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 p_(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 Br(){return Br=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},Br.apply(null,arguments)}function GS(n,e){return(GS=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,i){return t.__proto__=i,t})(n,e)}function tZ(n){return(tZ=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(n)}function eZ(){try{var n=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(eZ=function(){return!!n})()}function O4(n){var e=typeof Map=="function"?new Map:void 0;return O4=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(eZ())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,s);var c=new(r.bind.apply(r,a));return o&&GS(c,o.prototype),c})(t,arguments,tZ(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),GS(i,t)},O4(n)}var jr=(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,GS(e,t),i})(O4(Error));function Sq(n,e){return n.substr(-e.length)===e}var IEt=/^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;function wq(n){return typeof n!="string"?n:n.match(IEt)?parseFloat(n):n}var Pq=function(n){return function(e,t){t===void 0&&(t="16px");var i=e,r=t;if(typeof e=="string"){if(!Sq(e,"px"))throw new jr(69,n,e);i=wq(e)}if(typeof t=="string"){if(!Sq(t,"px"))throw new jr(70,n,t);r=wq(t)}if(typeof i=="string")throw new jr(71,e,n);if(typeof r=="string")throw new jr(72,t,n);return""+i/r+n}};Pq("em"),Pq("rem");function v4(n){return Math.round(255*n)}function NEt(n,e,t){return v4(n)+","+v4(e)+","+v4(t)}function Bg(n,e,t,i){if(i===void 0&&(i=NEt),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 kq={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"},AEt=/^#[a-fA-F0-9]{6}$/,REt=/^#[a-fA-F0-9]{8}$/,OEt=/^#[a-fA-F0-9]{3}$/,LEt=/^#[a-fA-F0-9]{4}$/,S4=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,FEt=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,zEt=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,$Et=/^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 h_(n){if(typeof n!="string")throw new jr(3);var e=(function(d){if(typeof d!="string")return d;var _=d.toLowerCase();return kq[_]?"#"+kq[_]:d})(n);if(e.match(AEt))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(REt)){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(OEt))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(LEt)){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=S4.exec(e);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var s=FEt.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=zEt.exec(e);if(o){var a="rgb("+Bg(parseInt(""+o[1],10),parseInt(""+o[2],10)/100,parseInt(""+o[3],10)/100)+")",c=S4.exec(a);if(!c)throw new jr(4,e,a);return{red:parseInt(""+c[1],10),green:parseInt(""+c[2],10),blue:parseInt(""+c[3],10)}}var l=$Et.exec(e.substring(0,50));if(l){var u="rgb("+Bg(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",h=S4.exec(u);if(!h)throw new jr(4,e,u);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+l[4])>1?parseFloat(""+l[4])/100:parseFloat(""+l[4])}}throw new jr(5)}function Jc(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}})(h_(n))}var L4=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 ud(n){var e=n.toString(16);return e.length===1?"0"+e:e}function w4(n){return ud(Math.round(255*n))}function DEt(n,e,t){return L4("#"+w4(n)+w4(e)+w4(t))}function AS(n,e,t){return Bg(n,e,t,DEt)}function F4(n,e,t){if(typeof n=="number"&&typeof e=="number"&&typeof t=="number")return L4("#"+ud(n)+ud(e)+ud(t));if(typeof n=="object"&&e===void 0&&t===void 0)return L4("#"+ud(n.red)+ud(n.green)+ud(n.blue));throw new jr(6)}function tw(n,e,t,i){if(typeof n=="string"&&typeof e=="number"){var r=h_(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?F4(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?F4(n.red,n.green,n.blue):"rgba("+n.red+","+n.green+","+n.blue+","+n.alpha+")";throw new jr(7)}function Qc(n){if(typeof n!="object")throw new jr(8);if((function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&typeof e.alpha=="number"})(n))return tw(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 F4(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?AS(e,t,i):"rgba("+Bg(e,t,i)+","+r+")";if(typeof e=="object"&&t===void 0&&i===void 0&&r===void 0)return e.alpha>=1?AS(e.hue,e.saturation,e.lightness):"rgba("+Bg(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new jr(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 AS(e,t,i);if(typeof e=="object"&&t===void 0&&i===void 0)return AS(e.hue,e.saturation,e.lightness);throw new jr(1)})(n);throw new jr(8)}function nZ(n,e,t){return function(){var i=t.concat(Array.prototype.slice.call(arguments));return i.length>=e?n.apply(this,i):nZ(n,e,i)}}function ss(n){return nZ(n,n.length,[])}ss(function(n,e){if(e==="transparent")return e;var t=Jc(e);return Qc(Br({},t,{hue:t.hue+parseFloat(n)}))});function m_(n,e,t){return Math.max(n,Math.min(e,t))}ss(function(n,e){if(e==="transparent")return e;var t=Jc(e);return Qc(Br({},t,{lightness:m_(0,1,t.lightness-parseFloat(n))}))});ss(function(n,e){if(e==="transparent")return e;var t=Jc(e);return Qc(Br({},t,{saturation:m_(0,1,t.saturation-parseFloat(n))}))});ss(function(n,e){if(e==="transparent")return e;var t=Jc(e);return Qc(Br({},t,{lightness:m_(0,1,t.lightness+parseFloat(n))}))});var iZ=ss(function(n,e,t){if(e==="transparent")return t;if(t==="transparent")return e;if(n===0)return t;var i=h_(e),r=Br({},i,{alpha:typeof i.alpha=="number"?i.alpha:1}),s=h_(t),o=Br({},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 tw({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))})});ss(function(n,e){if(e==="transparent")return e;var t=h_(e);return tw(Br({},t,{alpha:m_(0,1,(100*(typeof t.alpha=="number"?t.alpha:1)+100*parseFloat(n))/100)}))});ss(function(n,e){if(e==="transparent")return e;var t=Jc(e);return Qc(Br({},t,{saturation:m_(0,1,t.saturation+parseFloat(n))}))});ss(function(n,e){return e==="transparent"?e:Qc(Br({},Jc(e),{hue:parseFloat(n)}))});ss(function(n,e){return e==="transparent"?e:Qc(Br({},Jc(e),{lightness:parseFloat(n)}))});ss(function(n,e){return e==="transparent"?e:Qc(Br({},Jc(e),{saturation:parseFloat(n)}))});ss(function(n,e){return e==="transparent"?e:iZ(parseFloat(n),"rgb(0, 0, 0)",e)});ss(function(n,e){return e==="transparent"?e:iZ(parseFloat(n),"rgb(255, 255, 255)",e)});var jEt=ss(function(n,e){if(e==="transparent")return e;var t=h_(e);return tw(Br({},t,{alpha:m_(0,1,+(100*(typeof t.alpha=="number"?t.alpha:1)-100*parseFloat(n)).toFixed(2)/100)}))}),Tq=["blue","orange","purple","cyan","magenta","yellowgreen","darkgoldenrod","deeppink"],Yg=(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},Kn=(n,e)=>{try{return jEt(e,n)}catch(t){return console.error(t),n}},dd=(n,e)=>n==="top"?0:n==="bottom"?e-1:parseInt(n.slice(5)),ao=(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},U4=(n,e=.5,t=16)=>{let i=0,r=n;for(;i<t&&!(ao({width:r})<=e);)r/=2,i++;return Math.max(1,i)};function rZ(n,e,t=0,i=n.length-1,r=BEt){for(;i>t;){if(i-t>600){let c=i-t+1,l=e-t+1,u=Math.log(c),h=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*h*(c-h)/c)*(l-c/2<0?-1:1);rZ(n,e,Math.max(t,Math.floor(e-l*h/c+d)),Math.min(i,Math.floor(e+(c-l)*h/c+d)),r)}let s=n[e],o=t,a=i;for(Og(n,t,e),r(n[i],s)>0&&Og(n,t,i);o<a;){for(Og(n,o,a),o++,a--;r(n[o],s)<0;)o++;for(;r(n[a],s)>0;)a--}r(n[t],s)===0?Og(n,t,a):(a++,Og(n,a,i)),a<=e&&(t=a+1),e<=a&&(i=a-1)}}function Og(n,e,t){let i=n[e];n[e]=n[t],n[t]=i}function BEt(n,e){return n<e?-1:n>e?1:0}var YEt=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(!OS(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;OS(n,a)&&(e.leaf?t.push(o):k4(n,a)?this._all(o,t):r.push(o))}e=r.pop()}return t}collides(n){let e=this.data;if(!OS(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(OS(n,s)){if(e.leaf||k4(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=l_([]),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=XEt(n,t.children,e);if(l!==-1)return t.children.splice(l,1),r.push(t),this._condense(r),this}c||t.leaf||!k4(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=l_(n.slice(e,t+1)),c_(s,this.toBBox),s;i||(i=Math.ceil(Math.log(r)/Math.log(o)),o=Math.ceil(r/Math.pow(o,i-1))),s=l_([]),s.leaf=!1,s.height=i;let a=Math.ceil(r/o),c=a*Math.ceil(Math.sqrt(o));Mq(n,e,t,c,this.compareMinX);for(let l=e;l<=t;l+=c){let u=Math.min(l+c-1,t);Mq(n,l,u,a,this.compareMinY);for(let h=l;h<=u;h+=a){let d=Math.min(h+a-1,u);s.children.push(this._build(n,h,d,i-1))}}return c_(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=P4(c),u=GEt(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),Fg(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=l_(t.children.splice(s,t.children.length-s));o.height=t.height,o.leaf=t.leaf,c_(t,this.toBBox),c_(o,this.toBBox),e?n[e-1].children.push(o):this._splitRoot(t,o)}_splitRoot(n,e){this.data=l_([n,e]),this.data.height=n.height+1,this.data.leaf=!1,c_(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=Lg(n,0,o,this.toBBox),c=Lg(n,o,t,this.toBBox),l=HEt(a,c),u=P4(a)+P4(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:UEt,r=n.leaf?this.compareMinY:VEt;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=Lg(n,0,e,r),o=Lg(n,t-e,t,r),a=RS(s)+RS(o);for(let c=e;c<t-e;c++){let l=n.children[c];Fg(s,n.leaf?r(l):l),a+=RS(s)}for(let c=t-e-1;c>=e;c--){let l=n.children[c];Fg(o,n.leaf?r(l):l),a+=RS(o)}return a}_adjustParentBBoxes(n,e,t){for(let i=t;i>=0;i--)Fg(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():c_(n[t],this.toBBox)}};function XEt(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 c_(n,e){Lg(n,0,n.children.length,e,n)}function Lg(n,e,t,i,r){r||(r=l_(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];Fg(r,n.leaf?i(o):o)}return r}function Fg(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 UEt(n,e){return n.minX-e.minX}function VEt(n,e){return n.minY-e.minY}function P4(n){return(n.maxX-n.minX)*(n.maxY-n.minY)}function RS(n){return n.maxX-n.minX+(n.maxY-n.minY)}function GEt(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 HEt(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 k4(n,e){return n.minX<=e.minX&&n.minY<=e.minY&&e.maxX<=n.maxX&&e.maxY<=n.maxY}function OS(n,e){return e.minX<=n.maxX&&e.minY<=n.maxY&&e.maxX>=n.minX&&e.maxY>=n.minY}function l_(n){return{children:n,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Mq(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;rZ(n,o,e,t,r),s.push(e,o,o,t)}}var Eq=class{constructor(n=9){f(this,"tree");this.tree=new YEt(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()}},WEt=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}},Cq=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],Iq=class sZ{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=Cq[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 sZ(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=Cq.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 h=this.data=new r(8+u+c*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new i(h,8,4*c),this._indices=new this.IndexArrayType(h,8+u,c),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(h,0,2).set([251,48+l]),new Uint16Array(h,2,1)[0]=t,new Uint32Array(h,4,1)[0]=e}this._queue=new WEt}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++],h=Math.floor(65535*((a+l)/2-this.minX)/t),d=Math.floor(65535*((c+u)/2-this.minY)/i);r[s]=ZEt(h,d)}z4(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++],h=e[o++],d=e[o++];for(let _=1;_<this.nodeSize&&o<a;_++)l=Math.min(l,e[o++]),u=Math.min(u,e[o++]),h=Math.max(h,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++]=h,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,Nq(o,this._levelBounds));for(let u=o;u<l;u+=4){let h=this._boxes[u];if(i<h)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,h,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,Nq(o,this._levelBounds));for(let h=o;h<u;h+=4){let d=0|this._indices[h>>2],_=this._boxes[h],g=this._boxes[h+1],x=this._boxes[h+2],v=this._boxes[h+3],P=e<_?_-e:e>x?e-x:0,w=t<g?g-t:t>v?t-v:0,T=P*P+w*w;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 Nq(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 z4(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 h=i-1,d=r+1;for(;;){do h++;while(n[h]<l);do d--;while(n[d]>l);if(h>=d)break;qEt(n,e,t,h,d)}z4(n,e,t,i,d,s),z4(n,e,t,d+1,r,s)}function qEt(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],h=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]=h;let d=t[i];t[i]=t[r],t[r]=d}function ZEt(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,h=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),h=16711935&(h|h<<8),h=252645135&(h|h<<4),h=858993459&(h|h<<2),h=1431655765&(h|h<<1),(h<<1|u)>>>0}var KEt=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 Iq(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 Iq(this.capacity)}},oZ=class{constructor(n="native",e=[]){f(this,"idx");f(this,"storage",[]);n==="flatbush"?e.length===0?(this.idx=new Eq,n="rbush"):this.idx=new KEt(e.length):this.idx=n==="rbush"?new Eq:new class{constructor(){f(this,"shi",new JEt(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})}},JEt=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 h=this.getBucketKey(l,u),d=this.buckets.get(h)||[];for(let _ of d)s.has(_[1])||(s.add(_[1]),r.push(_[0]))}return r}},QEt=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 h=a;h<=l;h+=this.CELL_SIZE){let d=this.getBucketKey(u,h),_=this.buckets.get(d)||[];for(let g of _)s.has(g[1])||(s.add(g[1]),r.push(g[0]))}return r}},tCt=class extends an{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(dd(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 oZ("flatbush",this.srj.obstacles),this.targets=this.computeTargets(),this.targetTree=new QEt(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===dd(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:[dd(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 h=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>=h&&s<=d&&c>=_&&a<=g||s>=h&&o<=d&&a>=_&&c<=g||h>=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(!Jq(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(!A4(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(`
161
+ `),{solved:!1,connectionName:n.name}}createObstacleList({dominantLayer:n,connection:e,obstaclesFromTraces:t}){return new hH(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),ed.enabled&&this.drawDebugTraceObstacles(e),r.solved&&e.push(...pH(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:A3t(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})}}},O3t=(0,mH.default)("autorouting-dataset:infinite-grid-ijump-astar:get-distance-to-overcome-obstacle");function e4({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 h=e.dy===0,d=h?i.height:i.width;if((h?u.height:u.width)>d)return O3t("next obstacle on path is bigger, not trying to overcome it"),l;let g=e4({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 L3t=class extends fH{constructor(){super(...arguments);f(this,"MAX_ITERATIONS",200)}getNeighbors(e){let t=this.obstacles,i=this.goalPoint,r;e.parent?r=iH(e.parent,e):r=iH(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=e4({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=cH(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 F3t(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,P=d*1.1,w=Math.abs(r*c)+Math.abs(d*l);o.push({center:{x:t.x+x,y:t.y+v},width:P,height:w})}}else{let d=r/e;for(let _=0;_<e;_++){let g=(_-e/2+.5)*d,x=-g*l,v=g*c,P=Math.abs(i*c)+Math.abs(d*l),w=d*1.1;o.push({center:{x:t.x+x,y:t.y+v},width:P,height:w})}}return o}var uS=["top","inner1","inner2","bottom"],_H=(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=F3t(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:uS,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:uS,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:uS,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:uS,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=pH(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 oH(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 _H(i).map(r=>({...r,connectedTo:[t]}))}var yH=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=oH({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=oH({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=Tg(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]}},z3t=(n,e={})=>{let t={minTraceWidth:.1};t.layerCount=e.layerCount??1,t.obstacles=_H(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=GG(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 lS(n);s=yH({connection:s,pcbConnMap:o})}t.connections.push(s),$3t(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},$3t=(n,e,t)=>{for(let i of e)for(let r of n)D3t(i,r)&&r.connectedTo.push(t)};function D3t(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 aH(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 n4={1:["top"],2:["top","bottom"],4:["top","inner1","inner2","bottom"]},j3t=n=>n4[n];function gH(n,e){let i=n4[n].indexOf(e);if(i===-1)throw new Error(`Invalid layer for getLayerIndex (for layerCount === ${n}): "${e}"`);return i}function B3t(n,e){let i=n4[n][e];if(!i)throw new Error(`Invalid index for indexToLayer (for layerCount === ${n}): "${e}"`);return i}var Y3t=class extends hH{constructor(e,t){super([]);f(this,"obstacles");f(this,"GRID_STEP",.1);f(this,"layerCount");this.layerCount=e;let i=j3t(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:gH(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,h=null;if(l!==0){let d=o+l;return this.isObstacleAt(r,s,d,i)?(u=1,h=this.getObstacleAt(r,s,d,i)):u=1,{dx:a,dy:c,dl:l,wallDistance:u,obstacle:h}}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,P=null;a===1&&c===0?s>v&&s<x&&r<d.left&&(P=d.left-r):a===-1&&c===0?s>v&&s<x&&r>d.right&&(P=r-d.right):a===0&&c===1?r>_&&r<g&&s<d.bottom&&(P=d.bottom-s):a===0&&c===-1&&r>_&&r<g&&s>d.top&&(P=s-d.top),P!==null&&P<u&&(u=P,h=d)}return{dx:a,dy:c,dl:0,wallDistance:u,obstacle:h}}}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}},pS=class extends fH{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 lS,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?yH({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_${nH(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 Y3t(this.layerCount,this.allObstacles.filter(s=>!s.connectedTo.includes(r)).concat(i??[]))}computeG(e,t){let i=e.g+nd(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 gH(this.layerCount,e)}indexToLayer(e){return B3t(this.layerCount,e)}getNodeName(e){return`${lH(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=nd(e,i);if(r<=this.OBSTACLE_MARGIN)return this.getNeighborsSurroundingGoal(e);let s;e.parent?s=aH(e.parent,e):s=aH(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=nd(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(h=>h.dx===s.dx*-1&&h.dy===s.dy*-1&&h.dl===s.dl*-1?!1:!(h.dx===s.dx&&h.dy===s.dy&&h.dl===s.dl&&e.parent?.obstacleHit)).map(h=>t.getOrthoDirectionCollisionInfo(e,h,{margin:this.OBSTACLE_MARGIN})).filter(h=>!(h.wallDistance<this.OBSTACLE_MARGIN)),u=[];for(let h of l){let d=h.dx===0&&h.dy===0&&h.dl===1,_=h.dx===0&&h.dy===0&&h.dl===-1;if((d||_)&&![e.l,e.l+h.dl].every(w=>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:w}).length===0))continue;if(d){e.l<this.layerCount-1&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}if(_){e.l>0&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}let g=null;e?.obstacleHit&&(g=e4({node:e,travelDir:h,wallDir:{...s,wallDistance:this.OBSTACLE_MARGIN},obstacle:e.obstacleHit,obstacles:t,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let x=cH(e,i,h),v=(h.dx===0||Math.sign(i.x-e.x)===h.dx)&&(h.dy===0||Math.sign(i.y-e.y)===h.dy);if(x<h.wallDistance&&x>0&&v){let P=e.l===i.l,w=0;!P&&Math.abs(x-r)<this.GRID_STEP&&(w=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin),u.push({...h,travelDistance:x-w,enterMarginCost:0,travelMarginCostFactor:1})}else if(g!==null&&g<h.wallDistance){for(let{margin:P,enterCost:w,travelCostFactor:T}of this.marginsWithCosts)g-this.OBSTACLE_MARGIN+P*2<h.wallDistance&&u.push({...h,travelDistance:g-this.OBSTACLE_MARGIN+P,enterMarginCost:w,travelMarginCostFactor:T});if(h.wallDistance===1/0)u.push({...h,travelDistance:x,enterMarginCost:0,travelMarginCostFactor:1});else if(h.wallDistance>this.largestMargin)for(let{margin:P,enterCost:w,travelCostFactor:T}of this.marginsWithCosts)h.wallDistance>this.largestMargin+P&&u.push({...h,travelDistance:h.wallDistance-P,enterMarginCost:w,travelMarginCostFactor:T})}else if(h.wallDistance!==1/0)for(let{margin:P,enterCost:w,travelCostFactor:T}of this.marginsWithCosts)h.wallDistance>P&&u.push({...h,travelDistance:h.wallDistance-P,enterMarginCost:w,travelMarginCostFactor:T})}return u.map(h=>({x:e.x+h.dx*h.travelDistance,y:e.y+h.dy*h.travelDistance,l:e.l+h.dl,obstacleHit:h.obstacle,travelMarginCostFactor:h.travelMarginCostFactor,enterMarginCost:h.enterMarginCost}))}};function xH(n){let e=z3t(n),t=new L3t({input:e});return{solution:t.solveAndMapToTraces(),debugSolutions:t.debugSolutions,debugMessage:t.debugMessage}}J();J();St();J();J();St();St();J();J();St();J();J();J();J();St();J();J();J();St();J();J();St();J();J();J();J();J();J();J();J();J();J();St();J();St();J();St();J();J();St();St();J();St();J();J();St();J();J();J();St();J();St();J();St();J();St();J();St();J();St();J();St();J();J();J();J();J();J();J();J();St();J();St();J();J();St();J();St();J();J();J();St();J();St();St();J();J();J();St();J();J();J();St();J();St();J();St();J();St();J();St();J();St();J();St();J();St();J();J();St();J();St();J();St();J();J();St();St();J();J();St();St();J();J();St();J();St();J();St();J();St();J();St();J();St();J();J();St();J();St();J();St();J();St();J();St();J();St();J();St();J();St();St();J();St();J();St();J();J();St();J();St();J();St();J();St();J();St();J();J();var Ct=n=>{};Ct("extra props b");Ct("missing props b");Ct(!0);Ct("property a has mismatched types");var X3t=p.enum(["up","down","left","right"]),Ane=p.enum(["top-to-bottom","left-to-right","bottom-to-top","right-to-left"]);Ct(!0);Ct(!0);var ro=p.array(p.string().or(p.number()));Ct(!0);var fS=p.object({x:Y,y:Y,z:Y}),U3t=p.object({x:p.union([p.number(),p.string()]),y:p.union([p.number(),p.string()]),z:p.union([p.number(),p.string()])}),Uc=p.object({rotationOffset:p.number().or(U3t).optional(),positionOffset:fS.optional(),size:fS.optional(),modelUnitToMmScale:Y.optional(),zOffsetFromSurface:Y.optional()});Ct(!0);var V3t=Uc.extend({stlUrl:p.string()}),G3t=Uc.extend({objUrl:p.string(),mtlUrl:p.string().optional()}),H3t=Uc.extend({gltfUrl:p.string()}),W3t=Uc.extend({glbUrl:p.string()}),q3t=Uc.extend({stepUrl:p.string()}),Z3t=Uc.extend({wrlUrl:p.string()}),K3t=Uc.extend({jscad:p.record(p.any())}),MH=p.union([p.null(),p.string(),p.custom(n=>n&&typeof n=="object"&&"type"in n&&"props"in n),V3t,G3t,H3t,W3t,q3t,Z3t,K3t]);Ct(!0);var J3t=p.custom(n=>!0),s4=p.object({silkscreenFontSize:Y.optional(),viaPadDiameter:Y.optional(),viaHoleDiameter:Y.optional(),silkscreenTextPosition:p.union([p.enum(["centered","outside","none"]),p.object({offsetX:p.number(),offsetY:p.number()})]).optional(),silkscreenTextVisibility:p.enum(["hidden","visible","inherit"]).optional()});Ct(!0);var Q3t=p.custom(n=>!0),je=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbRotation:Qe.optional(),pcbPositionAnchor:p.string().optional(),pcbPositionMode:p.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),layer:pe.optional(),pcbMarginTop:Y.optional(),pcbMarginRight:Y.optional(),pcbMarginBottom:Y.optional(),pcbMarginLeft:Y.optional(),pcbMarginX:Y.optional(),pcbMarginY:Y.optional(),pcbStyle:s4.optional(),pcbRelative:p.boolean().optional(),relative:p.boolean().optional()});Ct(!0);var mS=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbRotation:Qe.optional(),pcbPositionAnchor:p.string().optional(),pcbPositionMode:p.enum(["relative_to_group_anchor","auto","relative_to_board_anchor","relative_to_component_anchor"]).optional(),pcbMarginTop:Y.optional(),pcbMarginRight:Y.optional(),pcbMarginBottom:Y.optional(),pcbMarginLeft:Y.optional(),pcbMarginX:Y.optional(),pcbMarginY:Y.optional(),pcbStyle:s4.optional(),schMarginTop:Y.optional(),schMarginRight:Y.optional(),schMarginBottom:Y.optional(),schMarginLeft:Y.optional(),schMarginX:Y.optional(),schMarginY:Y.optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Qe.optional(),layer:pe.optional(),footprint:J3t.optional(),symbol:Q3t.optional(),relative:p.boolean().optional(),schRelative:p.boolean().optional(),pcbRelative:p.boolean().optional()});Ct(!0);var tMt=p.object({supplierPartNumbers:p.record(Nm,p.array(p.string())).optional()});Ct(!0);var eMt=p.object({providesPower:p.boolean().optional(),requiresPower:p.boolean().optional(),providesGround:p.boolean().optional(),requiresGround:p.boolean().optional(),providesVoltage:p.union([p.string(),p.number()]).optional(),requiresVoltage:p.union([p.string(),p.number()]).optional(),doNotConnect:p.boolean().optional(),includeInBoardPinout:p.boolean().optional(),highlightColor:p.string().optional(),mustBeConnected:p.boolean().optional()});Ct(!0);var ri=mS.merge(tMt).extend({key:p.any().optional(),name:p.string(),cadModel:MH.optional(),children:p.any().optional(),symbolName:p.string().optional(),doNotPlace:p.boolean().optional(),obstructsWithinBounds:p.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:p.boolean().optional().describe("Whether to show this component's CAD model as translucent in the 3D viewer."),pinAttributes:p.record(p.string(),eMt).optional()});Ct(!0);var o4=["pin1","left","pin2","right"],_S=["pin1","left","anode","pos","pin2","right","cathode","neg"],Vne=Y.or(p.enum(["2x","3x","4x"]));var Vc=p.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 hS=p.object({pins:p.array(p.union([p.number(),p.string()])),direction:p.union([p.literal("top-to-bottom"),p.literal("left-to-right"),p.literal("bottom-to-top"),p.literal("right-to-left")])}),Eg=p.object({leftSize:p.number().optional().describe("@deprecated, use leftPinCount"),topSize:p.number().optional().describe("@deprecated, use topPinCount"),rightSize:p.number().optional().describe("@deprecated, use rightPinCount"),bottomSize:p.number().optional().describe("@deprecated, use bottomPinCount"),leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftSide:hS.optional(),rightSide:hS.optional(),topSide:hS.optional(),bottomSide:hS.optional()}),a4=Eg;Ct(!0);var Cg=p.record(p.object({marginLeft:Y.optional(),marginRight:Y.optional(),marginTop:Y.optional(),marginBottom:Y.optional(),leftMargin:Y.optional(),rightMargin:Y.optional(),topMargin:Y.optional(),bottomMargin:Y.optional()}));Ct(!0);var Cs=p.string().regex(/^[A-Za-z0-9_]+$/),t_=p.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),Ro=p.object({x:Y,y:Y}),Ig=p.object({edit_event_id:p.string(),in_progress:p.boolean().optional(),created_at:p.number()});Ct(!0);var nMt=Ig.extend({pcb_edit_event_type:p.literal("edit_component_location").describe("deprecated"),edit_event_type:p.literal("edit_pcb_component_location"),pcb_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var iMt=Ig.extend({pcb_edit_event_type:p.literal("edit_trace_hint").describe("deprecated"),edit_event_type:p.literal("edit_pcb_trace_hint").optional(),pcb_port_id:p.string(),pcb_trace_hint_id:p.string().optional(),route:p.array(p.object({x:p.number(),y:p.number(),via:p.boolean().optional()}))});Ct(!0);var rMt=Ig.extend({edit_event_type:p.literal("edit_schematic_component_location"),schematic_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var cie=Ig.extend({edit_event_type:p.literal("edit_pcb_group_location"),pcb_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var uie=Ig.extend({edit_event_type:p.literal("edit_schematic_group_location"),schematic_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});Ct(!0);var hie=p.union([nMt,iMt,rMt]);Ct(!0);var sMt=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Zt});Ct(!0);var oMt=p.object({pcb_port_selector:p.string(),offsets:p.array(Ji)});Ct(!0);var aMt=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Zt});Ct(!0);var cMt=p.object({pcb_placements:p.array(sMt).optional(),manual_trace_hints:p.array(oMt).optional(),schematic_placements:p.array(aMt).optional()});Ct(!0);var e_=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),id=n=>p.record(p.enum(n),e_),Mg=p.object({layoutMode:p.enum(["grid","flex","match-adapt","relative","none"]).optional(),position:p.enum(["absolute","relative"]).optional(),grid:p.boolean().optional(),gridCols:p.number().or(p.string()).optional(),gridRows:p.number().or(p.string()).optional(),gridTemplateRows:p.string().optional(),gridTemplateColumns:p.string().optional(),gridTemplate:p.string().optional(),gridGap:p.number().or(p.string()).optional(),gridRowGap:p.number().or(p.string()).optional(),gridColumnGap:p.number().or(p.string()).optional(),flex:p.boolean().or(p.string()).optional(),flexDirection:p.enum(["row","column"]).optional(),alignItems:p.enum(["start","center","end","stretch"]).optional(),justifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),flexRow:p.boolean().optional(),flexColumn:p.boolean().optional(),gap:p.number().or(p.string()).optional(),pack:p.boolean().optional().describe("Pack the contents of this group using a packing strategy"),packOrderStrategy:p.enum(["largest_to_smallest","first_to_last","highest_to_lowest_pin_count"]).optional(),packPlacementStrategy:p.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:p.boolean().optional(),matchAdaptTemplate:p.any().optional()});Ct(!0);var bH=p.object({strokeWidth:D.optional(),dashed:p.boolean().optional(),solid:p.boolean().optional()}),lMt=p.custom(n=>typeof n=="string"),uMt=p.object({serverUrl:p.string().optional(),inputFormat:p.enum(["simplified","circuit-json"]).optional(),serverMode:p.enum(["job","solve-endpoint"]).optional(),serverCacheEnabled:p.boolean().optional(),cache:p.custom(n=>!0).optional(),traceClearance:D.optional(),groupMode:p.enum(["sequential_trace","subcircuit","sequential-trace"]).optional(),algorithmFn:p.custom(n=>typeof n=="function"||n===void 0).optional(),preset:p.enum(["sequential_trace","subcircuit","auto","auto_local","auto_cloud","freerouting","laser_prefab","sequential-trace","auto-local","auto-cloud"]).optional(),local:p.boolean().optional()}),pMt=p.union([p.literal("sequential_trace"),p.literal("subcircuit"),p.literal("auto"),p.literal("auto_local"),p.literal("auto_cloud"),p.literal("freerouting"),p.literal("laser_prefab"),p.literal("sequential-trace"),p.literal("auto-local"),p.literal("auto-cloud")]),hMt=p.string(),EH=p.union([uMt,pMt,hMt]),c4=mS.extend({name:p.string().optional(),children:p.any().optional(),schTitle:p.string().optional(),key:p.any().optional(),showAsSchematicBox:p.boolean().optional(),connections:p.record(p.string(),e_.optional()).optional(),schPinArrangement:a4.optional(),schPinSpacing:D.optional(),schPinStyle:Cg.optional(),...Mg.shape,grid:Mg.shape.grid.describe("@deprecated use pcbGrid"),flex:Mg.shape.flex.describe("@deprecated use pcbFlex"),pcbGrid:p.boolean().optional(),pcbGridCols:p.number().or(p.string()).optional(),pcbGridRows:p.number().or(p.string()).optional(),pcbGridTemplateRows:p.string().optional(),pcbGridTemplateColumns:p.string().optional(),pcbGridTemplate:p.string().optional(),pcbGridGap:p.number().or(p.string()).optional(),pcbGridRowGap:p.number().or(p.string()).optional(),pcbGridColumnGap:p.number().or(p.string()).optional(),pcbFlex:p.boolean().or(p.string()).optional(),pcbFlexGap:p.number().or(p.string()).optional(),pcbFlexDirection:p.enum(["row","column"]).optional(),pcbAlignItems:p.enum(["start","center","end","stretch"]).optional(),pcbJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),pcbFlexRow:p.boolean().optional(),pcbFlexColumn:p.boolean().optional(),pcbGap:p.number().or(p.string()).optional(),pcbPack:p.boolean().optional(),pcbPackGap:p.number().or(p.string()).optional(),schGrid:p.boolean().optional(),schGridCols:p.number().or(p.string()).optional(),schGridRows:p.number().or(p.string()).optional(),schGridTemplateRows:p.string().optional(),schGridTemplateColumns:p.string().optional(),schGridTemplate:p.string().optional(),schGridGap:p.number().or(p.string()).optional(),schGridRowGap:p.number().or(p.string()).optional(),schGridColumnGap:p.number().or(p.string()).optional(),schFlex:p.boolean().or(p.string()).optional(),schFlexGap:p.number().or(p.string()).optional(),schFlexDirection:p.enum(["row","column"]).optional(),schAlignItems:p.enum(["start","center","end","stretch"]).optional(),schJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),schFlexRow:p.boolean().optional(),schFlexColumn:p.boolean().optional(),schGap:p.number().or(p.string()).optional(),schPack:p.boolean().optional(),schMatchAdapt:p.boolean().optional(),pcbWidth:D.optional(),pcbHeight:D.optional(),minTraceWidth:D.optional(),schWidth:D.optional(),schHeight:D.optional(),pcbLayout:Mg.optional(),schLayout:Mg.optional(),cellBorder:bH.nullable().optional(),border:bH.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:lMt.optional()}),CH=p.custom(n=>"findPart"in n),l4=c4.extend({manualEdits:cMt.optional(),schAutoLayoutEnabled:p.boolean().optional(),schTraceAutoLabelEnabled:p.boolean().optional(),schMaxTraceDistance:Y.optional(),routingDisabled:p.boolean().optional(),defaultTraceWidth:D.optional(),minTraceWidth:D.optional(),partsEngine:CH.optional(),pcbRouteCache:p.custom(n=>!0).optional(),autorouter:EH.optional(),square:p.boolean().optional(),emptyArea:p.string().optional(),filledArea:p.string().optional(),width:Y.optional(),height:Y.optional(),outline:p.array(Ro).optional(),outlineOffsetX:Y.optional(),outlineOffsetY:Y.optional(),circuitJson:p.array(p.any()).optional()}),dMt=l4.extend({subcircuit:p.literal(!0)}),IH=p.discriminatedUnion("subcircuit",[c4.extend({subcircuit:p.literal(!1).optional()}),dMt]);Ct(!0);Ct(!0);Ct(!0);Ct(!0);var Qm=p.custom(n=>typeof n=="string"),u4=l4.omit({connections:!0}).extend({material:p.enum(["fr4","fr1"]).default("fr4"),layers:p.union([p.literal(1),p.literal(2),p.literal(4),p.literal(6),p.literal(8)]).default(2),borderRadius:Y.optional(),thickness:Y.optional(),boardAnchorPosition:Ro.optional(),boardAnchorAlignment:t_.optional(),title:p.string().optional(),solderMaskColor:Qm.optional(),topSolderMaskColor:Qm.optional(),bottomSolderMaskColor:Qm.optional(),silkscreenColor:Qm.optional(),topSilkscreenColor:Qm.optional(),bottomSilkscreenColor:Qm.optional(),doubleSidedAssembly:p.boolean().optional().default(!1),schematicDisabled:p.boolean().optional()});Ct(!0);var NH=c4.omit({width:!0,height:!0,children:!0}).extend({width:Y,height:Y,children:p.any().optional(),noSolderMask:p.boolean().optional(),panelizationMethod:p.enum(["tab-routing","none"]).optional(),boardGap:Y.optional(),tabWidth:Y.optional(),tabLength:Y.optional(),mouseBites:p.boolean().optional()});Ct(!0);var wie=l4.extend({padding:Y.optional(),paddingLeft:Y.optional(),paddingRight:Y.optional(),paddingTop:Y.optional(),paddingBottom:Y.optional()});Ct(!0);var fMt=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),mMt=p.custom().pipe(p.record(p.string(),fMt)),_Mt=p.record(Cs,Cs.or(p.array(Cs).readonly()).or(p.array(Cs)));Ct(!0);var yMt=p.object({manufacturerPartNumber:p.string().optional(),supplierPartNumber:p.record(Nm,p.array(p.string())).optional()}),n_=ri.extend({manufacturerPartNumber:p.string().optional(),pinLabels:_Mt.optional(),showPinAliases:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),externallyConnectedPins:p.array(p.array(p.string())).optional(),schPinArrangement:Eg.optional(),schPortArrangement:Eg.optional(),pinCompatibleVariants:p.array(yMt).optional(),schPinStyle:Cg.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),noSchematicRepresentation:p.boolean().optional(),connections:mMt.optional()});Ct(!0);var AH=n_;Ct(!0);var p4=ri.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(Cs),Cs.or(p.array(Cs))).optional(),schPinStyle:Cg.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),schDirection:p.enum(["left","right"]).optional(),schPinArrangement:a4.optional(),schPortArrangement:Eg.optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),pinCount:p.union([p.literal(2),p.literal(3)]).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),connections:p.custom().pipe(p.record(p.string(),e_)).optional()});Ct(!0);var RH=p4.extend({bridgedPins:p.array(p.array(p.string())).optional(),bridged:p.boolean().optional()});Ct(!0);var Nie=ri.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(Cs),Cs.or(p.array(Cs))).optional(),schPinStyle:Cg.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional(),schDirection:p.enum(["left","right"]).optional(),schPortArrangement:Eg.optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),standard:p.enum(["usb_c","m2"]).optional()});Ct(!0);var Rie=ri.extend({standard:p.enum(["TSC0001_36P_XALT_2025_11"]).optional()});Ct(!0);var OH=ri.extend({currentRating:p.union([p.number(),p.string()]),voltageRating:p.union([p.number(),p.string()]).optional(),schShowRatings:p.boolean().optional(),schOrientation:Vc.optional(),connections:p.record(p.string(),p.union([p.string(),p.array(p.string()).readonly(),p.array(p.string())])).optional()}),dS=p.custom().transform(n=>{if(n!==void 0)return Y.parse(n)}),LH=p.discriminatedUnion("shape",[je.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circle"),holeDiameter:Y,outerDiameter:Y,padDiameter:Y.optional().describe("Diameter of the copper pad"),portHints:ro.optional(),solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}),je.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("oval"),outerWidth:Y,outerHeight:Y,holeWidth:dS,holeHeight:dS,innerWidth:Y.optional().describe("DEPRECATED use holeWidth"),innerHeight:Y.optional().describe("DEPRECATED use holeHeight"),portHints:ro.optional(),solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}),je.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill"),rectPad:p.boolean().optional(),outerWidth:Y,outerHeight:Y,holeWidth:dS,holeHeight:dS,innerWidth:Y.optional().describe("DEPRECATED use holeWidth"),innerHeight:Y.optional().describe("DEPRECATED use holeHeight"),portHints:ro.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional(),solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}),je.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circular_hole_with_rect_pad"),holeDiameter:Y,rectPadWidth:Y,rectPadHeight:Y,rectBorderRadius:Y.optional(),holeShape:p.literal("circle").optional(),padShape:p.literal("rect").optional(),portHints:ro.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional(),solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}),je.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill_hole_with_rect_pad"),holeShape:p.literal("pill"),padShape:p.literal("rect"),holeWidth:Y,holeHeight:Y,rectPadWidth:Y,rectPadHeight:Y,portHints:ro.optional(),holeOffsetX:Y.optional(),holeOffsetY:Y.optional(),solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}),je.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("hole_with_polygon_pad"),holeShape:p.enum(["circle","oval","pill","rotated_pill"]),holeDiameter:Y.optional(),holeWidth:Y.optional(),holeHeight:Y.optional(),padOutline:p.array(Ro),holeOffsetX:Y,holeOffsetY:Y,portHints:ro.optional(),solderMaskMargin:Y.optional(),coveredWithSolderMask:p.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 gMt=["pin1","pin2","pos","neg"],FH=ri.extend({resistance:zc,pullupFor:p.string().optional(),pullupTo:p.string().optional(),pulldownFor:p.string().optional(),pulldownTo:p.string().optional(),schOrientation:Vc.optional(),connections:id(gMt).optional()}),zH=o4;Ct(!0);var $H=ri.extend({maxResistance:zc,pinVariant:p.enum(["two_pin","three_pin"]).optional()});Ct(!0);var xMt=o4,DH=ri.extend({frequency:Fr,loadCapacitance:va,manufacturerPartNumber:p.string().optional(),mpn:p.string().optional(),pinVariant:p.enum(["two_pin","four_pin"]).optional(),schOrientation:Vc.optional(),connections:id(xMt).optional()});Ct(!0);var jH=ri.extend({frequency:Fr,loadCapacitance:va,pinVariant:p.enum(["no_ground","ground_pin","two_ground_pins"]).optional()});Ct(!0);var Hie=u4.extend({leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftPins:p.array(p.string()).optional(),rightPins:p.array(p.string()).optional(),topPins:p.array(p.string()).optional(),bottomPins:p.array(p.string()).optional(),pinPitch:Y.optional(),innerHoles:p.boolean().optional()});Ct(!0);var bMt=["pin1","pin2","pos","neg","anode","cathode"],BH=ri.extend({capacitance:va,maxVoltageRating:lr.optional(),schShowRatings:p.boolean().optional().default(!1),polarized:p.boolean().optional().default(!1),decouplingFor:p.string().optional(),decouplingTo:p.string().optional(),bypassFor:p.string().optional(),bypassTo:p.string().optional(),maxDecouplingTraceLength:p.number().optional(),schOrientation:Vc.optional(),connections:id(bMt).optional()}),YH=_S;Ct(!0);var Kie=p.object({name:p.string(),connectsTo:p.string().or(p.array(p.string())).optional(),highlightColor:p.string().optional(),isPowerNet:p.boolean().optional(),isGroundNet:p.boolean().optional()});Ct(!0);var Qie=p.object({name:p.string().optional(),pcbOnly:p.boolean().optional(),schOnly:p.boolean().optional()});Ct(!0);var vMt=p.object({pcb:p.literal(!0).optional(),xDist:Y,left:p.string(),right:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});Ct(!0);var SMt=p.object({pcb:p.literal(!0).optional(),yDist:Y,top:p.string(),bottom:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});Ct(!0);var wMt=p.object({pcb:p.literal(!0).optional(),sameY:p.literal(!0).optional(),for:p.array(p.string())});Ct(!0);var PMt=p.object({pcb:p.literal(!0).optional(),sameX:p.literal(!0).optional(),for:p.array(p.string())});Ct(!0);var XH=p.union([vMt,SMt,wMt,PMt]);Ct(!0);var kMt=je.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y});Ct(!0);var TMt=je.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:Y});Ct(!0);var MMt=je.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Ro)});Ct(!0);var UH=p.discriminatedUnion("shape",[kMt,TMt,MMt]),EMt=je.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y,rectBorderRadius:Y.optional(),cornerRadius:Y.optional(),portHints:ro.optional(),coveredWithSolderMask:p.boolean().optional(),solderMaskMargin:Y.optional()});Ct(!0);var CMt=je.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rotated_rect"),width:Y,height:Y,ccwRotation:p.number(),cornerRadius:Y.optional(),portHints:ro.optional(),coveredWithSolderMask:p.boolean().optional(),solderMaskMargin:Y.optional()});Ct(!0);var IMt=je.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:Y,portHints:ro.optional(),coveredWithSolderMask:p.boolean().optional(),solderMaskMargin:Y.optional()});Ct(!0);var NMt=je.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("pill"),width:Y,height:Y,radius:Y,portHints:ro.optional(),coveredWithSolderMask:p.boolean().optional(),solderMaskMargin:Y.optional()});Ct(!0);var AMt=je.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Ro),portHints:ro.optional(),coveredWithSolderMask:p.boolean().optional(),solderMaskMargin:Y.optional()});Ct(!0);var VH=p.discriminatedUnion("shape",[IMt,EMt,CMt,NMt,AMt]);Ct(!0);var RMt=je.omit({pcbRotation:!0}).extend({shape:p.literal("rect"),width:Y,height:Y});Ct(!0);var OMt=je.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:Y});Ct(!0);var rre=p.union([OMt,RMt]);Ct(!0);var LMt=je.extend({name:p.string().optional(),shape:p.literal("circle").optional(),diameter:Y.optional(),radius:Y.optional(),solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}).transform(n=>({...n,diameter:n.diameter??2*n.radius,radius:n.radius??n.diameter/2})),FMt=je.extend({name:p.string().optional(),shape:p.literal("pill"),width:Y,height:Y,solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}),zMt=je.extend({name:p.string().optional(),shape:p.literal("rect"),width:Y,height:Y,solderMaskMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional()}),GH=p.union([LMt,FMt,zMt]);Ct(!0);var i4=p.union([p.string(),p.custom(n=>!!n.getPortSelector)]),vH=p.object({key:p.string().optional(),thickness:Y.optional(),width:Y.optional().describe("Alias for trace thickness"),schematicRouteHints:p.array(Ro).optional(),pcbRouteHints:p.array(Ji).optional(),pcbPathRelativeTo:p.string().optional(),pcbPath:p.array(p.union([Ro,p.string()])).optional(),pcbStraightLine:p.boolean().optional().describe("Draw a straight pcb trace between the connected points"),schDisplayLabel:p.string().optional(),schStroke:p.string().optional(),highlightColor:p.string().optional(),maxLength:Y.optional()}),HH=p.union([vH.extend({path:p.array(i4)}),vH.extend({from:i4,to:i4})]),WH=p.object({children:p.any().optional(),originalLayer:pe.default("top").optional(),circuitJson:p.array(p.any()).optional()});Ct(!0);var qH=p.object({originalFacingDirection:p.enum(["up","down","left","right"]).default("right").optional()});Ct(!0);var $Mt=p.number().or(p.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"),ZH=ri.extend({capacity:$Mt.optional(),voltage:lr.optional(),standard:p.enum(["AA","AAA","9V","CR2032","18650","C"]).optional(),schOrientation:Vc.optional()});Ct(!0);var DMt=p.enum(["vertical","horizontal"]).describe("vertical means pins go 1->2 downward and horizontal means pins go 1->2 rightward");Ct(!0);var KH=ri.extend({pinCount:p.number(),pitch:Y.optional(),schFacingDirection:p.enum(["up","down","left","right"]).optional(),gender:p.enum(["male","female","unpopulated"]).optional().default("male"),showSilkscreenPinLabels:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),doubleRow:p.boolean().optional(),rightAngle:p.boolean().optional(),pcbOrientation:DMt.optional(),holeDiameter:Y.optional(),platedDiameter:Y.optional(),pinLabels:p.record(p.string(),Cs).or(p.array(Cs)).optional(),connections:p.custom().pipe(p.record(p.string(),e_)).optional(),facingDirection:p.enum(["left","right"]).optional(),schPinArrangement:a4.optional(),schPinStyle:Cg.optional(),schPinSpacing:Y.optional(),schWidth:Y.optional(),schHeight:Y.optional()});Ct(!0);var gre=p.object({net:p.string().optional(),connection:p.string().optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Qe.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});Ct(!0);var JH=p.object({net:p.string().optional(),connection:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),schX:Y.optional(),schY:Y.optional(),schRotation:Qe.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});Ct(!0);var QH=n_.extend({});Ct(!0);Ct(!0);var jMt=p.custom(n=>typeof n=="string"),tW=p.object({simulationType:p.literal("spice_transient_analysis").default("spice_transient_analysis"),duration:ur.optional(),timePerStep:ur.optional(),spiceEngine:jMt.optional()});Ct(!0);var BMt=["pin1","pin2","pin3","emitter","collector","base","gate","source","drain"],eW=ri.extend({type:p.enum(["npn","pnp","bjt","jfet","mosfet","igbt"]),connections:id(BMt).optional()});Ct(!0);var nW=ri.extend({channelType:p.enum(["n","p"]),mosfetMode:p.enum(["enhancement","depletion"])});Ct(!0);var YMt=o4,iW=ri.extend({inductance:Yx,maxCurrentRating:p.union([p.string(),p.number()]).optional(),schOrientation:Vc.optional(),connections:id(YMt).optional()});Ct(!0);var XMt=p.enum(["anode","cathode","pin1","pin2","pos","neg"]),UMt=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),VMt=p.record(XMt,UMt),GMt=p.enum(["standard","schottky","zener","avalanche","photo","tvs"]),rW=ri.extend({connections:VMt.optional(),variant:GMt.optional().default("standard"),standard:p.boolean().optional(),schottky:p.boolean().optional(),zener:p.boolean().optional(),avalanche:p.boolean().optional(),photo:p.boolean().optional(),tvs:p.boolean().optional(),schOrientation:Vc.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:p.ZodIssueCode.custom,message:"Exactly one diode variant must be enabled",path:[]}),p.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}),sW=_S;Ct(!0);var oW=ri.extend({color:p.string().optional(),wavelength:p.string().optional(),schDisplayValue:p.string().optional(),schOrientation:Vc.optional(),connections:id(_S).optional(),laser:p.boolean().optional()}),aW=_S,cW=ri.extend({type:p.enum(["spst","spdt","dpst","dpdt"]).optional(),isNormallyClosed:p.boolean().optional().default(!1),spst:p.boolean().optional(),spdt:p.boolean().optional(),dpst:p.boolean().optional(),dpdt:p.boolean().optional(),simSwitchFrequency:Fr.optional(),simCloseAt:ur.optional(),simOpenAt:ur.optional(),simStartClosed:p.boolean().optional(),simStartOpen:p.boolean().optional(),connections:p.custom().pipe(p.record(p.string(),e_)).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 lW=je.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional()});Ct(!0);var uW=je.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional(),cornerRadius:Y.optional()}),pW=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Ji),strokeWidth:D.optional(),color:p.string().optional()}),SH=p.union([p.string(),Ro]),hW=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:SH,to:SH,text:p.string().optional(),offset:Y.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional(),arrowSize:Y.optional(),units:p.enum(["in","mm"]).optional(),outerEdgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional(),innerEdgeToEdge:p.literal(!0).optional()});Ct(!0);var Bre=p.object({layer:p.string().optional(),thickness:Y.optional(),route:p.array(Ji)}),dW=mS.extend({name:p.string().optional(),fromLayer:pe,toLayer:pe,holeDiameter:Y.optional(),outerDiameter:Y.optional(),connectsTo:p.string().or(p.array(p.string())).optional(),netIsAssignable:p.boolean().optional()});Ct(!0);var HMt=p.object({pin1:e_}).strict(),fW=ri.extend({connections:HMt.optional(),footprintVariant:p.enum(["pad","through_hole"]).optional(),padShape:p.enum(["rect","circle"]).optional().default("circle"),padDiameter:Y.optional(),holeDiameter:Y.optional(),width:Y.optional(),height:Y.optional()}).refine(n=>n.footprintVariant!=="through_hole"||n.holeDiameter!==void 0,{message:"holeDiameter is required for through_hole testpoints"});Ct(!0);var mW=je.omit({pcbRotation:!0,layer:!0}).extend({connection:p.string()});Ct(!0);var _W=p.union([je.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:Y}),je.extend({shape:p.literal("rect"),width:Y,height:Y})]),Kre=je.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),tse=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({outline:p.array(Ro),strokeWidth:D.optional(),isClosed:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),yW=p.object({name:p.string().optional(),layer:pe,connectsTo:p.string(),padMargin:Y.optional(),traceMargin:Y.optional(),clearance:Y.optional(),boardEdgeMargin:Y.optional(),cutoutMargin:Y.optional(),coveredWithSolderMask:p.boolean().optional().default(!0)});Ct(!0);var gW=p.object({originalLayer:pe.default("top").optional(),children:p.any().optional()});Ct(!0);var WMt=p.object({pcbX:Y.optional(),pcbY:Y.optional(),pcbOffsetX:Y.optional(),pcbOffsetY:Y.optional(),pcbZ:Y.optional()}),qMt=Uc.extend({modelUrl:p.string(),stepUrl:p.string().optional()}),ZMt=qMt.merge(WMt);Ct(!0);var xW=p.union([p.null(),p.string(),ZMt]),bW=ri.extend({voltage:lr}),KMt=["pin1","pin2","pos","neg"],JMt=p.union([p.string(),p.number()]).transform(n=>typeof n=="string"?n.endsWith("%")?parseFloat(n.slice(0,-1))/100:parseFloat(n):n).pipe(p.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),vW=ri.extend({voltage:lr.optional(),frequency:Fr.optional(),peakToPeakVoltage:lr.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Qe.optional(),dutyCycle:JMt.optional(),connections:id(KMt).optional()});Ct(!0);var SW=ri.omit({name:!0}).extend({name:p.string().optional(),connectsTo:p.string(),referenceTo:p.string().optional(),color:p.string().optional()});Ct(!0);var wW=p.object({center:Zt,radius:Y,startAngleDegrees:Qe,endAngleDegrees:Qe,direction:p.enum(["clockwise","counterclockwise"]).default("counterclockwise"),strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),PW=p.object({schX:Y.optional(),schY:Y.optional(),width:Y.optional(),height:Y.optional(),overlay:p.array(p.string()).optional(),padding:Y.optional(),paddingLeft:Y.optional(),paddingRight:Y.optional(),paddingTop:Y.optional(),paddingBottom:Y.optional(),title:p.string().optional(),titleAlignment:t_.default("top_left"),titleColor:p.string().optional(),titleFontSize:Y.optional(),titleInside:p.boolean().default(!1),strokeStyle:p.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."}),kW=p.object({center:Zt,radius:Y,strokeWidth:Y.optional(),color:p.string().optional(),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),TW=p.object({schX:Y.optional(),schY:Y.optional(),width:Y,height:Y,rotation:Qe.default(0),strokeWidth:Y.optional(),color:p.string().optional(),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1),cornerRadius:Y.optional()}),MW=p.object({x1:Y,y1:Y,x2:Y,y2:Y,strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),QMt=p.enum(["center","left","right","top","bottom"]),EW=p.object({schX:Y.optional(),schY:Y.optional(),text:p.string(),fontSize:p.number().default(1),anchor:p.union([QMt.describe("legacy"),t_]).default("center"),color:p.string().default("#000000"),schRotation:Qe.default(0)}),kse=p.object({points:p.array(Zt),isFilled:p.boolean().optional().default(!1),fillColor:p.enum(["red","blue"]).optional()}),CW=p.object({schX:Y.optional(),schY:Y.optional(),children:p.any().optional(),cellPadding:Y.optional(),borderWidth:Y.optional(),anchor:t_.optional(),fontSize:Y.optional()});Ct(!0);var IW=p.object({children:p.any().optional(),height:Y.optional()});Ct(!0);var NW=p.object({children:p.string().optional(),horizontalAlign:p.enum(["left","center","right"]).optional(),verticalAlign:p.enum(["top","middle","bottom"]).optional(),fontSize:Y.optional(),rowSpan:p.number().optional(),colSpan:p.number().optional(),width:Y.optional(),text:p.string().optional()});Ct(!0);var Ose=je.extend({text:p.string(),anchorAlignment:t_.default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),layers:p.array(pe).optional()}),AW=je.extend({text:p.string(),anchorAlignment:t_.default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),isKnockout:p.boolean().optional(),knockoutPadding:D.optional(),knockoutPaddingLeft:D.optional(),knockoutPaddingRight:D.optional(),knockoutPaddingTop:D.optional(),knockoutPaddingBottom:D.optional(),layers:p.array(pe).optional()}),RW=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Ji),strokeWidth:D.optional()}),OW=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({strokeWidth:Y,x1:Y,y1:Y,x2:Y,y2:Y}),LW=je.omit({pcbRotation:!0}).extend({filled:p.boolean().default(!0).optional(),stroke:p.enum(["dashed","solid","none"]).optional(),strokeWidth:Y.optional(),width:Y,height:Y,cornerRadius:Y.optional()}),FW=je.omit({pcbRotation:!0}).extend({isFilled:p.boolean().optional(),isOutline:p.boolean().optional(),strokeWidth:Y.optional(),radius:Y}),wH=p.object({x:Y,y:Y,via:p.boolean().optional(),toLayer:pe.optional()}),zW=p.object({for:p.string().optional().describe("Selector for the port you're targeting, not required if you're inside a trace"),order:p.number().optional(),offset:Ji.or(wH).optional(),offsets:p.array(Ji).or(p.array(wH)).optional(),traceWidth:p.number().optional()}),Hse=mS.extend({name:p.string(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),direction:X3t,connectsTo:p.string().or(p.array(p.string())).optional()}),$W=je.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional()});Ct(!0);var DW=je.omit({pcbRotation:!0}).extend({width:Y,height:Y,strokeWidth:Y.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional(),cornerRadius:Y.optional()});Ct(!0);var jW=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({route:p.array(Ji),strokeWidth:D.optional(),color:p.string().optional()});Ct(!0);var BW=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({x1:Y,y1:Y,x2:Y,y2:Y,strokeWidth:Y.optional(),color:p.string().optional(),isDashed:p.boolean().optional()});Ct(!0);var PH=p.union([p.string(),Ro]),YW=je.omit({pcbX:!0,pcbY:!0,pcbOffsetX:!0,pcbOffsetY:!0,pcbRotation:!0}).extend({from:PH,to:PH,text:p.string().optional(),offset:Y.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:D.optional(),color:p.string().optional(),arrowSize:Y.optional(),units:p.enum(["in","mm"]).optional(),outerEdgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional(),innerEdgeToEdge:p.literal(!0).optional()});Ct(!0);var XW=p.array(p.any()).describe("Circuit JSON"),r4=p.object({footprintCircuitJson:p.array(p.any()),cadModel:MH.optional()}),kH=p.function().args(p.string()).returns(p.promise(r4)).or(p.function().args(p.string(),p.object({resolvedPcbStyle:s4.optional()}).optional()).returns(p.promise(r4))).describe("A function that takes a path and returns Circuit JSON"),tEt=p.object({loadFromUrl:p.function().args(p.string()).returns(p.promise(r4)).describe("A function that takes a footprint file URL and returns Circuit JSON")}),eEt=p.object({engineVersionString:p.string().optional(),simulationResultCircuitJson:XW}),nEt=p.object({simulate:p.function().args(p.string()).returns(p.promise(eEt)).describe("A function that takes a SPICE string and returns a simulation result")}),iEt=p.custom(n=>typeof n=="string"),TH=p.object({run:p.function().args().returns(p.promise(p.unknown())).describe("Run the autorouter"),getOutputSimpleRouteJson:p.function().args().returns(p.promise(p.any())).describe("Get the resulting SimpleRouteJson")}),rEt=p.object({createAutorouter:p.function().args(p.any(),p.any().optional()).returns(p.union([TH,p.promise(TH)])).describe("Create an autorouter instance")}),sEt=p.object({partsEngine:CH.optional(),autorouter:EH.optional(),autorouterMap:p.record(p.string(),rEt).optional(),registryApiUrl:p.string().optional(),cloudAutorouterUrl:p.string().optional(),projectName:p.string().optional(),projectBaseUrl:p.string().optional(),version:p.string().optional(),url:p.string().optional(),printBoardInformationToSilkscreen:p.boolean().optional(),includeBoardFiles:p.array(p.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:p.string().describe('The directory where snapshots are stored for "tsci snapshot", defaults to "tests/__snapshots__"').optional(),defaultSpiceEngine:iEt.optional(),localCacheEngine:p.any().optional(),pcbDisabled:p.boolean().optional(),schematicDisabled:p.boolean().optional(),partsEngineDisabled:p.boolean().optional(),spiceEngineMap:p.record(p.string(),nEt).optional(),footprintLibraryMap:p.record(p.string(),p.union([kH,p.record(p.string(),p.union([XW,kH]))])).optional(),footprintFileParserMap:p.record(p.string(),tEt).optional(),resolveProjectStaticFileImportUrl:p.function().args(p.string()).returns(p.promise(p.string())).describe("A function that returns a string URL for static files for the project").optional()});Ct(!0);var oEt=sEt,soe=oEt.pick({projectName:!0,projectBaseUrl:!0,version:!0,url:!0,printBoardInformationToSilkscreen:!0,includeBoardFiles:!0,snapshotsDir:!0,defaultSpiceEngine:!0});Ct(!0);St();J();St();St();St();Ta();J();var Va=Gt(Zs(),1);Ta();J();function Gc(){return new h4}var h4=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 yS(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 yS(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}},yS=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 Ia=class{constructor(e=""){f(this,"_name");f(this,"_value",0);f(this,"_context",null);f(this,"_id",aEt++);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 $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])}toJSON(){return{name:this._name,value:this._value}}toString(){return this._context+"["+this._name+":"+this._value+"]"}},aEt=0;var $n=class n{constructor(){f(this,"_terms");f(this,"_constant");let e=cEt(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 cEt(n){let e=0,t=()=>0,i=Gc();for(let r=0,s=n.length;r<s;++r){let o=n[r];if(typeof o=="number")e+=o;else if(o instanceof Ia)i.setDefault(o,t).second+=1;else if(o instanceof $n){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 Ia)i.setDefault(c,t).second+=a;else if(c instanceof $n){e+=c.constant()*a;let l=c.terms();for(let u=0,h=l.size();u<h;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 so=class so{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(so.required,e))}};f(so,"required",so.create(1e3,1e3,1e3)),f(so,"strong",so.create(1,0,0)),f(so,"medium",so.create(0,1,0)),f(so,"weak",so.create(0,0,1));var Rn=so;var si;(function(n){n[n.Le=0]="Le",n[n.Ge=1]="Ge",n[n.Eq=2]="Eq"})(si||(si={}));var Pi=class{constructor(e,t,i,r=Rn.required){f(this,"_expression");f(this,"_operator");f(this,"_strength");f(this,"_id",lEt++);this._operator=t,this._strength=Rn.clip(r),i===void 0&&e instanceof $n?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()+")"}},lEt=0;var i_=class{constructor(){f(this,"maxIterations",1e3);f(this,"_cnMap",uEt());f(this,"_rowMap",pEt());f(this,"_varMap",hEt());f(this,"_editMap",dEt());f(this,"_infeasibleRows",[]);f(this,"_objective",new bS);f(this,"_artificial",null);f(this,"_idTick",0)}createConstraint(e,t,i,r=Rn.required){let s=new Pi(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()===nn.Invalid&&r.allDummies())if(gS(r.constant()))o=s.marker;else throw new Error("unsatisfiable constraint");if(o.type()===nn.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()===nn.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=Rn.clip(t),t===Rn.required)throw new Error("bad required strength");let r=new $n(e),s=new Pi(r,si.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,h=r.size();u<h;++u){let d=r.itemAt(u),_=d.second,g=_.coefficientFor(a);g!==0&&_.add(o*g)<0&&d.first.type()!==nn.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(nn.External);return this._varMap.setDefault(e,t).second}_createRow(e){let t=e.expression(),i=new bS(t.constant()),r=t.terms();for(let c=0,l=r.size();c<l;++c){let u=r.itemAt(c);if(!gS(u.second)){let h=this._getVarSymbol(u.first),d=this._rowMap.find(h);d!==void 0?i.insertRow(d.second,u.second):i.insertSymbol(h,u.second)}}let s=this._objective,o=e.strength(),a={marker:Hc,other:Hc};switch(e.op()){case si.Le:case si.Ge:{let c=e.op()===si.Le?1:-1,l=this._makeSymbol(nn.Slack);if(a.marker=l,i.insertSymbol(l,c),o<Rn.required){let u=this._makeSymbol(nn.Error);a.other=u,i.insertSymbol(u,-c),s.insertSymbol(u,o)}break}case si.Eq:{if(o<Rn.required){let c=this._makeSymbol(nn.Error),l=this._makeSymbol(nn.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(nn.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()===nn.External)return a.first}let r=t.marker.type();return(r===nn.Slack||r===nn.Error)&&e.coefficientFor(t.marker)<0?t.marker:(r=t.other.type(),(r===nn.Slack||r===nn.Error)&&e.coefficientFor(t.other)<0?t.other:Hc)}_addWithArtificialVariable(e){let t=this._makeSymbol(nn.Slack);this._rowMap.insert(t,e.copy()),this._artificial=e.copy(),this._optimize(this._artificial);let i=gS(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()===nn.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()!==nn.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()===nn.Invalid)return;let r=this._getLeavingSymbol(i);if(r.type()===nn.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()===nn.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()!==nn.Dummy)return o}return Hc}_getDualEnteringSymbol(e){let t=Number.MAX_VALUE,i=Hc,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()!==nn.Dummy){let h=this._objective.coefficientFor(c)/l;h<t&&(t=h,i=c)}}return i}_getLeavingSymbol(e){let t=Number.MAX_VALUE,i=Hc,r=this._rowMap;for(let s=0,o=r.size();s<o;++s){let a=r.itemAt(s),c=a.first;if(c.type()!==nn.External){let l=a.second,u=l.coefficientFor(e);if(u<0){let h=-l.constant()/u;h<t&&(t=h,i=c)}}}return i}_getMarkerLeavingSymbol(e){let t=Number.MAX_VALUE,i=t,r=t,s=Hc,o=s,a=s,c=s,l=this._rowMap;for(let u=0,h=l.size();u<h;++u){let d=l.itemAt(u),_=d.second,g=_.coefficientFor(e);if(g===0)continue;let x=d.first;if(x.type()===nn.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()===nn.Error&&this._removeMarkerEffects(t.marker,e.strength()),t.other.type()===nn.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===nn.Slack||o===nn.Error)return s.first}return Hc}_makeSymbol(e){return new xS(e,this._idTick++)}};function gS(n){let e=1e-8;return n<0?-n<e:n<e}function uEt(){return Gc()}function pEt(){return Gc()}function hEt(){return Gc()}function dEt(){return Gc()}var nn;(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"})(nn||(nn={}));var xS=class{constructor(e,t){f(this,"_id");f(this,"_type");this._id=t,this._type=e}id(){return this._id}type(){return this._type}},Hc=new xS(nn.Invalid,-1),bS=class n{constructor(e=0){f(this,"_cellMap",Gc());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()!==nn.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);gS(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 snt=Gt(En(),1);J();St();St();er();var y4={};vh(y4,{areBoundsCompletelyInsidePolygon:()=>_4,areBoundsOverlappingPolygon:()=>m4,boundsAreaOverlap:()=>nq,boundsDistance:()=>iq,boundsIntersection:()=>rq,clamp:()=>Vn,computeDistanceBetweenBoxes:()=>Ao,computeGapBetweenBoxes:()=>t4,computeManhattanDistanceBetweenBoxes:()=>kg,distSq:()=>qW,distance:()=>Fi,doBoundsOverlap:()=>Wc,doSegmentsIntersect:()=>ki,doesLineIntersectLine:()=>Na,doesSegmentIntersectRect:()=>d4,findNearestPointsBetweenBoxSets:()=>Tg,getBoundingBox:()=>io,getBoundsFromPoints:()=>Oo,getSegmentIntersection:()=>od,getUnitVectorFromDirection:()=>kS,getUnitVectorFromPointAToB:()=>PS,grid:()=>sq,isPointInsidePolygon:()=>wS,isRectCompletelyInsidePolygon:()=>tq,isRectOverlappingPolygon:()=>QW,midpoint:()=>WW,normalizeDegrees:()=>ad,onSegment:()=>sd,orientation:()=>rd,pointToBoundsDistance:()=>HW,pointToBoxDistance:()=>GW,pointToSegmentClosestPoint:()=>VW,pointToSegmentDistance:()=>yi,range:()=>eq,segmentToBoundsMinDistance:()=>Ng,segmentToBoxMinDistance:()=>vS,segmentToCircleMinDistance:()=>SS,segmentToSegmentMinDistance:()=>r_});function Na([n,e],[t,i],{lineThickness:r=0}={}){return r===0?ki(n,e,t,i):fEt(n,e,t,i)<=r}function ki(n,e,t,i){let r=rd(n,e,t),s=rd(n,e,i),o=rd(t,i,n),a=rd(t,i,e);return!!(r!==s&&o!==a||r===0&&sd(n,t,e)||s===0&&sd(n,i,e)||o===0&&sd(t,n,i)||a===0&&sd(t,e,i))}function rd(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 sd(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 fEt(n,e,t,i){if(n.x===e.x&&n.y===e.y)return yi(n,t,i);if(t.x===i.x&&t.y===i.y)return yi(t,n,e);if(ki(n,e,t,i))return 0;let r=[yi(n,t,i),yi(e,t,i),yi(t,n,e),yi(i,n,e)];return Math.min(...r)}function yi(n,e,t){let i=(t.x-e.x)**2+(t.y-e.y)**2;if(i===0)return Fi(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 Fi(n,s)}function Fi(n,e){let t=n.x-e.x,i=n.y-e.y;return Math.sqrt(t*t+i*i)}function od(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 h=(l*o-c*a)/u,d=(r*l-s*c)/u,_=1e-9;if(h>=-_&&h<=1+_&&d>=-_&&d<=1+_){let g=n.x+h*r,x=n.y+h*s;return{x:g,y:x}}return null}function d4(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 ki(n,e,r,s)||ki(n,e,s,a)||ki(n,e,a,o)||ki(n,e,o,r)}function r_(n,e,t,i){if(n.x===e.x&&n.y===e.y)return yi(n,t,i);if(t.x===i.x&&t.y===i.y)return yi(t,n,e);if(ki(n,e,t,i))return 0;let r=[yi(n,t,i),yi(e,t,i),yi(t,n,e),yi(i,n,e)];return Math.min(...r)}function Ng(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(ki(n,e,i,r)||ki(n,e,r,o)||ki(n,e,o,s)||ki(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=[yi(i,n,e),yi(r,n,e),yi(s,n,e),yi(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=Vn(n.x,t.minX,t.maxX),l=Vn(n.y,t.minY,t.maxY);a.push(Fi(n,{x:c,y:l}))}if(e.x<t.minX||e.x>t.maxX||e.y<t.minY||e.y>t.maxY){let c=Vn(e.x,t.minX,t.maxX),l=Vn(e.y,t.minY,t.maxY);a.push(Fi(e,{x:c,y:l}))}return Math.min(...a)}function vS(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 Ng(n,e,s)}function SS(n,e,t){let i={x:t.x,y:t.y};if(n.x===e.x&&n.y===e.y)return Math.max(0,Fi(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=Fi(c,i);return Math.max(0,l-t.radius)}function VW(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 ad(n){return(n%360+360)%360}function GW(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=Vn(n.x,r,s),l=Vn(n.y,o,a);return Fi(n,{x:c,y:l})}function HW(n,e){if(n.x>=e.minX&&n.x<=e.maxX&&n.y>=e.minY&&n.y<=e.maxY)return 0;let t=Vn(n.x,e.minX,e.maxX),i=Vn(n.y,e.minY,e.maxY);return Fi(n,{x:t,y:i})}function WW(n,e){return{x:(n.x+e.x)/2,y:(n.y+e.y)/2}}function qW(n,e){let t=n.x-e.x,i=n.y-e.y;return t*t+i*i}var ZW=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}},f4=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}],KW=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},mEt=(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)},_Et=(n,e)=>n.x>=e.minX&&n.x<=e.maxX&&n.y>=e.minY&&n.y<=e.maxY,wS=(n,e)=>{if(e.length<3)return!1;let t=KW(e);for(let[r,s]of t)if(mEt(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},JW=(n,e)=>{let t=f4(n),i=[[t[0],t[1]],[t[1],t[2]],[t[2],t[3]],[t[3],t[0]]],r=KW(e);for(let[s,o]of r)for(let[a,c]of i)if(ki(s,o,a,c))return!0;return!1},m4=(n,e)=>e.length<3?!1:e.some(i=>_Et(i,n))||f4(n).some(i=>wS(i,e))?!0:JW(n,e),_4=(n,e)=>e.length<3||!f4(n).every(i=>wS(i,e))?!1:!JW(n,e),QW=(n,e)=>m4(ZW(n),e),tq=(n,e)=>_4(ZW(n),e);function eq(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 nq=(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 iq=(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 rq=(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 Wc=(n,e)=>!(n.maxX<e.minX||e.maxX<n.minX||n.maxY<e.minY||e.maxY<n.minY);var Oo=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 PS=(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}},kS=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 sq({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,h=i??1,d=r??e*u,_=s??n*h,g=l?-d/2:0,x=l?-_/2:0,v=r?r/e:u,P=s?s/n:h,w=[];for(let T=0;T<n;T++)for(let k=0;k<e;k++){let C=T*e+k,M=o+g+k*v+v/2,I=a+T*P+P/2,E=c==="cartesian"?a+x+(n-1-T)*P+P/2:a+x+T*P+P/2;w.push({index:C,center:{x:M,y:E},topLeft:{x:M-v/2,y:E+P/2},bottomRight:{x:M+v/2,y:E-P/2},row:T,col:k})}return w}St();Ag();var oq={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"}};St();er();Ae();var o9=Gt(Zs(),1);St();var hnt=Gt(En(),1);var W4={};vh(W4,{AssignableViaAutoroutingPipelineSolver:()=>aIt,AutoroutingPipelineSolver:()=>CZ,CapacityMeshSolver:()=>eIt,InMemoryCache:()=>pZ,LocalStorageCache:()=>hZ,calculateOptimalCapacityDepth:()=>U4,convertSrjToGraphicsObject:()=>Vg,getGlobalInMemoryCache:()=>__,getGlobalLocalStorageCache:()=>dZ,getTunedTotalCapacity1:()=>ao,setupGlobalCaches:()=>Ug});var uZ=Gt(CS(),1),wZ=Gt(CS(),1),TZ=Gt(CS(),1);var hd=(...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},an=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 bq(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 Kc(n,e,t){return Math.max(e,Math.min(t,n))}function zi(n,e,t,i){let r=IS(n,e,t),s=IS(n,e,i),o=IS(t,i,n),a=IS(t,i,e);return r!==s&&o!==a||!(r!==0||!NS(n,t,e))||!(s!==0||!NS(n,i,e))||!(o!==0||!NS(t,n,i))||!(a!==0||!NS(t,e,i))}function IS(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 NS(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 fr(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 Hq(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 h=(l*o-c*a)/u,d=(r*l-s*c)/u,_=1e-9;return h>=-1e-9&&h<=1+_&&d>=-1e-9&&d<=1+_?{x:n.x+h*r,y:n.y+h*s}:null}function vq(n,e){return{x:(n.x+e.x)/2,y:(n.y+e.y)/2}}var Wq=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}},X4=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}],qq=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},CEt=(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)},Zq=(n,e)=>{if(e.length<3)return!1;let t=qq(e);for(let[r,s]of t)if(CEt(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},Kq=(n,e)=>{let t=X4(n),i=[[t[0],t[1]],[t[1],t[2]],[t[2],t[3]],[t[3],t[0]]],r=qq(e);for(let[s,o]of r)for(let[a,c]of i)if(zi(s,o,a,c))return!0;return!1},A4=(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))||!!X4(t).some(r=>Zq(r,i))||Kq(t,i)))(Wq(n),e),Jq=(n,e)=>((t,i)=>!(i.length<3)&&!!X4(t).every(r=>Zq(r,i))&&!Kq(t,i))(Wq(n),e);function R4(n,e,t,i){if(n.x===e.x&&n.y===e.y)return fr(n,t,i);if(t.x===i.x&&t.y===i.y)return fr(t,n,e);if(zi(n,e,t,i))return 0;let r=[fr(n,t,i),fr(e,t,i),fr(t,n,e),fr(i,n,e)];return Math.min(...r)}function Qq(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},h={x:a.maxX,y:a.maxY};if(zi(s,o,c,l)||zi(s,o,l,h)||zi(s,o,h,u)||zi(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=[fr(c,s,o),fr(l,s,o),fr(u,s,o),fr(h,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 _=Kc(s.x,a.minX,a.maxX),g=Kc(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 _=Kc(o.x,a.minX,a.maxX),g=Kc(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 p_(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 Br(){return Br=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},Br.apply(null,arguments)}function GS(n,e){return(GS=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,i){return t.__proto__=i,t})(n,e)}function tZ(n){return(tZ=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(n)}function eZ(){try{var n=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(eZ=function(){return!!n})()}function O4(n){var e=typeof Map=="function"?new Map:void 0;return O4=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(eZ())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,s);var c=new(r.bind.apply(r,a));return o&&GS(c,o.prototype),c})(t,arguments,tZ(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),GS(i,t)},O4(n)}var jr=(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,GS(e,t),i})(O4(Error));function Sq(n,e){return n.substr(-e.length)===e}var IEt=/^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;function wq(n){return typeof n!="string"?n:n.match(IEt)?parseFloat(n):n}var Pq=function(n){return function(e,t){t===void 0&&(t="16px");var i=e,r=t;if(typeof e=="string"){if(!Sq(e,"px"))throw new jr(69,n,e);i=wq(e)}if(typeof t=="string"){if(!Sq(t,"px"))throw new jr(70,n,t);r=wq(t)}if(typeof i=="string")throw new jr(71,e,n);if(typeof r=="string")throw new jr(72,t,n);return""+i/r+n}};Pq("em"),Pq("rem");function v4(n){return Math.round(255*n)}function NEt(n,e,t){return v4(n)+","+v4(e)+","+v4(t)}function Bg(n,e,t,i){if(i===void 0&&(i=NEt),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 kq={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"},AEt=/^#[a-fA-F0-9]{6}$/,REt=/^#[a-fA-F0-9]{8}$/,OEt=/^#[a-fA-F0-9]{3}$/,LEt=/^#[a-fA-F0-9]{4}$/,S4=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,FEt=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,zEt=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,$Et=/^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 h_(n){if(typeof n!="string")throw new jr(3);var e=(function(d){if(typeof d!="string")return d;var _=d.toLowerCase();return kq[_]?"#"+kq[_]:d})(n);if(e.match(AEt))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(REt)){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(OEt))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(LEt)){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=S4.exec(e);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var s=FEt.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=zEt.exec(e);if(o){var a="rgb("+Bg(parseInt(""+o[1],10),parseInt(""+o[2],10)/100,parseInt(""+o[3],10)/100)+")",c=S4.exec(a);if(!c)throw new jr(4,e,a);return{red:parseInt(""+c[1],10),green:parseInt(""+c[2],10),blue:parseInt(""+c[3],10)}}var l=$Et.exec(e.substring(0,50));if(l){var u="rgb("+Bg(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",h=S4.exec(u);if(!h)throw new jr(4,e,u);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+l[4])>1?parseFloat(""+l[4])/100:parseFloat(""+l[4])}}throw new jr(5)}function Jc(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}})(h_(n))}var L4=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 ud(n){var e=n.toString(16);return e.length===1?"0"+e:e}function w4(n){return ud(Math.round(255*n))}function DEt(n,e,t){return L4("#"+w4(n)+w4(e)+w4(t))}function AS(n,e,t){return Bg(n,e,t,DEt)}function F4(n,e,t){if(typeof n=="number"&&typeof e=="number"&&typeof t=="number")return L4("#"+ud(n)+ud(e)+ud(t));if(typeof n=="object"&&e===void 0&&t===void 0)return L4("#"+ud(n.red)+ud(n.green)+ud(n.blue));throw new jr(6)}function tw(n,e,t,i){if(typeof n=="string"&&typeof e=="number"){var r=h_(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?F4(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?F4(n.red,n.green,n.blue):"rgba("+n.red+","+n.green+","+n.blue+","+n.alpha+")";throw new jr(7)}function Qc(n){if(typeof n!="object")throw new jr(8);if((function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&typeof e.alpha=="number"})(n))return tw(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 F4(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?AS(e,t,i):"rgba("+Bg(e,t,i)+","+r+")";if(typeof e=="object"&&t===void 0&&i===void 0&&r===void 0)return e.alpha>=1?AS(e.hue,e.saturation,e.lightness):"rgba("+Bg(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new jr(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 AS(e,t,i);if(typeof e=="object"&&t===void 0&&i===void 0)return AS(e.hue,e.saturation,e.lightness);throw new jr(1)})(n);throw new jr(8)}function nZ(n,e,t){return function(){var i=t.concat(Array.prototype.slice.call(arguments));return i.length>=e?n.apply(this,i):nZ(n,e,i)}}function ss(n){return nZ(n,n.length,[])}ss(function(n,e){if(e==="transparent")return e;var t=Jc(e);return Qc(Br({},t,{hue:t.hue+parseFloat(n)}))});function m_(n,e,t){return Math.max(n,Math.min(e,t))}ss(function(n,e){if(e==="transparent")return e;var t=Jc(e);return Qc(Br({},t,{lightness:m_(0,1,t.lightness-parseFloat(n))}))});ss(function(n,e){if(e==="transparent")return e;var t=Jc(e);return Qc(Br({},t,{saturation:m_(0,1,t.saturation-parseFloat(n))}))});ss(function(n,e){if(e==="transparent")return e;var t=Jc(e);return Qc(Br({},t,{lightness:m_(0,1,t.lightness+parseFloat(n))}))});var iZ=ss(function(n,e,t){if(e==="transparent")return t;if(t==="transparent")return e;if(n===0)return t;var i=h_(e),r=Br({},i,{alpha:typeof i.alpha=="number"?i.alpha:1}),s=h_(t),o=Br({},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 tw({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))})});ss(function(n,e){if(e==="transparent")return e;var t=h_(e);return tw(Br({},t,{alpha:m_(0,1,(100*(typeof t.alpha=="number"?t.alpha:1)+100*parseFloat(n))/100)}))});ss(function(n,e){if(e==="transparent")return e;var t=Jc(e);return Qc(Br({},t,{saturation:m_(0,1,t.saturation+parseFloat(n))}))});ss(function(n,e){return e==="transparent"?e:Qc(Br({},Jc(e),{hue:parseFloat(n)}))});ss(function(n,e){return e==="transparent"?e:Qc(Br({},Jc(e),{lightness:parseFloat(n)}))});ss(function(n,e){return e==="transparent"?e:Qc(Br({},Jc(e),{saturation:parseFloat(n)}))});ss(function(n,e){return e==="transparent"?e:iZ(parseFloat(n),"rgb(0, 0, 0)",e)});ss(function(n,e){return e==="transparent"?e:iZ(parseFloat(n),"rgb(255, 255, 255)",e)});var jEt=ss(function(n,e){if(e==="transparent")return e;var t=h_(e);return tw(Br({},t,{alpha:m_(0,1,+(100*(typeof t.alpha=="number"?t.alpha:1)-100*parseFloat(n)).toFixed(2)/100)}))}),Tq=["blue","orange","purple","cyan","magenta","yellowgreen","darkgoldenrod","deeppink"],Yg=(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},Kn=(n,e)=>{try{return jEt(e,n)}catch(t){return console.error(t),n}},dd=(n,e)=>n==="top"?0:n==="bottom"?e-1:parseInt(n.slice(5)),ao=(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},U4=(n,e=.5,t=16)=>{let i=0,r=n;for(;i<t&&!(ao({width:r})<=e);)r/=2,i++;return Math.max(1,i)};function rZ(n,e,t=0,i=n.length-1,r=BEt){for(;i>t;){if(i-t>600){let c=i-t+1,l=e-t+1,u=Math.log(c),h=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*h*(c-h)/c)*(l-c/2<0?-1:1);rZ(n,e,Math.max(t,Math.floor(e-l*h/c+d)),Math.min(i,Math.floor(e+(c-l)*h/c+d)),r)}let s=n[e],o=t,a=i;for(Og(n,t,e),r(n[i],s)>0&&Og(n,t,i);o<a;){for(Og(n,o,a),o++,a--;r(n[o],s)<0;)o++;for(;r(n[a],s)>0;)a--}r(n[t],s)===0?Og(n,t,a):(a++,Og(n,a,i)),a<=e&&(t=a+1),e<=a&&(i=a-1)}}function Og(n,e,t){let i=n[e];n[e]=n[t],n[t]=i}function BEt(n,e){return n<e?-1:n>e?1:0}var YEt=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(!OS(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;OS(n,a)&&(e.leaf?t.push(o):k4(n,a)?this._all(o,t):r.push(o))}e=r.pop()}return t}collides(n){let e=this.data;if(!OS(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(OS(n,s)){if(e.leaf||k4(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=l_([]),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=XEt(n,t.children,e);if(l!==-1)return t.children.splice(l,1),r.push(t),this._condense(r),this}c||t.leaf||!k4(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=l_(n.slice(e,t+1)),c_(s,this.toBBox),s;i||(i=Math.ceil(Math.log(r)/Math.log(o)),o=Math.ceil(r/Math.pow(o,i-1))),s=l_([]),s.leaf=!1,s.height=i;let a=Math.ceil(r/o),c=a*Math.ceil(Math.sqrt(o));Mq(n,e,t,c,this.compareMinX);for(let l=e;l<=t;l+=c){let u=Math.min(l+c-1,t);Mq(n,l,u,a,this.compareMinY);for(let h=l;h<=u;h+=a){let d=Math.min(h+a-1,u);s.children.push(this._build(n,h,d,i-1))}}return c_(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=P4(c),u=GEt(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),Fg(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=l_(t.children.splice(s,t.children.length-s));o.height=t.height,o.leaf=t.leaf,c_(t,this.toBBox),c_(o,this.toBBox),e?n[e-1].children.push(o):this._splitRoot(t,o)}_splitRoot(n,e){this.data=l_([n,e]),this.data.height=n.height+1,this.data.leaf=!1,c_(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=Lg(n,0,o,this.toBBox),c=Lg(n,o,t,this.toBBox),l=HEt(a,c),u=P4(a)+P4(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:UEt,r=n.leaf?this.compareMinY:VEt;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=Lg(n,0,e,r),o=Lg(n,t-e,t,r),a=RS(s)+RS(o);for(let c=e;c<t-e;c++){let l=n.children[c];Fg(s,n.leaf?r(l):l),a+=RS(s)}for(let c=t-e-1;c>=e;c--){let l=n.children[c];Fg(o,n.leaf?r(l):l),a+=RS(o)}return a}_adjustParentBBoxes(n,e,t){for(let i=t;i>=0;i--)Fg(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():c_(n[t],this.toBBox)}};function XEt(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 c_(n,e){Lg(n,0,n.children.length,e,n)}function Lg(n,e,t,i,r){r||(r=l_(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];Fg(r,n.leaf?i(o):o)}return r}function Fg(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 UEt(n,e){return n.minX-e.minX}function VEt(n,e){return n.minY-e.minY}function P4(n){return(n.maxX-n.minX)*(n.maxY-n.minY)}function RS(n){return n.maxX-n.minX+(n.maxY-n.minY)}function GEt(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 HEt(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 k4(n,e){return n.minX<=e.minX&&n.minY<=e.minY&&e.maxX<=n.maxX&&e.maxY<=n.maxY}function OS(n,e){return e.minX<=n.maxX&&e.minY<=n.maxY&&e.maxX>=n.minX&&e.maxY>=n.minY}function l_(n){return{children:n,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Mq(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;rZ(n,o,e,t,r),s.push(e,o,o,t)}}var Eq=class{constructor(n=9){f(this,"tree");this.tree=new YEt(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()}},WEt=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}},Cq=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],Iq=class sZ{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=Cq[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 sZ(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=Cq.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 h=this.data=new r(8+u+c*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new i(h,8,4*c),this._indices=new this.IndexArrayType(h,8+u,c),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(h,0,2).set([251,48+l]),new Uint16Array(h,2,1)[0]=t,new Uint32Array(h,4,1)[0]=e}this._queue=new WEt}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++],h=Math.floor(65535*((a+l)/2-this.minX)/t),d=Math.floor(65535*((c+u)/2-this.minY)/i);r[s]=ZEt(h,d)}z4(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++],h=e[o++],d=e[o++];for(let _=1;_<this.nodeSize&&o<a;_++)l=Math.min(l,e[o++]),u=Math.min(u,e[o++]),h=Math.max(h,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++]=h,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,Nq(o,this._levelBounds));for(let u=o;u<l;u+=4){let h=this._boxes[u];if(i<h)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,h,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,Nq(o,this._levelBounds));for(let h=o;h<u;h+=4){let d=0|this._indices[h>>2],_=this._boxes[h],g=this._boxes[h+1],x=this._boxes[h+2],v=this._boxes[h+3],P=e<_?_-e:e>x?e-x:0,w=t<g?g-t:t>v?t-v:0,T=P*P+w*w;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 Nq(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 z4(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 h=i-1,d=r+1;for(;;){do h++;while(n[h]<l);do d--;while(n[d]>l);if(h>=d)break;qEt(n,e,t,h,d)}z4(n,e,t,i,d,s),z4(n,e,t,d+1,r,s)}function qEt(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],h=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]=h;let d=t[i];t[i]=t[r],t[r]=d}function ZEt(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,h=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),h=16711935&(h|h<<8),h=252645135&(h|h<<4),h=858993459&(h|h<<2),h=1431655765&(h|h<<1),(h<<1|u)>>>0}var KEt=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 Iq(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 Iq(this.capacity)}},oZ=class{constructor(n="native",e=[]){f(this,"idx");f(this,"storage",[]);n==="flatbush"?e.length===0?(this.idx=new Eq,n="rbush"):this.idx=new KEt(e.length):this.idx=n==="rbush"?new Eq:new class{constructor(){f(this,"shi",new JEt(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})}},JEt=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 h=this.getBucketKey(l,u),d=this.buckets.get(h)||[];for(let _ of d)s.has(_[1])||(s.add(_[1]),r.push(_[0]))}return r}},QEt=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 h=a;h<=l;h+=this.CELL_SIZE){let d=this.getBucketKey(u,h),_=this.buckets.get(d)||[];for(let g of _)s.has(g[1])||(s.add(g[1]),r.push(g[0]))}return r}},tCt=class extends an{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(dd(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 oZ("flatbush",this.srj.obstacles),this.targets=this.computeTargets(),this.targetTree=new QEt(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===dd(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:[dd(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 h=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>=h&&s<=d&&c>=_&&a<=g||s>=h&&o<=d&&a>=_&&c<=g||h>=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(!Jq(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(!A4(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: ${ao(i).toFixed(2)}`].join(`
163
163
  `)})}return e.rects.sort((i,r)=>i.center.y-r.center.y),this.srj.connections.forEach((i,r)=>{let s=Tq[r%Tq.length];for(let o of i.pointsToConnect)e.points.push({x:o.x,y:o.y,label:`conn-${r} (${o.layer})`,color:s})}),e}},aZ=class extends tCt{constructor(e,t={}){super(e,t);f(this,"VIA_DIAMETER",.6);f(this,"OBSTACLE_MARGIN",.1);f(this,"OVERLAP_THRESHOLD_FOR_SINGLE_LAYER_NODES",.2);this.srj=e,this.opts=t}isNodeCompletelyOutsideBounds(e){if(this.outlinePolygon){let t=this.getNodeRect(e);if(!A4(t,this.outlinePolygon))return!0}return e.center.x+e.width/2<this.srj.bounds.minX||e.center.x-e.width/2>this.srj.bounds.maxX||e.center.y+e.height/2<this.srj.bounds.minY||e.center.y-e.height/2>this.srj.bounds.maxY}isNodePartiallyOutsideBounds(e){if(this.outlinePolygon){let t=this.getNodeRect(e);return!!A4(t,this.outlinePolygon)&&!Jq(t,this.outlinePolygon)}return e.center.x-e.width/2<this.srj.bounds.minX||e.center.x+e.width/2>this.srj.bounds.maxX||e.center.y-e.height/2<this.srj.bounds.minY||e.center.y+e.height/2>this.srj.bounds.maxY}getObstacleCoveragePercentage(e){let t=this.getXYZOverlappingObstacles(e);if(t.length===0)return 0;let i=e.center.x-e.width/2,r=e.center.x+e.width/2,s=e.center.y-e.height/2,o=e.center.y+e.height/2,a=e.width*e.height,c=0;for(let l of t){let u=Math.max(i,l.center.x-l.width/2),h=Math.min(r,l.center.x+l.width/2),d=Math.max(s,l.center.y-l.height/2),_=Math.min(o,l.center.y+l.height/2);u<h&&d<_&&(c+=(h-u)*(_-d))}return c/a}shouldFilterSingleLayerNodeForObstacle(e){return e.availableZ.length!==1||!e._containsObstacle?!1:this.getObstacleCoveragePercentage(e)>this.OVERLAP_THRESHOLD_FOR_SINGLE_LAYER_NODES}shouldFilterNodeForObstacle(e){return!!e._containsObstacle&&(e.availableZ.length!==1||this.shouldFilterSingleLayerNodeForObstacle(e))}createChildNodeAtPosition(e,t){let i={capacityMeshNodeId:this.getNextNodeId(),center:t.center,width:t.width,height:t.height,layer:e.layer,availableZ:t.availableZ,_depth:t._depth??(e._depth??0)+1,_parent:e},r=this.getXYZOverlappingObstacles(i);i._containsObstacle=r.length>0||this.isNodePartiallyOutsideBounds(i);let s=this.getTargetIfNodeContainsTarget(i);return s&&(i._targetConnectionName=s.connectionName,i._containsTarget=!0),i._containsObstacle&&(i._completelyInsideObstacle=this.isNodeCompletelyInsideObstacle(i)),i}getZSubdivisionChildNodes(e){if(e.availableZ.length===1)return[];let t=[],i=e.availableZ.map(r=>[r]);for(let r of i){let s=this.createChildNodeAtPosition(e,{center:{...e.center},width:e.width,height:e.height,availableZ:r,_depth:e._depth});this.isNodeCompletelyOutsideBounds(s)||t.push(s)}return t}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=this.createChildNodeAtPosition(e,{center:s,width:i.width,height:i.height,availableZ:e.availableZ});this.isNodeCompletelyOutsideBounds(o)||t.push(o)}return t}shouldNodeBeXYSubdivided(e){return!(e._depth>=this.MAX_DEPTH)&&(!!e._containsTarget||e.availableZ.length===1&&e._depth<=this.MAX_DEPTH||!(!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),a=s.availableZ.length>1&&!o&&(s._containsObstacle||s.width<this.VIA_DIAMETER+this.OBSTACLE_MARGIN);if(o)r.push(s);else if(o||this.shouldFilterNodeForObstacle(s)||a)if(!o&&s._containsTarget)if(a){let c=this.getZSubdivisionChildNodes(s);i.push(...c.filter(l=>l._containsTarget||!this.shouldFilterNodeForObstacle(l)))}else i.push(s);else a&&i.push(...this.getZSubdivisionChildNodes(s).filter(c=>!this.shouldFilterNodeForObstacle(c)));else i.push(s)}this.unfinishedNodes.push(...r),this.finishedNodes.push(...i)}};function d_(n){let e=new Map;for(let t of n)for(let i of t.nodeIds)e.set(i,[...e.get(i)??[],t]);return e}var cZ=class extends an{constructor({nodes:e,edges:t,capacityPaths:i,colorMap:r}){super();f(this,"nodes");f(this,"edges");f(this,"capacityPaths");f(this,"nodeMap");f(this,"nodeEdgeMap");f(this,"unprocessedNodeIds");f(this,"nodePortSegments");f(this,"colorMap");this.nodes=e,this.edges=t,this.nodeMap=new Map(e.map(s=>[s.capacityMeshNodeId,s])),this.nodeEdgeMap=d_(t),this.capacityPaths=i,this.colorMap=r??{},this.unprocessedNodeIds=[...new Set(i.flatMap(s=>s.nodeIds))],this.nodePortSegments=new Map}step(){let e=this.unprocessedNodeIds.pop();if(!e)return void(this.solved=!0);let t=[];for(let o of this.capacityPaths){let a=o.nodeIds.indexOf(e);a!==-1&&t.push({path:o,indexOfNodeInPath:a})}let i=this.nodeMap.get(e),r=[];for(let{path:o,indexOfNodeInPath:a}of t){let c=o.nodeIds[a-1],l=o.nodeIds[a+1];for(let u of[c,l]){let h=this.nodeMap.get(u);if(!h)continue;let d=eCt(i,h),_=h.availableZ.filter(x=>i.availableZ.includes(x));if(_.length===0)continue;let g={capacityMeshNodeId:e,start:d.start,end:d.end,connectionNames:[o.connectionName],availableZ:_};r.push(g)}}let s=(function(o){let a=[],c=o.map(l=>({...l,connectionNames:[...l.connectionNames],availableZ:[...l.availableZ].sort((u,h)=>u-h)}));for(;c.length>0;){let l=c.pop(),u=!1;for(let h=0;h<a.length;h++){let d=a[h],_=LS(d.start,l.start)&&LS(d.end,l.end)||LS(d.start,l.end)&&LS(d.end,l.start),g=nCt(d.availableZ,l.availableZ);if(_&&g){let x=new Set(d.connectionNames);l.connectionNames.forEach(v=>x.add(v)),d.connectionNames=Array.from(x),u=!0;break}}u||a.push(l)}return a})(r);this.nodePortSegments.set(e,s)}visualize(){let e={lines:[],points:[],rects:[],circles:[]};return this.nodePortSegments.forEach((t,i)=>{this.nodeMap.get(i),t.forEach(r=>{r.start.x,r.end.x;for(let s=0;s<r.connectionNames.length;s++){let o={x:.05*Math.max(...r.availableZ),y:.05*Math.max(...r.availableZ)},a={x:(r.start.x+r.end.x)/2,y:(r.start.y+r.end.y)/2},c={x:a.x+o.x,y:a.y+o.y};o.x>0&&e.lines.push({points:[a,c],strokeColor:"rgba(0, 0, 0, 0.25)",strokeDash:"5 5"}),e.points.push({x:c.x,y:c.y,label:`${i}: ${r.connectionNames.join(", ")}
164
164
  availableZ: ${r.availableZ.join(",")}
@@ -243,10 +243,10 @@ ${o.decouplingCapGroupId}`,r.fill=HNt(o.decouplingCapGroupId,.8))}return t}getCo
243
243
  ${_.join(`
244
244
  `)}
245
245
  </div>`},rAt=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:xQ(l),label:l})}return t};function Aw(n){return n.replace(/repeat\((\d+),\s*([^)]+)\)/g,(e,t,i)=>Array(Number(t)).fill(i.trim()).join(" "))}function Rw(n){return n.trim().split(/\s+/).filter(Boolean)}function _Q(n){return n?Rw(Aw(n)).length:0}function yQ(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 gQ(n,e){return n>0?n:e+2+n}var sAt=n=>{let e=n.opts,t=e.children,i,r;if("gridTemplate"in e&&typeof e.gridTemplate=="string"){let[M,I]=e.gridTemplate.split("/");i=M?.trim(),r=I?.trim()}else i=typeof e.gridTemplateRows=="string"?e.gridTemplateRows:void 0,r=typeof e.gridTemplateColumns=="string"?e.gridTemplateColumns:void 0;let s=_Q(r),o=_Q(i);function a(M,I,E,A){if(!M)return 0;let R=Aw(M),B=Rw(R),j=B.length,U=0,V=!1;for(let et=0;et<B.length;et++){let tt=B[et];if(tt.endsWith("px"))U+=parseFloat(tt);else if(tt.endsWith("em"))U+=parseFloat(tt)*16;else if(tt.endsWith("fr")||tt==="auto"){V=!0;let mt=0;for(let G of I){let Q=E?G.columnStart||G.column:G.rowStart||G.row,nt=E?G.columnSpan||1:G.rowSpan||1,pt=E?G.contentWidth:G.contentHeight,ht=(typeof Q=="number"?Q:parseInt(Q||"1"))-1,wt=typeof nt=="number"?nt:parseInt(nt.toString());if(ht<=et&&et<ht+wt&&pt){let Et=typeof pt=="string"&&pt.endsWith("px")?parseFloat(pt):typeof pt=="number"?pt:0;mt=Math.max(mt,Et/wt)}}U+=mt}}let H=A*(j-1);return U+H}function c(M,I,E,A=!0,R=1){if(!M)return[];if(I==null){let nt=Aw(M),pt=Rw(nt),ht=pt.length,wt=X=>X===void 0?0:typeof X=="number"?X:(X.endsWith("px"),parseFloat(X)),Et=new Array(ht).fill(0),ot=0;for(let X of t){let W=A?typeof X.columnSpan=="number"?X.columnSpan:X.columnSpan?parseInt(X.columnSpan.toString()):1:typeof X.rowSpan=="number"?X.rowSpan:X.rowSpan?parseInt(X.rowSpan.toString()):1,rt=A?X.contentWidth:X.contentHeight,ut=wt(rt)/W,yt;A?(X.columnStart!==void 0||X.column!==void 0)&&(yt=parseInt(X.columnStart??X.column)-1):(X.rowStart!==void 0||X.row!==void 0)&&(yt=parseInt(X.rowStart??X.row)-1),(yt===void 0||Number.isNaN(yt))&&(A?yt=ot%ht:yt=Math.floor(ot/R),ot+=W);for(let Z=0;Z<W&&yt+Z<ht;Z++)Et[yt+Z]=Math.max(Et[yt+Z],ut)}return pt.forEach((X,W)=>{let rt=yQ(X,void 0);typeof rt=="number"&&(Et[W]=rt)}),Et}let B=Aw(M),j=Rw(B),U=j.length,V=I;V==null&&(V=a(M,t,A,E));let H=V-E*(U-1),et=0,tt=0,mt=[],G=[];j.forEach((nt,pt)=>{let ht=yQ(nt,H);typeof ht=="number"?(G.push(ht),et+=ht):ht&&typeof ht=="object"&&"fr"in ht?(G.push(ht),tt+=ht.fr,mt.push({idx:pt,fr:ht.fr})):(G.push(0),et+=0)});let Q=Math.max(H-et,0);return G.map(nt=>typeof nt=="number"?nt:tt>0?Q/tt*nt.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,h=c(i,e.containerHeight,l,!1,s||1),d=c(r,e.containerWidth,u,!0,o||1),_=h.length,g=d.length;g===0&&t.length>0&&(g=1);let x=[],v=0;for(let M of t){let I=M.rowStart!==void 0?M.rowStart:M.row,E=M.columnStart!==void 0?M.columnStart:M.column,A=M.rowSpan!==void 0?typeof M.rowSpan=="string"?parseInt(M.rowSpan):M.rowSpan:1,R=M.columnSpan!==void 0?typeof M.columnSpan=="string"?parseInt(M.columnSpan):M.columnSpan:1;if(M.rowEnd!==void 0){let U=typeof M.rowEnd=="string"?parseInt(M.rowEnd):M.rowEnd;I!==void 0?A=U-(typeof I=="string"?parseInt(I):I):I=U-A}if(M.columnEnd!==void 0){let U=typeof M.columnEnd=="string"?parseInt(M.columnEnd):M.columnEnd;E!==void 0?R=U-(typeof E=="string"?parseInt(E):E):E=U-R}if(typeof I=="string"&&(I=parseInt(I)),typeof E=="string"&&(E=parseInt(E)),typeof I=="number"&&I<0&&(I=gQ(I,_)),typeof E=="number"&&E<0&&(E=gQ(E,g)),I===void 0&&E!==void 0)I=1;else if(E===void 0&&I!==void 0)E=1;else if(I===void 0&&E===void 0){let U=v;I=Math.floor(U/g)+1,E=U%g+1}let B=I-1,j=E-1;A=Math.max(1,A),R=Math.max(1,R),x.push({key:M.key,row:B,column:j,rowSpan:A,columnSpan:R,x:0,y:0,width:0,height:0}),v+=R}let P=h.length,w=d.length;for(let M of x)M.row+M.rowSpan>P&&(P=M.row+M.rowSpan),M.column+M.columnSpan>w&&(w=M.column+M.columnSpan);if(h.length===0&&P>0&&e.containerHeight){let M=P,E=(e.containerHeight-l*(M-1))/M;for(let A=0;A<M;A++)h.push(E)}else for(;h.length<P;)h.push(0);if(d.length===0&&w>0&&e.containerWidth){let M=w,E=(e.containerWidth-u*(M-1))/M;for(let A=0;A<M;A++)d.push(E)}else if(d.length===0&&t.length>0&&e.containerWidth)d.push(e.containerWidth);else for(;d.length<w;)d.push(0);let T=(M,I,E)=>{let A=0;for(let R=0;R<M;R++)A+=I[R]||0,A+=E;return A},k=(M,I,E,A)=>{let R=0;for(let B=M;B<M+I;B++)R+=E[B]||0,B>M&&(R+=A);return R},C={};for(let M of x){let I=t.find(G=>G.key===M.key),E=T(M.column,d,u),A=T(M.row,h,l),R=k(M.column,M.columnSpan,d,u),B=k(M.row,M.rowSpan,h,l),j=G=>G===void 0?0:typeof G=="string"?G.endsWith("px")?parseFloat(G):G.endsWith("%")?0:parseFloat(G):G,U=j(I?.contentWidth),V=j(I?.contentHeight),H=R,et=B,tt=E,mt=A;if(U>0)switch(H=U,e.justifyItems||"stretch"){case"start":tt=E;break;case"end":tt=E+R-H;break;case"center":tt=E+(R-H)/2;break;case"stretch":H=R,tt=E;break}if(V>0)switch(et=V,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}M.x=tt,M.y=mt,M.width=H,M.height=et,C[M.key]={x:tt,y:mt,width:H,height:et}}return{cells:x,rowSizes:h,columnSizes:d,rowGap:l,columnGap:u,itemCoordinates:C}},bQ=class{constructor(n){f(this,"opts");this.opts=n}layout(){return sAt(this)}convertToHtml(){return iAt(this)}visualize(){return rAt(this)}};St();var xnt=Gt(En(),1);Ae();Ae();St();var uA=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}};Ag();var x1=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,h=l+(+(u<r)&+(t[u]<t[l]));if(t[h]>=o)break;e[a]=e[h],t[a]=t[h],a=h}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 vQ=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],pA=3,b1=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!==pA)throw new Error(`Got v${s} data when expected v${pA}.`);let o=vQ[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=vQ.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 h=this.data=new r(8+u+c*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new i(h,8,c*4),this._indices=new this.IndexArrayType(h,8+u,c),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(h,0,2).set([251,(pA<<4)+l]),new Uint16Array(h,2,1)[0]=t,new Uint32Array(h,4,1)[0]=e}this._queue=new x1}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++],h=e[a++],d=Math.floor(s*((c+u)/2-this.minX)/t),_=Math.floor(s*((l+h)/2-this.minY)/i);r[o]=aAt(d,_)}hA(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++],h=e[a++],d=e[a++],_=e[a++];for(let g=1;g<this.nodeSize&&a<c;g++)u=Math.min(u,e[a++]),h=Math.min(h,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++]=h,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,SQ(o,this._levelBounds));for(let u=o;u<l;u+=4){let h=this._boxes[u];if(i<h)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,h,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,SQ(o,this._levelBounds));for(let h=o;h<u;h+=4){let d=this._indices[h>>2]|0,_=this._boxes[h],g=this._boxes[h+1],x=this._boxes[h+2],v=this._boxes[h+3],P=e<_?_-e:e>x?e-x:0,w=t<g?g-t:t>v?t-v:0,T=P*P+w*w;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 SQ(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 hA(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 h=i-1,d=r+1;for(;;){do h++;while(n[h]<l);do d--;while(n[d]>l);if(h>=d)break;oAt(n,e,t,h,d)}hA(n,e,t,i,d,s),hA(n,e,t,d+1,r,s)}function oAt(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],h=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]=h;let d=t[i];t[i]=t[r],t[r]=d}function aAt(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,h=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,h=(h|h<<8)&16711935,h=(h|h<<4)&252645135,h=(h|h<<2)&858993459,h=(h|h<<1)&1431655765,(h<<1|u)>>>0}var Pr=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:[]}}},bA=n=>{let e=new uA({});for(let i of n.directConnections)e.addConnections([i.netId?[i.netId,...i.pinIds]:i.pinIds]);let t=new uA(e.netMap);for(let i of n.netConnections)t.addConnections([[i.netId,...i.pinIds]]);return{directConnMap:e,netConnMap:t}};function cAt(n,e={}){let t=n.length,i=e?.maxDistance??Number.POSITIVE_INFINITY;if(t<=1)return[];{let u=new Set;for(let h of n){if(u.has(h.pinId))throw new Error(`Duplicate pinId detected: "${h.pinId}"`);u.add(h.pinId)}}let r=(u,h)=>Math.abs(u.x-h.x)+Math.abs(u.y-h.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 h=-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,h=g)}s[h]=!0,a[h]!==-1&&l.push([n[h].pinId,n[a[h]].pinId]);for(let g=0;g<t;g++)if(!s[g]){let x=r(n[h],n[g]),v=e?.forbidEdge?.(n[h],n[g])??!1,P=x>i||v?Number.POSITIVE_INFINITY:x;(P<o[g]||P===o[g]&&n[h].pinId<n[a[g]]?.pinId)&&(o[g]=P,a[g]=h)}}return l}var v1=(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,h=a-i,d=i-c,_=l-t,g=t-u,x=Math.min(h,d,_,g);return x===h?"y+":x===d?"y-":x===_?"x+":"x-"},lAt=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 P of x)if(P.pinIds.includes(v))for(let w of P.pinIds)_.has(w)||(_.add(w),g.push(w))}return _},o=e[0].pinId,a=e[1].pinId,c=new Set([...s(o),...s(a)]),l=new Map,u=new Map,h=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??v1(_,g),v=u.get(g.chipId);if(!v){v={center:g.center};let P={xPos:0,xNeg:0,yPos:0,yNeg:0};for(let w of g.pins){let T=w._facingDirection??v1(w,g);T==="x+"&&P.xPos++,T==="x-"&&P.xNeg++,T==="y+"&&P.yPos++,T==="y-"&&P.yNeg++}v.counts=P,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))&&h.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},dA=n=>{let{inputProblem:e,chipMap:t,pinIdMap:i,p1:r,p2:s}=n,o=lAt({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},h=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 h&&d},Rs=(n,e=1)=>`hsl(${n.split("").reduce((i,r)=>i*31+r.charCodeAt(0),0)%360}, 100%, 50%, ${e})`,cs=(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:Rs(o.chipId,i)});for(let a of o.pins)r.points.push({label:`${a.pinId}
246
- ${a._facingDirection??v1(a,o)}`,x:a.x,y:a.y,color:Rs(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:Rs(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],h=a[l];r.lines.push({points:[{x:u.x,y:u.y},{x:h.x,y:h.y}],strokeColor:Rs(o.netId,t),strokeDash:"4 2"})}}return r},uAt=class extends Pr{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}=bA(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 h=new Map(Object.entries(this.pinMap));if(dA({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:h,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=cAt(i.map(o=>this.pinMap[o]).filter(Boolean),{maxDistance:this.maxMspPairDistance,forbidEdge:(o,a)=>dA({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(dA({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:r,p1:c,p2:l}))continue;let u=this.globalConnMap.getNetConnectedToId(o),h=this.userNetIdByPinId[o]??this.userNetIdByPinId[a];this.mspConnectionPairs.push({mspPairId:`${o}-${a}`,dcConnNetId:e,globalConnNetId:u,userNetId:h,pins:[c,l]})}}visualize(){let e=cs(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:Rs(t.mspPairId,.75)});return e}};function vA(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 pAt=n=>{let e=vA(n);return{chipId:n.chipId,...e}},Lw=n=>n.chips.map(pAt),SA=1e-9,$a=(n,e,t=SA)=>Math.abs(n.x-e.x)<t,ul=(n,e,t=SA)=>Math.abs(n.y-e.y)<t,w1=(n,e,t,i=SA)=>{let r=$a(n,e,i),s=ul(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}},hAt=(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)&&w1(r,s,a))return{segIndex:i,rect:a}}return null},dAt=(n,e)=>{for(let t=0;t<n.length-1;t++)for(let i of e)if(w1(n[t],n[t+1],i))return!0;return!1},RQ=1e-9,fAt=(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)}),wQ=(n,e,t,i=RQ)=>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],mAt=(n,e,t,i,r,s=RQ)=>{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,h=[];return l!==void 0&&h.push((l+e.minX)/2),u!==void 0&&h.push((e.maxX+u)/2),h}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,h=[];return l!==void 0&&h.push((l+e.minY)/2),u!==void 0&&h.push((e.maxY+u)/2),h}},_At=1e-9,yAt=(n,e,t,i,r=_At)=>{if(e<0||e>=n.length-1)return null;let s=n[e],o=n[e+1],a=$a(s,o,r),c=ul(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],h=l[e];if(Math.abs(u.x-h.x)+Math.abs(u.y-h.y)<r)return null}if(e+2<=l.length-1){let u=l[e+1],h=l[e+2];if(Math.abs(u.x-h.x)+Math.abs(u.y-h.y)<r)return null}for(let u=0;u<l.length-1;u++){let h=l[u],d=l[u+1];if(!ul(h,d,r)&&!$a(h,d,r))return null}return l},PQ=(n,e=6)=>n.map(i=>`${i.x.toFixed(e)},${i.y.toFixed(e)}`).join("|"),OQ=class extends Pr{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=v1(r,s)}this.obstacles=Lw(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=fAt({x:t.x,y:t.y},{x:i.x,y:i.y}),this.queue.push({path:this.baseElbow,collisionChipIds:new Set}),this.visited.add(PQ(this.baseElbow))}getConstructorParams(){return{chipMap:this.chipMap,pins:this.pins,inputProblem:this.inputProblem}}axisOfSegment(e,t){return $a(e,t)?"x":ul(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=hAt(t,this.obstacles);if(!o){let v=t[0],P=t[t.length-1],w=1e-9,T=(k,C)=>Math.abs(k.x-C.x)<w&&Math.abs(k.y-C.y)<w;T(v,{x:r.x,y:r.y})&&T(P,{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 h=t[a],d=t[a+1],_=this.axisOfSegment(h,d);if(!_)return;let g=[];if(i.size===0){let v=wQ(_,{x:r.x,y:r.y},c),P=wQ(_,{x:s.x,y:s.y},c),w=[...v,...P],T=[...new Set(w)];g.push(...T)}else{let v=mAt(_,c,this.rectById,i,this.aabb);g.push(...v)}let x=[];for(let v of g){let P=yAt(t,a,_,v);if(!P)continue;let w=PQ(P);if(this.visited.has(w))continue;this.visited.add(w);let T=new Set(i);T.add(c.chipId);let k=this.pathLength(P);x.push({path:P,collisionRectIds:T,len:k})}x.sort((v,P)=>v.len-P.len);for(let v of x)this.queue.push({path:v.path,collisionChipIds:v.collisionRectIds})}visualize(){let e=cs(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}},gAt=class extends Pr{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 OQ({inputProblem:this.inputProblem,pins:t,chipMap:this.chipMap})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=cs(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}},xAt=({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})}},bAt=class extends Pr{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 h=this.traceNetIslands[s.connNetId][l],d=this.correctedTraceMap[h.mspPairId]??h,_=d.tracePath.map(w=>({...w})),g=Array.from(u).sort((w,T)=>w-T),x=Array.from(u).sort((w,T)=>w-T).reverse(),v=this.SHIFT_DISTANCE;for(let w of x)if(!(w<0||w>=_.length-1))if(w===0||w===_.length-2)xAt({pts:_,segmentIndex:w,offset:a,JOG_SIZE:v,EPS:1e-6});else{let T=_[w],k=_[w+1],C=Math.abs(T.x-k.x)<1e-6,M=Math.abs(T.y-k.y)<1e-6;if(!C&&!M)continue;C?(T.x+=a,k.x+=a):(T.y+=a,k.y+=a)}let P=[];for(let w of _)(P.length===0||!r(P[P.length-1],w))&&P.push(w);this.correctedTraceMap[h.mspPairId]={...d,tracePath:P}}}),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}},vAt=class extends Pr{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=[],h=new Set,d=new Set,_=(g,x,v,P)=>{let w=Math.min(g,x),T=Math.max(g,x),k=Math.min(v,P),C=Math.max(v,P);return Math.min(T,C)-Math.max(w,k)>.002};for(let g=0;g<a.length;g++){let v=a[g].tracePath;for(let P=0;P<v.length-1;P++){let w=v[P],T=v[P+1],k=Math.abs(w.x-T.x)<.002,C=Math.abs(w.y-T.y)<.002;if(!(!k&&!C))for(let M=0;M<c.length;M++){let E=c[M].tracePath;for(let A=0;A<E.length-1;A++){let R=E[A],B=E[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(w.x-R.x)<.002&&_(w.y,T.y,R.y,B.y)){let V=`${g}:${P}`,H=`${M}:${A}`;h.has(V)||(l.push({solvedTracePathIndex:g,traceSegmentIndex:P}),h.add(V)),d.has(H)||(u.push({solvedTracePathIndex:M,traceSegmentIndex:A}),d.add(H))}}else if(C&&U&&Math.abs(w.y-R.y)<.002&&_(w.x,T.x,R.x,B.x)){let V=`${g}:${P}`,H=`${M}:${A}`;h.has(V)||(l.push({solvedTracePathIndex:g,traceSegmentIndex:P}),h.add(V)),d.has(H)||(u.push({solvedTracePathIndex:M,traceSegmentIndex:A}),d.add(H))}}}}}}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,h=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 P=0;h&&P++,d&&P++;let w=v<P?g:x;return i.splice(r+1,0,w),!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 bAt({overlappingTraceSegments:t,traceNetIslands:this.traceNetIslands})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=cs(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}},SAt=class{constructor(n){f(this,"chips");f(this,"spatialIndex");f(this,"spatialIndexIdToChip");this.chips=n.map(e=>({...e,bounds:vA(e),spatialIndexId:null})),this.spatialIndexIdToChip=new Map,this.spatialIndex=new b1(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}},wAt=.45,kQ=.2;function gA(n){let{orientation:e,netLabelWidth:t}=n,i=typeof t=="number"?t:wAt;return e==="y+"||e==="y-"?{width:kQ,height:i}:{width:i,height:kQ}}function xA(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 Td(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 LQ(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 FQ(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)&&LQ(o[a],o[a+1],n))return{hasIntersection:!0,mspPairId:r,segIndex:a}}return{hasIntersection:!1}}function TQ(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 zQ(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 h=l==null?[]:a.filter(d=>d.pins[0].chipId===l||d.pins[1].chipId===l);return h.length>0?h.reduce((d,_)=>TQ(d)>=TQ(_)?d:_):r}function PAt(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 kAt(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 M of e.chips){let I=M.pins.find(E=>E.pinId===a);if(I){c={x:I.x,y:I.y},l=I._facingDirection||v1(I,M);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-"],h={x:c.x,y:c.y},d=M=>M==="x+"?{x:1,y:0}:M==="x-"?{x:-1,y:0}:M==="y+"?{x:0,y:1}:{x:0,y:-1},_=[];for(let M of u){let{width:I,height:E}=gA({orientation:M,netLabelWidth:o}),A=xA(h,M,I,E),R=d(M),B=.001,j={x:A.x+R.x*B,y:A.y+R.y*B},U=Td(j,I,E);if(i.getChipsInBounds(U).length>0){_.push({center:j,width:I,height:E,bounds:U,anchor:h,orientation:M,status:"chip-collision",hostSegIndex:-1});continue}if(FQ(U,t,"",-1).hasIntersection){_.push({center:j,width:I,height:E,bounds:U,anchor:h,orientation:M,status:"trace-collision",hostSegIndex:-1});continue}return _.push({center:j,width:I,height:E,bounds:U,anchor:h,orientation:M,status:"ok",hostSegIndex:-1}),{placement:{globalConnNetId:r.globalConnNetId,dcConnNetId:void 0,netId:r.netId,mspConnectionPairIds:[],pinIds:[a],orientation:M,anchorPoint:h,width:I,height:E,center:j},testedCandidates:_}}let g=l,{width:x,height:v}=gA({orientation:g,netLabelWidth:o}),P=xA(h,g,x,v),w=d(g),T=.001,k={x:P.x+w.x*T,y:P.y+w.y*T};return{placement:{globalConnNetId:r.globalConnNetId,dcConnNetId:void 0,netId:r.netId,mspConnectionPairIds:[],pinIds:[a],orientation:g,anchorPoint:h,width:x,height:v,center:k},testedCandidates:_}}function TAt(n){let e=cs(n.inputProblem),t=n.overlappingSameNetTraceGroup.globalConnNetId,i=zQ({inputProblem:n.inputProblem,inputTraceMap:n.inputTraceMap,globalConnNetId:t,fallbackTrace:n.overlappingSameNetTraceGroup.overlappingTraces}),r=Rs(t,.9),s=Rs(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 MQ=class extends Pr{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 SAt(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=kAt({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=zQ({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,h=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],P=Math.abs(x.y-v.y)<h,w=Math.abs(x.x-v.x)<h;if(!P&&!w)continue;let T=P?["y+","y-"]:["x+","x-"],k=o.filter(M=>T.includes(M));if(k.length===0)continue;let C=PAt(x,v);for(let M of C)for(let I of k){let{width:E,height:A}=gA({orientation:I,netLabelWidth:this.netLabelWidth}),R=xA(M,I,E,A),B=I==="x+"?{x:1,y:0}:I==="x-"?{x:-1,y:0}:I==="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},V=Td(U,E,A);if(this.chipObstacleSpatialIndex.getChipsInBounds(V).length>0){this.testedCandidates.push({center:U,width:E,height:A,bounds:V,anchor:M,orientation:I,status:"chip-collision",hostSegIndex:g});continue}if(FQ(V,this.inputTraceMap,d.mspPairId,g).hasIntersection){this.testedCandidates.push({center:U,width:E,height:A,bounds:V,anchor:M,orientation:I,status:"trace-collision",hostSegIndex:g});continue}if(this.testedCandidates.push({center:U,width:E,height:A,bounds:V,anchor:M,orientation:I,status:"ok",hostSegIndex:g}),a){let tt=c(I,M);tt>u+1e-9&&(u=tt,l={anchor:M,orientation:I,width:E,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:I,anchorPoint:M,width:E,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 TAt(this)}},EQ=class extends Pr{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}=bA(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(_)),h={};for(let _ of u)h[_]=new Set;for(let _ of e[c]??[]){let g=_.pins[0].pinId,x=_.pins[1].pinId;h[g]&&h[x]&&(h[g].add(x),h[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 P=g.pop();x.add(P);for(let w of h[P]??[])d.has(w)||(d.add(w),g.push(w))}let v=(e[c]??[]).filter(P=>x.has(P.pins[0].pinId)&&x.has(P.pins[1].pinId));if(v.length>0){let P=I=>{let E=0,A=I.tracePath;for(let R=0;R<A.length-1;R++)E+=Math.abs(A[R+1].x-A[R].x)+Math.abs(A[R+1].y-A[R].y);return E},w=v[0],T=P(w);for(let I=1;I<v.length;I++){let E=P(v[I]);E>T&&(w=v[I],T=E)}let k=v.find(I=>I.userNetId!=null)?.userNetId;if(!k){for(let I of x)if(r[I]){k=r[I];break}}let C=Array.from(new Set(v.flatMap(I=>I.mspConnectionPairIds??[I.mspPairId]))),M={globalConnNetId:c,netId:k,overlappingTraces:w,mspConnectionPairIds:C};s.push(M)}else for(let P of x){let w=r[P];w&&s.push({globalConnNetId:c,netId:w,portOnlyPinId:P})}}}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 MQ({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 MQ({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=cs(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:Rs(t.globalConnNetId,.35),strokeColor:Rs(t.globalConnNetId,.9)}),e.points.push({x:t.anchorPoint.x,y:t.anchorPoint.y,color:Rs(t.globalConnNetId,.9)});return e}},MAt=class extends Pr{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 P=Td(v.center,v.width,v.height);a=Math.min(a,P.minX),c=Math.min(c,P.minY),l=Math.max(l,P.maxX),u=Math.max(u,P.maxY)}let h=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:h,height:d,center:{x:a+h/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=cs(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=Rs(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=Td(c.center,c.width,c.height),u={x:l.minX,y:l.minY},h={x:l.maxX,y:l.minY},d={x:l.maxX,y:l.maxY},_={x:l.minX,y:l.maxY};e.lines.push({points:[u,h,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}},EAt=(n,e)=>{let t=[];for(let i of n)for(let r of e){let s=Td(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(LQ(a,c,s)){if(i.globalConnNetId===r.globalConnNetId)break;t.push({trace:i,label:r});break}}}return t},CAt=(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}},IAt=({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 h=r+s*r,d=i.minX-h,_=i.maxX+h,g=i.maxY+h,x=i.minY-h;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])},NAt=({initialTrace:n,label:e,labelBounds:t,paddingBuffer:i,detourCount:r})=>{let s=-1;for(let h=0;h<n.tracePath.length-1;h++)if(w1(n.tracePath[h],n.tracePath[h+1],t)){s=h;break}if(s===-1)return[];let o=n.tracePath[s],a=n.tracePath[s+1];if(!o||!a)return[];let c=[],l=Td(e.center,e.width,e.height),u=i+r*i;if($a(o,a)){let h=[l.maxX+u,l.minX-u];for(let d of h)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 h=[l.maxY+u,l.minY-u];for(let d of h)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(h=>[...n.tracePath.slice(0,s+1),...h,...n.tracePath.slice(s+1)])},S1=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];$a(r,s)&&$a(s,o)||ul(r,s)&&ul(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];$a(r,s)&&$a(s,o)||ul(r,s)&&ul(s,o)||t.push(s)}return t.push(e[e.length-1]),t},AAt=({trace:n,label:e,paddingBuffer:t,detourCount:i})=>{let r={...n,tracePath:S1(n.tracePath)};if(n.globalConnNetId===e.globalConnNetId)return[r.tracePath];let s=t,o=Td(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=NAt({initialTrace:r,label:e,labelBounds:a,paddingBuffer:t,detourCount:i}),{firstInsideIndex:l,lastInsideIndex:u}=CAt(r.tracePath,a),h=IAt({initialTrace:r,firstInsideIndex:l,lastInsideIndex:u,labelBounds:a,paddingBuffer:t,detourCount:i});return[...c,...h]},RAt=class extends Pr{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=AAt({...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=Lw(this.problem)}_step(){if(this.queuedCandidatePaths.length===0){this.failed=!0;return}let e=this.queuedCandidatePaths.shift(),t=S1(e);dAt(t,this.obstacles)||(this.solvedTracePath=t,this.solved=!0)}visualize(){let e=cs(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}},OAt=class extends Pr{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=EAt(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 RAt({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=cs(this.inputProblem);e.lines||(e.lines=[]);for(let t of this.allTraces)e.lines.push({points:t.tracePath,strokeColor:"purple"});return e}},LAt=class extends Pr{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 MAt({netLabelPlacements:this.netLabelPlacements,inputProblem:this.inputProblem,traces:this.traces}),this.activeSubSolver=this.labelMergingSolver;break;case 1:this.overlapAvoidanceSolver=new OAt({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=cs(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=Rs(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}},FAt=n=>{for(let e of n.chips){let t=vA(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}}},zAt=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 $At(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(Pi(i,r,a,c))return!0}}return!1}var DAt=3,jAt=(n,e)=>Math.sqrt(Math.pow(n.x-e.x,2)+Math.pow(n.y-e.y,2)),BAt=class extends Pr{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}=bA(t);this.netConnMap=o;let a=new Map;for(let u of t.chips){this.chipMap[u.chipId]=u;for(let h of u.pins)a.set(h.pinId,{...h,chipId:u.chipId})}let c=[],l=new Set;for(let u of Object.keys(o.netMap)){let h=o.getIdsConnectedToNet(u);if(h.length<2)continue;let d=h.filter(_=>!s.has(_));for(let _ of d){let g=a.get(_);if(!g)continue;let x=h.filter(v=>v!==_).flatMap(v=>{let P=a.get(v);return P?[{pin:P,distance:jAt(g,P)}]:[]}).sort((v,P)=>v.distance-P.distance).slice(0,DAt);for(let v of x){let P=[g,v.pin],w=P.map(T=>T.pinId).sort().join("--");l.has(w)||(c.push(P),l.add(w))}}}this.queuedCandidatePairs=c}getConstructorParams(){return this.params}_step(){if(this.subSolver?.solved){let e=this.subSolver.solvedTracePath;if(e&&this.currentCandidatePair&&!$At(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 OQ({inputProblem:this.params.inputProblem,pins:this.currentCandidatePair,chipMap:this.chipMap});return}}this.solved=!0}visualize(){if(this.subSolver)return this.subSolver.visualize();let e=cs(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}}},fA=(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(vS(i,r,o)<=0)return!0}}return!1},mA=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},CQ=(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},_A=(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(w1(i,r,s))return!0}return!1},YAt=(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 h=n[r-1],d=h.x===s.x,_=Math.sign(d?s.y-h.y:s.x-h.x);if(c&&d&&u!==_||!c&&!d&&u!==_){i=!1;break}}t=r+2}return i&&t-e>=3?t:-1},A_=(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},XAt=({path:n,obstacles:e,labelBounds:t,originalPath:i})=>{if(n.length<=2)return n;let r=[...n],s=mA(r),o=!0;for(;o;){o=!1;for(let c=0;c<r.length-3;c++){let l=YAt(r,c);if(l>0){if(A_(r[c],r[c+1],i)||A_(r[l-1],r[l],i))continue;let u=r[c],h=r[l],d=CQ(u,h);for(let _ of d){let g=[...r.slice(0,c+1),..._.slice(1,-1),...r.slice(l)],x=fA(_,e),v=_A(_,t);if(!x&&!v){let P=mA(g);r=g,s=P,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 h=c+u+1;if(h>=r.length||A_(r[c],r[c+1],i)||A_(r[h-1],r[h],i))continue;let d=r[c],_=r[h],g=CQ(d,_);for(let x of g){let v=[...r.slice(0,c+1),...x.slice(1,-1),...r.slice(h)],P=x,w=fA(P,e),T=_A(P,t);if(!w&&!T){let k=mA(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],h=r[c+2];if(A_(l,u,i)||A_(u,h,i))continue;let d=l.x===u.x&&u.x===h.x,_=l.y===u.y&&u.y===h.y;if(d||_){let g=[...r.slice(0,c+1),...r.slice(c+2)],x=fA([l,h],e),v=_A([l,h],t);if(!x&&!v){r=g,o=!0;break}}}}return S1(r)},UAt=({targetMspConnectionPairId:n,traces:e,inputProblem:t,allLabelPlacements:i,mergedLabelNetIdMap:r,paddingBuffer:s})=>{let o=e.find(w=>w.mspPairId===n);if(!o)throw new Error(`Target trace ${n} not found`);let a=e.filter(w=>w.mspPairId!==n),c=.01,l=a.flatMap((w,T)=>w.tracePath.slice(0,-1).map((k,C)=>{let M=w.tracePath[C+1];return{chipId:`trace-obstacle-${T}-${C}`,minX:Math.min(k.x,M.x)-c/2,minY:Math.min(k.y,M.y)-c/2,maxX:Math.max(k.x,M.x)+c/2,maxY:Math.max(k.y,M.y)+c/2}})),u=Lw(t),h=.01,_=[...u.map(w=>({...w,minX:w.minX-h,minY:w.minY-h,maxX:w.maxX+h,maxY:w.maxY+h})),...l],g=o.tracePath,v=i.filter(w=>{let T=r[w.globalConnNetId];return T?!T.has(o.globalConnNetId):w.globalConnNetId!==o.globalConnNetId}).map(w=>({minX:w.center.x-w.width/2-s,maxX:w.center.x+w.width/2+s,minY:w.center.y-w.height/2-s,maxY:w.center.y+w.height/2+s})),P=XAt({path:g,obstacles:_,labelBounds:v,originalPath:g});return{...o,tracePath:P}},VAt=({targetMspConnectionPairId:n,traces:e,inputProblem:t,allLabelPlacements:i,mergedLabelNetIdMap:r,paddingBuffer:s})=>{let o=e.find(w=>w.mspPairId===n);if(!o)throw new Error(`Target trace ${n} not found`);let a=1e-5,c=e.filter(w=>w.mspPairId!==n),l=.01,u=c.flatMap((w,T)=>w.tracePath.slice(0,-1).map((k,C)=>{let M=w.tracePath[C+1];return{chipId:`trace-obstacle-${T}-${C}`,minX:Math.min(k.x,M.x)-l/2,minY:Math.min(k.y,M.y)-l/2,maxX:Math.max(k.x,M.x)+l/2,maxY:Math.max(k.y,M.y)+l/2}})),d=[...Lw(t).map(w=>({...w,minX:w.minX+a,maxX:w.maxX-a,minY:w.minY+a,maxY:w.maxY-a})),...u],_=(w,T,k)=>{for(let C of k)if(w1(w,T,C))return!0;return!1},x=i.filter(w=>{let T=r[w.globalConnNetId];return T?!T.has(o.globalConnNetId):w.globalConnNetId!==o.globalConnNetId}).map(w=>({minX:w.center.x-w.width/2+a,maxX:w.center.x+w.width/2-a,minY:w.center.y-w.height/2+a,maxY:w.center.y+w.height/2-a})),v=[...o.tracePath];if(v.length<4)return{...o};if(v.length===4){let[w,T,k,C]=v,M,I;if(w.y===T.y&&T.x===k.x&&k.y===C.y){let R=(w.x+C.x)/2;M={x:R,y:T.y},I={x:R,y:k.y}}else{let R=(w.y+C.y)/2;M={x:T.x,y:R},I={x:k.x,y:R}}return _(w,M,d)||_(M,I,d)||_(I,C,d)||_(w,M,x)||_(M,I,x)||_(I,C,x)||(v[1]=M,v[2]=I),{...o,tracePath:S1(v)}}for(let w=1;w<v.length-4;w++){let T=v[w],k=v[w+1],C=v[w+2],M=v[w+3],I=T.y===k.y&&k.x===C.x&&C.y===M.y,E=T.x===k.x&&k.y===C.y&&C.x===M.x,A=T.y===k.y&&k.y===C.y&&C.y===M.y,R=T.x===k.x&&k.x===C.x&&C.x===M.x,B=A||R,j=!1;if(I?j=Math.sign(k.x-T.x)===Math.sign(M.x-C.x):E&&(j=Math.sign(k.y-T.y)===Math.sign(M.y-C.y)),!((I||E)&&!B&&j))continue;let V,H,et=Math.abs(I?T.x-k.x:T.y-k.y),tt=Math.abs(I?C.x-M.x:C.y-M.y);if(Math.abs(et-tt)<.001)continue;if(I){let G=(T.x+M.x)/2;V={x:G,y:k.y},H={x:G,y:C.y}}else{let G=(T.y+M.y)/2;V={x:k.x,y:G},H={x:C.x,y:G}}_(T,V,d)||_(V,H,d)||_(H,M,d)||_(T,V,x)||_(V,H,x)||_(H,M,x)||(v[w+1]=V,v[w+2]=H,w=0)}let P=S1(v);return{...o,tracePath:P}},GAt=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},HAt=(n,e)=>{let t=[];for(let i of n)i.mspPairId!==e&&t.push({points:i.tracePath});return t},IQ=(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=od(n,e,a,c);l&&i.push(l)}}return i},za=1e-6,cl=(n,e,t=za)=>Math.abs(n.x-e.x)<t,WAt=({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:h}=e,d,_=i,g=r;if(Math.abs(o.x-c)<za&&Math.abs(o.y-(l+h))<za)d={x:c+u+t,y:l-t},cl(s,o)?_={x:i.x,y:i.y-t}:_={x:i.x+t,y:i.y},cl(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))<za&&Math.abs(o.y-(l+h))<za)d={x:c-t,y:l-t},cl(s,o)?_={x:i.x,y:i.y-t}:_={x:i.x-t,y:i.y},cl(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)<za&&Math.abs(o.y-l)<za)d={x:c+u+t,y:l+h+t},cl(s,o)?_={x:i.x,y:i.y+t}:_={x:i.x+t,y:i.y},cl(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))<za&&Math.abs(o.y-l)<za)d={x:c-t,y:l+h+t},cl(s,o)?_={x:i.x,y:i.y+t}:_={x:i.x-t,y:i.y},cl(o,a)?g={x:r.x,y:r.y+t}:g={x:r.x-t,y:r.y};else return[];return[[_,d,g]]},qAt=(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=od(r,s,c,l);if(u)return{isColliding:!0,collidingTraceId:o.mspPairId,collisionPoint:u}}}return{isColliding:!1}},ZAt=(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},Ow=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},NQ=(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},AQ=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},KAt=(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},yA=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},JAt=n=>{let e={circles:[]};return n?.isColliding&&n.collisionPoint&&e.circles.push({center:n.collisionPoint,radius:.01,fill:"red"}),e},QAt=class extends Pr{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=GAt(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=HAt(this.input.allTraces,this.currentLShape.traceId),t=IQ(this.currentLShape.p1,this.currentLShape.p2,e),i=IQ(this.currentLShape.p2,this.currentLShape.p3,e);if(this.intersectionPoints=[...t,...i],t.length===0||i.length===0){this.lShapeProcessingStep="idle";return}this.rectangleCandidates=ZAt(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=WAt({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=qAt(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 Ow(this.lShapesToProcess);case"intersection_points":return yA([this.currentLShape?Ow(this.currentLShape):void 0,NQ(this.intersectionPoints)]);case"tight_rectangle":return yA([this.currentLShape?Ow(this.currentLShape):void 0,NQ(this.intersectionPoints),this.tightRectangle?AQ(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]),yA([e,this.currentLShape?Ow(this.currentLShape):void 0,this.tightRectangle?AQ(this.tightRectangle):void 0,t?KAt([t],this.bestRouteFound?"green":"blue",this.intersectionPoints):void 0,this.lastCollision?JAt(this.lastCollision):void 0])}default:return{}}}},t9t=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},e9t=class extends Pr{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 QAt({...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(t9t(i.tracePath))return;let r=Array.from(this.tracesMap.values()),s;e==="minimizing_turns"?s=UAt({...this.input,targetMspConnectionPairId:t,traces:r}):s=VAt({...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=cs(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 ll(n,e,t,i={}){return{solverName:n,solverClass:e,getConstructorParams:t,onSolved:i.onSolved,shouldSkip:i.shouldSkip}}var $Q=class extends Pr{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",[ll("mspConnectionPairSolver",uAt,()=>[{inputProblem:this.inputProblem}],{onSolved:e=>{}}),ll("schematicTraceLinesSolver",gAt,()=>[{mspConnectionPairs:this.mspConnectionPairSolver.mspConnectionPairs,dcConnMap:this.mspConnectionPairSolver.dcConnMap,globalConnMap:this.mspConnectionPairSolver.globalConnMap,inputProblem:this.inputProblem,chipMap:this.mspConnectionPairSolver.chipMap}]),ll("longDistancePairSolver",BAt,e=>[{inputProblem:e.inputProblem,primaryMspConnectionPairs:e.mspConnectionPairSolver.mspConnectionPairs,alreadySolvedTraces:e.schematicTraceLinesSolver.solvedTracePaths}],{onSolved:e=>{}}),ll("traceOverlapShiftSolver",vAt,()=>[{inputProblem:this.inputProblem,inputTracePaths:this.longDistancePairSolver?.getOutput().allTracesMerged,globalConnMap:this.mspConnectionPairSolver.globalConnMap}],{onSolved:e=>{}}),ll("netLabelPlacementSolver",EQ,()=>[{inputProblem:this.inputProblem,inputTraceMap:this.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(this.longDistancePairSolver.getOutput().allTracesMerged.map(e=>[e.mspPairId,e]))}],{onSolved:e=>{}}),ll("traceLabelOverlapAvoidanceSolver",LAt,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}]}),ll("traceCleanupSolver",e9t,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}]}),ll("netLabelPlacementSolver",EQ,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 zAt(t),FAt(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=[cs(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 bnt=Gt(En(),1);var vnt=Gt(En(),1);var Snt=Gt(En(),1);er();Ae();var n9t=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(`
246
+ ${a._facingDirection??v1(a,o)}`,x:a.x,y:a.y,color:Rs(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:Rs(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],h=a[l];r.lines.push({points:[{x:u.x,y:u.y},{x:h.x,y:h.y}],strokeColor:Rs(o.netId,t),strokeDash:"4 2"})}}return r},uAt=class extends Pr{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}=bA(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 h=new Map(Object.entries(this.pinMap));if(dA({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:h,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=cAt(i.map(o=>this.pinMap[o]).filter(Boolean),{maxDistance:this.maxMspPairDistance,forbidEdge:(o,a)=>dA({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(dA({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:r,p1:c,p2:l}))continue;let u=this.globalConnMap.getNetConnectedToId(o),h=this.userNetIdByPinId[o]??this.userNetIdByPinId[a];this.mspConnectionPairs.push({mspPairId:`${o}-${a}`,dcConnNetId:e,globalConnNetId:u,userNetId:h,pins:[c,l]})}}visualize(){let e=cs(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:Rs(t.mspPairId,.75)});return e}};function vA(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 pAt=n=>{let e=vA(n);return{chipId:n.chipId,...e}},Lw=n=>n.chips.map(pAt),SA=1e-9,$a=(n,e,t=SA)=>Math.abs(n.x-e.x)<t,ul=(n,e,t=SA)=>Math.abs(n.y-e.y)<t,w1=(n,e,t,i=SA)=>{let r=$a(n,e,i),s=ul(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}},hAt=(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)&&w1(r,s,a))return{segIndex:i,rect:a}}return null},dAt=(n,e)=>{for(let t=0;t<n.length-1;t++)for(let i of e)if(w1(n[t],n[t+1],i))return!0;return!1},RQ=1e-9,fAt=(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)}),wQ=(n,e,t,i=RQ)=>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],mAt=(n,e,t,i,r,s=RQ)=>{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,h=[];return l!==void 0&&h.push((l+e.minX)/2),u!==void 0&&h.push((e.maxX+u)/2),h}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,h=[];return l!==void 0&&h.push((l+e.minY)/2),u!==void 0&&h.push((e.maxY+u)/2),h}},_At=1e-9,yAt=(n,e,t,i,r=_At)=>{if(e<0||e>=n.length-1)return null;let s=n[e],o=n[e+1],a=$a(s,o,r),c=ul(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],h=l[e];if(Math.abs(u.x-h.x)+Math.abs(u.y-h.y)<r)return null}if(e+2<=l.length-1){let u=l[e+1],h=l[e+2];if(Math.abs(u.x-h.x)+Math.abs(u.y-h.y)<r)return null}for(let u=0;u<l.length-1;u++){let h=l[u],d=l[u+1];if(!ul(h,d,r)&&!$a(h,d,r))return null}return l},PQ=(n,e=6)=>n.map(i=>`${i.x.toFixed(e)},${i.y.toFixed(e)}`).join("|"),OQ=class extends Pr{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=v1(r,s)}this.obstacles=Lw(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=fAt({x:t.x,y:t.y},{x:i.x,y:i.y}),this.queue.push({path:this.baseElbow,collisionChipIds:new Set}),this.visited.add(PQ(this.baseElbow))}getConstructorParams(){return{chipMap:this.chipMap,pins:this.pins,inputProblem:this.inputProblem}}axisOfSegment(e,t){return $a(e,t)?"x":ul(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=hAt(t,this.obstacles);if(!o){let v=t[0],P=t[t.length-1],w=1e-9,T=(k,C)=>Math.abs(k.x-C.x)<w&&Math.abs(k.y-C.y)<w;T(v,{x:r.x,y:r.y})&&T(P,{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 h=t[a],d=t[a+1],_=this.axisOfSegment(h,d);if(!_)return;let g=[];if(i.size===0){let v=wQ(_,{x:r.x,y:r.y},c),P=wQ(_,{x:s.x,y:s.y},c),w=[...v,...P],T=[...new Set(w)];g.push(...T)}else{let v=mAt(_,c,this.rectById,i,this.aabb);g.push(...v)}let x=[];for(let v of g){let P=yAt(t,a,_,v);if(!P)continue;let w=PQ(P);if(this.visited.has(w))continue;this.visited.add(w);let T=new Set(i);T.add(c.chipId);let k=this.pathLength(P);x.push({path:P,collisionRectIds:T,len:k})}x.sort((v,P)=>v.len-P.len);for(let v of x)this.queue.push({path:v.path,collisionChipIds:v.collisionRectIds})}visualize(){let e=cs(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}},gAt=class extends Pr{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 OQ({inputProblem:this.inputProblem,pins:t,chipMap:this.chipMap})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=cs(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}},xAt=({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})}},bAt=class extends Pr{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 h=this.traceNetIslands[s.connNetId][l],d=this.correctedTraceMap[h.mspPairId]??h,_=d.tracePath.map(w=>({...w})),g=Array.from(u).sort((w,T)=>w-T),x=Array.from(u).sort((w,T)=>w-T).reverse(),v=this.SHIFT_DISTANCE;for(let w of x)if(!(w<0||w>=_.length-1))if(w===0||w===_.length-2)xAt({pts:_,segmentIndex:w,offset:a,JOG_SIZE:v,EPS:1e-6});else{let T=_[w],k=_[w+1],C=Math.abs(T.x-k.x)<1e-6,M=Math.abs(T.y-k.y)<1e-6;if(!C&&!M)continue;C?(T.x+=a,k.x+=a):(T.y+=a,k.y+=a)}let P=[];for(let w of _)(P.length===0||!r(P[P.length-1],w))&&P.push(w);this.correctedTraceMap[h.mspPairId]={...d,tracePath:P}}}),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}},vAt=class extends Pr{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=[],h=new Set,d=new Set,_=(g,x,v,P)=>{let w=Math.min(g,x),T=Math.max(g,x),k=Math.min(v,P),C=Math.max(v,P);return Math.min(T,C)-Math.max(w,k)>.002};for(let g=0;g<a.length;g++){let v=a[g].tracePath;for(let P=0;P<v.length-1;P++){let w=v[P],T=v[P+1],k=Math.abs(w.x-T.x)<.002,C=Math.abs(w.y-T.y)<.002;if(!(!k&&!C))for(let M=0;M<c.length;M++){let E=c[M].tracePath;for(let A=0;A<E.length-1;A++){let R=E[A],B=E[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(w.x-R.x)<.002&&_(w.y,T.y,R.y,B.y)){let V=`${g}:${P}`,H=`${M}:${A}`;h.has(V)||(l.push({solvedTracePathIndex:g,traceSegmentIndex:P}),h.add(V)),d.has(H)||(u.push({solvedTracePathIndex:M,traceSegmentIndex:A}),d.add(H))}}else if(C&&U&&Math.abs(w.y-R.y)<.002&&_(w.x,T.x,R.x,B.x)){let V=`${g}:${P}`,H=`${M}:${A}`;h.has(V)||(l.push({solvedTracePathIndex:g,traceSegmentIndex:P}),h.add(V)),d.has(H)||(u.push({solvedTracePathIndex:M,traceSegmentIndex:A}),d.add(H))}}}}}}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,h=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 P=0;h&&P++,d&&P++;let w=v<P?g:x;return i.splice(r+1,0,w),!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 bAt({overlappingTraceSegments:t,traceNetIslands:this.traceNetIslands})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=cs(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}},SAt=class{constructor(n){f(this,"chips");f(this,"spatialIndex");f(this,"spatialIndexIdToChip");this.chips=n.map(e=>({...e,bounds:vA(e),spatialIndexId:null})),this.spatialIndexIdToChip=new Map,this.spatialIndex=new b1(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}},wAt=.45,kQ=.2;function gA(n){let{orientation:e,netLabelWidth:t}=n,i=typeof t=="number"?t:wAt;return e==="y+"||e==="y-"?{width:kQ,height:i}:{width:i,height:kQ}}function xA(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 Td(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 LQ(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 FQ(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)&&LQ(o[a],o[a+1],n))return{hasIntersection:!0,mspPairId:r,segIndex:a}}return{hasIntersection:!1}}function TQ(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 zQ(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 h=l==null?[]:a.filter(d=>d.pins[0].chipId===l||d.pins[1].chipId===l);return h.length>0?h.reduce((d,_)=>TQ(d)>=TQ(_)?d:_):r}function PAt(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 kAt(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 M of e.chips){let I=M.pins.find(E=>E.pinId===a);if(I){c={x:I.x,y:I.y},l=I._facingDirection||v1(I,M);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-"],h={x:c.x,y:c.y},d=M=>M==="x+"?{x:1,y:0}:M==="x-"?{x:-1,y:0}:M==="y+"?{x:0,y:1}:{x:0,y:-1},_=[];for(let M of u){let{width:I,height:E}=gA({orientation:M,netLabelWidth:o}),A=xA(h,M,I,E),R=d(M),B=.001,j={x:A.x+R.x*B,y:A.y+R.y*B},U=Td(j,I,E);if(i.getChipsInBounds(U).length>0){_.push({center:j,width:I,height:E,bounds:U,anchor:h,orientation:M,status:"chip-collision",hostSegIndex:-1});continue}if(FQ(U,t,"",-1).hasIntersection){_.push({center:j,width:I,height:E,bounds:U,anchor:h,orientation:M,status:"trace-collision",hostSegIndex:-1});continue}return _.push({center:j,width:I,height:E,bounds:U,anchor:h,orientation:M,status:"ok",hostSegIndex:-1}),{placement:{globalConnNetId:r.globalConnNetId,dcConnNetId:void 0,netId:r.netId,mspConnectionPairIds:[],pinIds:[a],orientation:M,anchorPoint:h,width:I,height:E,center:j},testedCandidates:_}}let g=l,{width:x,height:v}=gA({orientation:g,netLabelWidth:o}),P=xA(h,g,x,v),w=d(g),T=.001,k={x:P.x+w.x*T,y:P.y+w.y*T};return{placement:{globalConnNetId:r.globalConnNetId,dcConnNetId:void 0,netId:r.netId,mspConnectionPairIds:[],pinIds:[a],orientation:g,anchorPoint:h,width:x,height:v,center:k},testedCandidates:_}}function TAt(n){let e=cs(n.inputProblem),t=n.overlappingSameNetTraceGroup.globalConnNetId,i=zQ({inputProblem:n.inputProblem,inputTraceMap:n.inputTraceMap,globalConnNetId:t,fallbackTrace:n.overlappingSameNetTraceGroup.overlappingTraces}),r=Rs(t,.9),s=Rs(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 MQ=class extends Pr{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 SAt(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=kAt({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=zQ({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,h=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],P=Math.abs(x.y-v.y)<h,w=Math.abs(x.x-v.x)<h;if(!P&&!w)continue;let T=P?["y+","y-"]:["x+","x-"],k=o.filter(M=>T.includes(M));if(k.length===0)continue;let C=PAt(x,v);for(let M of C)for(let I of k){let{width:E,height:A}=gA({orientation:I,netLabelWidth:this.netLabelWidth}),R=xA(M,I,E,A),B=I==="x+"?{x:1,y:0}:I==="x-"?{x:-1,y:0}:I==="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},V=Td(U,E,A);if(this.chipObstacleSpatialIndex.getChipsInBounds(V).length>0){this.testedCandidates.push({center:U,width:E,height:A,bounds:V,anchor:M,orientation:I,status:"chip-collision",hostSegIndex:g});continue}if(FQ(V,this.inputTraceMap,d.mspPairId,g).hasIntersection){this.testedCandidates.push({center:U,width:E,height:A,bounds:V,anchor:M,orientation:I,status:"trace-collision",hostSegIndex:g});continue}if(this.testedCandidates.push({center:U,width:E,height:A,bounds:V,anchor:M,orientation:I,status:"ok",hostSegIndex:g}),a){let tt=c(I,M);tt>u+1e-9&&(u=tt,l={anchor:M,orientation:I,width:E,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:I,anchorPoint:M,width:E,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 TAt(this)}},EQ=class extends Pr{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}=bA(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(_)),h={};for(let _ of u)h[_]=new Set;for(let _ of e[c]??[]){let g=_.pins[0].pinId,x=_.pins[1].pinId;h[g]&&h[x]&&(h[g].add(x),h[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 P=g.pop();x.add(P);for(let w of h[P]??[])d.has(w)||(d.add(w),g.push(w))}let v=(e[c]??[]).filter(P=>x.has(P.pins[0].pinId)&&x.has(P.pins[1].pinId));if(v.length>0){let P=I=>{let E=0,A=I.tracePath;for(let R=0;R<A.length-1;R++)E+=Math.abs(A[R+1].x-A[R].x)+Math.abs(A[R+1].y-A[R].y);return E},w=v[0],T=P(w);for(let I=1;I<v.length;I++){let E=P(v[I]);E>T&&(w=v[I],T=E)}let k=v.find(I=>I.userNetId!=null)?.userNetId;if(!k){for(let I of x)if(r[I]){k=r[I];break}}let C=Array.from(new Set(v.flatMap(I=>I.mspConnectionPairIds??[I.mspPairId]))),M={globalConnNetId:c,netId:k,overlappingTraces:w,mspConnectionPairIds:C};s.push(M)}else for(let P of x){let w=r[P];w&&s.push({globalConnNetId:c,netId:w,portOnlyPinId:P})}}}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 MQ({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 MQ({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=cs(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:Rs(t.globalConnNetId,.35),strokeColor:Rs(t.globalConnNetId,.9)}),e.points.push({x:t.anchorPoint.x,y:t.anchorPoint.y,color:Rs(t.globalConnNetId,.9)});return e}},MAt=class extends Pr{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 P=Td(v.center,v.width,v.height);a=Math.min(a,P.minX),c=Math.min(c,P.minY),l=Math.max(l,P.maxX),u=Math.max(u,P.maxY)}let h=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:h,height:d,center:{x:a+h/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=cs(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=Rs(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=Td(c.center,c.width,c.height),u={x:l.minX,y:l.minY},h={x:l.maxX,y:l.minY},d={x:l.maxX,y:l.maxY},_={x:l.minX,y:l.maxY};e.lines.push({points:[u,h,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}},EAt=(n,e)=>{let t=[];for(let i of n)for(let r of e){let s=Td(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(LQ(a,c,s)){if(i.globalConnNetId===r.globalConnNetId)break;t.push({trace:i,label:r});break}}}return t},CAt=(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}},IAt=({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 h=r+s*r,d=i.minX-h,_=i.maxX+h,g=i.maxY+h,x=i.minY-h;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])},NAt=({initialTrace:n,label:e,labelBounds:t,paddingBuffer:i,detourCount:r})=>{let s=-1;for(let h=0;h<n.tracePath.length-1;h++)if(w1(n.tracePath[h],n.tracePath[h+1],t)){s=h;break}if(s===-1)return[];let o=n.tracePath[s],a=n.tracePath[s+1];if(!o||!a)return[];let c=[],l=Td(e.center,e.width,e.height),u=i+r*i;if($a(o,a)){let h=[l.maxX+u,l.minX-u];for(let d of h)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 h=[l.maxY+u,l.minY-u];for(let d of h)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(h=>[...n.tracePath.slice(0,s+1),...h,...n.tracePath.slice(s+1)])},S1=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];$a(r,s)&&$a(s,o)||ul(r,s)&&ul(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];$a(r,s)&&$a(s,o)||ul(r,s)&&ul(s,o)||t.push(s)}return t.push(e[e.length-1]),t},AAt=({trace:n,label:e,paddingBuffer:t,detourCount:i})=>{let r={...n,tracePath:S1(n.tracePath)};if(n.globalConnNetId===e.globalConnNetId)return[r.tracePath];let s=t,o=Td(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=NAt({initialTrace:r,label:e,labelBounds:a,paddingBuffer:t,detourCount:i}),{firstInsideIndex:l,lastInsideIndex:u}=CAt(r.tracePath,a),h=IAt({initialTrace:r,firstInsideIndex:l,lastInsideIndex:u,labelBounds:a,paddingBuffer:t,detourCount:i});return[...c,...h]},RAt=class extends Pr{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=AAt({...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=Lw(this.problem)}_step(){if(this.queuedCandidatePaths.length===0){this.failed=!0;return}let e=this.queuedCandidatePaths.shift(),t=S1(e);dAt(t,this.obstacles)||(this.solvedTracePath=t,this.solved=!0)}visualize(){let e=cs(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}},OAt=class extends Pr{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=EAt(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 RAt({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=cs(this.inputProblem);e.lines||(e.lines=[]);for(let t of this.allTraces)e.lines.push({points:t.tracePath,strokeColor:"purple"});return e}},LAt=class extends Pr{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 MAt({netLabelPlacements:this.netLabelPlacements,inputProblem:this.inputProblem,traces:this.traces}),this.activeSubSolver=this.labelMergingSolver;break;case 1:this.overlapAvoidanceSolver=new OAt({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=cs(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=Rs(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}},FAt=n=>{for(let e of n.chips){let t=vA(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}}},zAt=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 $At(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(ki(i,r,a,c))return!0}}return!1}var DAt=3,jAt=(n,e)=>Math.sqrt(Math.pow(n.x-e.x,2)+Math.pow(n.y-e.y,2)),BAt=class extends Pr{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}=bA(t);this.netConnMap=o;let a=new Map;for(let u of t.chips){this.chipMap[u.chipId]=u;for(let h of u.pins)a.set(h.pinId,{...h,chipId:u.chipId})}let c=[],l=new Set;for(let u of Object.keys(o.netMap)){let h=o.getIdsConnectedToNet(u);if(h.length<2)continue;let d=h.filter(_=>!s.has(_));for(let _ of d){let g=a.get(_);if(!g)continue;let x=h.filter(v=>v!==_).flatMap(v=>{let P=a.get(v);return P?[{pin:P,distance:jAt(g,P)}]:[]}).sort((v,P)=>v.distance-P.distance).slice(0,DAt);for(let v of x){let P=[g,v.pin],w=P.map(T=>T.pinId).sort().join("--");l.has(w)||(c.push(P),l.add(w))}}}this.queuedCandidatePairs=c}getConstructorParams(){return this.params}_step(){if(this.subSolver?.solved){let e=this.subSolver.solvedTracePath;if(e&&this.currentCandidatePair&&!$At(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 OQ({inputProblem:this.params.inputProblem,pins:this.currentCandidatePair,chipMap:this.chipMap});return}}this.solved=!0}visualize(){if(this.subSolver)return this.subSolver.visualize();let e=cs(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}}},fA=(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(vS(i,r,o)<=0)return!0}}return!1},mA=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},CQ=(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},_A=(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(w1(i,r,s))return!0}return!1},YAt=(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 h=n[r-1],d=h.x===s.x,_=Math.sign(d?s.y-h.y:s.x-h.x);if(c&&d&&u!==_||!c&&!d&&u!==_){i=!1;break}}t=r+2}return i&&t-e>=3?t:-1},A_=(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},XAt=({path:n,obstacles:e,labelBounds:t,originalPath:i})=>{if(n.length<=2)return n;let r=[...n],s=mA(r),o=!0;for(;o;){o=!1;for(let c=0;c<r.length-3;c++){let l=YAt(r,c);if(l>0){if(A_(r[c],r[c+1],i)||A_(r[l-1],r[l],i))continue;let u=r[c],h=r[l],d=CQ(u,h);for(let _ of d){let g=[...r.slice(0,c+1),..._.slice(1,-1),...r.slice(l)],x=fA(_,e),v=_A(_,t);if(!x&&!v){let P=mA(g);r=g,s=P,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 h=c+u+1;if(h>=r.length||A_(r[c],r[c+1],i)||A_(r[h-1],r[h],i))continue;let d=r[c],_=r[h],g=CQ(d,_);for(let x of g){let v=[...r.slice(0,c+1),...x.slice(1,-1),...r.slice(h)],P=x,w=fA(P,e),T=_A(P,t);if(!w&&!T){let k=mA(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],h=r[c+2];if(A_(l,u,i)||A_(u,h,i))continue;let d=l.x===u.x&&u.x===h.x,_=l.y===u.y&&u.y===h.y;if(d||_){let g=[...r.slice(0,c+1),...r.slice(c+2)],x=fA([l,h],e),v=_A([l,h],t);if(!x&&!v){r=g,o=!0;break}}}}return S1(r)},UAt=({targetMspConnectionPairId:n,traces:e,inputProblem:t,allLabelPlacements:i,mergedLabelNetIdMap:r,paddingBuffer:s})=>{let o=e.find(w=>w.mspPairId===n);if(!o)throw new Error(`Target trace ${n} not found`);let a=e.filter(w=>w.mspPairId!==n),c=.01,l=a.flatMap((w,T)=>w.tracePath.slice(0,-1).map((k,C)=>{let M=w.tracePath[C+1];return{chipId:`trace-obstacle-${T}-${C}`,minX:Math.min(k.x,M.x)-c/2,minY:Math.min(k.y,M.y)-c/2,maxX:Math.max(k.x,M.x)+c/2,maxY:Math.max(k.y,M.y)+c/2}})),u=Lw(t),h=.01,_=[...u.map(w=>({...w,minX:w.minX-h,minY:w.minY-h,maxX:w.maxX+h,maxY:w.maxY+h})),...l],g=o.tracePath,v=i.filter(w=>{let T=r[w.globalConnNetId];return T?!T.has(o.globalConnNetId):w.globalConnNetId!==o.globalConnNetId}).map(w=>({minX:w.center.x-w.width/2-s,maxX:w.center.x+w.width/2+s,minY:w.center.y-w.height/2-s,maxY:w.center.y+w.height/2+s})),P=XAt({path:g,obstacles:_,labelBounds:v,originalPath:g});return{...o,tracePath:P}},VAt=({targetMspConnectionPairId:n,traces:e,inputProblem:t,allLabelPlacements:i,mergedLabelNetIdMap:r,paddingBuffer:s})=>{let o=e.find(w=>w.mspPairId===n);if(!o)throw new Error(`Target trace ${n} not found`);let a=1e-5,c=e.filter(w=>w.mspPairId!==n),l=.01,u=c.flatMap((w,T)=>w.tracePath.slice(0,-1).map((k,C)=>{let M=w.tracePath[C+1];return{chipId:`trace-obstacle-${T}-${C}`,minX:Math.min(k.x,M.x)-l/2,minY:Math.min(k.y,M.y)-l/2,maxX:Math.max(k.x,M.x)+l/2,maxY:Math.max(k.y,M.y)+l/2}})),d=[...Lw(t).map(w=>({...w,minX:w.minX+a,maxX:w.maxX-a,minY:w.minY+a,maxY:w.maxY-a})),...u],_=(w,T,k)=>{for(let C of k)if(w1(w,T,C))return!0;return!1},x=i.filter(w=>{let T=r[w.globalConnNetId];return T?!T.has(o.globalConnNetId):w.globalConnNetId!==o.globalConnNetId}).map(w=>({minX:w.center.x-w.width/2+a,maxX:w.center.x+w.width/2-a,minY:w.center.y-w.height/2+a,maxY:w.center.y+w.height/2-a})),v=[...o.tracePath];if(v.length<4)return{...o};if(v.length===4){let[w,T,k,C]=v,M,I;if(w.y===T.y&&T.x===k.x&&k.y===C.y){let R=(w.x+C.x)/2;M={x:R,y:T.y},I={x:R,y:k.y}}else{let R=(w.y+C.y)/2;M={x:T.x,y:R},I={x:k.x,y:R}}return _(w,M,d)||_(M,I,d)||_(I,C,d)||_(w,M,x)||_(M,I,x)||_(I,C,x)||(v[1]=M,v[2]=I),{...o,tracePath:S1(v)}}for(let w=1;w<v.length-4;w++){let T=v[w],k=v[w+1],C=v[w+2],M=v[w+3],I=T.y===k.y&&k.x===C.x&&C.y===M.y,E=T.x===k.x&&k.y===C.y&&C.x===M.x,A=T.y===k.y&&k.y===C.y&&C.y===M.y,R=T.x===k.x&&k.x===C.x&&C.x===M.x,B=A||R,j=!1;if(I?j=Math.sign(k.x-T.x)===Math.sign(M.x-C.x):E&&(j=Math.sign(k.y-T.y)===Math.sign(M.y-C.y)),!((I||E)&&!B&&j))continue;let V,H,et=Math.abs(I?T.x-k.x:T.y-k.y),tt=Math.abs(I?C.x-M.x:C.y-M.y);if(Math.abs(et-tt)<.001)continue;if(I){let G=(T.x+M.x)/2;V={x:G,y:k.y},H={x:G,y:C.y}}else{let G=(T.y+M.y)/2;V={x:k.x,y:G},H={x:C.x,y:G}}_(T,V,d)||_(V,H,d)||_(H,M,d)||_(T,V,x)||_(V,H,x)||_(H,M,x)||(v[w+1]=V,v[w+2]=H,w=0)}let P=S1(v);return{...o,tracePath:P}},GAt=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},HAt=(n,e)=>{let t=[];for(let i of n)i.mspPairId!==e&&t.push({points:i.tracePath});return t},IQ=(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=od(n,e,a,c);l&&i.push(l)}}return i},za=1e-6,cl=(n,e,t=za)=>Math.abs(n.x-e.x)<t,WAt=({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:h}=e,d,_=i,g=r;if(Math.abs(o.x-c)<za&&Math.abs(o.y-(l+h))<za)d={x:c+u+t,y:l-t},cl(s,o)?_={x:i.x,y:i.y-t}:_={x:i.x+t,y:i.y},cl(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))<za&&Math.abs(o.y-(l+h))<za)d={x:c-t,y:l-t},cl(s,o)?_={x:i.x,y:i.y-t}:_={x:i.x-t,y:i.y},cl(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)<za&&Math.abs(o.y-l)<za)d={x:c+u+t,y:l+h+t},cl(s,o)?_={x:i.x,y:i.y+t}:_={x:i.x+t,y:i.y},cl(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))<za&&Math.abs(o.y-l)<za)d={x:c-t,y:l+h+t},cl(s,o)?_={x:i.x,y:i.y+t}:_={x:i.x-t,y:i.y},cl(o,a)?g={x:r.x,y:r.y+t}:g={x:r.x-t,y:r.y};else return[];return[[_,d,g]]},qAt=(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=od(r,s,c,l);if(u)return{isColliding:!0,collidingTraceId:o.mspPairId,collisionPoint:u}}}return{isColliding:!1}},ZAt=(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},Ow=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},NQ=(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},AQ=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},KAt=(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},yA=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},JAt=n=>{let e={circles:[]};return n?.isColliding&&n.collisionPoint&&e.circles.push({center:n.collisionPoint,radius:.01,fill:"red"}),e},QAt=class extends Pr{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=GAt(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=HAt(this.input.allTraces,this.currentLShape.traceId),t=IQ(this.currentLShape.p1,this.currentLShape.p2,e),i=IQ(this.currentLShape.p2,this.currentLShape.p3,e);if(this.intersectionPoints=[...t,...i],t.length===0||i.length===0){this.lShapeProcessingStep="idle";return}this.rectangleCandidates=ZAt(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=WAt({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=qAt(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 Ow(this.lShapesToProcess);case"intersection_points":return yA([this.currentLShape?Ow(this.currentLShape):void 0,NQ(this.intersectionPoints)]);case"tight_rectangle":return yA([this.currentLShape?Ow(this.currentLShape):void 0,NQ(this.intersectionPoints),this.tightRectangle?AQ(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]),yA([e,this.currentLShape?Ow(this.currentLShape):void 0,this.tightRectangle?AQ(this.tightRectangle):void 0,t?KAt([t],this.bestRouteFound?"green":"blue",this.intersectionPoints):void 0,this.lastCollision?JAt(this.lastCollision):void 0])}default:return{}}}},t9t=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},e9t=class extends Pr{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 QAt({...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(t9t(i.tracePath))return;let r=Array.from(this.tracesMap.values()),s;e==="minimizing_turns"?s=UAt({...this.input,targetMspConnectionPairId:t,traces:r}):s=VAt({...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=cs(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 ll(n,e,t,i={}){return{solverName:n,solverClass:e,getConstructorParams:t,onSolved:i.onSolved,shouldSkip:i.shouldSkip}}var $Q=class extends Pr{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",[ll("mspConnectionPairSolver",uAt,()=>[{inputProblem:this.inputProblem}],{onSolved:e=>{}}),ll("schematicTraceLinesSolver",gAt,()=>[{mspConnectionPairs:this.mspConnectionPairSolver.mspConnectionPairs,dcConnMap:this.mspConnectionPairSolver.dcConnMap,globalConnMap:this.mspConnectionPairSolver.globalConnMap,inputProblem:this.inputProblem,chipMap:this.mspConnectionPairSolver.chipMap}]),ll("longDistancePairSolver",BAt,e=>[{inputProblem:e.inputProblem,primaryMspConnectionPairs:e.mspConnectionPairSolver.mspConnectionPairs,alreadySolvedTraces:e.schematicTraceLinesSolver.solvedTracePaths}],{onSolved:e=>{}}),ll("traceOverlapShiftSolver",vAt,()=>[{inputProblem:this.inputProblem,inputTracePaths:this.longDistancePairSolver?.getOutput().allTracesMerged,globalConnMap:this.mspConnectionPairSolver.globalConnMap}],{onSolved:e=>{}}),ll("netLabelPlacementSolver",EQ,()=>[{inputProblem:this.inputProblem,inputTraceMap:this.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(this.longDistancePairSolver.getOutput().allTracesMerged.map(e=>[e.mspPairId,e]))}],{onSolved:e=>{}}),ll("traceLabelOverlapAvoidanceSolver",LAt,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}]}),ll("traceCleanupSolver",e9t,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}]}),ll("netLabelPlacementSolver",EQ,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 zAt(t),FAt(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=[cs(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 bnt=Gt(En(),1);var vnt=Gt(En(),1);var Snt=Gt(En(),1);er();Ae();var n9t=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
  `)},i9t=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 n9t(this)}},Da=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()}},r9t=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}},s9t=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}},wA=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}},o9t=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}},a9t=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}},DQ=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 jQ(n){let e=new i9t("* Circuit JSON to SPICE Netlist"),t=Ee(n).source_component.list(),i=Ee(n).source_port.list(),r=Ee(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=tH(n),l=new Map,u=new Map,h=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&&(h=Math.max(..._)+1);let g=new Set,x=new Set(Ee(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 Ee(n).source_trace.list())if(T.connected_source_port_ids.length>0&&T.connected_source_net_ids.some(C=>x.has(C))){let C=T.connected_source_port_ids[0],M=c.getNetConnectedToId(C);M&&g.add(M)}}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 Ee(n).simulation_voltage_source.list()){let k=T.negative_source_port_id??T.terminal2_source_port_id;if(k){let C=c.getNetConnectedToId(k);C&&g.add(C)}}for(let T of g)u.set(T,"0");if(s.length>0)for(let T of s){if(!T.name)continue;let k;if(T.source_port_id)k=c.getNetConnectedToId(T.source_port_id);else if(T.source_net_id){let C=r.find(M=>M.connected_source_net_ids.includes(T.source_net_id));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):T.source_port_id&&T.name&&l.set(T.source_port_id,T.name)}for(let T of i){let k=T.source_port_id,C=c.getNetConnectedToId(k);C&&(u.has(C)||u.set(C,`N${h++}`),l.set(k,u.get(C)))}for(let T of i){let k=T.source_port_id;l.has(k)||l.set(k,`N${h++}`)}for(let T of t){if(T.type!=="source_component")continue;let k=Ee(n).source_port.list({source_component_id:T.source_component_id}).sort((M,I)=>(M.pin_number??0)-(I.pin_number??0)),C=k.map(M=>l.get(M.source_port_id)||"0");if("ftype"in T){let M=null;switch(T.ftype){case"simple_resistor":{if("resistance"in T&&"name"in T){let I=new r9t({name:T.name,positiveNode:C[0]||"0",negativeNode:C[1]||"0",value:c9t(T.resistance)});M=new Da(T.name,I,C)}break}case"simple_switch":{let I=p9t(T.name??T.source_component_id,"SW"),E=C[0]||"0",A=C[1]||"0",R=`NCTRL_${I}`,B=`SW_${I}`,j=a.get(T.source_component_id),U=h9t(j),V=new DQ({name:I,positiveNode:E,negativeNode:A,positiveControl:R,negativeControl:"0",model:B});M=new Da(I,V,[E,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 H=`CTRL_${I}`,et=new wA({name:H,positiveNode:R,negativeNode:"0",value:U}),tt=new Da(H,et,[R,"0"]);e.addComponent(tt);break}case"simple_capacitor":{if("capacitance"in T&&"name"in T){let I=new s9t({name:T.name,positiveNode:C[0]||"0",negativeNode:C[1]||"0",value:l9t(T.capacitance)});M=new Da(T.name,I,C)}break}case"simple_diode":{if("name"in T){let I=k.find(U=>U.name?.toLowerCase()==="anode"||U.port_hints?.includes("anode")),E=k.find(U=>U.name?.toLowerCase()==="cathode"||U.port_hints?.includes("cathode")),A=l.get(I?.source_port_id??"")||"0",R=l.get(E?.source_port_id??"")||"0",B="D",j=new o9t({name:T.name,positiveNode:A,negativeNode:R,model:B});e.models.set(B,`.MODEL ${B} D`),M=new Da(T.name,j,[A,R])}break}case"simple_inductor":{if("inductance"in T&&"name"in T){let I=new a9t({name:T.name,positiveNode:C[0]||"0",negativeNode:C[1]||"0",value:u9t(T.inductance)});M=new Da(T.name,I,C)}break}case"simple_mosfet":{if("name"in T){let I=k.find(H=>H.name?.toLowerCase()==="drain"||H.port_hints?.includes("drain")),E=k.find(H=>H.name?.toLowerCase()==="gate"||H.port_hints?.includes("gate")),A=k.find(H=>H.name?.toLowerCase()==="source"||H.port_hints?.includes("source")),R=l.get(I?.source_port_id??"")||"0",B=l.get(E?.source_port_id??"")||"0",j=l.get(A?.source_port_id??"")||"0",U="SWMOD",V=new DQ({name:T.name,positiveNode:R,negativeNode:j,positiveControl:B,negativeControl:j,model:U});e.models.set(U,`.MODEL ${U} SW`),M=new Da(T.name,V,[R,B,j])}break}}M&&e.addComponent(M)}}let P=Ee(n).simulation_voltage_source.list();for(let T of P)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",C=l.get(T.terminal2_source_port_id)||"0",M="",I=T.wave_shape;if(I==="sinewave"){let A=T.voltage??0,R=T.frequency??0,B=0,j=0,U=T.phase??0;R>0?M=`SIN(0 ${A} ${R} ${B} ${j} ${U})`:M=`DC ${T.voltage??0}`}else if(I==="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,V=j*U;M=`PULSE(0 ${A} 0 1n 1n ${V} ${j})`}else T.voltage!==void 0&&(M=`DC ${T.voltage}`);if(M){let E=new wA({name:T.simulation_voltage_source_id,positiveNode:k,negativeNode:C,value:M}),A=new Da(T.simulation_voltage_source_id,E,[k,C]);e.addComponent(A)}}}else{let k=T.positive_source_port_id??T.terminal1_source_port_id,C=T.negative_source_port_id??T.terminal2_source_port_id;if(k&&C&&"voltage"in T&&T.voltage!==void 0){let M=l.get(k)||"0",I=l.get(C)||"0",E=new wA({name:T.simulation_voltage_source_id,positiveNode:M,negativeNode:I,value:`DC ${T.voltage}`}),A=new Da(T.simulation_voltage_source_id,E,[M,I]);e.addComponent(A)}}let w=n.find(T=>T.type==="simulation_experiment");if(w){if(s.length>0){let M=new Set;for(let I of s){let E;if(I.source_port_id)E=l.get(I.source_port_id);else if(I.source_net_id){let A=r.find(R=>R.connected_source_net_ids.includes(I.source_net_id));if(A&&A.connected_source_port_ids.length>0){let R=A.connected_source_port_ids[0];E=l.get(R)}}E&&E!=="0"&&M.add(`V(${E})`)}M.size>0&&w.experiment_type?.includes("transient")&&e.printStatements.push(`.PRINT TRAN ${[...M].join(" ")}`)}let T=w.time_per_step,k=w.end_time_ms,C=w.start_time_ms;if(T&&k){let M=(C??0)/1e3,I=`.tran ${Xi(T/1e3)} ${Xi(k/1e3)}`;M>0&&(I+=` ${Xi(M)}`),I+=" UIC",e.tranCommand=I}}return e}function c9t(n){return n>=1e6?`${n/1e6}MEG`:n>=1e3?`${n/1e3}K`:n.toString()}function l9t(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 u9t(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 p9t(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 h9t(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 h=1/c,d=a&&a>o?Math.min(a-o,h):0,_=d>0?d:Math.max(h/2,1e-9);return`PULSE(${Xi(l)} ${Xi(u)} ${Xi(o)} 1n 1n ${Xi(_)} ${Xi(h)})`}if(a!==void 0&&a>o){let h=Math.max(a-o,1e-9),d=o+h*2;return`PULSE(${Xi(l)} ${Xi(u)} ${Xi(o)} 1n 1n ${Xi(h)} ${Xi(d)})`}if(o>0){let h=o*2,d=Math.max(h/2,1e-9);return`PULSE(${Xi(l)} ${Xi(u)} ${Xi(o)} 1n 1n ${Xi(d)} ${Xi(h)})`}return`DC ${s?5:0}`}function Xi(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 wnt=Gt(En(),1);var oi=1e-15,d9t=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 mr(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 f9t(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=>mr(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 m9t(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=mr(i[s]),a=mr(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 _9t(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,oi);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,oi);return n.v2+(n.v1-n.v2)*s}return n.v1}function y9t(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,oi),o=(e-i.t)/s;return i.v+(r.v-i.v)*o}}return n[n.length-1].v}function g9t(n){let e=/"[^"]*"|\w+\s*\([^)]*\)|\([^()]*\)|\S+/g,t=[],i;for(;(i=e.exec(n))!==null;)t.push(i[0]);return t}function un(n,e,t){let i=n[e];if(i==null)throw new Error(t);return i}function x9t(n){let e=new Map,t=new Map,i={nodes:new d9t,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=g9t(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=un(l,1,".ac missing mode").toLowerCase();if(g!=="dec"&&g!=="lin")throw new Error(".ac supports 'dec' or 'lin'");let x=parseInt(un(l,2,".ac missing point count"),10),v=mr(un(l,3,".ac missing start frequency")),P=mr(un(l,4,".ac missing stop frequency"));i.analyses.ac={mode:g,N:x,f1:v,f2:P}}else if(_===".tran"){let g=mr(un(l,1,".tran missing timestep")),x=mr(un(l,2,".tran missing stop time"));i.analyses.tran={dt:g,tstop:x}}else if(_===".print")if(un(l,1,".print missing analysis type").toLowerCase()==="tran"){let x=l.slice(2);for(let v of x){let P=v.match(/^v\(([^)]+)\)$/i);if(P&&P[1]){let w=P[1];i.probes.tran.some(T=>T.toUpperCase()===w.toUpperCase())||i.probes.tran.push(w)}}}else i.skipped.push(c);else if(_===".model"){let g=un(l,1,".model missing name"),v=un(l,2,".model missing type"),P="";if(v.includes("(")){let T=v.indexOf("(");P=v.slice(T+1),v=v.slice(0,T)}if(!P)P=l.slice(3).join(" ").replace(/^\(/,"").replace(/\)$/,"");else{let T=l.slice(3).join(" ").replace(/\)$/,"");P=`${P} ${T}`.trim()}P=P.replace(/^\(/,"").replace(/\)$/,"").trim();let w=v.toLowerCase();if(w==="vswitch"||w==="sw"){let T={name:g,Ron:1,Roff:1e12,Von:0,Voff:0},k,C;if(P.length>0){let M=P.split(/[\s,]+/).filter(Boolean);for(let I of M){let[E,A]=I.split("=");if(!E||A==null)continue;let R=E.toLowerCase(),B=mr(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"&&(C=B))}}if(k!==void 0){let M=C??0;T.Von=k+M/2,T.Voff=k-M/2}e.set(g.toLowerCase(),T)}else if(w==="d"){let T={name:g,Is:1e-14,N:1};if(P.length>0){let k=P.split(/[\s,]+/).filter(Boolean);for(let C of k){let[M,I]=C.split("=");if(!M||I==null)continue;let E=M.toLowerCase(),A=mr(I);Number.isNaN(A)||(E==="is"?T.Is=A:E==="n"&&(T.N=A))}}t.set(g.toLowerCase(),T)}else i.skipped.push(c)}else i.skipped.push(c);continue}let h=u.charAt(0).toLowerCase(),d=u;try{if(h==="r"){let _=i.nodes.getOrCreate(un(l,1,"Resistor missing node")),g=i.nodes.getOrCreate(un(l,2,"Resistor missing node")),x=mr(un(l,3,"Resistor missing value"));i.R.push({name:d,n1:_,n2:g,R:x})}else if(h==="c"){let _=i.nodes.getOrCreate(un(l,1,"Capacitor missing node")),g=i.nodes.getOrCreate(un(l,2,"Capacitor missing node")),x=mr(un(l,3,"Capacitor missing value"));i.C.push({name:d,n1:_,n2:g,C:x,vPrev:0})}else if(h==="l"){let _=i.nodes.getOrCreate(un(l,1,"Inductor missing node")),g=i.nodes.getOrCreate(un(l,2,"Inductor missing node")),x=mr(un(l,3,"Inductor missing value"));i.L.push({name:d,n1:_,n2:g,L:x,iPrev:0})}else if(h==="v"){let _=i.nodes.getOrCreate(un(l,1,"Voltage source missing node")),g=i.nodes.getOrCreate(un(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=mr(l[v]),v++);v<l.length;){let P=l[v].toLowerCase();if(P==="dc"){let w=un(l,v+1,"DC value missing");x.dc=mr(w),v+=2}else if(P==="ac"){let w=un(l,v+1,"AC magnitude missing");x.acMag=mr(w);let T=l[v+2];T!=null&&/^[+-]?\d/.test(T)?(x.acPhaseDeg=mr(T),v+=3):v+=2}else if(P.startsWith("pulse")){let w=P.includes("(")?P:un(l,v+1,"PULSE() missing arguments");if(!w||!/\(.*\)/.test(w))throw new Error("Malformed PULSE() specification");let T=f9t(w);x.waveform=k=>_9t(T,k),v+=P.includes("(")?1:2}else if(P.startsWith("pwl")){let w=P.includes("(")?P:un(l,v+1,"PWL() missing arguments");if(!w||!/\(.*\)/.test(w))throw new Error("Malformed PWL() specification");let T=m9t(w);x.waveform=k=>y9t(T,k),v+=P.includes("(")?1:2}else/^\(.*\)$/.test(P),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(h==="s"){let _=i.nodes.getOrCreate(un(l,1,"Switch missing node")),g=i.nodes.getOrCreate(un(l,2,"Switch missing node")),x=i.nodes.getOrCreate(un(l,3,"Switch missing control node")),v=i.nodes.getOrCreate(un(l,4,"Switch missing control node")),P=un(l,5,"Switch missing model");i.S.push({name:d,n1:_,n2:g,ncPos:x,ncNeg:v,modelName:P.toLowerCase(),model:null,isOn:!1})}else if(h==="d")if(l.length===4){let _=i.nodes.getOrCreate(un(l,1,"Diode missing node")),g=i.nodes.getOrCreate(un(l,2,"Diode missing node")),x=un(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 pn=class ja{constructor(e=0,t=0){f(this,"re");f(this,"im");this.re=e,this.im=t}static from(e,t=0){return new ja(e,t)}static fromPolar(e,t=0){let i=t*Math.PI/180;return new ja(e*Math.cos(i),e*Math.sin(i))}clone(){return new ja(this.re,this.im)}add(e){return new ja(this.re+e.re,this.im+e.im)}sub(e){return new ja(this.re-e.re,this.im-e.im)}mul(e){return new ja(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<oi)throw new Error("Complex divide by ~0");return new ja((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<oi)throw new Error("Complex invert by ~0");return new ja(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 b9t(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 h=n[u];if(!h)throw new Error("Matrix row missing");let d=h[r]?.abs()??0;d>a&&(a=d,s=u)}if(a<oi)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 h=n[u];if(!h)throw new Error("Matrix row missing");let d=h[r];if(!d)continue;let _=d.div(l);if(!(_.abs()<oi))for(let g=r;g<=t;g++){let x=h[g],v=c[g];!x||!v||(h[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 v9t(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-oi))&&s.push(e),s}function PA(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)??pn.from(0,0).sub(r),c[s]=c[s]?.sub(r)??pn.from(0,0).sub(r)}}function S9t(n,e,t,i,r){let s=t.matrixIndexOfNode(i.n1),o=t.matrixIndexOfNode(i.n2),a=i.index,c=pn.from(1,0),l=pn.from(-1,0);if(s>=0){let h=n[s];if(!h)throw new Error("Matrix row missing while stamping voltage source");h[a]=h[a]?.add(c)??c}if(o>=0){let h=n[o];if(!h)throw new Error("Matrix row missing while stamping voltage source");h[a]=h[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]??pn.from(0,0)).add(r)}function w9t(n){let{mode:e,N:t,f1:i,f2:r}=n;if(e==="dec")return v9t(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 P9t(n,e,t){let i=Array.from({length:t},()=>Array.from({length:t},()=>pn.from(0,0))),r=Array.from({length:t},()=>pn.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=pn.from(1/o.R,0);PA(i,n.nodes,o.n1,o.n2,a)}for(let o of n.C){let a=pn.from(0,s*e*o.C);PA(i,n.nodes,o.n1,o.n2,a)}for(let o of n.L){let a=pn.from(0,s*e*o.L),c=a.abs()<oi?pn.from(0,0):pn.from(1,0).div(a);PA(i,n.nodes,o.n1,o.n2,c)}for(let o of n.V){let a=pn.fromPolar(o.acMag||0,o.acPhaseDeg||0);S9t(i,r,n.nodes,o,a)}return{A:i,b:r}}function k9t(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=w9t({mode:e,N:t,f1:i,f2:r}),l={};n.nodes.rev.forEach((v,P)=>{P!==0&&(l[v]=[])});let u={},h=2*Math.PI;for(let v of c){let{A:P,b:w}=P9t(n,v,a),T=b9t(P,w);for(let k=1;k<n.nodes.count();k++){let C=k-1,M=n.nodes.rev[k];if(!M)continue;let I=l[M];I&&I.push(T[C]??pn.from(0,0))}for(let k of n.R){let C=k.n1===0?pn.from(0,0):T[k.n1-1]??pn.from(0,0),M=k.n2===0?pn.from(0,0):T[k.n2-1]??pn.from(0,0),E=pn.from(1/k.R,0).mul(C.sub(M));(u[d=k.name]||(u[d]=[])).push(E)}for(let k of n.C){let C=k.n1===0?pn.from(0,0):T[k.n1-1]??pn.from(0,0),M=k.n2===0?pn.from(0,0):T[k.n2-1]??pn.from(0,0),E=pn.from(0,h*v*k.C).mul(C.sub(M));(u[_=k.name]||(u[_]=[])).push(E)}for(let k of n.L){let C=k.n1===0?pn.from(0,0):T[k.n1-1]??pn.from(0,0),M=k.n2===0?pn.from(0,0):T[k.n2-1]??pn.from(0,0),I=pn.from(0,h*v*k.L),A=(I.abs()<oi?pn.from(0,0):pn.from(1,0).div(I)).mul(C.sub(M));(u[g=k.name]||(u[g]=[])).push(A)}for(let k of n.V){let C=T[k.index]??pn.from(0,0);(u[x=k.name]||(u[x]=[])).push(C)}}return{freqs:c,nodeVoltages:l,elementCurrents:u}}var BQ=.02585;function T9t(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 h=n[u];if(!h)throw new Error("Matrix row missing");let d=Math.abs(h[r]??0);d>a&&(a=d,s=u)}if(a<oi)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 h=n[u];if(!h)throw new Error("Matrix row missing");let d=h[r];if(d==null)continue;let _=d/l;if(!(Math.abs(_)<oi))for(let g=r;g<=t;g++){let x=h[g],v=c[g];x==null||v==null||(h[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 P1(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 kA(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 M9t(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 E9t(n,e){let t=n>oi?n:Math.max(e/1e3,oi),i=Math.max(1,Math.ceil(e/Math.max(t,oi)));return{dt:i>0?e/i:e,steps:i}}function C9t(n,e,t,i,r,s,o){for(let a of t.R){let c=1/a.R;P1(n,t.nodes,a.n1,a.n2,c)}for(let a of t.C){let c=a.C/Math.max(r,oi);P1(n,t.nodes,a.n1,a.n2,c);let l=-c*a.vPrev;kA(e,t.nodes,a.n1,a.n2,l)}for(let a of t.L){let c=Math.max(r,oi)/a.L;P1(n,t.nodes,a.n1,a.n2,c),kA(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,h=1/Math.max(Math.abs(l),oi);P1(n,t.nodes,a.n1,a.n2,h)}for(let a of t.V){let c=a.waveform?a.waveform(i):a.dc||0;M9t(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,h=t.nodes.matrixIndexOfNode(l),d=t.nodes.matrixIndexOfNode(u),_=l===0?0:s[h]??0,g=u===0?0:s[d]??0,x=_-g,v=o===0?a.vdPrev:x,P=c.N*BQ,w=v;v>.8&&(w=.8),v<-1&&(w=-1);let T=Math.exp(w/P),k=c.Is*(T-1),C=Math.max(c.Is/P*T,1e-12),M=k-C*w;P1(n,t.nodes,l,u,C),kA(e,t.nodes,l,u,M)}}function I9t(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 N9t(n){var d,_,g,x,v,P;if(!n.analyses.tran)return null;let{dt:e,tstop:t}=n.analyses.tran,{dt:i,steps:r}=E9t(e,t),s=n.nodes.count()-1,o=n.V.length,a=s+o,c=[],l={};n.nodes.rev.forEach((w,T)=>{T!==0&&(l[w]=[])});let u={},h=0;for(let w=0;w<=r;w++,h=w*i){c.push(h);let T=new Array(a).fill(0);for(let k=0;k<20;k++){let C=Array.from({length:a},()=>new Array(a).fill(0)),M=new Array(a).fill(0);if(C9t(C,M,n,h,i,T,k),T=T9t(C,M),!I9t(n,T)||k===19)break}for(let k=1;k<n.nodes.count();k++){let C=k-1,M=n.nodes.rev[k];if(!M)continue;let I=l[M];I&&I.push(T[C]??0)}for(let k of n.R){let C=k.n1===0?0:T[k.n1-1]??0,M=k.n2===0?0:T[k.n2-1]??0,I=(C-M)/k.R;(u[d=k.name]||(u[d]=[])).push(I)}for(let k of n.C){let C=k.n1===0?0:T[k.n1-1]??0,M=k.n2===0?0:T[k.n2-1]??0,I=k.C*(C-M-k.vPrev)/Math.max(i,oi);(u[_=k.name]||(u[_]=[])).push(I)}for(let k of n.L){let C=k.n1===0?0:T[k.n1-1]??0,M=k.n2===0?0:T[k.n2-1]??0,E=Math.max(i,oi)/k.L*(C-M)+k.iPrev;(u[g=k.name]||(u[g]=[])).push(E)}for(let k of n.V){let C=T[k.index]??0;(u[x=k.name]||(u[x]=[])).push(C)}for(let k of n.S){let C=k.model;if(!C)continue;let M=k.n1===0?0:T[k.n1-1]??0,I=k.n2===0?0:T[k.n2-1]??0,E=k.isOn?C.Ron:C.Roff,A=Math.max(Math.abs(E),oi),R=(M-I)/A;(u[v=k.name]||(u[v]=[])).push(R)}for(let k of n.D){if(!k.model)continue;let{nPlus:C,nMinus:M,model:I}=k,E=C===0?0:T[C-1]??0,A=M===0?0:T[M-1]??0,R=E-A,B=I.N*BQ,j=Math.exp(R/B),U=I.Is*(j-1);(u[P=k.name]||(u[P]=[])).push(U)}for(let k of n.C){let C=k.n1===0?0:T[k.n1-1]??0,M=k.n2===0?0:T[k.n2-1]??0;k.vPrev=C-M}for(let k of n.L){let C=k.n1===0?0:T[k.n1-1]??0,M=k.n2===0?0:T[k.n2-1]??0,I=Math.max(i,oi)/k.L;k.iPrev=I*(C-M)+k.iPrev}for(let k of n.D){let C=k.nPlus===0?0:T[k.nPlus-1]??0,M=k.nMinus===0?0:T[k.nMinus-1]??0;k.vdPrev=C-M}}if(n.probes.tran.length>0){let w={},T=n.probes.tran.map(k=>k.toUpperCase());for(let k in l)T.includes(k.toUpperCase())&&(w[k]=l[k]);return{times:c,nodeVoltages:w,elementCurrents:u}}return{times:c,nodeVoltages:l,elementCurrents:u}}function YQ(n){let e=x9t(n),t=k9t(e),i=N9t(e);return{circuit:e,ac:t,tran:i}}function XQ(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}er();Ae();er();Ae();Ae();St();Ae();Ae();ii();Ae();er();Ae();er();Ae();Ae();er();Ae();function UQ(n,e,t,i){return Math.sqrt((t-n)**2+(i-e)**2)}var A9t=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=>UQ(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 UQ(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 GQ(n){A9t(n);let e=n.filter(o=>o.type==="source_trace"),t=n.filter(o=>o.type==="pcb_port"),i=[],r=tr(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],h=r.getNetConnectedToId(u.pcb_port_id);r.getIdsConnectedToNet(h).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 R9t=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}`,h=this.buckets.get(u);h?h.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 h=u.findIndex(d=>d.spatialIndexId===n);h!==-1&&(u.splice(h,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}`,h=this.buckets.get(u)||[];for(let d of h){let _=d.spatialIndexId;i.has(_)||(i.add(_),t.push(d))}}return t}},k1=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)}:o_([n]),TA=.1,O9t=.15;var L9t=.2,F9t=.3,T1=.005;function z9t(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 MA(n){let e=new Set;for(let t of n)for(let i of z9t(t))e.add(i);return Array.from(e)}var $9t=(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=Vo(((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=Vo(((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},h=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=h*g-d*d;if(v<1e-10)return D9t(t,i,r,s,o,a,c,l);let P=(d*x-g*_)/v,w=(h*x-d*_)/v;P=Vo(P,0,1),w=Vo(w,0,1),w=(P*d+x)/g,w=Vo(w,0,1),P=(w*d-_)/h,P=Vo(P,0,1);let T={x:t.x+P*o.x,y:t.y+P*o.y},k={x:r.x+w*a.x,y:r.y+w*a.y},C=T.x-k.x,M=T.y-k.y,I=Math.sqrt(C*C+M*M);return{x:(T.x+k.x)/2,y:(T.y+k.y)/2}},D9t=(n,e,t,i,r,s,o,a)=>{let c=((t.x-n.x)*r.x+(t.y-n.y)*r.y)/o;c=Vo(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=Vo(u,0,1);let h={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=Vo(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=Vo(g,0,1);let x={x:t.x+g*s.x,y:t.y+g*s.y},P=[{pointA:l,pointB:t,distance:Math.sqrt((l.x-t.x)**2+(l.y-t.y)**2)},{pointA:h,pointB:i,distance:Math.sqrt((h.x-i.x)**2+(h.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((w,T)=>T.distance<w.distance?T:w);return{x:(P.pointA.x+P.pointB.x)/2,y:(P.pointA.y+P.pointB.y)/2}},Vo=(n,e,t)=>Math.max(e,Math.min(t,n)),j9t=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)}`)},VQ=(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 E=Math.max(r,Math.min(o,t.x)),A=Math.max(s,Math.min(a,t.y));return E===t.x&&A===t.y?{x:t.x,y:t.y}:{x:E,y:A}}let c=i.x-t.x,l=i.y-t.y,u=c!==0?(r-t.x)/c:Number.NEGATIVE_INFINITY,h=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,h),Math.min(d,_)),x=Math.min(Math.max(u,h),Math.max(d,_));if(g<=x&&x>=0&&g<=1){let E=Math.max(0,Math.min(1,g));return{x:t.x+E*c,y:t.y+E*l}}let v={x:Math.max(r,Math.min(o,t.x)),y:Math.max(s,Math.min(a,t.y))},P={x:Math.max(r,Math.min(o,i.x)),y:Math.max(s,Math.min(a,i.y))},w=(v.x-t.x)**2+(v.y-t.y)**2,T=(P.x-i.x)**2+(P.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}}],C=Math.min(w,T),M=w<=T?v:P,I=(E,A,R)=>Math.max(A,Math.min(R,E));for(let E of k){let A={x:i.x-t.x,y:i.y-t.y},R={x:E.end.x-E.start.x,y:E.end.y-E.start.y},B={x:t.x-E.start.x,y:t.y-E.start.y},j=A.x*A.x+A.y*A.y,U=A.x*R.x+A.y*R.y,V=A.x*B.x+A.y*B.y,H=R.x*R.x+R.y*R.y,et=R.x*B.x+R.y*B.y,tt=j*H-U*U;if(Math.abs(tt)<1e-10)continue;let mt=(U*et-H*V)/tt,G=(j*et-U*V)/tt;mt=I(mt,0,1),G=I(G,0,1);let Q={x:t.x+mt*A.x,y:t.y+mt*A.y},nt={x:E.start.x+G*R.x,y:E.start.y+G*R.y},pt=Q.x-nt.x,ht=Q.y-nt.y,wt=pt*pt+ht*ht;wt<C&&(C=wt,M={x:(Q.x+nt.x)/2,y:(Q.y+nt.y)/2})}return M};function B9t(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:[...Am]:n.type==="pcb_hole"?[...Am]:n.type==="pcb_via"?Array.isArray(n.layers)?n.layers:[...Am]:n.type==="pcb_keepout"?Array.isArray(n.layers)?n.layers:[]:[]}function HQ(n,{connMap:e}={}){let t=[];e??(e=tr(n));let r=Ze(n).pcb_trace.list().flatMap(g=>{let x=[];for(let v=0;v<g.route.length-1;v++){let P=g.route[v],w=g.route[v+1];P.route_type==="wire"&&w.route_type==="wire"&&P.layer===w.layer&&x.push({type:"pcb_trace_segment",pcb_trace_id:g.pcb_trace_id,_pcbTrace:g,thickness:"width"in P?P.width:"width"in w?w.width:O9t,layer:P.layer,x1:P.x,y1:P.y,x2:w.x,y2:w.y})}return x}),s=Ze(n).pcb_smtpad.list(),o=Ze(n).pcb_plated_hole.list(),a=Ze(n).pcb_hole.list(),c=Ze(n).pcb_via.list(),l=Ze(n).pcb_keepout.list(),u=[...r,...s,...o,...a,...c,...l],h=new R9t({objects:u,getBounds:k1}),d=g=>Is(n,g),_=new Set;for(let g of r){let x=TA,v=k1(g),P=h.getObjectsInBounds(v,x+g.thickness/2);if(!(g.x1===g.x2&&g.y1===g.y2))for(let w of P){if(!B9t(w).includes(g.layer))continue;if(w.type==="pcb_trace_segment"){let M=w;if(g.layer!==M.layer||e.areIdsConnected(g.pcb_trace_id,M.pcb_trace_id))continue;let I=r_({x:g.x1,y:g.y1},{x:g.x2,y:g.y2},{x:M.x1,y:M.y1},{x:M.x2,y:M.y2})-g.thickness/2-M.thickness/2;if(I>TA-T1)continue;let E=`overlap_${g.pcb_trace_id}_${M.pcb_trace_id}`,A=`overlap_${M.pcb_trace_id}_${g.pcb_trace_id}`;if(_.has(E)||_.has(A))continue;_.add(E),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(g.pcb_trace_id)} overlaps with ${d(M.pcb_trace_id)} ${I<0?"(accidental contact)":`(gap: ${I.toFixed(3)}mm)`}`,pcb_trace_id:g.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:E,pcb_component_ids:[],center:$9t(g,M),pcb_port_ids:MA([g._pcbTrace,M._pcbTrace])});continue}let T=Lo(w);if(e.areIdsConnected(g.pcb_trace_id,"pcb_trace_id"in w?w.pcb_trace_id:T))continue;if(w.type==="pcb_via"||w.type==="pcb_plated_hole"&&w.shape==="circle"||w.type==="pcb_hole"||w.type==="pcb_smtpad"&&w.shape==="circle"){let M=j9t(w),E=SS({x:g.x1,y:g.y1},{x:g.x2,y:g.y2},{x:w.x,y:w.y,radius:M})-g.thickness/2;if(E>TA-T1)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 ${w.type} "${d(Lo(w))}" ${E<0?"(accidental contact)":`(gap: ${E.toFixed(3)}mm)`}`,pcb_trace_id:g.pcb_trace_id,center:VQ(g,k1(w)),source_trace_id:"",pcb_trace_error_id:A,pcb_component_ids:["pcb_component_id"in w?w.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...MA([g._pcbTrace]),"pcb_port_id"in w?w.pcb_port_id:void 0].filter(Boolean)})}let C=Ng({x:g.x1,y:g.y1},{x:g.x2,y:g.y2},k1(w))-g.thickness/2;if(C+T1<x){let M=`overlap_${g.pcb_trace_id}_${T}`;if(_.has(M))continue;_.add(M),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(g.pcb_trace_id)} overlaps with ${w.type} "${d(Lo(w))}" ${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:["pcb_component_id"in w?w.pcb_component_id:void 0].filter(Boolean),center:VQ(g,k1(w)),pcb_port_ids:[...MA([g._pcbTrace]),"pcb_port_id"in w?w.pcb_port_id:void 0].filter(Boolean)})}}}return t}function WQ(n){return n.area()>=0}function qQ({center:n,size:e,rotationDeg:t=0}){let i=n.x,r=n.y,s=e.width/2,o=e.height/2,a=[new Uo(i-s,r-o),new Uo(i+s,r-o),new Uo(i+s,r+o),new Uo(i-s,r+o)],c=new y1(a);if(t){let l=oS(t,i,r),u=a.map(h=>{let d=oe(l,{x:h.x,y:h.y});return new Uo(d.x,d.y)});c=new y1(u)}return WQ(c)||c.reverse(),c}function Y9t({board:n}){if(n.outline&&n.outline.length>0){let e=n.outline.map(i=>new Uo(i.x,i.y)),t=new y1(e);return WQ(t)||t.reverse(),t}return n.center&&typeof n.width=="number"&&typeof n.height=="number"?qQ({center:n.center,size:{width:n.width,height:n.height},rotationDeg:0}):null}function X9t({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 Is(n,e.pcb_component_id)||"Unknown"}function U9t(n,e,t,i,r,s){let o=new Uo(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 h=oS(s,t.x,t.y),d=x=>{let v=oe(h,x);return new Uo(v.x,v.y)},_=l.concat(u).map(d),g=0;for(let x of _)if(!e.contains(x)){let v=e.distanceTo(x),P=Array.isArray(v)?v[0]:Number(v)||0;P>g&&(g=P)}if(g>0)return g;try{let x=QN.intersect(n,e),v=0;x?Array.isArray(x)?v=x.reduce((w,T)=>w+(typeof T.area=="function"?T.area():0),0):typeof x.area=="function"?v=x.area():v=0:v=0;let P=n.area();if(v>0&&v<P){let w=1-v/P,T=Math.abs(i),k=Math.abs(r);return Math.min(T,k)*w}else return .1}catch{return .1}}function ZQ(n){let e=n.find(s=>s.type==="pcb_board");if(!e)return[];let t=Y9t({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=qQ({center:s.center,size:{width:s.width,height:s.height},rotationDeg:s.rotation||0});if(o.area()===0||t.contains(o))continue;let c=U9t(o,t,s.center,s.width,s.height,s.rotation||0),l=X9t({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 V9t(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}function KQ(n,{connMap:e,minSpacing:t=L9t}={}){let i=n.filter(o=>o.type==="pcb_via");if(i.length<2)return[];e??(e=tr(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=V9t(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+T1>=t)continue;let h=[c.pcb_via_id,l.pcb_via_id].sort().join("_");s.has(h)||(s.add(h),r.push({type:"pcb_via_clearance_error",pcb_error_id:`same_net_vias_close_${h}`,message:`Vias ${Is(n,c.pcb_via_id)} and ${Is(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 G9t(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}function JQ(n,{connMap:e,minSpacing:t=F9t}={}){let i=n.filter(o=>o.type==="pcb_via");if(i.length<2)return[];e??(e=tr(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=G9t(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+T1>=t)continue;let h=[c.pcb_via_id,l.pcb_via_id].sort().join("_");s.has(h)||(s.add(h),r.push({type:"pcb_via_clearance_error",pcb_error_id:`different_net_vias_close_${h}`,message:`Vias ${Is(n,c.pcb_via_id)} and ${Is(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 H9t=.2;function W9t(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 QQ(n,e={}){let t=[],i=e.margin??H9t,r=n.find(a=>a.type==="pcb_board");if(!r)return t;let s=W9t(r);if(!s)return t;let o=Ze(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 h="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 P=s[v],w=s[(v+1)%s.length],T=r_(d,_,P,w);T<g&&(g=T)}let x=h/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 q9t(n,e){let t=o_([n]),i=o_([e]);return Wc(t,i)}function ttt(n){let e=[],t=tr(n),i=Ze(n).pcb_smtpad.list(),r=Ze(n).pcb_plated_hole.list(),s=Ze(n).pcb_hole.list(),o=new Map;for(let c of i){let l=c.pcb_component_id||`standalone_pad_${Lo(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_${Lo(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_${Lo(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=o_(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],h=a[l];if(Wc(u.bounds,h.bounds))for(let d of u.elements)for(let _ of h.elements){let g=Lo(d),x=Lo(_);if(!(d.type==="pcb_smtpad"&&_.type==="pcb_smtpad"&&t.areIdsConnected(g,x))&&q9t(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 ett(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}St();var EA=[{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 gi(n){if(n==null)return"";if(n===0)return"0";let e=Math.abs(n),t=EA.find(s=>{let o=e/s.value;return o>=1&&o<1e3})||EA[EA.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}`}St();Ae();Ag();var Z9t=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())},CA=(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)},K9t=n=>n.shape==="rect",J9t=n=>n.shape==="trace",Q9t=n=>n.shape==="circle",t6t=n=>n.shape==="polygon",e6t=(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(h=>L.point(h.x,h.y)));l.area()<0&&l.reverse();let u=l.vertices;for(let h=0;h<u.length;h++){let d=u[h===0?u.length-1:h-1],_=u[h],g=u[(h+1)%u.length];if(!d||!_||!g)continue;let x=new L.Vector(d,_),v=new L.Vector(_,g),P=x.cross(v),w=new L.Circle(_,a);if(r.push(CA(w)),P<0){let T=new L.Box(_.x-a,_.y-a,_.x+a,_.y+a);r.push(new L.Polygon(T.toPoints()))}}for(let h=0;h<u.length;h++){let d=u[h],_=u[(h+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,P=(d.y+_.y)/2,w=Math.atan2(_.y-d.y,_.x-d.x)*180/Math.PI,T=g/2,k=x/2,C=w*Math.PI/180,M=Math.cos(C),I=Math.sin(C),A=[{x:-T,y:-k},{x:T,y:-k},{x:T,y:k},{x:-T,y:k}].map(R=>({x:v+R.x*M-R.y*I,y:P+R.x*I+R.y*M}));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 h=l.connectivityKey.startsWith("hole:")||l.connectivityKey.startsWith("cutout:");if(Q9t(l)){let d=h?c??0:s,_=new L.Circle(new L.Point(l.x,l.y),l.radius+d);r.push(CA(_));continue}if(K9t(l)){let d=h?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(t6t(l)){let d=h?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=[],P=x.vertices;for(let T=0;T<P.length;T++){let k=P[T],C=P[(T+1)%P.length],M=L.segment(k,C);if(M.length===0)continue;let I=L.line(M.start,M.end),E=I.norm,A=I.translate(E.multiply(-d));v.push(A)}let w=[];for(let T=0;T<v.length;T++){let k=v[T],C=v[(T+1)%v.length],M=k.intersect(C);M.length>0&&w.push(M[0])}w.length>=3&&r.push(new L.Polygon(w));continue}if(J9t(l)){for(let d of l.segments){let _=new L.Circle(new L.Point(d.x,d.y),l.width/2+o);r.push(CA(_))}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,P=(_.x+g.x)/2,w=(_.y+g.y)/2,T=Math.atan2(g.y-_.y,g.x-_.x)*180/Math.PI,k=x/2,C=v/2,M=T*Math.PI/180,I=Math.cos(M),E=Math.sin(M),R=[{x:-k,y:-C},{x:k,y:-C},{x:k,y:C},{x:-k,y:C}].map(B=>({x:P+B.x*I-B.y*E,y:w+B.x*E+B.y*I}));r.push(new L.Polygon(R.map(B=>L.point(B.x,B.y))))}continue}}return{polygonsToSubtract:r}},ntt=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}),n6t=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(h=>h.orientation()===L.ORIENTATION.CCW),c=o.filter(h=>h.orientation()===L.ORIENTATION.CW);if(!a)continue;a.reverse();let l=ntt(a),u=c.map(h=>(h.reverse(),{vertices:ntt(h)}));e.push({outer_ring:{vertices:l},inner_rings:u})}}return e},itt=class extends JJ{constructor(e){super(e);f(this,"pipelineDef",[]);this.input=e}getOutput(){let e=[];for(let t of this.input.regionsForPour){let i=Z9t(t),r=this.input.pads.filter(c=>c.layer===t.layer),{polygonsToSubtract:s}=e6t(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 h of l){let d=L.BooleanOperations.subtract(h,c);d&&(Array.isArray(d)?u.push(...d.filter(_=>!_.isEmpty())):d.isEmpty()||u.push(d))}o=u}let a=n6t(o);e.push(...a)}return{brep_shapes:e}}},rtt=(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 h=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])),_={...h,...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 C;k.pcb_port_id&&(C=l[k.pcb_port_id]),C||(C=`unconnected:${k.pcb_smtpad_id}`),k.shape==="rect"?x.push({shape:"rect",padId:k.pcb_smtpad_id,layer:k.layer,connectivityKey:C,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:C,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 C=u[k.pcb_plated_hole_id];C||(C=`unconnected-plated-hole:${k.pcb_plated_hole_id}`),x.push({shape:"circle",padId:k.pcb_plated_hole_id,layer:e.layer,connectivityKey:C,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 C=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:C,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 C=_[k.source_trace_id];if(!C)continue;let M=[],I=null,E=()=>{M.length>1&&x.push({shape:"trace",padId:`${k.pcb_trace_id}-${x.length}`,layer:e.layer,connectivityKey:C,segments:M,width:I}),M=[],I=null};for(let A of k.route){let R=A;R.route_type==="wire"&&R.layer===e.layer?(I===null&&(I=R.width),M.push({x:R.x,y:R.y})):E()}E()}let{width:v,height:P}=a,w=[{shape:"rect",layer:e.layer,bounds:{minX:-v/2,minY:-P/2,maxX:v/2,maxY:P/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:w}};Ta();St();Ae();var git=Gt(Zs(),1);var u9=Gt(En(),1),U_=Gt(Zs(),1),M1e=Gt(Zs(),1);var Ad=Gt(Md(),1);var xit=Gt(Md(),1),bit=Gt(Md(),1);var vit=Gt(Md(),1);var Sit=Gt(Md(),1);var wit=Gt(Md(),1),Pit=Gt(Zs(),1);var iOt=Object.defineProperty,rOt=(n,e)=>{for(var t in e)iOt(n,t,{get:e[t],enumerable:!0})},Wet={};rOt(Wet,{AnalogSimulation:()=>_it,Battery:()=>Knt,Board:()=>b9,Breakout:()=>Xnt,BreakoutPoint:()=>Unt,CadAssembly:()=>unt,CadModel:()=>lnt,Capacitor:()=>v9,Chip:()=>U1,Constraint:()=>Ant,CopperPour:()=>Znt,Crystal:()=>nit,Cutout:()=>B1,Diode:()=>S9,FabricationNoteDimension:()=>Fnt,FabricationNotePath:()=>Ont,FabricationNoteRect:()=>Rnt,FabricationNoteText:()=>Lnt,Footprint:()=>ont,Fuse:()=>Tnt,Group:()=>yl,Hole:()=>V_,Inductor:()=>P9,Jumper:()=>Mnt,Keepout:()=>Qw,Led:()=>Cnt,Mosfet:()=>iit,Net:()=>d9,NetLabel:()=>Vnt,NormalComponent:()=>Gn,Panel:()=>Pnt,PcbNoteDimension:()=>Bnt,PcbNoteLine:()=>znt,PcbNotePath:()=>jnt,PcbNoteRect:()=>$nt,PcbNoteText:()=>Dnt,PcbTrace:()=>m9,PinHeader:()=>Jnt,Pinout:()=>knt,PlatedHole:()=>Nd,Port:()=>Vi,Potentiometer:()=>tit,PowerSource:()=>Int,PrimitiveComponent:()=>Me,PushButton:()=>eit,Renderable:()=>p9,Resistor:()=>w9,Resonator:()=>Qnt,SchematicArc:()=>lit,SchematicBox:()=>pit,SchematicCell:()=>fit,SchematicCircle:()=>uit,SchematicLine:()=>ait,SchematicRect:()=>cit,SchematicRow:()=>dit,SchematicTable:()=>hit,SchematicText:()=>oit,SilkscreenCircle:()=>Gnt,SilkscreenLine:()=>Wnt,SilkscreenPath:()=>f9,SilkscreenRect:()=>Hnt,SilkscreenText:()=>rP,SmtPad:()=>j1,SolderJumper:()=>Ent,Subcircuit:()=>Ynt,Switch:()=>rit,Symbol:()=>mit,TestPoint:()=>sit,Trace:()=>Fs,TraceHint:()=>g9,Transistor:()=>k9,Via:()=>qnt,VoltageProbe:()=>yit,VoltageSource:()=>Nnt});var sOt=(0,Ket.default)("tscircuit:renderable"),Ua=["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","PcbTraceHintRender","PcbManualTraceRender","PcbTraceRender","PcbRouteNetIslands","PcbCopperPourRender","PcbDesignRuleChecks","SilkscreenOverlapAdjustment","CadModelRender","PartsEngineRender","SimulationSpiceEngineRender"],oOt={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"]},aOt=0,p9=class Jet{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=`${aOt++}`,this.children=[],this.renderPhaseStates={};for(let t of Ua)this.renderPhaseStates[t]={initialized:!1,dirty:!1}}_markDirty(e){this.renderPhaseStates[e].dirty=!0;let t=Ua.indexOf(e);for(let i=t+1;i<Ua.length;i++)this.renderPhaseStates[Ua[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
- ${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){sOt(`${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)}_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 Jet;)e=e.parent;return e}runRenderCycle(){for(let e of Ua)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=Ua.indexOf(e)-1;if(s>=0){let a=Ua[s];if(this._asyncEffects.filter(l=>l.phase===a).some(l=>!l.complete))return}let o=oOt[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))}},Jw={},Qet=n=>{let e=Object.fromEntries(Object.entries(n).map(([t,i])=>[t.toLowerCase(),i]));Object.assign(Jw,n),Object.assign(Jw,e)},cOt=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 h of u)typeof h=="string"&&(h.startsWith(" ")||h.endsWith(" "))&&s.push(`pinLabels.${c} ("${h}" 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 WA(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 h9={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=h9.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},lOt={...h9,getChildren:n=>n.children.filter(e=>!e.isSubcircuit)},get={...h9,getChildren:n=>n.children.filter(e=>e.isSubcircuit)},uOt=(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`},xet=(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(uOt(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()},qA={adapter:lOt,cacheResults:!0},Me=class extends p9{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 cOt(this.lowercaseComponentName,this.props,i.error.format())}get config(){return{componentName:"",zodProps:p.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}computePcbPropsTransform(){let{_parsedProps:e}=this,t=this._getPcbRotationBeforeLayout()??0;return mi(An(e.pcbX??0,e.pcbY??0),Dc(t*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 mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Sr(),mi(An(e.x,e.y),Dc(t*Math.PI/180)))}if(this.isPcbPrimitive){let t=this.getPrimitiveContainer();if(t&&t._parsedProps.layer==="bottom")return mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Sr(),NB(),this.computePcbPropsTransform())}return mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Sr(),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 mi(An(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){let e=this._getSchematicGlobalManualPlacementTransform(this);return e||mi(this.parent?.computeSchematicGlobalTransform?.()??Sr(),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 _i&&r===0)return u;if(a in _i&&r===90)return a;if(l in _i&&r===180)return l;if(c in _i&&r===270)return c;if(s in _i&&(r===0||r===180))return s;if(o in _i&&(r===90||r===270))return o;if(t in _i)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?_i[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(WA(e,r.selector)||e.props.name===r.selector)return $e(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(WA(e,r.selector)||e.props.name===r.selector)return $e(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((WA(e,i.selector)||e.props.name===i.selector)&&i.relative_to==="group_center")return mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Sr(),An(i.center.x,i.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return $e(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return $e(this.computeSchematicGlobalTransform(),{x:0,y:0})}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=xet(e,this),i=B5(t,this,qA);if(i.length>0)return this._cachedSelectAllQueries.set(e,i),i;let[r,...s]=t.split(" "),o=rS(r,this,{adapter:get});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=xet(e,this);t?.port&&(t.type="port");let r=null;if(t?.type&&(r=B5(i,this,qA).find(l=>l.lowercaseComponentName===t.type)),r??(r=rS(i,this,qA)),r)return this._cachedSelectOneQueries.set(e,r),r;let[s,...o]=i.split(" "),a=rS(s,this,{adapter:get});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()}},pOt=class extends Me{constructor(n,e){super(n),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:n.pcbX,pcbY:n.pcbY,schX:n.schX,schY:n.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:p.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 hOt(n,e){return new pOt(n,e)}function dOt(n,e){let t=n;return t.__tsci={...e},n}var fOt={supportsMutation:!0,createInstance(n,e){let t=Jw[n];if(!t)throw Object.keys(Jw).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 dOt(new t(e),{})}catch(i){return hOt({...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:()=>Ww.DefaultEventPriority,getCurrentUpdatePriority:()=>Ww.DefaultEventPriority,resolveUpdatePriority:()=>Ww.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},Uw=(0,Zet.default)(fOt),tnt=n=>{let e={children:[],props:{name:"$root"},add(s){s.parent=this,this.children.push(s)},computePcbGlobalTransform(){return Sr()}},t=[],i=Uw.createContainer(e,0,null,!1,null,"tsci",s=>{console.log("Error in createContainer"),console.error(s),t.push(s)},null);if(Uw.updateContainerSync(n,i,null,()=>{}),Uw.flushSyncWork(),t.length>0)throw t[0];let r=Uw.getPublicRootInstance(i);return r||e.children[0]},Y1=(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}"`)},mOt=(n,e)=>{if(!n)return;let t={},i={};for(let[r,s]of Object.entries(n)){let o=Y1(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},_Ot=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 ent(n){let e=[];for(let t=0;t<n.length-1;t++)e.push([n[t],n[t+1]]);return e}var yOt=p.object({name:p.string().refine(n=>!/[+-]/.test(n),n=>({message:`Net names cannot contain "+" or "-" (component "Net" received "${n}"). Try using underscores instead, e.g. VCC_P`}))}),d9=class extends Me{constructor(){super(...arguments);f(this,"source_net_id");f(this,"subcircuit_connectivity_map_key",null)}get config(){return{componentName:"Net",zodProps:yOt}}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=ent(r);for(let[o,a]of s){let c=o.ports.map(P=>P._getGlobalPcbPositionBeforeLayout()),l=a.ports.map(P=>P._getGlobalPcbPositionBeforeLayout()),u=1/0,h=[-1,-1];for(let P=0;P<c.length;P++){let w=c[P];for(let T=0;T<l.length;T++){let k=l[T],C=Math.sqrt((w.x-k.x)**2+(w.y-k.y)**2);C<u&&(u=C,h=[P,T])}}let d=o.ports[h[0]],_=a.ports[h[1]],g=e.toArray().filter(P=>P.type==="pcb_smtpad"||P.type==="pcb_trace"||P.type==="pcb_plated_hole"||P.type==="pcb_hole"||P.type==="source_port"||P.type==="pcb_port"),{solution:x}=xH(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)}},iP=(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 d9({name:t.split("net.")[1]});i.add(r)}}},j1=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:VH}}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(),h=(eo(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,d=.01,_=Math.abs(h)<d||Math.abs(h-180)<d||Math.abs(h-360)<d,g=Math.abs(h-90)<d||Math.abs(h-270)<d,x=Math.abs(h-360)<d?0:h,v=x,{maybeFlipLayer:P,isFlipped:w}=this._getPcbPrimitiveFlippedHelpers();w&&(x=(360-x+360)%360);let T=t.portHints?.map(M=>M.toString())??[],k=null,C=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(t.shape==="circle")k=e.pcb_smtpad.insert({pcb_component_id:C,pcb_port_id:this.matchedPort?.pcb_port_id,layer:P(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:C,pcb_port_id:this.matchedPort?.pcb_port_id,layer:P(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:C,pcb_port_id:this.matchedPort?.pcb_port_id,layer:P(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:P(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:P(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 M=t.ccwRotation??0,I=(v+M+360)%360,E=w?(360-I+360)%360:I;k=e.pcb_smtpad.insert({pcb_component_id:C,pcb_port_id:this.matchedPort?.pcb_port_id,layer:P(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: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}),r&&e.pcb_solder_paste.insert({layer:P(t.layer??"top"),shape:"rotated_rect",width:k.width*.7,height:k.height*.7,x:a.x,y:a.y,ccw_rotation:E,pcb_component_id:C,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 M=t.points.map(I=>{let E=$e(c,{x:Y.parse(I.x),y:Y.parse(I.y)});return{x:E.x,y:E.y}});k=e.pcb_smtpad.insert({pcb_component_id:C,pcb_port_id:this.matchedPort?.pcb_port_id,layer:P(t.layer??"top"),shape:"polygon",points: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})}else t.shape==="pill"&&(k=e.pcb_smtpad.insert({pcb_component_id:C,pcb_port_id:this.matchedPort?.pcb_port_id,layer:P(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)}},f9=class extends Me{constructor(){super(...arguments);f(this,"pcb_silkscreen_path_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:RW}}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=$e(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}}},gOt=p.object({route:p.array(Hx),source_trace_id:p.string().optional()}),m9=class extends Me{constructor(){super(...arguments);f(this,"pcb_trace_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:gOt}}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:h,...d}=l,_=$e(o,{x:u,y:h});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}}},Nd=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:LH}}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 h=typeof u.x=="number"?u.x:parseFloat(String(u.x)),d=typeof u.y=="number"?u.y:parseFloat(String(u.y));return{x:h,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})}},Qw=class extends Me{constructor(){super(...arguments);f(this,"pcb_keepout_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:_W}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let e=this.getSubcircuit(),{db:t}=this.root,{_parsedProps:i}=this,r=this._getGlobalPcbPositionBeforeLayout(),s=eo(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)}},V_=class extends Me{constructor(){super(...arguments);f(this,"pcb_hole_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:GH}}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})}},rP=class extends Me{constructor(){super(...arguments);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:AW}}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=eo(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"],h=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:h,layer:s(d),text: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}}},B1=class extends Me{constructor(){super(...arguments);f(this,"pcb_cutout_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:UH}}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,h={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(h)}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(),h={shape:"polygon",points:t.points.map(d=>$e(l,d)),subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=e.pcb_cutout.insert(h)}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})}}}},xOt=({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 rP({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})},bOt=(n,e)=>{let t=parseInt(n||"0",10),i;return e!=null?i=e-t:i=t,(i%360+360)%360},G_=({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 j1({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 j1({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 j1({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 f9({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?o.push(new Nd({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 Nd({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 Nd({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 Nd({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 Nd({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 Qw({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 Qw({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 V_({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_hole"&&a.hole_shape==="rect")o.push(new V_({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 V_({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 V_({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 B1({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height})):a.shape==="circle"?o.push(new B1({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius})):a.shape==="polygon"&&o.push(new B1({shape:"polygon",points:a.points}));else if(a.type==="pcb_silkscreen_text"){let c=bOt(e,a.ccw_rotation);t?.includes("pinrow")&&a.text.includes("PIN")?o.push(xOt({elm:a,pinLabels:r??i??{},layer:a.layer,readableRotation:c,anchorAlignment:a.anchor_alignment})):o.push(new rP({anchorAlignment:a.anchor_alignment||"center",text:n,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 m9({route:a.route}));return o};function sP(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:h,height:d}=c.getPcbSize();e=Math.min(e,l-h/2),t=Math.min(t,u-d/2),i=Math.max(i,l+h/2),r=Math.max(r,u+d/2),s=!0}else if(c.children.length>0){let l=sP(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 vOt(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 SOt(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)vOt(g,o,a,s)&&c.add(g);let u=1/0,h=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),P=e.y+t*Math.sin(x);u=Math.min(u,v),d=Math.max(d,v),h=Math.min(h,P),_=Math.max(_,P)}return!Number.isFinite(u)||!Number.isFinite(h)?null:{minX:u,maxX:d,minY:h,maxY:_}}function nnt(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,h=s.y1??0,d=s.x2??0,_=s.y2??0;o=(u+d)/2,a=(h+_)/2,c=Math.abs(d-u),l=Math.abs(_-h)}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=SOt(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 wOt(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 vet=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},wet=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}},POt=p.object({name:p.string().optional(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),layer:p.string().optional(),layers:p.array(p.string()).optional(),schX:p.number().optional(),schY:p.number().optional(),direction:p.enum(["up","down","left","right"]).optional(),connectsTo:p.union([p.string(),p.array(p.string())]).optional()}),Vi=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:POt}}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=mi(i.computeSchematicGlobalTransform(),An(-r.center.x,-r.center.y));return $e(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 $e(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},h=this.getSubcircuit(),d=e.pcb_port.insert({pcb_component_id:void 0,layers:c.getAvailablePcbLayers(),subcircuit_id:h?.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(!vet(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=wet(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 h=e.pcb_port.get(u.pcb_port_id),d={x:h.x,y:h.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{vet(t)&&(i=wet(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=wOt(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}`}},int=n=>{let e=n.find(t=>/^(pin)?\d+$/.test(t));return e?Number.parseInt(e.replace(/^pin/,"")):null};function F1(n,e){let t=int(n);if(!t)return null;let r=[...n.filter(s=>s.toString()!==t.toString()&&s!==`pin${t}`),...e?.additionalAliases?.[`pin${t}`]??[]];return new Vi({pinNumber:t,aliases:r})}var kOt=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},TOt=n=>{if(kOt(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}},Vw=.4;function rnt(n){let e=n;return e.leftSide!==void 0||e.rightSide!==void 0||e.topSide!==void 0||e.bottomSide!==void 0}var MOt=n=>{let e=n.portDistanceFromEdge??.4,t=n.schPortArrangement?TOt(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||!rnt(n.schPortArrangement))return v+1;let P={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[g],w=n.schPortArrangement?.[`${g}Side`]?.direction??P,T=n.schPortArrangement?.[`${g}Side`]?.pins,k=x;return w!==P&&(k=T.length-x-1),Y1(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+Vw,i.bottom+Vw),n.pinLabels&&o.filter(w=>w.side==="left"||w.side==="right").some(w=>n.pinLabels?.[`pin${w.pinNumber}`]||n.pinLabels?.[w.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+Vw,i.right+Vw));let h={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,P=h[v],w=d[v];return{x:P.x+x*w.x,y:P.y+x*w.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}},EOt=(0,snt.default)("tscircuit:core:footprint"),ont=class extends Me{get config(){return{componentName:"Footprint",zodProps:WH}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let n=this.children.filter(h=>h.componentName==="Constraint");if(n.length===0)return;let{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers(),t=h=>e&&"left"in h&&"right"in h?{...h,left:h.right,right:h.left}:h,i=n.flatMap(h=>h._getAllReferencedComponents().componentsWithSelectors).map(({component:h,selector:d,componentSelector:_,edge:g})=>({component:h,selector:d,componentSelector:_,edge:g,bounds:h._getPcbCircuitJsonBounds()}));if(i.some(h=>h.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function r(h){return i.find(({selector:d})=>d===h)}let s=new i_,o={};function a(h){return h in o||(o[h]=new Ia(h),s.addEditVariable(o[h],Rn.weak)),o[h]}for(let{selector:h,bounds:d}of i){let _=a(`${h}_x`),g=a(`${h}_y`);s.suggestValue(_,d.center.x),s.suggestValue(g,d.center.y)}for(let h of n){let d=h._parsedProps;if("xDist"in d){let{xDist:_,left:g,right:x,edgeToEdge:v,centerToCenter:P}=t(d),w=a(`${g}_x`),T=a(`${x}_x`),k=r(g)?.bounds,C=r(x)?.bounds;if(P){let M=new $n(T,[-1,w]);s.addConstraint(new wi(M,si.Eq,d.xDist,Rn.required))}else if(v){let M=new $n(T,-C.width/2,[-1,w],-k.width/2);s.addConstraint(new wi(M,si.Eq,d.xDist,Rn.required))}}else if("yDist"in d){let{yDist:_,top:g,bottom:x,edgeToEdge:v,centerToCenter:P}=d,w=a(`${g}_y`),T=a(`${x}_y`),k=r(g)?.bounds,C=r(x)?.bounds;if(P){let M=new $n(w,[-1,T]);s.addConstraint(new wi(M,si.Eq,d.yDist,Rn.required))}else if(v){let M=new $n(w,k.height/2,[-1,T],-C.height/2);s.addConstraint(new wi(M,si.Eq,d.yDist,Rn.required))}}else if("sameY"in d){let{for:_}=d;if(_.length<2)continue;let g=_.map(v=>a(`${v}_y`)),x=new $n(...g.slice(1));s.addConstraint(new wi(x,si.Eq,g[0],Rn.required))}else if("sameX"in d){let{for:_}=d;if(_.length<2)continue;let g=_.map(v=>a(`${v}_x`)),x=new $n(...g.slice(1));s.addConstraint(new wi(x,si.Eq,g[0],Rn.required))}}s.updateVariables(),EOt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(o).map(([h,d])=>({var:h,val:d.value()}))));let c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:h,bounds:{width:d,height:_}}of i){let g=a(`${h}_x`),x=a(`${h}_y`),v=g.value()-d/2,P=g.value()+d/2,w=x.value()+_/2,T=x.value()-_/2;c.left=Math.min(c.left,v),c.right=Math.max(c.right,P),c.top=Math.max(c.top,w),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:h,selector:d}of i){let _=a(`${d}_x`),g=a(`${d}_y`);h._setPositionFromLayout({x:_.value()+l.x,y:g.value()+l.y})}}},ant=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},COt=(n,e)=>{let t=n.replace(/\/+$/,""),i=e.replace(/^\/+/,"");return`${t}/${i}`},cnt=(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():COt(e,n)}catch{return n}},ZA=p.union([p.number(),p.string()]),Pet=p.object({x:ZA,y:ZA,z:ZA}),lnt=class extends Me{get config(){return{componentName:"CadModel",zodProps:xW}}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=eo(o).rotation.angle*180/Math.PI,l=Pet.parse({x:0,y:0,z:0});if(typeof s.rotationOffset=="number")l.z=Number(s.rotationOffset);else if(typeof s.rotationOffset=="object"){let v=Pet.parse(s.rotationOffset);l.x=Number(v.x),l.y=Number(v.y),l.z=Number(v.z)}let u=fS.parse({x:s.pcbX??0,y:s.pcbY??0,z:s.pcbZ??0,...typeof s.positionOffset=="object"?s.positionOffset:{}}),h=s.zOffsetFromSurface!==void 0?Y.parse(s.zOffsetFromSurface):0,d=n.props.layer==="bottom"?"bottom":"top",_=s.modelUrl?ant(s.modelUrl):void 0,g={};if(_==="stl"?g.model_stl_url=this._addCachebustToModelUrl(s.modelUrl):_==="obj"?g.model_obj_url=this._addCachebustToModelUrl(s.modelUrl):_==="gltf"?g.model_gltf_url=this._addCachebustToModelUrl(s.modelUrl):_==="glb"?g.model_glb_url=this._addCachebustToModelUrl(s.modelUrl):_==="step"||_==="stp"?g.model_step_url=this._addCachebustToModelUrl(s.modelUrl):_==="wrl"||_==="vrml"?g.model_wrl_url=this._addCachebustToModelUrl(s.modelUrl):g.model_stl_url=this._addCachebustToModelUrl(s.modelUrl),s.stepUrl){let v=this._addCachebustToModelUrl(s.stepUrl);v&&(g.model_step_url=v)}let x=e.cad_component.insert({position:{x:i.center.x+Number(u.x),y:i.center.y+Number(u.y),z:(d==="bottom"?-t/2:t/2)+(d==="bottom"?-h:h)+Number(u.z)},rotation:{x:Number(l.x),y:(d==="top"?0:180)+Number(l.y),z:d==="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,...g});this.cad_component_id=x.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=cnt(n,e);if(!t.includes("modelcdn.tscircuit.com"))return t;let i=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(i)}`}},unt=class extends Me{constructor(){super(...arguments);f(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:gW}}},IOt=(n,e)=>{if(!n)return;let t={};for(let[i,r]of Object.entries(n)){let s=Y1(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},ket=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}},NOt=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}},Tet=["top","bottom","inner1","inner2"],qw=(n,e=[])=>{let t=[];if(e.length===0){let a=n[0].layers;for(let c of a)t.push(...qw(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)?[]:qw(n.slice(1),e.concat([s]));let o=(i.optional_via?Tet:Tet.filter(a=>a!==s)).filter(a=>!i.layers||i.layers?.includes(a));for(let a of o)t.push(...qw(n.slice(1),e.concat(a)));return t};function Met(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 j_(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}var AOt=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(j_(t,r),j_(t,s)),a=Math.min(j_(i,r),j_(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],h=u[0],d=u[u.length-1],_=j_(l,h),g=j_(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},ROt=(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 OOt(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=ROt(n,r);s<i&&(t=r,i=s)}return t}var LOt=(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},X1=n=>({up:"bottom",down:"top",left:"right",right:"left"})[n]??null,n9=({firstEdge:n,firstEdgePort:e,firstDominantDirection:t,lastEdge:i,lastEdgePort:r,lastDominantDirection:s})=>{if(n&&e)return n9({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=>Fi(a.from,a.to)>.01),o};function FOt(n){try{return[n(),null]}catch(e){return[null,e]}}var zOt=(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 $Ot({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 DOt=(n,{db:e})=>{let t=e.pcb_board.list()[0];if(t.outline){let c=t.outline,l=(u,h)=>{let d=!1;for(let _=0,g=h.length-1;_<h.length;g=_++){let x=h[_].x,v=h[_].y,P=h[g].x,w=h[g].y;v>u.y!=w>u.y&&u.x<(P-x)*(u.y-v)/(w-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)},Eet=(n,e)=>Math.abs(n-e)<1e-4,jOt=(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=Eet(s.y,o.y),l=Eet(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 h={type:"rect",layers:[s.layer,o.layer],center:{x:s.x,y:s.y},connectedTo:[e],width:t,height:t};i.push(h)}}return i};function BOt(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,P=d*1.1,w=Math.abs(r*c)+Math.abs(d*l);o.push({center:{x:t.x+x,y:t.y+v},width:P,height:w})}}else{let d=r/e;for(let _=0;_<e;_++){let g=(_-e/2+.5)*d,x=-g*l,v=g*c,P=Math.abs(i*c)+Math.abs(d*l),w=d*1.1;o.push({center:{x:t.x+x,y:t.y+v},width:P,height:w})}}return o}function YOt(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 h=n[u],d=n[(u+1)%n.length];if(h.y<=c&&d.y>c||d.y<=c&&h.y>c){let _=(c-h.y)*(d.x-h.x)/(d.y-h.y)+h.x;l.push(_)}}l.sort((u,h)=>u-h);for(let u=0;u<l.length;u+=2)if(u+1<l.length){let h=l[u],_=l[u+1]-h;_>1e-6&&i.push({center:{x:h+_/2,y:c},width:_,height:t})}}return i}function XOt(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 Go=["top","inner1","inner2","bottom"],pnt=(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=BOt(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:Go,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.shape==="circle"){let s=XOt({center:r.center,radius:r.radius},{rectHeight:.6});for(let o of s)i.push({type:"rect",layers:Go,center:o.center,width:o.width,height:o.height,connectedTo:[]})}else if(r.shape==="polygon"){let s=YOt(r.points,{rectHeight:.6});for(let o of s)i.push({type:"rect",layers:Go,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:Go,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:Go,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:Go,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:Go,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:Go,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:Go,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),h=(a+c)/2,d=(l+u)/2;i.push({type:"rect",layers:Go,center:{x:h,y:d},width:c-a,height:u-l,connectedTo:t([r.pcb_plated_hole_id])})}}else if(r.type==="pcb_trace"){let s=jOt(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},_l=({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},_9=({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},UOt=({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(Na([r.from,r.to],[x.from,x.to],{lineThickness:.01})){let w=s==="vertical"?r.from.x:x.from.x,T=s==="vertical"?x.from.y:r.from.y,k={x:w,y:T};o.push({otherEdge:x,crossingPoint:k,distanceFromEdgeFrom:Fi(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=PS(r.from,c),h={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},_=Fi(d,r.to)<l,g=[{from:r.from,to:h},{from:h,to:d,is_crossing:!0},{from:d,to:r.to}];t.splice(i,1,...g),i+=g.length-2,_&&i++}return t},i9=.001,B_=(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},Cet=n=>{let e=Math.abs(n.from.x-n.to.x)<i9,t=Math.abs(n.from.y-n.to.y)<i9;return e?"vertical":t?"horizontal":"diagonal"},VOt=(n,e)=>{let t=Cet(n),i=Cet(e);if(t===i)return null;if(t==="vertical"&&i==="horizontal"||t==="horizontal"&&i==="vertical"){let h=t==="vertical"?n:e,d=t==="horizontal"?n:e,_=h.from.x,g=d.from.y,x={x:_,y:g};return B_(x,n)&&B_(x,e)?x:null}if(t==="vertical"||i==="vertical"){let h=t==="vertical"?n:e,d=t==="vertical"?e:n,_=h.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,P={x:_,y:v};return B_(P,n)&&B_(P,e)?P: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)<i9)return null;let c=(a-s)/(r-o),l=r*c+s,u={x:c,y:l};return B_(u,n)&&B_(u,e)?u:null},GOt=({edges:n,db:e,source_trace_id:t})=>{let i=_9({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=VOt(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 HOt(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,h=.01;return[{type:"rect",layers:["top"],center:{x:(a+c)/2,y:l},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(a+c)/2,y:u},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:a,y:(l+u)/2},width:h,height:l-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:c,y:(l+u)/2},width:h,height:l-u,connectedTo:[]}]}var WOt=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?kS(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=nnt(e.toArray());return r.push(...HOt(s,{padding:1})),r},qOt=({edges:n,db:e,source_trace_id:t})=>{let i=e.source_trace.get(t),r=_9({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&&Na([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()}},r9=n=>{switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},ZOt=oq.version??"unknown",z1=class extends Error{constructor(n){super(`${n} (capacity-autorouter@${ZOt})`),this.name="AutorouterError"}},tP=class extends Error{constructor(n){super(n.message),this.errorData=n,this.name="TraceConnectionError"}},KOt=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 V=n._findConnectedPorts();r=V.allPortsFound,s=V.portsWithSelectors??[]}catch(V){if(V instanceof tP){e.source_trace_not_connected_error.insert({...V.errorData,error_type:"source_trace_not_connected_error"});return}throw V}let{netsWithSelectors:o}=n._findConnectedNets();if(!r)return;let c=s.map(V=>V.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:[]},h=WOt(n),d=s.filter(({port:V})=>V.schematic_port_id!==null).map(({port:V})=>({port:V,position:V._getGlobalSchematicPositionAfterLayout(),schematic_port_id:V.schematic_port_id??void 0,facingDirection:V.facingDirection}));if(d.length===1&&o.length===1){let V=o[0].net,{port:H,position:et}=d[0],tt=n.getSubcircuit().selectAll("netlabel").find(Q=>{let nt=Q._parsedProps.connection??Q._parsedProps.connectsTo;return nt?Array.isArray(nt)?nt.some(ht=>n.getSubcircuit().selectOne(ht,{port:!0})===H):n.getSubcircuit().selectOne(nt,{port:!0})===H:!1});if(!tt){let Q=e.schematic_net_label.getWhere({source_trace_id:n.source_trace_id});Q&&(tt=Q)}if(tt){let Q="_getGlobalSchematicPositionBeforeLayout"in tt?tt._getGlobalSchematicPositionBeforeLayout():tt.anchor_position,nt=[];et.x===Q.x||et.y===Q.y?nt.push({from:et,to:Q}):(nt.push({from:et,to:{x:Q.x,y:et.y}}),nt.push({from:{x:Q.x,y:et.y},to:Q}));let pt=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:nt,junctions:[],subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=pt.schematic_trace_id;return}if(n.props.schDisplayLabel){let Q=X1(H.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel,source_net_id:V.source_net_id,anchor_position:et,center:_l({anchor_position:et,anchor_side:Q,text:n.props.schDisplayLabel}),anchor_side:Q});return}let mt=X1(H.facingDirection)??"bottom",G=e.schematic_net_label.insert({text:V._parsedProps.name,source_net_id:V.source_net_id,anchor_position:et,center:_l({anchor_position:et,anchor_side:mt,text:V._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 V=[];for(let et=0;et<d.length-1;et++){let tt=d[et],mt=d[et+1],G=qc({x:tt.position.x,y:tt.position.y,facingDirection:r9(tt.facingDirection)},{x:mt.position.x,y:mt.position.y,facingDirection:r9(mt.facingDirection)});for(let Q=0;Q<G.length-1;Q++)V.push({from:G[Q],to:G[Q+1]})}let H=(et,tt)=>{let mt=tt.width/2,G=tt.height/2,Q=tt.center.x-mt,nt=tt.center.x+mt,pt=tt.center.y-G,ht=tt.center.y+G,wt=ot=>ot.x>=Q&&ot.x<=nt&&ot.y>=pt&&ot.y<=ht;return wt(et.from)||wt(et.to)?!0:[[{x:Q,y:pt},{x:nt,y:pt}],[{x:nt,y:pt},{x:nt,y:ht}],[{x:nt,y:ht},{x:Q,y:ht}],[{x:Q,y:ht},{x:Q,y:pt}]].some(ot=>Na([et.from,et.to],ot,{lineThickness:0}))};for(let et of V)for(let tt of h)if(H(et,tt))return null;return V})();x&&x.length===0&&(x=null),u.pointsToConnect=d.map(({position:V})=>({...V,layer:"top"}));let v=NOt(h),P=2,w={minTraceWidth:.1,obstacles:h,connections:[u],bounds:{minX:v.minX-P,maxX:v.maxX+P,minY:v.minY-P,maxY:v.maxY+P},layerCount:1},T=pS,k=!1;if(n.getSubcircuit().props._schDirectLineRoutingEnabled&&(T=ket,k=!0),!x){let H=new T({input:w,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(H.length===0){if(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection()){n._doInitialSchematicTraceRenderWithDisplayLabel();return}H=new ket({input:w}).solveAndMapToTraces(),k=!0}let[{route:et}]=H;x=[];for(let tt=0;tt<et.length-1;tt++)x.push({from:et[tt],to:et[tt+1]})}let C=n.source_trace_id,M=[];if(!k){qOt({edges:x,db:e,source_trace_id:C});let V=_9({db:e,source_trace_id:C,differentNetOnly:!0}).flatMap(H=>H.edges);x=UOt({edges:x,otherEdges:V}),M=GOt({edges:x,db:e,source_trace_id:n.source_trace_id})}if(!x||x.length===0)return;let I=x[x.length-1],E=d[d.length-1],A=Met(I);x.push(...n9({lastEdge:I,lastEdgePort:E,lastDominantDirection:A}));let R=x[0],B=d[0],j=Met(R);if(x.unshift(...n9({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&&LOt(M,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:M,subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=U.schematic_trace_id;for(let{port:V}of s)V.schematic_port_id&&e.schematic_port.update(V.schematic_port_id,{is_connected:!0});l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.add(c)};function s9(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 JOt=.3,QOt=.6,Iet=(n,e)=>{if(n===void 0)return e;if(typeof n=="number")return n;let t=parseFloat(n);return Number.isFinite(t)?t:e},y9=n=>({holeDiameter:Iet(n?.viaHoleDiameter,JOt),padDiameter:Iet(n?.viaPadDiameter,QOt)}),tLt=(n,e)=>{let t=y9(e);return{holeDiameter:n.holeDiameter??t.holeDiameter,padDiameter:n.padDiameter??t.padDiameter}},Gw=n=>({...n._getGlobalPcbPositionAfterLayout(),layers:n.getAvailablePcbLayers()}),eLt=!1;function nLt(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],V=u[0].net.getAllConnectedPorts().filter(et=>et!==j);if(V.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let H=OOt(j,V);c.push(H),a.push(H)}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 h=a.flatMap(j=>j.matchedComponents.filter(U=>U.componentName==="TraceHint")),d=(n._parsedProps.pcbRouteHints??[]).concat(h.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=[Gw(a[0]),Gw(a[1])]:x=[Gw(a[0]),...d,Gw(a[1])];let v=qw(x);if(eLt&&v.length===0){n.renderError(`Could not find a common layer (using hints) for trace ${n.getString()}`);return}let P=tr(n.root.db.toArray()),[w,T]=FOt(()=>pnt(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 w)if(j.connectedTo.length>0){let V=P.getNetConnectedToId(j.connectedTo[0]);V&&j.connectedTo.push(V)}let k=[];if(v.length===0)k=x;else{let j=v[0].layer_path;k=x.map((U,V)=>U.via?{...U,via_to_layer:j[V]}:{...U,layers:[j[V]]})}k[0].pcb_port_id=a[0].pcb_port_id,k[k.length-1].pcb_port_id=a[1].pcb_port_id;let C=[];for(let[j,U]of ent(k)){let V="via_to_layer"in j?j.via_to_layer:null,H=2,et="layers"in j&&j.layers.length===1?j.layers[0]:V??"top",tt="layers"in U&&U.layers.length===1?U.layers[0]:V??"top",mt="pcb_port_id"in j?j.pcb_port_id:null,G="pcb_port_id"in U?U.pcb_port_id:null,Q=n._getExplicitTraceThickness()??n.getSubcircuit()._parsedProps.minTraceWidth??.16,nt=new pS({OBSTACLE_MARGIN:Q*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(mt&&G),connMap:P,input:{obstacles:w,minTraceWidth:Q,connections:[{name:n.source_trace_id,pointsToConnect:[{...j,layer:et,pcb_port_id:mt},{...U,layer:tt,pcb_port_id:G}]}],layerCount:n.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(j.x,U.x)-H,maxX:Math.max(j.x,U.x)+H,minY:Math.min(j.y,U.y)-H,maxY:Math.max(j.y,U.y)+H}}}),pt=null;try{pt=nt.solveAndMapToTraces()}catch(Et){n.renderError({type:"pcb_trace_error",pcb_trace_error_id:n.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${Et.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(!pt)return;if(pt.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(Et=>Et.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:a.map(Et=>Et.pcb_component_id)});return}let[ht]=pt;V&&(ht.route=ht.route.map(Et=>(Et.route_type==="wire"&&!Et.layer&&(Et.layer=V),Et))),mt&&ht.route[0].route_type==="wire"&&(ht.route[0].start_pcb_port_id=mt);let wt=ht.route[ht.route.length-1];G&&wt.route_type==="wire"&&(wt.end_pcb_port_id=G),C.push(ht.route)}let M=AOt(C),I=s9(M),E=n.getInheritedMergedProperty("pcbStyle"),{holeDiameter:A,padDiameter:R}=y9(E),B=e.pcb_trace.insert({route:M,source_trace_id:n.source_trace_id,subcircuit_id:n.getSubcircuit()?.subcircuit_id,trace_length:I});n._portsRoutedOnPcb=a,n.pcb_trace_id=B.pcb_trace_id;for(let j of M)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(M,a)}function iLt(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,C]=a,M=k.getAvailablePcbLayers(),I=C.getAvailablePcbLayers(),A=M.find(H=>I.includes(H))??M[0]??I[0]??"top",R=k._getGlobalPcbPositionAfterLayout(),B=C._getGlobalPcbPositionAfterLayout(),j=[{route_type:"wire",x:R.x,y:R.y,width:u,layer:A,start_pcb_port_id:k.pcb_port_id},{route_type:"wire",x:B.x,y:B.y,width:u,layer:A,end_pcb_port_id:C.pcb_port_id}],U=s9(j),V=e.pcb_trace.insert({route:j,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:U});n._portsRoutedOnPcb=a,n.pcb_trace_id=V.pcb_trace_id,n._insertErrorIfTraceIsOutsideBoard(j,a);return}if(!t.pcbPath)return;let h;t.pcbPathRelativeTo&&(h=c.find(k=>k.selector===t.pcbPathRelativeTo)?.port,h||(h=n.getSubcircuit().selectOne(t.pcbPathRelativeTo))),h||(h=a[0]);let d=a.find(k=>k!==h)??a[1],_=h.getAvailablePcbLayers()[0]||"top",g=h._getGlobalPcbPositionAfterLayout(),x=d._getGlobalPcbPositionAfterLayout(),v=[];v.push({route_type:"wire",x:g.x,y:g.y,width:u,layer:_,start_pcb_port_id:h.pcb_port_id});let P=h?._computePcbGlobalTransformBeforeLayout?.()||Sr();for(let k of t.pcbPath){let C,M=!1;if(typeof k=="string"){let E=n.getSubcircuit().selectOne(k,{type:"port"});if(!E){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=E._getGlobalPcbPositionAfterLayout();C={x:A.x,y:A.y},M=!0}else C={x:k.x,y:k.y},M=!1;let I=M?C:$e(P,C);v.push({route_type:"wire",x:I.x,y:I.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 w=s9(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:w});n._portsRoutedOnPcb=a,n.pcb_trace_id=T.pcb_trace_id,n._insertErrorIfTraceIsOutsideBoard(v,a)}function rLt(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 h=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),w=x.parent?.config.shouldRenderAsSchematicBox?`${x?.parent?.props.name}_${x?.props.name}`:`${v?.parent?.props.name}_${v?.props.name}`,T=n.props.schDisplayLabel??w;if(_&&_.text!==T&&(_.text=`${T} / ${_.text}`),g&&g?.text!==T&&(g.text=`${T} / ${g.text}`),!g){let k=X1(d.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??w,source_net_id:d.source_port_id,anchor_position:h,center:_l({anchor_position:h,anchor_side:k,text:n.props.schDisplayLabel??w}),anchor_side:k})}if(!_){let k=X1(u.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??w,source_net_id:u.source_port_id,anchor_position:l,center:_l({anchor_position:l,anchor_side:k,text:n.props.schDisplayLabel??w}),anchor_side:k})}}function sLt(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}"`,C=n.getSubcircuit(),M=C.getGroup();throw new tP({error_type:"source_trace_not_connected_error",message:k,subcircuit_id:C.subcircuit_id??void 0,source_group_id:M?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[s]})}let h=u.children.filter(k=>k.componentName==="Port"),d=c.includes(".")?c.split(".").pop()??"":c,_=h.flatMap(k=>k.getNameAndAliases()),g=_.some(k=>!/^(pin\d+|\d+)$/.test(k)),x=Array.from(new Set(_)).join(", "),v;h.length===0?v="It has no ports":g?v=`It has [${x}]`:v=`It has ${h.length} pins and no pinLabels (consider adding pinLabels)`;let P=`Could not find port for selector "${s}". Component "${u.props.name??a}" found, but does not have pin "${d}". ${v}`,w=n.getSubcircuit(),T=w.getGroup();throw new tP({error_type:"source_trace_not_connected_error",message:P,subcircuit_id:w.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 Fs=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 sLt(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(){iP(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 h=this._findConnectedPorts();r=h.allPortsFound,s=h.portsWithSelectors??[]}catch(h){if(h instanceof tP){e.source_trace_not_connected_error.insert({...h.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw h}if(!r)return;this._traceConnectionHash=this._computeTraceConnectionHash();let a=e.source_trace.list().find(h=>h.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&h.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=$Ot({ports:s,nets:c}),u=e.source_trace.insert({connected_source_port_ids:s.map(h=>h.port.source_port_id),connected_source_net_ids:c.map(h=>h.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:zOt(s.map(h=>h.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;DOt(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(){iLt(this)}doInitialPcbTraceRender(){nLt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){rLt(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(){KOt(this)}},oLt=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=Oo(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},aLt=(n,e)=>{let{db:t}=n.root,i=t.toArray();if(n.pcb_component_id){TS(i,n.pcb_component_id,e);return}if(n.source_group_id){MS(i,n.source_group_id,e);return}throw new Error(`Cannot reposition component ${n.getString()}: no pcb_component_id or source_group_id`)},cLt=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&&lLt(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"}))},lLt=(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 uLt(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 pLt(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 io(u)});for(let c of r){let l=c.anchor_position,u=uLt(c),h={center:{x:u.x+u.width/2,y:u.y+u.height/2},width:u.width,height:u.height},d=io(h);if(!a.some(T=>Wc(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},P=io(v);a.some(T=>Wc(P,T))||e.pcb_silkscreen_text.update(c.pcb_silkscreen_text_id,{anchor_position:{x:g,y:x}})}}function hLt(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)dLt(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 dLt(n,e){try{let t={name:"test",footprint:"test",pinLabels:{[n]:e}};return n_.safeParse(t).success}catch{return!1}}var H_=n=>n.startsWith("http://")||n.startsWith("https://"),a9=n=>{if(H_(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}},c9=n=>n.startsWith("/"),fLt=(0,hnt.default)("tscircuit:core:resolveStaticFileImport");async function dnt(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){fLt("failed to resolve static file via platform resolver",i)}return cnt(n,e?.projectBaseUrl)}function mLt(n,e){let{footprint:t}=n.props;if(t??(t=n._getImpliedFootprintString?.()),!t)return;let{pcbRotation:i,pinLabels:r,pcbPinLabels:s}=n.props,o=ant(String(t)),a=o?n.root?.platform?.footprintFileParserMap?.[o]:null;if(typeof t=="string"&&(H_(t)||c9(t))&&a){if(n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0,e("load-footprint-from-platform-file-parser",async()=>{let c=H_(t)?t:await dnt(t,n.root?.platform);try{let l=await a.loadFromUrl(c),u=G_({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 h=n.getSubcircuit(),d=`${n.getString()} failed to load footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Rm.parse({type:"external_footprint_load_error",message:d,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:h.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"&&H_(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(),h=G_({componentName:n.name,componentRotation:i,footprinterString:c,pinLabels:r,pcbPinLabels:s},u);n.addAll(h),n._markDirty("InitializePortsFromChildren")}catch(l){let u=n.root?.db;if(u&&n.source_component_id&&n.pcb_component_id){let h=n.getSubcircuit(),d=`${n.getString()} failed to load external footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Rm.parse({type:"external_footprint_load_error",message:d,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:h.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=a9(t);if(!c||n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let u=n.root?.platform?.footprintLibraryMap?.[c.footprintLib],h;if(typeof u=="function"&&(h=u),!h)return;let d=n.getInheritedMergedProperty("pcbStyle");e("load-lib-footprint",async()=>{try{let _=await h(c.footprintName,{resolvedPcbStyle:d}),g=null;if(Array.isArray(_)?g=_:Array.isArray(_.footprintCircuitJson)&&(g=_.footprintCircuitJson),!g)return;let x=G_({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(_)),P=Rm.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(P)}throw _}});return}if(!(0,o9.isValidElement)(t)&&t.componentName==="Footprint"&&n.add(t),Array.isArray(t)&&!(0,o9.isValidElement)(t)&&t.length>0){try{let c=G_({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(),h=`${n.getString()} failed to load json footprint: `+(c instanceof Error?c.message:String(c)),d=qx.parse({type:"circuit_json_footprint_load_error",message:h,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 _Lt(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=sP(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 yLt=(0,qet.default)("tscircuit:core"),gLt=p.object({x:Qe,y:Qe,z:Qe}),Gn=class extends Me{constructor(e){let t={...e},i=[];if(t.pinLabels&&!Array.isArray(t.pinLabels)){let{validPinLabels:r,invalidPinLabelsMessages:s}=hLt(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 h of u){let d=Y1(h,this._parsedProps.pinLabels);i.push(new Vi({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 h=0;h<u;h++)i.push(new Vi({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,h=Array.isArray(c)?c.slice(1):[];l?(l.externallyAddedAliases.push(u,...h),l.props.name=u):(l=new Vi({pinNumber:parseInt(a),name:u,aliases:[...h,...e.additionalAliases?.[`pin${parseInt(a)}`]??[]]},{originDescription:`pinLabels:pin${a}`}),i.push(l))}if(t.schematicSymbolName&&!e.ignoreSymbolPorts){let a=_i[this._getSchematicSymbolNameOrThrow()];if(!a)return;for(let c of a.ports){let l=int(c.labels);if(!l)continue;let u=i.find(h=>h._parsedProps.pinNumber===Number(l));if(u)u.schematicSymbolPortDef=c;else{let h=F1(c.labels.concat(e.additionalAliases?.[`pin${l}`]??[]));h&&(h.originDescription=`schematicSymbol:labels[0]:${c.labels[0]}`,h.schematicSymbolPortDef=c,i.push(h))}}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 Vi({pinNumber:a,aliases:e.additionalAliases?.[`pin${a}`]??[]}));continue}let c=[...r.leftSide?.pins??[],...r.rightSide?.pins??[],...r.topSide?.pins??[],...r.bottomSide?.pins??[]].map(l=>Y1(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 Vi({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(H_(r)||c9(r)||a9(r))return;let s=vM.string(r).soup(),o=G_({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,Va.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=Gx.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=_i[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:_Ot(o),pin_spacing:t.schPinSpacing??.2,pin_styles:mOt(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,h=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 h=Om.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(h)}let s=this._computePcbGlobalTransformBeforeLayout(),a=eo(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 h=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=h.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 h=Zx.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(h)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:e}=this.root,{_parsedProps:t}=this,i=sP(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 h of u){if(h.isSchematicPrimitive&&h.componentName==="SchematicLine"){let d=e.schematic_line.get(h.schematic_line_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicRect"){let d=e.schematic_rect.get(h.schematic_rect_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicCircle"){let d=e.schematic_circle.get(h.schematic_circle_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicArc"){let d=e.schematic_arc.get(h.schematic_arc_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicText"){let d=e.schematic_text.get(h.schematic_text_id);d&&i.push(d)}h.children&&h.children.length>0&&r(h.children)}};if(r(this.children),i.length===0)return;let s=nnt(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(){_Lt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(e){let t=tnt(e);return{element:e,component:t}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let e=this.props.footprint;(0,Va.isValidElement)(e)&&(this.children.some(s=>s.componentName==="Footprint")||this.add(e));let t=this.props.symbol;(0,Va.isValidElement)(t)&&(this.children.some(s=>s.componentName==="Symbol")||this.add(t));let i=this.props.cadModel;if((0,Va.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(){mLt(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,Va.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&&yLt(`Similar ports added. Port 1: ${r}, Port 2: ${t}`)}super.add(t)}getPortsFromFootprint(e){let{footprint:t}=this.props;if((!t||(0,Va.isValidElement)(t))&&(t=this.children.find(r=>r.componentName==="Footprint")),typeof t=="string"){if(H_(t))return[];if(c9(t))return[];if(a9(t))return[];let r=vM.string(t).soup(),s=[];for(let o of r)if("port_hints"in o&&o.port_hints){let a=F1(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,Va.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(h=>h.startsWith("pin"))||(c=[...c,`pin${s}`]),s++;let u=F1(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=F1(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=_i[e.schematicSymbolName];if(!t)return[];let i=[];for(let r of t.ports){let s=F1(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){iP(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(!rnt(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 MOt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:i,numericSchPinStyle:IOt(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=gLt.parse({x:0,y:0,z:typeof r?.rotationOffset=="number"?r.rotationOffset:0,...typeof r?.rotationOffset=="object"?r.rotationOffset??{}:{}}),c=Dh.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?Y.parse(r.zOffsetFromSurface):0,u=this.props.layer==="bottom"?"bottom":"top",h=this._computePcbGlobalTransformBeforeLayout(),_=eo(h).rotation.angle*180/Math.PI,g=u==="bottom",x=_+(a.z??0),v=ad(x),P=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:ad(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});this.cad_component_id=P.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=Ux.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 Fs({from:`.${this.name} > .${t}`,to:String(s)}))}}doInitialSourceDesignRuleChecks(){cLt(this)}_getMinimumFlexContainerSize(){return oLt(this)}_repositionOnPcb(e){return aLt(this,e)}doInitialSilkscreenOverlapAdjustment(){return pLt(this)}isRelativelyPositioned(){return this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0}},xLt=({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}},bLt=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}=W4,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 z1(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 z1(n.message):new z1(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 z1(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},g9=class extends Me{constructor(){super(...arguments);f(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:zW}}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=>({...$e(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()})}},fnt=({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=Ee(n).pcb_component.get(s);if(!a)continue;let c=Ee(n).source_component.get(a.source_component_id);if(!c)continue;let l=i.pcb_placements?.findIndex(h=>h.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},mnt=({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=Ee(n).schematic_component.get(s);if(!a||!a.source_component_id)continue;let c=Ee(n).source_component.get(a.source_component_id);if(!c)continue;let l=i.schematic_placements?.findIndex(h=>h.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},vLt=({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=mnt({circuitJson:n,editEvents:i,manualEditsFile:s})),r.length>0&&(s=fnt({circuitJson:n,editEvents:r,manualEditsFile:s})),s},SLt=(n,e)=>{if(Ee(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=Ee(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},wLt=({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=An(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:x4(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=SLt(n,t));return n},_nt=(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},l9=({db:n,circuitJson:e,subcircuit_id:t,minTraceWidth:i=.1})=>{if(!n&&e&&(n=Ee(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 I=_nt(n,t);for(let E of I)s.add(E)}let o=(e??n.toArray()).filter(I=>!t||"subcircuit_id"in I&&s.has(I.subcircuit_id)),a=n.pcb_board.list()[0];n=Ee(o);let c=tr(o),l=pnt([...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(I=>!t||s?.has(I.subcircuit_id)),c);for(let I of l){let E=I.connectedTo.flatMap(A=>c.getIdsConnectedToNet(A));I.connectedTo.push(...E)}let u=l.flatMap(I=>[{x:I.center.x-I.width/2,y:I.center.y-I.height/2},{x:I.center.x+I.width/2,y:I.center.y+I.height/2}]).concat(a?.outline??[]),h;if(a&&!a.outline?h={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}:h={minX:Math.min(...u.map(I=>I.x))-1,maxX:Math.max(...u.map(I=>I.x))+1,minY:Math.min(...u.map(I=>I.y))-1,maxY:Math.max(...u.map(I=>I.y))+1},t){let I=n.pcb_group.getWhere({subcircuit_id:t});if(I?.width&&I.height){let E={minX:I.center.x-I.width/2,maxX:I.center.x+I.width/2,minY:I.center.y-I.height/2,maxY:I.center.y+I.height/2};h={minX:Math.min(h.minX,E.minX),maxX:Math.max(h.maxX,E.maxX),minY:Math.min(h.minY,E.minY),maxY:Math.max(h.maxY,E.maxY)}}}let d=new Set(n.pcb_trace.list().map(I=>I.source_trace_id).filter(I=>!!I)),_=n.source_trace.list().filter(I=>!d.has(I.source_trace_id)).map(I=>{let E=I.connected_source_port_ids.map(H=>{let et=n.source_port.get(H),tt=n.pcb_port.getWhere({source_port_id:H});return{...et,...tt}});if(E.length<2)return null;let[A,R]=E;if(A.x===void 0||A.y===void 0)return console.error(`(source_port_id: ${A.source_port_id}) for trace ${I.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 ${I.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(H=>H.pcb_port_id===A.pcb_port_id||H.pcb_port_id===R.pcb_port_id),V=[];for(let H of U){let tt=n.pcb_port.get(H.pcb_port_id)?.layers?.[0]??"top";for(let mt of H.route)V.push({x:mt.x,y:mt.y,layer:tt})}return{name:I.source_trace_id??c.getNetConnectedToId(I.source_trace_id)??"",source_trace_id:I.source_trace_id,width:I.min_trace_thickness,pointsToConnect:[{x:A.x,y:A.y,layer:B,pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},...V,{x:R.x,y:R.y,layer:j,pointId:R.pcb_port_id,pcb_port_id:R.pcb_port_id}]}}).filter(I=>I!==null),g=new Map(_.map(I=>[I.source_trace_id,I])),x=n.source_net.list().filter(I=>!t||s?.has(I.subcircuit_id)),v=[];for(let I of x){let E=n.source_trace.list().filter(A=>A.connected_source_net_ids?.includes(I.source_net_id));v.push({name:I.source_net_id??c.getNetConnectedToId(I.source_net_id),pointsToConnect:E.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 P=n.pcb_breakout_point.list().filter(I=>!t||s?.has(I.subcircuit_id)),w=[],T=new Map;for(let I of P){let E={x:I.x,y:I.y,layer:"top"};if(I.source_trace_id){let A=g.get(I.source_trace_id)??T.get(I.source_trace_id);if(A)A.pointsToConnect.push(E);else{let R={name:I.source_trace_id,source_trace_id:I.source_trace_id,pointsToConnect:[E]};w.push(R),T.set(I.source_trace_id,R)}}else if(I.source_net_id){let A=v.find(R=>R.name===I.source_net_id);A?A.pointsToConnect.push(E):w.push({name:I.source_net_id,pointsToConnect:[E]})}else if(I.source_port_id){let A=n.pcb_port.getWhere({source_port_id:I.source_port_id});A&&w.push({name:I.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},E]})}}let k=[..._,...v,...w],C=new Map;for(let I of k)for(let E of I.pointsToConnect)E.pointId&&C.set(E.pointId,I);let M=n.pcb_trace.list().filter(I=>!t||s?.has(I.subcircuit_id));for(let I of M){let E=new Set;for(let B of I.route)B.start_pcb_port_id&&E.add(B.start_pcb_port_id),B.end_pcb_port_id&&E.add(B.end_pcb_port_id);if(E.size<2)continue;let A=E.values().next().value;if(!A)continue;let R=C.get(A);R&&[...E].every(B=>C.get(B)===R)&&(R.externallyConnectedPointIds??(R.externallyConnectedPointIds=[]),R.externallyConnectedPointIds.push([...E]))}return{simpleRouteJson:{bounds:h,obstacles:l,connections:k,layerCount:a?.num_layers??2,minTraceWidth:i,outline:a?.outline?.map(I=>({...I}))},connMap:c}},PLt=n=>{let e={};if(!n)return e;for(let i of Ua)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},kLt=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 h of t[c])h.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 x9({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 Net=(0,ynt.default)("Group_doInitialSchematicLayoutMatchAdapt");function TLt(n){let{db:e}=n.root,t=Rg(e.toArray(),{source_group_id:n.source_group_id}),i=q4(t);Net.enabled&&global?.debugGraphics&&global.debugGraphics?.push(rl(i,{title:`floatingBpcGraph-${n.name}`}));let r=q4(t),s={boxes:r.boxes,pins:r.pins.map(c=>({...c,color:c.color.replace("not_connected","normal")}))},{result:o}=rJ([{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(h=>h.boxId===c.boxId).filter(h=>!h.color.includes("center")).length<=2).map(c=>c.boxId)),corpus:{}});Net.enabled&&global?.debugGraphics&&global.debugGraphics?.push(rl(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 h={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:h.x-l.center.x,y:h.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;x9({db:e,schematicComponentId:l.schematic_component_id,deltaX:g.x,deltaY:g.y}),l.center=h;continue}let u=e.schematic_net_label.get(c.boxId);if(u){let h=o.pins.find(_=>_.boxId===c.boxId&&_.color==="netlabel_center");if(!h)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+h.offset.x,y:d.y+h.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 xe=(0,gnt.default)("Group_doInitialSchematicLayoutMatchpack");function Aet(n){switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function Ret(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 MLt(n,e,t){let i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};xe(`[${t.name}] Processing ${n.childNodes.length} child nodes for input problem`),n.childNodes.forEach((s,o)=>{if(xe(`[${t.name}] Processing child ${o}: nodeType=${s.nodeType}`),s.nodeType==="component"?xe(`[${t.name}] - Component: ${s.sourceComponent?.name}`):s.nodeType==="group"&&xe(`[${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(w=>w.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 h=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-h)/2,v=(_-g)/2;i.chipMap[a]={chipId:a,pins:[],size:{x:(c.size?.width||1)+h+d,y:(c.size?.height||1)+_+g},availableRotations:u};let P=e.schematic_port.list({schematic_component_id:c.schematic_component_id});for(let w of P){let T=e.source_port.get(w.source_port_id);if(!T)continue;let k=`${a}.${T.pin_number||T.name||w.schematic_port_id}`;i.chipMap[a].pins.push(k);let C=Aet(w.facing_direction);i.chipPinMap[k]={pinId:k,offset:{x:(w.center?.x||0)-(c.center.x||0)+x,y:(w.center?.y||0)-(c.center.y||0)+v},side:C}}}else if(s.nodeType==="group"&&s.sourceGroup){let a=s.sourceGroup.name||`group_${o}`;xe(`[${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(xe(`[${t.name}] Found schematic_group for ${a}:`,c),c){xe(`[${t.name}] Treating group ${a} as composite chip`);let u=e.schematic_component.list({schematic_group_id:c.schematic_group_id});xe(`[${t.name}] Group ${a} has ${u.length} components:`,u.map(A=>A.source_component_id));let h=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;h=Math.min(h,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,P=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,w=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,T=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0,k=(P-v)/2,C=(w-T)/2,M=(x?d-h:2)+v+P,I=(x?g-_:2)+w+T;xe(`[${t.name}] Group ${a} computed size: ${M} x ${I}`);let E=[];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}`;E.push(U);let V=c.center||{x:0,y:0},H=Aet(B.facing_direction);i.chipPinMap[U]={pinId:U,offset:{x:(B.center?.x||0)-V.x+k,y:(B.center?.y||0)-V.y+C},side:H}}}xe(`[${t.name}] Group ${a} has ${E.length} pins:`,E),i.chipMap[a]={chipId:a,pins:E,size:{x:M,y:I}},xe(`[${t.name}] Added group ${a} to chipMap`)}else xe(`[${t.name}] Warning: No schematic_group found for group ${a}`)}}),xe(`[${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 h=e.schematic_component.list({schematic_group_id:u.schematic_group_id});for(let d of h){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),xe(`[${t.name}] \u2713 Pin ${a} has connectivity key: ${v}`)}else xe(`[${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 h of u){let d=h.pin_number||h.name;if(String(d)===String(c)&&h.subcircuit_connectivity_map_key){let _=h.subcircuit_connectivity_map_key;r.has(_)||r.set(_,[]),r.get(_).push(a),xe(`[${t.name}] Pin ${a} has connectivity key: ${_}`)}}}}xe(`[${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(xe(`[${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 h=[];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],P=n.childNodes.find(w=>w.nodeType==="component"&&w.sourceComponent?w.sourceComponent.name===v:w.nodeType==="group"&&w.sourceGroup?`group_${n.childNodes.indexOf(w)}`===v:!1);P?.nodeType==="component"&&P.sourceComponent&&e.source_port.list({source_component_id:P.sourceComponent.source_component_id}).some(T=>T.source_port_id===d)&&h.push(_)}}for(let d=0;d<h.length;d++)for(let _=d+1;_<h.length;_++){let g=h[d],x=h[_];i.pinStrongConnMap[`${g}-${x}`]=!0,i.pinStrongConnMap[`${x}-${g}`]=!0,xe(`[${t.name}] Created strong connection: ${g} <-> ${x}`)}}}if(c){let u=e.source_net.getWhere({subcircuit_connectivity_map_key:s}),h=u?.is_ground??!1,d=u?.is_power??!1;i.netMap[s]={netId:s,isGround:h,isPositiveVoltageSource:d};for(let _ of o)i.netConnMap[`${_}-${s}`]=!0;xe(`[${t.name}] Created net ${s} with ${o.length} pins:`,o)}}return i}function ELt(n){let{db:e}=n.root,t=a_(e.toArray(),{source_group_id:n.source_group_id});if(xe(`[${n.name}] Starting matchpack layout with ${t.childNodes.length} children`),xe(`[${n.name}] Tree structure:`,JSON.stringify(t,null,2)),t.childNodes.length<=1){xe(`[${n.name}] Only ${t.childNodes.length} children, skipping layout`);return}xe("Converting circuit tree to InputProblem...");let i=MLt(t,e,n);xe.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${n.name}`,content:JSON.stringify(i,null,2)});let r=new pQ(i);if(xe("Starting LayoutPipelineSolver..."),xe.enabled&&global?.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-initial-${n.name}`})}if(r.solve(),xe(`Solver completed in ${r.iterations} iterations`),xe(`Solved: ${r.solved}, Failed: ${r.failed}`),r.failed)throw xe(`Solver failed with error: ${r.error}`),new Error(`Matchpack layout solver failed: ${r.error}`);let s=r.getOutputLayout();if(xe("OutputLayout:",JSON.stringify(s,null,2)),xe("Solver completed successfully:",!r.failed),xe.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){xe(`Warning: Found ${o.length} overlapping components:`);for(let c of o)xe(` ${c.chip1} overlaps ${c.chip2} (area: ${c.overlapArea})`)}let a=n._getGlobalSchematicPositionBeforeLayout();xe(`Group offset: x=${a.x}, y=${a.y}`),xe(`Applying layout results for ${Object.keys(s.chipPlacements).length} chip placements`);for(let[c,l]of Object.entries(s.chipPlacements)){xe(`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 xe(` 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 xe(` Checking group ${_} (expected chipId: ${g}): matches=${x}`),x}return!1});if(!u){xe(`Warning: No tree node found for chip: ${c}`),xe("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 h={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){xe(`Moving component ${c} to (${h.x}, ${h.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:h.x-d.center.x,y:h.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(x9({db:e,schematicComponentId:d.schematic_component_id,deltaX:x.x,deltaY:x.y}),d.center=h,l.ccwRotationDegrees!==0){xe(`Component ${c} has rotation: ${l.ccwRotationDegrees}\xB0`);let v=l.ccwRotationDegrees*Math.PI/180,P=Math.cos(v),w=Math.sin(v);for(let T of _){let k=T.center.x-h.x,C=T.center.y-h.y,M=k*P-C*w,I=k*w+C*P;T.center.x=h.x+M,T.center.y=h.y+I;let E=T.facing_direction||"right";T.facing_direction=Ret(E,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-h.x,C=T.position.y-h.y,M=k*P-C*w,I=k*w+C*P;T.position.x=h.x+M,T.position.y=h.y+I}if(d.symbol_name){let T=d.symbol_name.match(/_(right|left|up|down)$/);T&&(d.symbol_name=d.symbol_name.replace(T[0],`_${Ret(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){xe(`Moving group ${c} to (${h.x}, ${h.y}) from (${d.center?.x}, ${d.center?.y})`);let _=e.schematic_component.list({schematic_group_id:d.schematic_group_id});xe(`Group ${c} has ${_.length} components to move`);let g=d.center||{x:0,y:0},x={x:h.x-g.x,y:h.y-g.y};xe(`Position delta for group ${c}: (${x.x}, ${x.y})`);for(let v of _)if(v.center){let P={...v.center};v.center.x+=x.x,v.center.y+=x.y,xe(`Moved component ${v.source_component_id} from (${P.x}, ${P.y}) to (${v.center.x}, ${v.center.y})`);let w=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 w)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=h,xe(`Updated group ${c} center to (${h.x}, ${h.y})`)}}}xe("Matchpack layout completed successfully")}function CLt(n){if(!n.isSubcircuit)return;let{db:e}=n.root,t=n.selectAll("trace"),i=n.selectAll("via"),r=n.selectAll("net"),s=new Jm({});s.addConnections(t.map(u=>{let h=e.source_trace.get(u.source_trace_id);return h?[h.source_trace_id,...h.connected_source_port_ids,...h.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 h=s.getNetConnectedToId(u.source_trace_id);h&&(u.subcircuit_connectivity_map_key=`${a??`unnamedsubcircuit${n._renderId}`}_${h}`,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 h=e.source_trace.get(u.source_trace_id);if(h)for(let d of h.connected_source_port_ids)c.add(d)}for(let u of c){let h=s.getNetConnectedToId(u);if(!h)continue;let d=`${a??`unnamedsubcircuit${n._renderId}`}_${h}`;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 h=e.source_trace.get(u.source_trace_id);if(h)for(let d of h.connected_source_net_ids)l.add(d)}for(let u of o)l.add(u.source_net_id);for(let u of l){let h=s.getNetConnectedToId(u);if(!h)continue;let d=`${a??`unnamedsubcircuit${n._renderId}`}_${h}`;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 h=u._getConnectedNetOrTrace();h&&h.subcircuit_connectivity_map_key&&(u.subcircuit_connectivity_map_key=h.subcircuit_connectivity_map_key)}}function ILt(n){let{db:e}=n.root,t=n._parsedProps,i=n.children.filter(C=>{let M=C._parsedProps?.schX!==void 0||C._parsedProps?.schY!==void 0;return C.schematic_component_id&&!M});if(i.length===0)return;let r=0,s=0;for(let C of i){let M=e.schematic_component.get(C.schematic_component_id);M?.size&&(r=Math.max(r,M.size.width),s=Math.max(s,M.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 h,d;o!==void 0&&a!==void 0?(h=o,d=a):o!==void 0?(h=o,d=Math.ceil(i.length/h)):a!==void 0?(d=a,h=Math.ceil(i.length/d)):(h=Math.ceil(Math.sqrt(i.length)),d=Math.ceil(i.length/h)),h===0&&i.length>0&&(h=1),d===0&&i.length>0&&(d=i.length);let _,g,x=C=>{if(C!==void 0)return typeof C=="number"?C:D.parse(C)};if(l!==void 0||u!==void 0){let C=typeof c=="object"&&c!==null?c.x:c,M=typeof c=="object"&&c!==null?c.y:c;_=x(u??C)??1,g=x(l??M)??1}else if(typeof c=="number")_=c,g=c;else if(typeof c=="string"){let C=D.parse(c);_=C,g=C}else if(typeof c=="object"&&c!==null){let C=c.x,M=c.y;_=typeof C=="number"?C:D.parse(C??"0mm"),g=typeof M=="number"?M:D.parse(M??"0mm")}else _=1,g=1;let v=h*r+Math.max(0,h-1)*_,P=d*s+Math.max(0,d-1)*g,w=n._getGlobalSchematicPositionBeforeLayout(),T=w.x-v/2+r/2,k=w.y+P/2-s/2;for(let C=0;C<i.length;C++){let M=i[C];if(!M.schematic_component_id)continue;let I=Math.floor(C/h),E=C%h;if(I>=d||E>=h){console.warn(`Schematic grid layout: Child ${M.getString()} at index ${C} (row ${I}, col ${E}) exceeds specified grid dimensions (${d}x${h}). Skipping placement.`);continue}let A=T+E*(r+_),R=k-I*(s+g),B=e.schematic_component.get(M.schematic_component_id);if(B){let j=B.center,U={x:A,y:R};e.schematic_component.update(M.schematic_component_id,{center:U});let V=U.x-j.x,H=U.y-j.y,et=e.schematic_port.list({schematic_component_id:M.schematic_component_id});for(let mt of et)e.schematic_port.update(mt.schematic_port_id,{center:{x:mt.center.x+V,y:mt.center.y+H}});let tt=e.schematic_text.list({schematic_component_id:M.schematic_component_id});for(let mt of tt)e.schematic_text.update(mt.schematic_text_id,{position:{x:mt.position.x+V,y:mt.position.y+H}});x9({db:e,schematicComponentId:M.schematic_component_id,deltaX:V,deltaY:H})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:v,height:P,center:w})}var Oet=(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,h=l-c;return{width:u,height:h}}return null},NLt=n=>{let{db:e}=n.root,t=n._parsedProps,i=a_(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,h=0;typeof o=="object"?(u=o.y??0,h=o.x??0):typeof o=="number"?(u=o,h=o):typeof o=="string"&&(u=D.parse(o),h=D.parse(o));let d,_=t.width??t.schWidth??void 0,g=t.height??t.schHeight??void 0;(_===void 0||g===void 0)&&(d=ES(i.childNodes.map(k=>Oet(e,k)).filter(k=>k!==null),{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h}),_=d.width,g=d.height);let v=new Nw(_,g,{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h});for(let k of i.childNodes){let C=Oet(e,k);v.addChild({metadata:k,width:C?.width??0,height:C?.height??0,flexBasis:C?a==="row"?C.width:C.height:void 0})}v.build();let P={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let k of v.children)P.minX=Math.min(P.minX,k.position.x),P.minY=Math.min(P.minY,k.position.y),P.maxX=Math.max(P.maxX,k.position.x+k.size.width),P.maxY=Math.max(P.maxY,k.position.y+k.size.height);P.width=P.maxX-P.minX,P.height=P.maxY-P.minY;let w={x:-(P.maxX+P.minX)/2,y:-(P.maxY+P.minY)/2},T=e.toArray();for(let k of v.children){let{sourceComponent:C,sourceGroup:M}=k.metadata;if(C){let I=e.schematic_component.getWhere({source_component_id:C.source_component_id});if(!I)continue;mq(T,I.schematic_component_id,{x:k.position.x+k.size.width/2+w.x,y:k.position.y+k.size.height/2+w.y})}if(M){if(!e.schematic_group.getWhere({source_group_id:M.source_group_id}))continue;yq(T,M.source_group_id,{x:k.position.x+k.size.width/2+w.x,y:k.position.y+k.size.height/2+w.y})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:P.width,height:P.height})},KA=1;function ALt(n){let{db:e}=n.root,t=n._parsedProps,i=RLt(n);if(i.length===0)return;let r=OLt({db:e,pcbChildren:i}),s=LLt(t),o=FLt({props:t,pcbChildren:i,childDimensions:r,gridConfig:s}),a=DLt({pcbChildren:i,childDimensions:r,gridLayout:o,gridConfig:s}),{itemCoordinates:c}=a.layout();jLt({db:e,group:n,pcbChildren:i,itemCoordinates:c,gridLayout:o}),BLt({db:e,group:n,props:t,gridLayout:o})}function RLt(n){return n.children.filter(e=>e.pcb_component_id||e.pcb_group_id)}function OLt(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 LLt(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=h=>h===void 0?KA:typeof h=="number"?h:D.parse(h),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=KA,u=KA;if(a!==void 0||c!==void 0){let h=typeof o=="object"?o?.x:o,d=typeof o=="object"?o?.y:o;l=s(c??h),u=s(a??d)}else if(typeof o=="object"&&o!==null)l=s(o.x),u=s(o.y);else{let h=s(o);l=h,u=h}return{cols:e,rows:t,gapX:l,gapY:u,templateColumns:i,templateRows:r}}function FLt(n){let{props:e,pcbChildren:t,childDimensions:i,gridConfig:r}=n;return e.pcbGridTemplateColumns||e.pcbGridTemplateRows?zLt({props:e,gridConfig:r,pcbChildren:t,childDimensions:i}):$Lt({gridConfig:r,pcbChildren:t,childDimensions:i})}function zLt(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,h=l*r.height+Math.max(0,l-1)*t.gapY;return{gridTemplateColumns:s,gridTemplateRows:o,containerWidth:u,containerHeight:h}}function $Lt(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 DLt(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 bQ({containerWidth:i.containerWidth,containerHeight:i.containerHeight,gridTemplateColumns:i.gridTemplateColumns,gridTemplateRows:i.gridTemplateRows,gap:[r.gapY,r.gapX],children:s})}function jLt(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}`,h=r[u];if(!h){console.warn(`PCB grid layout: No coordinates found for child ${u}`);continue}let d=o.x-s.containerWidth/2+h.x+h.width/2,_=o.y+s.containerHeight/2-h.y-h.height/2;if(l.pcb_component_id)TS(a,l.pcb_component_id,{x:d,y:_});else{let g=l;g.pcb_group_id&&g.source_group_id&&MS(a,g.source_group_id,{x:d,y:_})}}}function BLt(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 YLt(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 XLt=(n,e)=>{let t=n.children.filter(h=>h.componentName==="Constraint"&&h._parsedProps.pcb),i=new Map,r={},s=h=>(r[h]!==h&&(r[h]=s(r[h])),r[h]),o=(h,d)=>{let _=s(h),g=s(d);_!==g&&(r[g]=_)},a=h=>{h in r||(r[h]=h)},c=h=>{let d=h.startsWith(".")?h.slice(1):h;return n.children.find(g=>g.name===d)?.pcb_component_id??void 0};for(let h of t){let d=h._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 h of Object.keys(r)){let d=s(h);i.has(d)||i.set(d,{componentIds:[],constraints:[]}),i.get(d).componentIds.push(h)}for(let h of t){let d=h._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(h)}let l={},u=Object.fromEntries(e.components.map(h=>[h.componentId,h]));for(let[h,d]of i.entries()){if(d.componentIds.length<=1)continue;let _=new i_,g={},x=(A,R)=>{let B=`${A}_${R}`;return g[B]||(g[B]=new Ia(B)),g[B]},v=d.componentIds[0];_.addConstraint(new wi(x(v,"x"),si.Eq,0,Rn.required)),_.addConstraint(new wi(x(v,"y"),si.Eq,0,Rn.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 wi(new $n(x(j,"x"),[-1,x(B,"x")]),si.Eq,R.xDist,Rn.required))}else if("yDist"in R){let B=c(R.top),j=c(R.bottom);B&&j&&_.addConstraint(new wi(new $n(x(B,"y"),[-1,x(j,"y")]),si.Eq,R.yDist,Rn.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 wi(new $n(x(B[U],"x"),[-1,j]),si.Eq,0,Rn.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 wi(new $n(x(B[U],"y"),[-1,j]),si.Eq,0,Rn.required))}}}_.updateVariables();let P={};for(let A of d.componentIds)P[A]={x:x(A,"x").value(),y:x(A,"y").value()};let w=1/0,T=1/0,k=-1/0,C=-1/0;for(let A of d.componentIds){let R=u[A],B=P[A];if(R)for(let j of R.pads){let U=B.x+j.offset.x,V=B.y+j.offset.y;w=Math.min(w,U-j.size.x/2),k=Math.max(k,U+j.size.x/2),T=Math.min(T,V-j.size.y/2),C=Math.max(C,V+j.size.y/2)}}let M={x:(w+k)/2,y:(T+C)/2},I=[],E={};for(let A of d.componentIds){let R=u[A],B=P[A];if(R){E[A]={x:B.x-M.x,y:B.y-M.y};for(let j of R.pads)I.push({padId:j.padId,networkId:j.networkId,type:j.type,size:j.size,offset:{x:B.x+j.offset.x-M.x,y:B.y+j.offset.y-M.y}})}}e.components=e.components.filter(A=>!d.componentIds.includes(A.componentId)),e.components.push({componentId:d.componentIds[0],pads:I,availableRotationDegrees:[0]}),d.relativeCenters=E,l[d.componentIds[0]]=d}return l},Let=({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:ad(o+s)};n.cad_component.update(r.cad_component_id,{rotation:a}),r.rotation=a},$1=(n,e,t)=>{if(e===t)return!0;let i=n.source_group.get(e);return!i||!i.parent_source_group_id?!1:$1(n,i.parent_source_group_id,t)},ULt=(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,P=v*Math.PI/180;for(let w of l.componentIds){let T=l.relativeCenters[w];if(!T)continue;let k={x:T.x*Math.cos(P)-T.y*Math.sin(P),y:T.x*Math.sin(P)+T.y*Math.cos(P)},C=i.pcb_component.get(w);if(!C)continue;let M=C.center,I=mi(n._computePcbGlobalTransformBeforeLayout(),An(s.x+k.x,s.y+k.y),Dc(P),An(-M.x,-M.y)),E=i.toArray().filter(A=>"pcb_component_id"in A&&A.pcb_component_id===w);s_(E,I),Let({db:i,pcbComponentId:w,rotationDegrees:v,layer:C.layer})}continue}let u=i.pcb_component.get(o);if(u){let v=n.source_group_id,w=i.source_component.get(u.source_component_id)?.source_group_id;if(w!==void 0&&!$1(i,w,v))continue;let T=u.center,k=c??a??0,C=mi(n._computePcbGlobalTransformBeforeLayout(),An(s.x,s.y),Dc(k*Math.PI/180),An(-T.x,-T.y)),M=i.toArray().filter(I=>"pcb_component_id"in I&&I.pcb_component_id===o);s_(M,C),Let({db:i,pcbComponentId:o,rotationDegrees:k,layer:u.layer});continue}let h=i.pcb_group.list().find(v=>v.source_group_id===o);if(!h)continue;let d=h.center,_=c??a??0,g=mi(n._computePcbGlobalTransformBeforeLayout(),An(s.x,s.y),Dc(_*Math.PI/180),An(-d.x,-d.y)),x=i.toArray().filter(v=>{if("source_group_id"in v&&v.source_group_id&&(v.source_group_id===o||$1(i,v.source_group_id,o)))return!0;if("source_component_id"in v&&v.source_component_id){let P=i.source_component.get(v.source_component_id);if(P?.source_group_id&&(P.source_group_id===o||$1(i,P.source_group_id,o)))return!0}if("pcb_component_id"in v&&v.pcb_component_id){let P=i.pcb_component.get(v.pcb_component_id);if(P?.source_component_id){let w=i.source_component.get(P.source_component_id);if(w?.source_group_id&&(w.source_group_id===o||$1(i,w.source_group_id,o)))return!0}}return!1});s_(x,g),i.pcb_group.update(h.pcb_group_id,{center:s})}};function VLt(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 GLt(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 HLt="1mm",Fet=(0,xnt.default)("Group_doInitialPcbLayoutPack"),WLt=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??HLt),u={},h=new Set,d=k=>{if(k?.pcb_component_id&&k?._parsedProps){let C=k._parsedProps,M=D.parse(C.pcbMarginLeft??C.pcbMarginX??0),I=D.parse(C.pcbMarginRight??C.pcbMarginX??0),E=D.parse(C.pcbMarginTop??C.pcbMarginY??0),A=D.parse(C.pcbMarginBottom??C.pcbMarginY??0);(M||I||E||A)&&(u[k.pcb_component_id]={left:M,right:I,top:E,bottom:A})}k?.children&&k.children.forEach(d)};d(n);let _=new Set;for(let k of n.children){let C=k;C._isNormalComponent&&C.isRelativelyPositioned?.()&&(C.pcb_component_id&&h.add(C.pcb_component_id),C.pcb_group_id&&_.add(C.pcb_group_id))}let g=e.toArray().filter(k=>k.type==="pcb_component"?!h.has(k.pcb_component_id):k.type==="pcb_group"?!_.has(k.pcb_group_id):!0),x=[];for(let k of h){let C=e.toArray().find(R=>R.type==="pcb_component"&&R.pcb_component_id===k);if(!C)continue;let M=C.center.x,I=C.center.y,E=e.toArray().filter(R=>R.type==="pcb_smtpad"&&R.pcb_component_id===k);for(let R of E){let B=VLt(R);if(!B||B.width===0||B.height===0)continue;let j,U;if(R.shape==="polygon"){let V=R.points.map(et=>et.x),H=R.points.map(et=>et.y);j=M+(Math.min(...V)+Math.max(...V))/2,U=I+(Math.min(...H)+Math.max(...H))/2}else j=M+R.x,U=I+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=GLt(R);if(!B||B.width===0||B.height===0)continue;let j=M+R.x,U=I+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),C=D.parse(t.height);v={minX:-k/2,maxX:k/2,minY:-C/2,maxY:C/2}}let P={...lQ(cQ(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},w=XLt(n,P);Fet.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:P}));let T=Ew(P);if(Fet.enabled&&global?.debugGraphics){let k=oA(T);k.title=`packOutput-${n.name}`,global.debugGraphics?.push(k)}ULt(n,T,w)},qLt=n=>{let{db:e}=n.root,{_parsedProps:t}=n,i=n.children.filter(C=>C.pcb_component_id||C.pcb_group_id);if(i.some(C=>{let M=C._parsedProps;return M?.pcbX!==void 0||M?.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 h=0,d=0;typeof a=="object"?(h=a.y??0,d=a.x??0):typeof a=="number"?(h=a,d=a):typeof a=="string"&&(h=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)&&(_=ES(i.map(C=>C._getMinimumFlexContainerSize()).filter(C=>C!==null),{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d}),g=_.width,x=_.height);let P=new Nw(g,x,{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d});for(let C of i){let M=C._getMinimumFlexContainerSize();P.addChild({metadata:C,width:M?.width??0,height:M?.height??0,flexBasis:M?c==="row"?M.width:M.height:void 0})}P.build();let w={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let C of P.children)w.minX=Math.min(w.minX,C.position.x),w.minY=Math.min(w.minY,C.position.y),w.maxX=Math.max(w.maxX,C.position.x+C.size.width),w.maxY=Math.max(w.maxY,C.position.y+C.size.height);w.width=w.maxX-w.minX,w.height=w.maxY-w.minY;let T=n._getGlobalPcbPositionBeforeLayout(),k={x:T.x-(w.maxX+w.minX)/2,y:T.y-(w.maxY+w.minY)/2};for(let C of P.children)C.metadata._repositionOnPcb({x:C.position.x+C.size.width/2+k.x,y:C.position.y+C.size.height/2+k.y});e.pcb_group.update(n.pcb_group_id,{width:w.width,height:w.height,center:T})};function ZLt(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=[],h=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}),V=e.schematic_port.list({schematic_component_id:R.schematic_component_id});for(let H of V){let et=`${U?.name??R.schematic_component_id}.${H.pin_number}`;h.set(et,H.schematic_port_id),d.set(H.schematic_port_id,et)}for(let H of V){let et=d.get(H.schematic_port_id);j.push({pinId:et,x:H.center.x,y:H.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 P=new Set;n.subcircuit_id&&P.add(n.subcircuit_id);for(let R of a)R.subcircuit_id&&P.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&&P.add(B.subcircuit_id)}let k=[],C=new Map;for(let R of e.source_trace.list()){if(R.subcircuit_id&&!P.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),V=[j,U].sort().join("::");if(!C.has(V)){C.set(V,R.source_trace_id);let H=R.display_name??R.source_trace_id;R.subcircuit_connectivity_map_key&&(r.add(R.subcircuit_connectivity_map_key),v.set(H,R.subcircuit_connectivity_map_key),i.set(R.subcircuit_connectivity_map_key,H)),k.push({pinIds:[j,U].map(et=>d.get(et)),netId:H})}}}let M=[];for(let R of e.source_net.list().filter(B=>!B.subcircuit_id||P.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 I=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),I.has(U)||I.set(U,[]),I.get(U).push(R)}for(let[R,B]of I){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 H=.1*(.18/.18),et=Number((String(U).length*H).toFixed(2));M.push({netId:U,pinIds:B.map(tt=>d.get(tt)),netLabelWidth:et})}}let E=(()=>{let R={},B=new Set(M.map(j=>j.netId));for(let j of e.source_net.list().filter(U=>!U.subcircuit_id||P.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:M,availableNetLabelOrientations:E,maxMspPairDistance:n._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:h,pairKeyToSourceTraceId:C,sckToSourceNet:t,sckToUserNetId:i,userNetIdToSck:v,allSourceAndSchematicPortIdsInScope:_,schPortIdToSourcePortId:g,displayLabelTraces:o,allScks:r}}var _r=1e-6;function zet(n){let e=Math.abs(n.to.x-n.from.x),t=Math.abs(n.to.y-n.from.y);return e>=t}function eP(n,e){return Math.hypot(e.x-n.x,e.y-n.y)}function $et(n,e,t){return{x:n.x+(e.x-n.x)*t,y:n.y+(e.y-n.y)*t}}function Det(n,e,t){let i=eP(n,e);if(i<_r)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 Hw(n,e,t,i){return n*i-e*t}function KLt(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=Hw(r.x,r.y,s.x,s.y),a={x:t.x-n.x,y:t.y-n.y},c=Hw(a.x,a.y,r.x,r.y);if(Math.abs(o)<_r&&Math.abs(c)<_r||Math.abs(o)<_r&&Math.abs(c)>=_r)return null;let l=Hw(a.x,a.y,s.x,s.y)/o,u=Hw(a.x,a.y,r.x,r.y)/o;return l<-_r||l>1+_r||u<-_r||u>1+_r?null:{x:n.x+l*r.x,y:n.y+l*r.y}}function JLt(n,e=_r){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 QLt(n,e,t){let i=eP(n.from,n.to);if(i<_r||e.length===0)return[n];let r=t/2,s=e.map(h=>({start:Math.max(0,h-r),end:Math.min(i,h+r)})).filter(h=>h.end-h.start>_r),o=JLt(s),a=[],c=0,l={x:n.to.x-n.from.x,y:n.to.y-n.from.y},u=(h,d,_)=>{if(d-h<=_r)return;let g=h/i,x=d/i;a.push({from:$et(n.from,n.to,g),to:$et(n.from,n.to,x),..._?{is_crossing:!0}:{}})};for(let h of o)h.start-c>_r&&u(c,h.start,!1),u(h.start,h.end,!0),c=h.end;return i-c>_r&&u(c,i,!1),a.length>0?a:[n]}function t7t(n,e={}){let t=e.crossSegmentLength??.075,i=e.tolerance??_r,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 h=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=KLt(h.from,h.to,x.from,x.to);if(!v)continue;let P=eP(h.from,h.to),w=eP(x.from,x.to);if(P<i||w<i)continue;let T=Det(h.from,h.to,v),k=Det(x.from,x.to,v),C=T<=i||Math.abs(P-T)<=i||Number.isNaN(T),M=k<=i||Math.abs(w-k)<=i||Number.isNaN(k);if(!C&&!M){let I=zet(h),E=zet(x),A;if(I!==E)A=I;else{let j=Math.abs(h.to.x-h.from.x),U=Math.abs(h.to.y-h.from.y),V=Math.abs(x.to.x-x.from.x),H=Math.abs(x.to.y-x.from.y),et=j-U,tt=V-H;A=et===tt?!0:et>tt}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 h=s({traceIdx:c,edgeIdx:u}),d=r.get(h)??[];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=QLt(l.edges[u],_,t);a[c].edges.push(...g)}}return a}var Ho=1e-6;function nP(n,e,t=Ho){return Math.abs(n-e)<=t}function W_(n,e,t=Ho){return nP(n.x,e.x,t)&&nP(n.y,e.y,t)}function jet(n,e,t,i=Ho){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 Bet(n,e=Ho){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 Yet(n){return{x:n.to.x-n.from.x,y:n.to.y-n.from.y}}function JA(n,e,t=Ho){let i=Yet(n),r=Yet(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 D1(n,e,t=Ho){return n.edges.filter(i=>W_(i.from,e,t)||W_(i.to,e,t))}function Xet(n,e,t=Ho){for(let i of n.edges){if(W_(i.from,e,t))return i.from;if(W_(i.to,e,t))return i.to}return null}function e7t(n,e,t=Ho){let i=W_(n.from,e,t)||nP(n.from.x,e.x,t)&&nP(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 Y_(n,e,t=Ho){let i=D1(n,e,t);if(i.length<2)return null;let r=i.map(h=>e7t(h,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 n7t(n,e={}){let t=e.tolerance??Ho,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 Bet(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 h of a)for(let d of u)if(W_(h,d,t)){let _=D1(o,h,t),g=D1(l,d,t),x=_.some(T=>g.some(k=>!JA(T,k,t))),v=Y_(o,h,t),P=Y_(l,d,t);x&&!(v!==null&&P!==null&&v===P)&&(i[o.source_trace_id].push(h),o.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(d))}for(let h of a)for(let d of l.edges)if(jet(h,d.from,d.to,t)){let g=D1(o,h,t).some(T=>!JA(T,d,t)),x=Y_(o,h,t),v=Xet(l,h,t*1e3),P=v?Y_(l,v,t):null;g&&!(x!==null&&P!==null&&x===P)&&(i[o.source_trace_id].push(h),o.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(h))}for(let h of u)for(let d of o.edges)if(jet(h,d.from,d.to,t)){let g=D1(l,h,t).some(T=>!JA(d,T,t)),x=Y_(l,h,t),v=Xet(o,h,t*1e3),P=v?Y_(o,v,t):null;g&&!(P!==null&&x!==null&&P===x)&&(i[l.source_trace_id].push(h),o.source_trace_id!==l.source_trace_id&&i[o.source_trace_id].push(h))}}}for(let s of Object.keys(i))i[s]=Bet(i[s],t);return i}var QA=(0,vnt.default)("Group_doInitialSchematicTraceRender");function i7t(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=[];QA(`Traces inside SchematicTraceSolver output: ${(o??[]).length}`);for(let u of o??[]){let h=u?.tracePath;if(!Array.isArray(h)||h.length<2){QA(`Skipping trace ${u?.pinIds.join(",")} because it has less than 2 points`);continue}let d=[];for(let x=0;x<h.length-1;x++)d.push({from:{x:h[x].x,y:h[x].y},to:{x:h[x+1].x,y:h[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 P of[x,v])s.schematic_port.get(P)&&s.schematic_port.update(P,{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})}QA(`Applying ${a.length} traces from SchematicTraceSolver output`);let c=t7t(a.map(u=>({source_trace_id:u.source_trace_id,edges:u.edges}))),l=n7t(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(h=>h.source_trace_id===u.source_trace_id)?.subcircuit_connectivity_map_key})}var r7t=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"}},s7t=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}},t9=(0,Snt.default)("Group_doInitialSchematicTraceRender");function o7t(n){let{group:e,solver:t,sckToSourceNet:i,allScks:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,userNetIdToSck:a,pinIdToSchematicPortId:c,schematicPortIdsWithPreExistingNetLabels:l,schematicPortIdsWithRoutedTraces:u}=n,{db:h}=e.root,d=t.netLabelPlacementSolver?.netLabelPlacements??t.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],_=t.mspConnectionPairSolver.globalConnMap;for(let g of d){t9(`processing placement: ${g.netId}`);let x=_.getIdsConnectedToNet(g.globalConnNetId).find(R=>a.get(R)),v=a.get(x),P=g.anchorPoint,w=g.orientation,T=r7t(w),k=v?i.get(v):void 0,C=g.pinIds.map(R=>c.get(R));if(C.some(R=>l.has(R))){t9(`skipping net label placement for "${g.netId}" REASON:schematic port has pre-existing net label`);continue}if(k){let R=k.name,B=_l({anchor_position:P,anchor_side:T,text:R});h.schematic_net_label.insert({text:R,anchor_position:P,center:B,anchor_side:T,...k?.source_net_id?{source_net_id:k.source_net_id}:{}});continue}let M=e.selectAll("port").filter(R=>R._getSubcircuitConnectivityKey()===v),{name:I,wasAssignedDisplayLabel:E}=s7t(M);if(!E&&C.some(R=>u.has(R))){t9(`skipping net label placement for "${g.netId}" REASON:schematic port has routed traces and no display label`);continue}let A=_l({anchor_position:P,anchor_side:T,text:I});h.schematic_net_label.insert({text:I,anchor_position:P,center:A,anchor_side:T})}}var a7t=({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 h=o.source_port.get(l)?.subcircuit_connectivity_map_key;if(!h)continue;let d=i.get(h);if(!d||o.schematic_net_label.list().some(P=>Math.abs(P.anchor_position.x-c.center.x)<.1&&Math.abs(P.anchor_position.y-c.center.y)<.1?d.source_net_id&&P.source_net_id?P.source_net_id===d.source_net_id:P.text===(d.name||h):!1))continue;let g=d.name||d.source_net_id||h,x=X1(c.facing_direction||"right")||"right",v=_l({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}:{}})}},c7t=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},l7t=({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},u7t=(0,bnt.default)("Group_doInitialSchematicTraceRender"),p7t=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}=ZLt(n),u=c7t(n);u7t.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(e,null,2)});let h=new $Q(e);h.solve();let d=l7t({solver:h,pinIdToSchematicPortId:t});i7t({group:n,solver:h,pinIdToSchematicPortId:t,userNetIdToSck:l}),o7t({group:n,solver:h,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,pinIdToSchematicPortId:t,allScks:c,userNetIdToSck:l,schematicPortIdsWithPreExistingNetLabels:u,schematicPortIdsWithRoutedTraces:d}),a7t({group:n,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,sckToSourceNet:r,pinIdToSchematicPortId:t,schematicPortIdsWithPreExistingNetLabels:u})},h7t=()=>({async simulate(n){let e="spice-experiment-1",{circuit:t,tran:i}=YQ(n);return{simulationResultCircuitJson:XQ(i,t,e)}}}),Uet=["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)"],Zw=new Map,Kw=0;function d7t(n){if(Zw.has(n))return Zw.get(n);let e=Uet[Kw];return Kw=(Kw+1)%Uet.length,Zw.set(n,e),e}function f7t(){Zw.clear(),Kw=0}var Xa=(0,wnt.default)("tscircuit:core:Group_doInitialSimulationSpiceEngineRender");function m7t(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");f7t();let r={...e.platform?.spiceEngineMap};r.spicey||(r.spicey=h7t());let s=e.db.toArray(),o,a;try{a=jQ(s),o=a.toSpiceString(),Xa(`Generated SPICE string:
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){sOt(`${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)}_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 Jet;)e=e.parent;return e}runRenderCycle(){for(let e of Ua)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=Ua.indexOf(e)-1;if(s>=0){let a=Ua[s];if(this._asyncEffects.filter(l=>l.phase===a).some(l=>!l.complete))return}let o=oOt[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))}},Jw={},Qet=n=>{let e=Object.fromEntries(Object.entries(n).map(([t,i])=>[t.toLowerCase(),i]));Object.assign(Jw,n),Object.assign(Jw,e)},cOt=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 h of u)typeof h=="string"&&(h.startsWith(" ")||h.endsWith(" "))&&s.push(`pinLabels.${c} ("${h}" 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 WA(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 h9={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=h9.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},lOt={...h9,getChildren:n=>n.children.filter(e=>!e.isSubcircuit)},get={...h9,getChildren:n=>n.children.filter(e=>e.isSubcircuit)},uOt=(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`},xet=(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(uOt(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()},qA={adapter:lOt,cacheResults:!0},Me=class extends p9{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 cOt(this.lowercaseComponentName,this.props,i.error.format())}get config(){return{componentName:"",zodProps:p.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}computePcbPropsTransform(){let{_parsedProps:e}=this,t=this._getPcbRotationBeforeLayout()??0;return mi(An(e.pcbX??0,e.pcbY??0),Dc(t*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 mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Sr(),mi(An(e.x,e.y),Dc(t*Math.PI/180)))}if(this.isPcbPrimitive){let t=this.getPrimitiveContainer();if(t&&t._parsedProps.layer==="bottom")return mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Sr(),NB(),this.computePcbPropsTransform())}return mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Sr(),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 mi(An(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){let e=this._getSchematicGlobalManualPlacementTransform(this);return e||mi(this.parent?.computeSchematicGlobalTransform?.()??Sr(),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 _i&&r===0)return u;if(a in _i&&r===90)return a;if(l in _i&&r===180)return l;if(c in _i&&r===270)return c;if(s in _i&&(r===0||r===180))return s;if(o in _i&&(r===90||r===270))return o;if(t in _i)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?_i[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(WA(e,r.selector)||e.props.name===r.selector)return $e(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(WA(e,r.selector)||e.props.name===r.selector)return $e(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((WA(e,i.selector)||e.props.name===i.selector)&&i.relative_to==="group_center")return mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Sr(),An(i.center.x,i.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return $e(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return $e(this.computeSchematicGlobalTransform(),{x:0,y:0})}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=xet(e,this),i=B5(t,this,qA);if(i.length>0)return this._cachedSelectAllQueries.set(e,i),i;let[r,...s]=t.split(" "),o=rS(r,this,{adapter:get});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=xet(e,this);t?.port&&(t.type="port");let r=null;if(t?.type&&(r=B5(i,this,qA).find(l=>l.lowercaseComponentName===t.type)),r??(r=rS(i,this,qA)),r)return this._cachedSelectOneQueries.set(e,r),r;let[s,...o]=i.split(" "),a=rS(s,this,{adapter:get});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()}},pOt=class extends Me{constructor(n,e){super(n),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:n.pcbX,pcbY:n.pcbY,schX:n.schX,schY:n.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:p.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 hOt(n,e){return new pOt(n,e)}function dOt(n,e){let t=n;return t.__tsci={...e},n}var fOt={supportsMutation:!0,createInstance(n,e){let t=Jw[n];if(!t)throw Object.keys(Jw).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 dOt(new t(e),{})}catch(i){return hOt({...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:()=>Ww.DefaultEventPriority,getCurrentUpdatePriority:()=>Ww.DefaultEventPriority,resolveUpdatePriority:()=>Ww.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},Uw=(0,Zet.default)(fOt),tnt=n=>{let e={children:[],props:{name:"$root"},add(s){s.parent=this,this.children.push(s)},computePcbGlobalTransform(){return Sr()}},t=[],i=Uw.createContainer(e,0,null,!1,null,"tsci",s=>{console.log("Error in createContainer"),console.error(s),t.push(s)},null);if(Uw.updateContainerSync(n,i,null,()=>{}),Uw.flushSyncWork(),t.length>0)throw t[0];let r=Uw.getPublicRootInstance(i);return r||e.children[0]},Y1=(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}"`)},mOt=(n,e)=>{if(!n)return;let t={},i={};for(let[r,s]of Object.entries(n)){let o=Y1(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},_Ot=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 ent(n){let e=[];for(let t=0;t<n.length-1;t++)e.push([n[t],n[t+1]]);return e}var yOt=p.object({name:p.string().refine(n=>!/[+-]/.test(n),n=>({message:`Net names cannot contain "+" or "-" (component "Net" received "${n}"). Try using underscores instead, e.g. VCC_P`}))}),d9=class extends Me{constructor(){super(...arguments);f(this,"source_net_id");f(this,"subcircuit_connectivity_map_key",null)}get config(){return{componentName:"Net",zodProps:yOt}}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=ent(r);for(let[o,a]of s){let c=o.ports.map(P=>P._getGlobalPcbPositionBeforeLayout()),l=a.ports.map(P=>P._getGlobalPcbPositionBeforeLayout()),u=1/0,h=[-1,-1];for(let P=0;P<c.length;P++){let w=c[P];for(let T=0;T<l.length;T++){let k=l[T],C=Math.sqrt((w.x-k.x)**2+(w.y-k.y)**2);C<u&&(u=C,h=[P,T])}}let d=o.ports[h[0]],_=a.ports[h[1]],g=e.toArray().filter(P=>P.type==="pcb_smtpad"||P.type==="pcb_trace"||P.type==="pcb_plated_hole"||P.type==="pcb_hole"||P.type==="source_port"||P.type==="pcb_port"),{solution:x}=xH(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)}},iP=(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 d9({name:t.split("net.")[1]});i.add(r)}}},j1=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:VH}}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(),h=(eo(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,d=.01,_=Math.abs(h)<d||Math.abs(h-180)<d||Math.abs(h-360)<d,g=Math.abs(h-90)<d||Math.abs(h-270)<d,x=Math.abs(h-360)<d?0:h,v=x,{maybeFlipLayer:P,isFlipped:w}=this._getPcbPrimitiveFlippedHelpers();w&&(x=(360-x+360)%360);let T=t.portHints?.map(M=>M.toString())??[],k=null,C=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(t.shape==="circle")k=e.pcb_smtpad.insert({pcb_component_id:C,pcb_port_id:this.matchedPort?.pcb_port_id,layer:P(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:C,pcb_port_id:this.matchedPort?.pcb_port_id,layer:P(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:C,pcb_port_id:this.matchedPort?.pcb_port_id,layer:P(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:P(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:P(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 M=t.ccwRotation??0,I=(v+M+360)%360,E=w?(360-I+360)%360:I;k=e.pcb_smtpad.insert({pcb_component_id:C,pcb_port_id:this.matchedPort?.pcb_port_id,layer:P(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: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}),r&&e.pcb_solder_paste.insert({layer:P(t.layer??"top"),shape:"rotated_rect",width:k.width*.7,height:k.height*.7,x:a.x,y:a.y,ccw_rotation:E,pcb_component_id:C,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 M=t.points.map(I=>{let E=$e(c,{x:Y.parse(I.x),y:Y.parse(I.y)});return{x:E.x,y:E.y}});k=e.pcb_smtpad.insert({pcb_component_id:C,pcb_port_id:this.matchedPort?.pcb_port_id,layer:P(t.layer??"top"),shape:"polygon",points: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})}else t.shape==="pill"&&(k=e.pcb_smtpad.insert({pcb_component_id:C,pcb_port_id:this.matchedPort?.pcb_port_id,layer:P(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)}},f9=class extends Me{constructor(){super(...arguments);f(this,"pcb_silkscreen_path_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:RW}}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=$e(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}}},gOt=p.object({route:p.array(Hx),source_trace_id:p.string().optional()}),m9=class extends Me{constructor(){super(...arguments);f(this,"pcb_trace_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:gOt}}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:h,...d}=l,_=$e(o,{x:u,y:h});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}}},Nd=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:LH}}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 h=typeof u.x=="number"?u.x:parseFloat(String(u.x)),d=typeof u.y=="number"?u.y:parseFloat(String(u.y));return{x:h,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})}},Qw=class extends Me{constructor(){super(...arguments);f(this,"pcb_keepout_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:_W}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let e=this.getSubcircuit(),{db:t}=this.root,{_parsedProps:i}=this,r=this._getGlobalPcbPositionBeforeLayout(),s=eo(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)}},V_=class extends Me{constructor(){super(...arguments);f(this,"pcb_hole_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:GH}}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})}},rP=class extends Me{constructor(){super(...arguments);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:AW}}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=eo(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"],h=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:h,layer:s(d),text: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}}},B1=class extends Me{constructor(){super(...arguments);f(this,"pcb_cutout_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:UH}}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,h={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(h)}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(),h={shape:"polygon",points:t.points.map(d=>$e(l,d)),subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=e.pcb_cutout.insert(h)}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})}}}},xOt=({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 rP({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})},bOt=(n,e)=>{let t=parseInt(n||"0",10),i;return e!=null?i=e-t:i=t,(i%360+360)%360},G_=({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 j1({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 j1({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 j1({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 f9({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?o.push(new Nd({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 Nd({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 Nd({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 Nd({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 Nd({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 Qw({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 Qw({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 V_({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_hole"&&a.hole_shape==="rect")o.push(new V_({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 V_({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 V_({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 B1({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height})):a.shape==="circle"?o.push(new B1({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius})):a.shape==="polygon"&&o.push(new B1({shape:"polygon",points:a.points}));else if(a.type==="pcb_silkscreen_text"){let c=bOt(e,a.ccw_rotation);t?.includes("pinrow")&&a.text.includes("PIN")?o.push(xOt({elm:a,pinLabels:r??i??{},layer:a.layer,readableRotation:c,anchorAlignment:a.anchor_alignment})):o.push(new rP({anchorAlignment:a.anchor_alignment||"center",text:n,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 m9({route:a.route}));return o};function sP(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:h,height:d}=c.getPcbSize();e=Math.min(e,l-h/2),t=Math.min(t,u-d/2),i=Math.max(i,l+h/2),r=Math.max(r,u+d/2),s=!0}else if(c.children.length>0){let l=sP(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 vOt(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 SOt(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)vOt(g,o,a,s)&&c.add(g);let u=1/0,h=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),P=e.y+t*Math.sin(x);u=Math.min(u,v),d=Math.max(d,v),h=Math.min(h,P),_=Math.max(_,P)}return!Number.isFinite(u)||!Number.isFinite(h)?null:{minX:u,maxX:d,minY:h,maxY:_}}function nnt(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,h=s.y1??0,d=s.x2??0,_=s.y2??0;o=(u+d)/2,a=(h+_)/2,c=Math.abs(d-u),l=Math.abs(_-h)}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=SOt(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 wOt(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 vet=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},wet=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}},POt=p.object({name:p.string().optional(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),layer:p.string().optional(),layers:p.array(p.string()).optional(),schX:p.number().optional(),schY:p.number().optional(),direction:p.enum(["up","down","left","right"]).optional(),connectsTo:p.union([p.string(),p.array(p.string())]).optional()}),Vi=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:POt}}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=mi(i.computeSchematicGlobalTransform(),An(-r.center.x,-r.center.y));return $e(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 $e(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},h=this.getSubcircuit(),d=e.pcb_port.insert({pcb_component_id:void 0,layers:c.getAvailablePcbLayers(),subcircuit_id:h?.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(!vet(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=wet(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 h=e.pcb_port.get(u.pcb_port_id),d={x:h.x,y:h.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{vet(t)&&(i=wet(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=wOt(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}`}},int=n=>{let e=n.find(t=>/^(pin)?\d+$/.test(t));return e?Number.parseInt(e.replace(/^pin/,"")):null};function F1(n,e){let t=int(n);if(!t)return null;let r=[...n.filter(s=>s.toString()!==t.toString()&&s!==`pin${t}`),...e?.additionalAliases?.[`pin${t}`]??[]];return new Vi({pinNumber:t,aliases:r})}var kOt=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},TOt=n=>{if(kOt(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}},Vw=.4;function rnt(n){let e=n;return e.leftSide!==void 0||e.rightSide!==void 0||e.topSide!==void 0||e.bottomSide!==void 0}var MOt=n=>{let e=n.portDistanceFromEdge??.4,t=n.schPortArrangement?TOt(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||!rnt(n.schPortArrangement))return v+1;let P={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[g],w=n.schPortArrangement?.[`${g}Side`]?.direction??P,T=n.schPortArrangement?.[`${g}Side`]?.pins,k=x;return w!==P&&(k=T.length-x-1),Y1(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+Vw,i.bottom+Vw),n.pinLabels&&o.filter(w=>w.side==="left"||w.side==="right").some(w=>n.pinLabels?.[`pin${w.pinNumber}`]||n.pinLabels?.[w.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+Vw,i.right+Vw));let h={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,P=h[v],w=d[v];return{x:P.x+x*w.x,y:P.y+x*w.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}},EOt=(0,snt.default)("tscircuit:core:footprint"),ont=class extends Me{get config(){return{componentName:"Footprint",zodProps:WH}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let n=this.children.filter(h=>h.componentName==="Constraint");if(n.length===0)return;let{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers(),t=h=>e&&"left"in h&&"right"in h?{...h,left:h.right,right:h.left}:h,i=n.flatMap(h=>h._getAllReferencedComponents().componentsWithSelectors).map(({component:h,selector:d,componentSelector:_,edge:g})=>({component:h,selector:d,componentSelector:_,edge:g,bounds:h._getPcbCircuitJsonBounds()}));if(i.some(h=>h.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function r(h){return i.find(({selector:d})=>d===h)}let s=new i_,o={};function a(h){return h in o||(o[h]=new Ia(h),s.addEditVariable(o[h],Rn.weak)),o[h]}for(let{selector:h,bounds:d}of i){let _=a(`${h}_x`),g=a(`${h}_y`);s.suggestValue(_,d.center.x),s.suggestValue(g,d.center.y)}for(let h of n){let d=h._parsedProps;if("xDist"in d){let{xDist:_,left:g,right:x,edgeToEdge:v,centerToCenter:P}=t(d),w=a(`${g}_x`),T=a(`${x}_x`),k=r(g)?.bounds,C=r(x)?.bounds;if(P){let M=new $n(T,[-1,w]);s.addConstraint(new Pi(M,si.Eq,d.xDist,Rn.required))}else if(v){let M=new $n(T,-C.width/2,[-1,w],-k.width/2);s.addConstraint(new Pi(M,si.Eq,d.xDist,Rn.required))}}else if("yDist"in d){let{yDist:_,top:g,bottom:x,edgeToEdge:v,centerToCenter:P}=d,w=a(`${g}_y`),T=a(`${x}_y`),k=r(g)?.bounds,C=r(x)?.bounds;if(P){let M=new $n(w,[-1,T]);s.addConstraint(new Pi(M,si.Eq,d.yDist,Rn.required))}else if(v){let M=new $n(w,k.height/2,[-1,T],-C.height/2);s.addConstraint(new Pi(M,si.Eq,d.yDist,Rn.required))}}else if("sameY"in d){let{for:_}=d;if(_.length<2)continue;let g=_.map(v=>a(`${v}_y`)),x=new $n(...g.slice(1));s.addConstraint(new Pi(x,si.Eq,g[0],Rn.required))}else if("sameX"in d){let{for:_}=d;if(_.length<2)continue;let g=_.map(v=>a(`${v}_x`)),x=new $n(...g.slice(1));s.addConstraint(new Pi(x,si.Eq,g[0],Rn.required))}}s.updateVariables(),EOt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(o).map(([h,d])=>({var:h,val:d.value()}))));let c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:h,bounds:{width:d,height:_}}of i){let g=a(`${h}_x`),x=a(`${h}_y`),v=g.value()-d/2,P=g.value()+d/2,w=x.value()+_/2,T=x.value()-_/2;c.left=Math.min(c.left,v),c.right=Math.max(c.right,P),c.top=Math.max(c.top,w),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:h,selector:d}of i){let _=a(`${d}_x`),g=a(`${d}_y`);h._setPositionFromLayout({x:_.value()+l.x,y:g.value()+l.y})}}},ant=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},COt=(n,e)=>{let t=n.replace(/\/+$/,""),i=e.replace(/^\/+/,"");return`${t}/${i}`},cnt=(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():COt(e,n)}catch{return n}},ZA=p.union([p.number(),p.string()]),Pet=p.object({x:ZA,y:ZA,z:ZA}),lnt=class extends Me{get config(){return{componentName:"CadModel",zodProps:xW}}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=eo(o).rotation.angle*180/Math.PI,l=Pet.parse({x:0,y:0,z:0});if(typeof s.rotationOffset=="number")l.z=Number(s.rotationOffset);else if(typeof s.rotationOffset=="object"){let v=Pet.parse(s.rotationOffset);l.x=Number(v.x),l.y=Number(v.y),l.z=Number(v.z)}let u=fS.parse({x:s.pcbX??0,y:s.pcbY??0,z:s.pcbZ??0,...typeof s.positionOffset=="object"?s.positionOffset:{}}),h=s.zOffsetFromSurface!==void 0?Y.parse(s.zOffsetFromSurface):0,d=n.props.layer==="bottom"?"bottom":"top",_=s.modelUrl?ant(s.modelUrl):void 0,g={};if(_==="stl"?g.model_stl_url=this._addCachebustToModelUrl(s.modelUrl):_==="obj"?g.model_obj_url=this._addCachebustToModelUrl(s.modelUrl):_==="gltf"?g.model_gltf_url=this._addCachebustToModelUrl(s.modelUrl):_==="glb"?g.model_glb_url=this._addCachebustToModelUrl(s.modelUrl):_==="step"||_==="stp"?g.model_step_url=this._addCachebustToModelUrl(s.modelUrl):_==="wrl"||_==="vrml"?g.model_wrl_url=this._addCachebustToModelUrl(s.modelUrl):g.model_stl_url=this._addCachebustToModelUrl(s.modelUrl),s.stepUrl){let v=this._addCachebustToModelUrl(s.stepUrl);v&&(g.model_step_url=v)}let x=e.cad_component.insert({position:{x:i.center.x+Number(u.x),y:i.center.y+Number(u.y),z:(d==="bottom"?-t/2:t/2)+(d==="bottom"?-h:h)+Number(u.z)},rotation:{x:Number(l.x),y:(d==="top"?0:180)+Number(l.y),z:d==="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,...g});this.cad_component_id=x.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=cnt(n,e);if(!t.includes("modelcdn.tscircuit.com"))return t;let i=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(i)}`}},unt=class extends Me{constructor(){super(...arguments);f(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:gW}}},IOt=(n,e)=>{if(!n)return;let t={};for(let[i,r]of Object.entries(n)){let s=Y1(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},ket=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}},NOt=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}},Tet=["top","bottom","inner1","inner2"],qw=(n,e=[])=>{let t=[];if(e.length===0){let a=n[0].layers;for(let c of a)t.push(...qw(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)?[]:qw(n.slice(1),e.concat([s]));let o=(i.optional_via?Tet:Tet.filter(a=>a!==s)).filter(a=>!i.layers||i.layers?.includes(a));for(let a of o)t.push(...qw(n.slice(1),e.concat(a)));return t};function Met(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 j_(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}var AOt=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(j_(t,r),j_(t,s)),a=Math.min(j_(i,r),j_(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],h=u[0],d=u[u.length-1],_=j_(l,h),g=j_(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},ROt=(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 OOt(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=ROt(n,r);s<i&&(t=r,i=s)}return t}var LOt=(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},X1=n=>({up:"bottom",down:"top",left:"right",right:"left"})[n]??null,n9=({firstEdge:n,firstEdgePort:e,firstDominantDirection:t,lastEdge:i,lastEdgePort:r,lastDominantDirection:s})=>{if(n&&e)return n9({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=>Fi(a.from,a.to)>.01),o};function FOt(n){try{return[n(),null]}catch(e){return[null,e]}}var zOt=(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 $Ot({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 DOt=(n,{db:e})=>{let t=e.pcb_board.list()[0];if(t.outline){let c=t.outline,l=(u,h)=>{let d=!1;for(let _=0,g=h.length-1;_<h.length;g=_++){let x=h[_].x,v=h[_].y,P=h[g].x,w=h[g].y;v>u.y!=w>u.y&&u.x<(P-x)*(u.y-v)/(w-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)},Eet=(n,e)=>Math.abs(n-e)<1e-4,jOt=(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=Eet(s.y,o.y),l=Eet(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 h={type:"rect",layers:[s.layer,o.layer],center:{x:s.x,y:s.y},connectedTo:[e],width:t,height:t};i.push(h)}}return i};function BOt(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,P=d*1.1,w=Math.abs(r*c)+Math.abs(d*l);o.push({center:{x:t.x+x,y:t.y+v},width:P,height:w})}}else{let d=r/e;for(let _=0;_<e;_++){let g=(_-e/2+.5)*d,x=-g*l,v=g*c,P=Math.abs(i*c)+Math.abs(d*l),w=d*1.1;o.push({center:{x:t.x+x,y:t.y+v},width:P,height:w})}}return o}function YOt(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 h=n[u],d=n[(u+1)%n.length];if(h.y<=c&&d.y>c||d.y<=c&&h.y>c){let _=(c-h.y)*(d.x-h.x)/(d.y-h.y)+h.x;l.push(_)}}l.sort((u,h)=>u-h);for(let u=0;u<l.length;u+=2)if(u+1<l.length){let h=l[u],_=l[u+1]-h;_>1e-6&&i.push({center:{x:h+_/2,y:c},width:_,height:t})}}return i}function XOt(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 Go=["top","inner1","inner2","bottom"],pnt=(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=BOt(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:Go,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.shape==="circle"){let s=XOt({center:r.center,radius:r.radius},{rectHeight:.6});for(let o of s)i.push({type:"rect",layers:Go,center:o.center,width:o.width,height:o.height,connectedTo:[]})}else if(r.shape==="polygon"){let s=YOt(r.points,{rectHeight:.6});for(let o of s)i.push({type:"rect",layers:Go,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:Go,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:Go,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:Go,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:Go,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:Go,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:Go,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),h=(a+c)/2,d=(l+u)/2;i.push({type:"rect",layers:Go,center:{x:h,y:d},width:c-a,height:u-l,connectedTo:t([r.pcb_plated_hole_id])})}}else if(r.type==="pcb_trace"){let s=jOt(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},_l=({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},_9=({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},UOt=({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(Na([r.from,r.to],[x.from,x.to],{lineThickness:.01})){let w=s==="vertical"?r.from.x:x.from.x,T=s==="vertical"?x.from.y:r.from.y,k={x:w,y:T};o.push({otherEdge:x,crossingPoint:k,distanceFromEdgeFrom:Fi(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=PS(r.from,c),h={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},_=Fi(d,r.to)<l,g=[{from:r.from,to:h},{from:h,to:d,is_crossing:!0},{from:d,to:r.to}];t.splice(i,1,...g),i+=g.length-2,_&&i++}return t},i9=.001,B_=(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},Cet=n=>{let e=Math.abs(n.from.x-n.to.x)<i9,t=Math.abs(n.from.y-n.to.y)<i9;return e?"vertical":t?"horizontal":"diagonal"},VOt=(n,e)=>{let t=Cet(n),i=Cet(e);if(t===i)return null;if(t==="vertical"&&i==="horizontal"||t==="horizontal"&&i==="vertical"){let h=t==="vertical"?n:e,d=t==="horizontal"?n:e,_=h.from.x,g=d.from.y,x={x:_,y:g};return B_(x,n)&&B_(x,e)?x:null}if(t==="vertical"||i==="vertical"){let h=t==="vertical"?n:e,d=t==="vertical"?e:n,_=h.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,P={x:_,y:v};return B_(P,n)&&B_(P,e)?P: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)<i9)return null;let c=(a-s)/(r-o),l=r*c+s,u={x:c,y:l};return B_(u,n)&&B_(u,e)?u:null},GOt=({edges:n,db:e,source_trace_id:t})=>{let i=_9({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=VOt(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 HOt(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,h=.01;return[{type:"rect",layers:["top"],center:{x:(a+c)/2,y:l},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(a+c)/2,y:u},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:a,y:(l+u)/2},width:h,height:l-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:c,y:(l+u)/2},width:h,height:l-u,connectedTo:[]}]}var WOt=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?kS(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=nnt(e.toArray());return r.push(...HOt(s,{padding:1})),r},qOt=({edges:n,db:e,source_trace_id:t})=>{let i=e.source_trace.get(t),r=_9({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&&Na([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()}},r9=n=>{switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},ZOt=oq.version??"unknown",z1=class extends Error{constructor(n){super(`${n} (capacity-autorouter@${ZOt})`),this.name="AutorouterError"}},tP=class extends Error{constructor(n){super(n.message),this.errorData=n,this.name="TraceConnectionError"}},KOt=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 V=n._findConnectedPorts();r=V.allPortsFound,s=V.portsWithSelectors??[]}catch(V){if(V instanceof tP){e.source_trace_not_connected_error.insert({...V.errorData,error_type:"source_trace_not_connected_error"});return}throw V}let{netsWithSelectors:o}=n._findConnectedNets();if(!r)return;let c=s.map(V=>V.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:[]},h=WOt(n),d=s.filter(({port:V})=>V.schematic_port_id!==null).map(({port:V})=>({port:V,position:V._getGlobalSchematicPositionAfterLayout(),schematic_port_id:V.schematic_port_id??void 0,facingDirection:V.facingDirection}));if(d.length===1&&o.length===1){let V=o[0].net,{port:H,position:et}=d[0],tt=n.getSubcircuit().selectAll("netlabel").find(Q=>{let nt=Q._parsedProps.connection??Q._parsedProps.connectsTo;return nt?Array.isArray(nt)?nt.some(ht=>n.getSubcircuit().selectOne(ht,{port:!0})===H):n.getSubcircuit().selectOne(nt,{port:!0})===H:!1});if(!tt){let Q=e.schematic_net_label.getWhere({source_trace_id:n.source_trace_id});Q&&(tt=Q)}if(tt){let Q="_getGlobalSchematicPositionBeforeLayout"in tt?tt._getGlobalSchematicPositionBeforeLayout():tt.anchor_position,nt=[];et.x===Q.x||et.y===Q.y?nt.push({from:et,to:Q}):(nt.push({from:et,to:{x:Q.x,y:et.y}}),nt.push({from:{x:Q.x,y:et.y},to:Q}));let pt=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:nt,junctions:[],subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=pt.schematic_trace_id;return}if(n.props.schDisplayLabel){let Q=X1(H.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel,source_net_id:V.source_net_id,anchor_position:et,center:_l({anchor_position:et,anchor_side:Q,text:n.props.schDisplayLabel}),anchor_side:Q});return}let mt=X1(H.facingDirection)??"bottom",G=e.schematic_net_label.insert({text:V._parsedProps.name,source_net_id:V.source_net_id,anchor_position:et,center:_l({anchor_position:et,anchor_side:mt,text:V._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 V=[];for(let et=0;et<d.length-1;et++){let tt=d[et],mt=d[et+1],G=qc({x:tt.position.x,y:tt.position.y,facingDirection:r9(tt.facingDirection)},{x:mt.position.x,y:mt.position.y,facingDirection:r9(mt.facingDirection)});for(let Q=0;Q<G.length-1;Q++)V.push({from:G[Q],to:G[Q+1]})}let H=(et,tt)=>{let mt=tt.width/2,G=tt.height/2,Q=tt.center.x-mt,nt=tt.center.x+mt,pt=tt.center.y-G,ht=tt.center.y+G,wt=ot=>ot.x>=Q&&ot.x<=nt&&ot.y>=pt&&ot.y<=ht;return wt(et.from)||wt(et.to)?!0:[[{x:Q,y:pt},{x:nt,y:pt}],[{x:nt,y:pt},{x:nt,y:ht}],[{x:nt,y:ht},{x:Q,y:ht}],[{x:Q,y:ht},{x:Q,y:pt}]].some(ot=>Na([et.from,et.to],ot,{lineThickness:0}))};for(let et of V)for(let tt of h)if(H(et,tt))return null;return V})();x&&x.length===0&&(x=null),u.pointsToConnect=d.map(({position:V})=>({...V,layer:"top"}));let v=NOt(h),P=2,w={minTraceWidth:.1,obstacles:h,connections:[u],bounds:{minX:v.minX-P,maxX:v.maxX+P,minY:v.minY-P,maxY:v.maxY+P},layerCount:1},T=pS,k=!1;if(n.getSubcircuit().props._schDirectLineRoutingEnabled&&(T=ket,k=!0),!x){let H=new T({input:w,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(H.length===0){if(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection()){n._doInitialSchematicTraceRenderWithDisplayLabel();return}H=new ket({input:w}).solveAndMapToTraces(),k=!0}let[{route:et}]=H;x=[];for(let tt=0;tt<et.length-1;tt++)x.push({from:et[tt],to:et[tt+1]})}let C=n.source_trace_id,M=[];if(!k){qOt({edges:x,db:e,source_trace_id:C});let V=_9({db:e,source_trace_id:C,differentNetOnly:!0}).flatMap(H=>H.edges);x=UOt({edges:x,otherEdges:V}),M=GOt({edges:x,db:e,source_trace_id:n.source_trace_id})}if(!x||x.length===0)return;let I=x[x.length-1],E=d[d.length-1],A=Met(I);x.push(...n9({lastEdge:I,lastEdgePort:E,lastDominantDirection:A}));let R=x[0],B=d[0],j=Met(R);if(x.unshift(...n9({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&&LOt(M,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:M,subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=U.schematic_trace_id;for(let{port:V}of s)V.schematic_port_id&&e.schematic_port.update(V.schematic_port_id,{is_connected:!0});l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.add(c)};function s9(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 JOt=.3,QOt=.6,Iet=(n,e)=>{if(n===void 0)return e;if(typeof n=="number")return n;let t=parseFloat(n);return Number.isFinite(t)?t:e},y9=n=>({holeDiameter:Iet(n?.viaHoleDiameter,JOt),padDiameter:Iet(n?.viaPadDiameter,QOt)}),tLt=(n,e)=>{let t=y9(e);return{holeDiameter:n.holeDiameter??t.holeDiameter,padDiameter:n.padDiameter??t.padDiameter}},Gw=n=>({...n._getGlobalPcbPositionAfterLayout(),layers:n.getAvailablePcbLayers()}),eLt=!1;function nLt(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],V=u[0].net.getAllConnectedPorts().filter(et=>et!==j);if(V.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let H=OOt(j,V);c.push(H),a.push(H)}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 h=a.flatMap(j=>j.matchedComponents.filter(U=>U.componentName==="TraceHint")),d=(n._parsedProps.pcbRouteHints??[]).concat(h.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=[Gw(a[0]),Gw(a[1])]:x=[Gw(a[0]),...d,Gw(a[1])];let v=qw(x);if(eLt&&v.length===0){n.renderError(`Could not find a common layer (using hints) for trace ${n.getString()}`);return}let P=tr(n.root.db.toArray()),[w,T]=FOt(()=>pnt(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 w)if(j.connectedTo.length>0){let V=P.getNetConnectedToId(j.connectedTo[0]);V&&j.connectedTo.push(V)}let k=[];if(v.length===0)k=x;else{let j=v[0].layer_path;k=x.map((U,V)=>U.via?{...U,via_to_layer:j[V]}:{...U,layers:[j[V]]})}k[0].pcb_port_id=a[0].pcb_port_id,k[k.length-1].pcb_port_id=a[1].pcb_port_id;let C=[];for(let[j,U]of ent(k)){let V="via_to_layer"in j?j.via_to_layer:null,H=2,et="layers"in j&&j.layers.length===1?j.layers[0]:V??"top",tt="layers"in U&&U.layers.length===1?U.layers[0]:V??"top",mt="pcb_port_id"in j?j.pcb_port_id:null,G="pcb_port_id"in U?U.pcb_port_id:null,Q=n._getExplicitTraceThickness()??n.getSubcircuit()._parsedProps.minTraceWidth??.16,nt=new pS({OBSTACLE_MARGIN:Q*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(mt&&G),connMap:P,input:{obstacles:w,minTraceWidth:Q,connections:[{name:n.source_trace_id,pointsToConnect:[{...j,layer:et,pcb_port_id:mt},{...U,layer:tt,pcb_port_id:G}]}],layerCount:n.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(j.x,U.x)-H,maxX:Math.max(j.x,U.x)+H,minY:Math.min(j.y,U.y)-H,maxY:Math.max(j.y,U.y)+H}}}),pt=null;try{pt=nt.solveAndMapToTraces()}catch(Et){n.renderError({type:"pcb_trace_error",pcb_trace_error_id:n.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${Et.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(!pt)return;if(pt.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(Et=>Et.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:a.map(Et=>Et.pcb_component_id)});return}let[ht]=pt;V&&(ht.route=ht.route.map(Et=>(Et.route_type==="wire"&&!Et.layer&&(Et.layer=V),Et))),mt&&ht.route[0].route_type==="wire"&&(ht.route[0].start_pcb_port_id=mt);let wt=ht.route[ht.route.length-1];G&&wt.route_type==="wire"&&(wt.end_pcb_port_id=G),C.push(ht.route)}let M=AOt(C),I=s9(M),E=n.getInheritedMergedProperty("pcbStyle"),{holeDiameter:A,padDiameter:R}=y9(E),B=e.pcb_trace.insert({route:M,source_trace_id:n.source_trace_id,subcircuit_id:n.getSubcircuit()?.subcircuit_id,trace_length:I});n._portsRoutedOnPcb=a,n.pcb_trace_id=B.pcb_trace_id;for(let j of M)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(M,a)}function iLt(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,C]=a,M=k.getAvailablePcbLayers(),I=C.getAvailablePcbLayers(),A=M.find(H=>I.includes(H))??M[0]??I[0]??"top",R=k._getGlobalPcbPositionAfterLayout(),B=C._getGlobalPcbPositionAfterLayout(),j=[{route_type:"wire",x:R.x,y:R.y,width:u,layer:A,start_pcb_port_id:k.pcb_port_id},{route_type:"wire",x:B.x,y:B.y,width:u,layer:A,end_pcb_port_id:C.pcb_port_id}],U=s9(j),V=e.pcb_trace.insert({route:j,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:U});n._portsRoutedOnPcb=a,n.pcb_trace_id=V.pcb_trace_id,n._insertErrorIfTraceIsOutsideBoard(j,a);return}if(!t.pcbPath)return;let h;t.pcbPathRelativeTo&&(h=c.find(k=>k.selector===t.pcbPathRelativeTo)?.port,h||(h=n.getSubcircuit().selectOne(t.pcbPathRelativeTo))),h||(h=a[0]);let d=a.find(k=>k!==h)??a[1],_=h.getAvailablePcbLayers()[0]||"top",g=h._getGlobalPcbPositionAfterLayout(),x=d._getGlobalPcbPositionAfterLayout(),v=[];v.push({route_type:"wire",x:g.x,y:g.y,width:u,layer:_,start_pcb_port_id:h.pcb_port_id});let P=h?._computePcbGlobalTransformBeforeLayout?.()||Sr();for(let k of t.pcbPath){let C,M=!1;if(typeof k=="string"){let E=n.getSubcircuit().selectOne(k,{type:"port"});if(!E){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=E._getGlobalPcbPositionAfterLayout();C={x:A.x,y:A.y},M=!0}else C={x:k.x,y:k.y},M=!1;let I=M?C:$e(P,C);v.push({route_type:"wire",x:I.x,y:I.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 w=s9(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:w});n._portsRoutedOnPcb=a,n.pcb_trace_id=T.pcb_trace_id,n._insertErrorIfTraceIsOutsideBoard(v,a)}function rLt(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 h=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),w=x.parent?.config.shouldRenderAsSchematicBox?`${x?.parent?.props.name}_${x?.props.name}`:`${v?.parent?.props.name}_${v?.props.name}`,T=n.props.schDisplayLabel??w;if(_&&_.text!==T&&(_.text=`${T} / ${_.text}`),g&&g?.text!==T&&(g.text=`${T} / ${g.text}`),!g){let k=X1(d.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??w,source_net_id:d.source_port_id,anchor_position:h,center:_l({anchor_position:h,anchor_side:k,text:n.props.schDisplayLabel??w}),anchor_side:k})}if(!_){let k=X1(u.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??w,source_net_id:u.source_port_id,anchor_position:l,center:_l({anchor_position:l,anchor_side:k,text:n.props.schDisplayLabel??w}),anchor_side:k})}}function sLt(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}"`,C=n.getSubcircuit(),M=C.getGroup();throw new tP({error_type:"source_trace_not_connected_error",message:k,subcircuit_id:C.subcircuit_id??void 0,source_group_id:M?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[s]})}let h=u.children.filter(k=>k.componentName==="Port"),d=c.includes(".")?c.split(".").pop()??"":c,_=h.flatMap(k=>k.getNameAndAliases()),g=_.some(k=>!/^(pin\d+|\d+)$/.test(k)),x=Array.from(new Set(_)).join(", "),v;h.length===0?v="It has no ports":g?v=`It has [${x}]`:v=`It has ${h.length} pins and no pinLabels (consider adding pinLabels)`;let P=`Could not find port for selector "${s}". Component "${u.props.name??a}" found, but does not have pin "${d}". ${v}`,w=n.getSubcircuit(),T=w.getGroup();throw new tP({error_type:"source_trace_not_connected_error",message:P,subcircuit_id:w.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 Fs=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 sLt(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(){iP(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 h=this._findConnectedPorts();r=h.allPortsFound,s=h.portsWithSelectors??[]}catch(h){if(h instanceof tP){e.source_trace_not_connected_error.insert({...h.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw h}if(!r)return;this._traceConnectionHash=this._computeTraceConnectionHash();let a=e.source_trace.list().find(h=>h.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&h.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=$Ot({ports:s,nets:c}),u=e.source_trace.insert({connected_source_port_ids:s.map(h=>h.port.source_port_id),connected_source_net_ids:c.map(h=>h.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:zOt(s.map(h=>h.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;DOt(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(){iLt(this)}doInitialPcbTraceRender(){nLt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){rLt(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(){KOt(this)}},oLt=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=Oo(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},aLt=(n,e)=>{let{db:t}=n.root,i=t.toArray();if(n.pcb_component_id){TS(i,n.pcb_component_id,e);return}if(n.source_group_id){MS(i,n.source_group_id,e);return}throw new Error(`Cannot reposition component ${n.getString()}: no pcb_component_id or source_group_id`)},cLt=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&&lLt(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"}))},lLt=(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 uLt(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 pLt(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 io(u)});for(let c of r){let l=c.anchor_position,u=uLt(c),h={center:{x:u.x+u.width/2,y:u.y+u.height/2},width:u.width,height:u.height},d=io(h);if(!a.some(T=>Wc(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},P=io(v);a.some(T=>Wc(P,T))||e.pcb_silkscreen_text.update(c.pcb_silkscreen_text_id,{anchor_position:{x:g,y:x}})}}function hLt(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)dLt(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 dLt(n,e){try{let t={name:"test",footprint:"test",pinLabels:{[n]:e}};return n_.safeParse(t).success}catch{return!1}}var H_=n=>n.startsWith("http://")||n.startsWith("https://"),a9=n=>{if(H_(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}},c9=n=>n.startsWith("/"),fLt=(0,hnt.default)("tscircuit:core:resolveStaticFileImport");async function dnt(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){fLt("failed to resolve static file via platform resolver",i)}return cnt(n,e?.projectBaseUrl)}function mLt(n,e){let{footprint:t}=n.props;if(t??(t=n._getImpliedFootprintString?.()),!t)return;let{pcbRotation:i,pinLabels:r,pcbPinLabels:s}=n.props,o=ant(String(t)),a=o?n.root?.platform?.footprintFileParserMap?.[o]:null;if(typeof t=="string"&&(H_(t)||c9(t))&&a){if(n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0,e("load-footprint-from-platform-file-parser",async()=>{let c=H_(t)?t:await dnt(t,n.root?.platform);try{let l=await a.loadFromUrl(c),u=G_({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 h=n.getSubcircuit(),d=`${n.getString()} failed to load footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Rm.parse({type:"external_footprint_load_error",message:d,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:h.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"&&H_(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(),h=G_({componentName:n.name,componentRotation:i,footprinterString:c,pinLabels:r,pcbPinLabels:s},u);n.addAll(h),n._markDirty("InitializePortsFromChildren")}catch(l){let u=n.root?.db;if(u&&n.source_component_id&&n.pcb_component_id){let h=n.getSubcircuit(),d=`${n.getString()} failed to load external footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=Rm.parse({type:"external_footprint_load_error",message:d,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:h.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=a9(t);if(!c||n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let u=n.root?.platform?.footprintLibraryMap?.[c.footprintLib],h;if(typeof u=="function"&&(h=u),!h)return;let d=n.getInheritedMergedProperty("pcbStyle");e("load-lib-footprint",async()=>{try{let _=await h(c.footprintName,{resolvedPcbStyle:d}),g=null;if(Array.isArray(_)?g=_:Array.isArray(_.footprintCircuitJson)&&(g=_.footprintCircuitJson),!g)return;let x=G_({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(_)),P=Rm.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(P)}throw _}});return}if(!(0,o9.isValidElement)(t)&&t.componentName==="Footprint"&&n.add(t),Array.isArray(t)&&!(0,o9.isValidElement)(t)&&t.length>0){try{let c=G_({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(),h=`${n.getString()} failed to load json footprint: `+(c instanceof Error?c.message:String(c)),d=qx.parse({type:"circuit_json_footprint_load_error",message:h,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 _Lt(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=sP(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 yLt=(0,qet.default)("tscircuit:core"),gLt=p.object({x:Qe,y:Qe,z:Qe}),Gn=class extends Me{constructor(e){let t={...e},i=[];if(t.pinLabels&&!Array.isArray(t.pinLabels)){let{validPinLabels:r,invalidPinLabelsMessages:s}=hLt(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 h of u){let d=Y1(h,this._parsedProps.pinLabels);i.push(new Vi({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 h=0;h<u;h++)i.push(new Vi({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,h=Array.isArray(c)?c.slice(1):[];l?(l.externallyAddedAliases.push(u,...h),l.props.name=u):(l=new Vi({pinNumber:parseInt(a),name:u,aliases:[...h,...e.additionalAliases?.[`pin${parseInt(a)}`]??[]]},{originDescription:`pinLabels:pin${a}`}),i.push(l))}if(t.schematicSymbolName&&!e.ignoreSymbolPorts){let a=_i[this._getSchematicSymbolNameOrThrow()];if(!a)return;for(let c of a.ports){let l=int(c.labels);if(!l)continue;let u=i.find(h=>h._parsedProps.pinNumber===Number(l));if(u)u.schematicSymbolPortDef=c;else{let h=F1(c.labels.concat(e.additionalAliases?.[`pin${l}`]??[]));h&&(h.originDescription=`schematicSymbol:labels[0]:${c.labels[0]}`,h.schematicSymbolPortDef=c,i.push(h))}}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 Vi({pinNumber:a,aliases:e.additionalAliases?.[`pin${a}`]??[]}));continue}let c=[...r.leftSide?.pins??[],...r.rightSide?.pins??[],...r.topSide?.pins??[],...r.bottomSide?.pins??[]].map(l=>Y1(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 Vi({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(H_(r)||c9(r)||a9(r))return;let s=vM.string(r).soup(),o=G_({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,Va.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=Gx.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=_i[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:_Ot(o),pin_spacing:t.schPinSpacing??.2,pin_styles:mOt(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,h=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 h=Om.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(h)}let s=this._computePcbGlobalTransformBeforeLayout(),a=eo(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 h=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=h.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 h=Zx.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(h)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:e}=this.root,{_parsedProps:t}=this,i=sP(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 h of u){if(h.isSchematicPrimitive&&h.componentName==="SchematicLine"){let d=e.schematic_line.get(h.schematic_line_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicRect"){let d=e.schematic_rect.get(h.schematic_rect_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicCircle"){let d=e.schematic_circle.get(h.schematic_circle_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicArc"){let d=e.schematic_arc.get(h.schematic_arc_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicText"){let d=e.schematic_text.get(h.schematic_text_id);d&&i.push(d)}h.children&&h.children.length>0&&r(h.children)}};if(r(this.children),i.length===0)return;let s=nnt(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(){_Lt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(e){let t=tnt(e);return{element:e,component:t}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let e=this.props.footprint;(0,Va.isValidElement)(e)&&(this.children.some(s=>s.componentName==="Footprint")||this.add(e));let t=this.props.symbol;(0,Va.isValidElement)(t)&&(this.children.some(s=>s.componentName==="Symbol")||this.add(t));let i=this.props.cadModel;if((0,Va.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(){mLt(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,Va.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&&yLt(`Similar ports added. Port 1: ${r}, Port 2: ${t}`)}super.add(t)}getPortsFromFootprint(e){let{footprint:t}=this.props;if((!t||(0,Va.isValidElement)(t))&&(t=this.children.find(r=>r.componentName==="Footprint")),typeof t=="string"){if(H_(t))return[];if(c9(t))return[];if(a9(t))return[];let r=vM.string(t).soup(),s=[];for(let o of r)if("port_hints"in o&&o.port_hints){let a=F1(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,Va.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(h=>h.startsWith("pin"))||(c=[...c,`pin${s}`]),s++;let u=F1(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=F1(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=_i[e.schematicSymbolName];if(!t)return[];let i=[];for(let r of t.ports){let s=F1(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){iP(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(!rnt(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 MOt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:i,numericSchPinStyle:IOt(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=gLt.parse({x:0,y:0,z:typeof r?.rotationOffset=="number"?r.rotationOffset:0,...typeof r?.rotationOffset=="object"?r.rotationOffset??{}:{}}),c=Dh.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?Y.parse(r.zOffsetFromSurface):0,u=this.props.layer==="bottom"?"bottom":"top",h=this._computePcbGlobalTransformBeforeLayout(),_=eo(h).rotation.angle*180/Math.PI,g=u==="bottom",x=_+(a.z??0),v=ad(x),P=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:ad(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});this.cad_component_id=P.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=Ux.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 Fs({from:`.${this.name} > .${t}`,to:String(s)}))}}doInitialSourceDesignRuleChecks(){cLt(this)}_getMinimumFlexContainerSize(){return oLt(this)}_repositionOnPcb(e){return aLt(this,e)}doInitialSilkscreenOverlapAdjustment(){return pLt(this)}isRelativelyPositioned(){return this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0}},xLt=({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}},bLt=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}=W4,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 z1(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 z1(n.message):new z1(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 z1(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},g9=class extends Me{constructor(){super(...arguments);f(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:zW}}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=>({...$e(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()})}},fnt=({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=Ee(n).pcb_component.get(s);if(!a)continue;let c=Ee(n).source_component.get(a.source_component_id);if(!c)continue;let l=i.pcb_placements?.findIndex(h=>h.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},mnt=({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=Ee(n).schematic_component.get(s);if(!a||!a.source_component_id)continue;let c=Ee(n).source_component.get(a.source_component_id);if(!c)continue;let l=i.schematic_placements?.findIndex(h=>h.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},vLt=({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=mnt({circuitJson:n,editEvents:i,manualEditsFile:s})),r.length>0&&(s=fnt({circuitJson:n,editEvents:r,manualEditsFile:s})),s},SLt=(n,e)=>{if(Ee(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=Ee(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},wLt=({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=An(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:x4(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=SLt(n,t));return n},_nt=(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},l9=({db:n,circuitJson:e,subcircuit_id:t,minTraceWidth:i=.1})=>{if(!n&&e&&(n=Ee(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 I=_nt(n,t);for(let E of I)s.add(E)}let o=(e??n.toArray()).filter(I=>!t||"subcircuit_id"in I&&s.has(I.subcircuit_id)),a=n.pcb_board.list()[0];n=Ee(o);let c=tr(o),l=pnt([...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(I=>!t||s?.has(I.subcircuit_id)),c);for(let I of l){let E=I.connectedTo.flatMap(A=>c.getIdsConnectedToNet(A));I.connectedTo.push(...E)}let u=l.flatMap(I=>[{x:I.center.x-I.width/2,y:I.center.y-I.height/2},{x:I.center.x+I.width/2,y:I.center.y+I.height/2}]).concat(a?.outline??[]),h;if(a&&!a.outline?h={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}:h={minX:Math.min(...u.map(I=>I.x))-1,maxX:Math.max(...u.map(I=>I.x))+1,minY:Math.min(...u.map(I=>I.y))-1,maxY:Math.max(...u.map(I=>I.y))+1},t){let I=n.pcb_group.getWhere({subcircuit_id:t});if(I?.width&&I.height){let E={minX:I.center.x-I.width/2,maxX:I.center.x+I.width/2,minY:I.center.y-I.height/2,maxY:I.center.y+I.height/2};h={minX:Math.min(h.minX,E.minX),maxX:Math.max(h.maxX,E.maxX),minY:Math.min(h.minY,E.minY),maxY:Math.max(h.maxY,E.maxY)}}}let d=new Set(n.pcb_trace.list().map(I=>I.source_trace_id).filter(I=>!!I)),_=n.source_trace.list().filter(I=>!d.has(I.source_trace_id)).map(I=>{let E=I.connected_source_port_ids.map(H=>{let et=n.source_port.get(H),tt=n.pcb_port.getWhere({source_port_id:H});return{...et,...tt}});if(E.length<2)return null;let[A,R]=E;if(A.x===void 0||A.y===void 0)return console.error(`(source_port_id: ${A.source_port_id}) for trace ${I.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 ${I.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(H=>H.pcb_port_id===A.pcb_port_id||H.pcb_port_id===R.pcb_port_id),V=[];for(let H of U){let tt=n.pcb_port.get(H.pcb_port_id)?.layers?.[0]??"top";for(let mt of H.route)V.push({x:mt.x,y:mt.y,layer:tt})}return{name:I.source_trace_id??c.getNetConnectedToId(I.source_trace_id)??"",source_trace_id:I.source_trace_id,width:I.min_trace_thickness,pointsToConnect:[{x:A.x,y:A.y,layer:B,pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},...V,{x:R.x,y:R.y,layer:j,pointId:R.pcb_port_id,pcb_port_id:R.pcb_port_id}]}}).filter(I=>I!==null),g=new Map(_.map(I=>[I.source_trace_id,I])),x=n.source_net.list().filter(I=>!t||s?.has(I.subcircuit_id)),v=[];for(let I of x){let E=n.source_trace.list().filter(A=>A.connected_source_net_ids?.includes(I.source_net_id));v.push({name:I.source_net_id??c.getNetConnectedToId(I.source_net_id),pointsToConnect:E.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 P=n.pcb_breakout_point.list().filter(I=>!t||s?.has(I.subcircuit_id)),w=[],T=new Map;for(let I of P){let E={x:I.x,y:I.y,layer:"top"};if(I.source_trace_id){let A=g.get(I.source_trace_id)??T.get(I.source_trace_id);if(A)A.pointsToConnect.push(E);else{let R={name:I.source_trace_id,source_trace_id:I.source_trace_id,pointsToConnect:[E]};w.push(R),T.set(I.source_trace_id,R)}}else if(I.source_net_id){let A=v.find(R=>R.name===I.source_net_id);A?A.pointsToConnect.push(E):w.push({name:I.source_net_id,pointsToConnect:[E]})}else if(I.source_port_id){let A=n.pcb_port.getWhere({source_port_id:I.source_port_id});A&&w.push({name:I.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},E]})}}let k=[..._,...v,...w],C=new Map;for(let I of k)for(let E of I.pointsToConnect)E.pointId&&C.set(E.pointId,I);let M=n.pcb_trace.list().filter(I=>!t||s?.has(I.subcircuit_id));for(let I of M){let E=new Set;for(let B of I.route)B.start_pcb_port_id&&E.add(B.start_pcb_port_id),B.end_pcb_port_id&&E.add(B.end_pcb_port_id);if(E.size<2)continue;let A=E.values().next().value;if(!A)continue;let R=C.get(A);R&&[...E].every(B=>C.get(B)===R)&&(R.externallyConnectedPointIds??(R.externallyConnectedPointIds=[]),R.externallyConnectedPointIds.push([...E]))}return{simpleRouteJson:{bounds:h,obstacles:l,connections:k,layerCount:a?.num_layers??2,minTraceWidth:i,outline:a?.outline?.map(I=>({...I}))},connMap:c}},PLt=n=>{let e={};if(!n)return e;for(let i of Ua)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},kLt=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 h of t[c])h.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 x9({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 Net=(0,ynt.default)("Group_doInitialSchematicLayoutMatchAdapt");function TLt(n){let{db:e}=n.root,t=Rg(e.toArray(),{source_group_id:n.source_group_id}),i=q4(t);Net.enabled&&global?.debugGraphics&&global.debugGraphics?.push(rl(i,{title:`floatingBpcGraph-${n.name}`}));let r=q4(t),s={boxes:r.boxes,pins:r.pins.map(c=>({...c,color:c.color.replace("not_connected","normal")}))},{result:o}=rJ([{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(h=>h.boxId===c.boxId).filter(h=>!h.color.includes("center")).length<=2).map(c=>c.boxId)),corpus:{}});Net.enabled&&global?.debugGraphics&&global.debugGraphics?.push(rl(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 h={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:h.x-l.center.x,y:h.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;x9({db:e,schematicComponentId:l.schematic_component_id,deltaX:g.x,deltaY:g.y}),l.center=h;continue}let u=e.schematic_net_label.get(c.boxId);if(u){let h=o.pins.find(_=>_.boxId===c.boxId&&_.color==="netlabel_center");if(!h)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+h.offset.x,y:d.y+h.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 xe=(0,gnt.default)("Group_doInitialSchematicLayoutMatchpack");function Aet(n){switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function Ret(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 MLt(n,e,t){let i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};xe(`[${t.name}] Processing ${n.childNodes.length} child nodes for input problem`),n.childNodes.forEach((s,o)=>{if(xe(`[${t.name}] Processing child ${o}: nodeType=${s.nodeType}`),s.nodeType==="component"?xe(`[${t.name}] - Component: ${s.sourceComponent?.name}`):s.nodeType==="group"&&xe(`[${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(w=>w.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 h=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-h)/2,v=(_-g)/2;i.chipMap[a]={chipId:a,pins:[],size:{x:(c.size?.width||1)+h+d,y:(c.size?.height||1)+_+g},availableRotations:u};let P=e.schematic_port.list({schematic_component_id:c.schematic_component_id});for(let w of P){let T=e.source_port.get(w.source_port_id);if(!T)continue;let k=`${a}.${T.pin_number||T.name||w.schematic_port_id}`;i.chipMap[a].pins.push(k);let C=Aet(w.facing_direction);i.chipPinMap[k]={pinId:k,offset:{x:(w.center?.x||0)-(c.center.x||0)+x,y:(w.center?.y||0)-(c.center.y||0)+v},side:C}}}else if(s.nodeType==="group"&&s.sourceGroup){let a=s.sourceGroup.name||`group_${o}`;xe(`[${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(xe(`[${t.name}] Found schematic_group for ${a}:`,c),c){xe(`[${t.name}] Treating group ${a} as composite chip`);let u=e.schematic_component.list({schematic_group_id:c.schematic_group_id});xe(`[${t.name}] Group ${a} has ${u.length} components:`,u.map(A=>A.source_component_id));let h=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;h=Math.min(h,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,P=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,w=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,T=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0,k=(P-v)/2,C=(w-T)/2,M=(x?d-h:2)+v+P,I=(x?g-_:2)+w+T;xe(`[${t.name}] Group ${a} computed size: ${M} x ${I}`);let E=[];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}`;E.push(U);let V=c.center||{x:0,y:0},H=Aet(B.facing_direction);i.chipPinMap[U]={pinId:U,offset:{x:(B.center?.x||0)-V.x+k,y:(B.center?.y||0)-V.y+C},side:H}}}xe(`[${t.name}] Group ${a} has ${E.length} pins:`,E),i.chipMap[a]={chipId:a,pins:E,size:{x:M,y:I}},xe(`[${t.name}] Added group ${a} to chipMap`)}else xe(`[${t.name}] Warning: No schematic_group found for group ${a}`)}}),xe(`[${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 h=e.schematic_component.list({schematic_group_id:u.schematic_group_id});for(let d of h){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),xe(`[${t.name}] \u2713 Pin ${a} has connectivity key: ${v}`)}else xe(`[${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 h of u){let d=h.pin_number||h.name;if(String(d)===String(c)&&h.subcircuit_connectivity_map_key){let _=h.subcircuit_connectivity_map_key;r.has(_)||r.set(_,[]),r.get(_).push(a),xe(`[${t.name}] Pin ${a} has connectivity key: ${_}`)}}}}xe(`[${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(xe(`[${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 h=[];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],P=n.childNodes.find(w=>w.nodeType==="component"&&w.sourceComponent?w.sourceComponent.name===v:w.nodeType==="group"&&w.sourceGroup?`group_${n.childNodes.indexOf(w)}`===v:!1);P?.nodeType==="component"&&P.sourceComponent&&e.source_port.list({source_component_id:P.sourceComponent.source_component_id}).some(T=>T.source_port_id===d)&&h.push(_)}}for(let d=0;d<h.length;d++)for(let _=d+1;_<h.length;_++){let g=h[d],x=h[_];i.pinStrongConnMap[`${g}-${x}`]=!0,i.pinStrongConnMap[`${x}-${g}`]=!0,xe(`[${t.name}] Created strong connection: ${g} <-> ${x}`)}}}if(c){let u=e.source_net.getWhere({subcircuit_connectivity_map_key:s}),h=u?.is_ground??!1,d=u?.is_power??!1;i.netMap[s]={netId:s,isGround:h,isPositiveVoltageSource:d};for(let _ of o)i.netConnMap[`${_}-${s}`]=!0;xe(`[${t.name}] Created net ${s} with ${o.length} pins:`,o)}}return i}function ELt(n){let{db:e}=n.root,t=a_(e.toArray(),{source_group_id:n.source_group_id});if(xe(`[${n.name}] Starting matchpack layout with ${t.childNodes.length} children`),xe(`[${n.name}] Tree structure:`,JSON.stringify(t,null,2)),t.childNodes.length<=1){xe(`[${n.name}] Only ${t.childNodes.length} children, skipping layout`);return}xe("Converting circuit tree to InputProblem...");let i=MLt(t,e,n);xe.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${n.name}`,content:JSON.stringify(i,null,2)});let r=new pQ(i);if(xe("Starting LayoutPipelineSolver..."),xe.enabled&&global?.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-initial-${n.name}`})}if(r.solve(),xe(`Solver completed in ${r.iterations} iterations`),xe(`Solved: ${r.solved}, Failed: ${r.failed}`),r.failed)throw xe(`Solver failed with error: ${r.error}`),new Error(`Matchpack layout solver failed: ${r.error}`);let s=r.getOutputLayout();if(xe("OutputLayout:",JSON.stringify(s,null,2)),xe("Solver completed successfully:",!r.failed),xe.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){xe(`Warning: Found ${o.length} overlapping components:`);for(let c of o)xe(` ${c.chip1} overlaps ${c.chip2} (area: ${c.overlapArea})`)}let a=n._getGlobalSchematicPositionBeforeLayout();xe(`Group offset: x=${a.x}, y=${a.y}`),xe(`Applying layout results for ${Object.keys(s.chipPlacements).length} chip placements`);for(let[c,l]of Object.entries(s.chipPlacements)){xe(`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 xe(` 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 xe(` Checking group ${_} (expected chipId: ${g}): matches=${x}`),x}return!1});if(!u){xe(`Warning: No tree node found for chip: ${c}`),xe("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 h={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){xe(`Moving component ${c} to (${h.x}, ${h.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:h.x-d.center.x,y:h.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(x9({db:e,schematicComponentId:d.schematic_component_id,deltaX:x.x,deltaY:x.y}),d.center=h,l.ccwRotationDegrees!==0){xe(`Component ${c} has rotation: ${l.ccwRotationDegrees}\xB0`);let v=l.ccwRotationDegrees*Math.PI/180,P=Math.cos(v),w=Math.sin(v);for(let T of _){let k=T.center.x-h.x,C=T.center.y-h.y,M=k*P-C*w,I=k*w+C*P;T.center.x=h.x+M,T.center.y=h.y+I;let E=T.facing_direction||"right";T.facing_direction=Ret(E,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-h.x,C=T.position.y-h.y,M=k*P-C*w,I=k*w+C*P;T.position.x=h.x+M,T.position.y=h.y+I}if(d.symbol_name){let T=d.symbol_name.match(/_(right|left|up|down)$/);T&&(d.symbol_name=d.symbol_name.replace(T[0],`_${Ret(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){xe(`Moving group ${c} to (${h.x}, ${h.y}) from (${d.center?.x}, ${d.center?.y})`);let _=e.schematic_component.list({schematic_group_id:d.schematic_group_id});xe(`Group ${c} has ${_.length} components to move`);let g=d.center||{x:0,y:0},x={x:h.x-g.x,y:h.y-g.y};xe(`Position delta for group ${c}: (${x.x}, ${x.y})`);for(let v of _)if(v.center){let P={...v.center};v.center.x+=x.x,v.center.y+=x.y,xe(`Moved component ${v.source_component_id} from (${P.x}, ${P.y}) to (${v.center.x}, ${v.center.y})`);let w=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 w)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=h,xe(`Updated group ${c} center to (${h.x}, ${h.y})`)}}}xe("Matchpack layout completed successfully")}function CLt(n){if(!n.isSubcircuit)return;let{db:e}=n.root,t=n.selectAll("trace"),i=n.selectAll("via"),r=n.selectAll("net"),s=new Jm({});s.addConnections(t.map(u=>{let h=e.source_trace.get(u.source_trace_id);return h?[h.source_trace_id,...h.connected_source_port_ids,...h.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 h=s.getNetConnectedToId(u.source_trace_id);h&&(u.subcircuit_connectivity_map_key=`${a??`unnamedsubcircuit${n._renderId}`}_${h}`,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 h=e.source_trace.get(u.source_trace_id);if(h)for(let d of h.connected_source_port_ids)c.add(d)}for(let u of c){let h=s.getNetConnectedToId(u);if(!h)continue;let d=`${a??`unnamedsubcircuit${n._renderId}`}_${h}`;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 h=e.source_trace.get(u.source_trace_id);if(h)for(let d of h.connected_source_net_ids)l.add(d)}for(let u of o)l.add(u.source_net_id);for(let u of l){let h=s.getNetConnectedToId(u);if(!h)continue;let d=`${a??`unnamedsubcircuit${n._renderId}`}_${h}`;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 h=u._getConnectedNetOrTrace();h&&h.subcircuit_connectivity_map_key&&(u.subcircuit_connectivity_map_key=h.subcircuit_connectivity_map_key)}}function ILt(n){let{db:e}=n.root,t=n._parsedProps,i=n.children.filter(C=>{let M=C._parsedProps?.schX!==void 0||C._parsedProps?.schY!==void 0;return C.schematic_component_id&&!M});if(i.length===0)return;let r=0,s=0;for(let C of i){let M=e.schematic_component.get(C.schematic_component_id);M?.size&&(r=Math.max(r,M.size.width),s=Math.max(s,M.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 h,d;o!==void 0&&a!==void 0?(h=o,d=a):o!==void 0?(h=o,d=Math.ceil(i.length/h)):a!==void 0?(d=a,h=Math.ceil(i.length/d)):(h=Math.ceil(Math.sqrt(i.length)),d=Math.ceil(i.length/h)),h===0&&i.length>0&&(h=1),d===0&&i.length>0&&(d=i.length);let _,g,x=C=>{if(C!==void 0)return typeof C=="number"?C:D.parse(C)};if(l!==void 0||u!==void 0){let C=typeof c=="object"&&c!==null?c.x:c,M=typeof c=="object"&&c!==null?c.y:c;_=x(u??C)??1,g=x(l??M)??1}else if(typeof c=="number")_=c,g=c;else if(typeof c=="string"){let C=D.parse(c);_=C,g=C}else if(typeof c=="object"&&c!==null){let C=c.x,M=c.y;_=typeof C=="number"?C:D.parse(C??"0mm"),g=typeof M=="number"?M:D.parse(M??"0mm")}else _=1,g=1;let v=h*r+Math.max(0,h-1)*_,P=d*s+Math.max(0,d-1)*g,w=n._getGlobalSchematicPositionBeforeLayout(),T=w.x-v/2+r/2,k=w.y+P/2-s/2;for(let C=0;C<i.length;C++){let M=i[C];if(!M.schematic_component_id)continue;let I=Math.floor(C/h),E=C%h;if(I>=d||E>=h){console.warn(`Schematic grid layout: Child ${M.getString()} at index ${C} (row ${I}, col ${E}) exceeds specified grid dimensions (${d}x${h}). Skipping placement.`);continue}let A=T+E*(r+_),R=k-I*(s+g),B=e.schematic_component.get(M.schematic_component_id);if(B){let j=B.center,U={x:A,y:R};e.schematic_component.update(M.schematic_component_id,{center:U});let V=U.x-j.x,H=U.y-j.y,et=e.schematic_port.list({schematic_component_id:M.schematic_component_id});for(let mt of et)e.schematic_port.update(mt.schematic_port_id,{center:{x:mt.center.x+V,y:mt.center.y+H}});let tt=e.schematic_text.list({schematic_component_id:M.schematic_component_id});for(let mt of tt)e.schematic_text.update(mt.schematic_text_id,{position:{x:mt.position.x+V,y:mt.position.y+H}});x9({db:e,schematicComponentId:M.schematic_component_id,deltaX:V,deltaY:H})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:v,height:P,center:w})}var Oet=(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,h=l-c;return{width:u,height:h}}return null},NLt=n=>{let{db:e}=n.root,t=n._parsedProps,i=a_(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,h=0;typeof o=="object"?(u=o.y??0,h=o.x??0):typeof o=="number"?(u=o,h=o):typeof o=="string"&&(u=D.parse(o),h=D.parse(o));let d,_=t.width??t.schWidth??void 0,g=t.height??t.schHeight??void 0;(_===void 0||g===void 0)&&(d=ES(i.childNodes.map(k=>Oet(e,k)).filter(k=>k!==null),{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h}),_=d.width,g=d.height);let v=new Nw(_,g,{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h});for(let k of i.childNodes){let C=Oet(e,k);v.addChild({metadata:k,width:C?.width??0,height:C?.height??0,flexBasis:C?a==="row"?C.width:C.height:void 0})}v.build();let P={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let k of v.children)P.minX=Math.min(P.minX,k.position.x),P.minY=Math.min(P.minY,k.position.y),P.maxX=Math.max(P.maxX,k.position.x+k.size.width),P.maxY=Math.max(P.maxY,k.position.y+k.size.height);P.width=P.maxX-P.minX,P.height=P.maxY-P.minY;let w={x:-(P.maxX+P.minX)/2,y:-(P.maxY+P.minY)/2},T=e.toArray();for(let k of v.children){let{sourceComponent:C,sourceGroup:M}=k.metadata;if(C){let I=e.schematic_component.getWhere({source_component_id:C.source_component_id});if(!I)continue;mq(T,I.schematic_component_id,{x:k.position.x+k.size.width/2+w.x,y:k.position.y+k.size.height/2+w.y})}if(M){if(!e.schematic_group.getWhere({source_group_id:M.source_group_id}))continue;yq(T,M.source_group_id,{x:k.position.x+k.size.width/2+w.x,y:k.position.y+k.size.height/2+w.y})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:P.width,height:P.height})},KA=1;function ALt(n){let{db:e}=n.root,t=n._parsedProps,i=RLt(n);if(i.length===0)return;let r=OLt({db:e,pcbChildren:i}),s=LLt(t),o=FLt({props:t,pcbChildren:i,childDimensions:r,gridConfig:s}),a=DLt({pcbChildren:i,childDimensions:r,gridLayout:o,gridConfig:s}),{itemCoordinates:c}=a.layout();jLt({db:e,group:n,pcbChildren:i,itemCoordinates:c,gridLayout:o}),BLt({db:e,group:n,props:t,gridLayout:o})}function RLt(n){return n.children.filter(e=>e.pcb_component_id||e.pcb_group_id)}function OLt(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 LLt(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=h=>h===void 0?KA:typeof h=="number"?h:D.parse(h),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=KA,u=KA;if(a!==void 0||c!==void 0){let h=typeof o=="object"?o?.x:o,d=typeof o=="object"?o?.y:o;l=s(c??h),u=s(a??d)}else if(typeof o=="object"&&o!==null)l=s(o.x),u=s(o.y);else{let h=s(o);l=h,u=h}return{cols:e,rows:t,gapX:l,gapY:u,templateColumns:i,templateRows:r}}function FLt(n){let{props:e,pcbChildren:t,childDimensions:i,gridConfig:r}=n;return e.pcbGridTemplateColumns||e.pcbGridTemplateRows?zLt({props:e,gridConfig:r,pcbChildren:t,childDimensions:i}):$Lt({gridConfig:r,pcbChildren:t,childDimensions:i})}function zLt(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,h=l*r.height+Math.max(0,l-1)*t.gapY;return{gridTemplateColumns:s,gridTemplateRows:o,containerWidth:u,containerHeight:h}}function $Lt(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 DLt(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 bQ({containerWidth:i.containerWidth,containerHeight:i.containerHeight,gridTemplateColumns:i.gridTemplateColumns,gridTemplateRows:i.gridTemplateRows,gap:[r.gapY,r.gapX],children:s})}function jLt(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}`,h=r[u];if(!h){console.warn(`PCB grid layout: No coordinates found for child ${u}`);continue}let d=o.x-s.containerWidth/2+h.x+h.width/2,_=o.y+s.containerHeight/2-h.y-h.height/2;if(l.pcb_component_id)TS(a,l.pcb_component_id,{x:d,y:_});else{let g=l;g.pcb_group_id&&g.source_group_id&&MS(a,g.source_group_id,{x:d,y:_})}}}function BLt(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 YLt(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 XLt=(n,e)=>{let t=n.children.filter(h=>h.componentName==="Constraint"&&h._parsedProps.pcb),i=new Map,r={},s=h=>(r[h]!==h&&(r[h]=s(r[h])),r[h]),o=(h,d)=>{let _=s(h),g=s(d);_!==g&&(r[g]=_)},a=h=>{h in r||(r[h]=h)},c=h=>{let d=h.startsWith(".")?h.slice(1):h;return n.children.find(g=>g.name===d)?.pcb_component_id??void 0};for(let h of t){let d=h._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 h of Object.keys(r)){let d=s(h);i.has(d)||i.set(d,{componentIds:[],constraints:[]}),i.get(d).componentIds.push(h)}for(let h of t){let d=h._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(h)}let l={},u=Object.fromEntries(e.components.map(h=>[h.componentId,h]));for(let[h,d]of i.entries()){if(d.componentIds.length<=1)continue;let _=new i_,g={},x=(A,R)=>{let B=`${A}_${R}`;return g[B]||(g[B]=new Ia(B)),g[B]},v=d.componentIds[0];_.addConstraint(new Pi(x(v,"x"),si.Eq,0,Rn.required)),_.addConstraint(new Pi(x(v,"y"),si.Eq,0,Rn.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 Pi(new $n(x(j,"x"),[-1,x(B,"x")]),si.Eq,R.xDist,Rn.required))}else if("yDist"in R){let B=c(R.top),j=c(R.bottom);B&&j&&_.addConstraint(new Pi(new $n(x(B,"y"),[-1,x(j,"y")]),si.Eq,R.yDist,Rn.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 Pi(new $n(x(B[U],"x"),[-1,j]),si.Eq,0,Rn.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 Pi(new $n(x(B[U],"y"),[-1,j]),si.Eq,0,Rn.required))}}}_.updateVariables();let P={};for(let A of d.componentIds)P[A]={x:x(A,"x").value(),y:x(A,"y").value()};let w=1/0,T=1/0,k=-1/0,C=-1/0;for(let A of d.componentIds){let R=u[A],B=P[A];if(R)for(let j of R.pads){let U=B.x+j.offset.x,V=B.y+j.offset.y;w=Math.min(w,U-j.size.x/2),k=Math.max(k,U+j.size.x/2),T=Math.min(T,V-j.size.y/2),C=Math.max(C,V+j.size.y/2)}}let M={x:(w+k)/2,y:(T+C)/2},I=[],E={};for(let A of d.componentIds){let R=u[A],B=P[A];if(R){E[A]={x:B.x-M.x,y:B.y-M.y};for(let j of R.pads)I.push({padId:j.padId,networkId:j.networkId,type:j.type,size:j.size,offset:{x:B.x+j.offset.x-M.x,y:B.y+j.offset.y-M.y}})}}e.components=e.components.filter(A=>!d.componentIds.includes(A.componentId)),e.components.push({componentId:d.componentIds[0],pads:I,availableRotationDegrees:[0]}),d.relativeCenters=E,l[d.componentIds[0]]=d}return l},Let=({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:ad(o+s)};n.cad_component.update(r.cad_component_id,{rotation:a}),r.rotation=a},$1=(n,e,t)=>{if(e===t)return!0;let i=n.source_group.get(e);return!i||!i.parent_source_group_id?!1:$1(n,i.parent_source_group_id,t)},ULt=(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,P=v*Math.PI/180;for(let w of l.componentIds){let T=l.relativeCenters[w];if(!T)continue;let k={x:T.x*Math.cos(P)-T.y*Math.sin(P),y:T.x*Math.sin(P)+T.y*Math.cos(P)},C=i.pcb_component.get(w);if(!C)continue;let M=C.center,I=mi(n._computePcbGlobalTransformBeforeLayout(),An(s.x+k.x,s.y+k.y),Dc(P),An(-M.x,-M.y)),E=i.toArray().filter(A=>"pcb_component_id"in A&&A.pcb_component_id===w);s_(E,I),Let({db:i,pcbComponentId:w,rotationDegrees:v,layer:C.layer})}continue}let u=i.pcb_component.get(o);if(u){let v=n.source_group_id,w=i.source_component.get(u.source_component_id)?.source_group_id;if(w!==void 0&&!$1(i,w,v))continue;let T=u.center,k=c??a??0,C=mi(n._computePcbGlobalTransformBeforeLayout(),An(s.x,s.y),Dc(k*Math.PI/180),An(-T.x,-T.y)),M=i.toArray().filter(I=>"pcb_component_id"in I&&I.pcb_component_id===o);s_(M,C),Let({db:i,pcbComponentId:o,rotationDegrees:k,layer:u.layer});continue}let h=i.pcb_group.list().find(v=>v.source_group_id===o);if(!h)continue;let d=h.center,_=c??a??0,g=mi(n._computePcbGlobalTransformBeforeLayout(),An(s.x,s.y),Dc(_*Math.PI/180),An(-d.x,-d.y)),x=i.toArray().filter(v=>{if("source_group_id"in v&&v.source_group_id&&(v.source_group_id===o||$1(i,v.source_group_id,o)))return!0;if("source_component_id"in v&&v.source_component_id){let P=i.source_component.get(v.source_component_id);if(P?.source_group_id&&(P.source_group_id===o||$1(i,P.source_group_id,o)))return!0}if("pcb_component_id"in v&&v.pcb_component_id){let P=i.pcb_component.get(v.pcb_component_id);if(P?.source_component_id){let w=i.source_component.get(P.source_component_id);if(w?.source_group_id&&(w.source_group_id===o||$1(i,w.source_group_id,o)))return!0}}return!1});s_(x,g),i.pcb_group.update(h.pcb_group_id,{center:s})}};function VLt(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 GLt(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 HLt="1mm",Fet=(0,xnt.default)("Group_doInitialPcbLayoutPack"),WLt=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??HLt),u={},h=new Set,d=k=>{if(k?.pcb_component_id&&k?._parsedProps){let C=k._parsedProps,M=D.parse(C.pcbMarginLeft??C.pcbMarginX??0),I=D.parse(C.pcbMarginRight??C.pcbMarginX??0),E=D.parse(C.pcbMarginTop??C.pcbMarginY??0),A=D.parse(C.pcbMarginBottom??C.pcbMarginY??0);(M||I||E||A)&&(u[k.pcb_component_id]={left:M,right:I,top:E,bottom:A})}k?.children&&k.children.forEach(d)};d(n);let _=new Set;for(let k of n.children){let C=k;C._isNormalComponent&&C.isRelativelyPositioned?.()&&(C.pcb_component_id&&h.add(C.pcb_component_id),C.pcb_group_id&&_.add(C.pcb_group_id))}let g=e.toArray().filter(k=>k.type==="pcb_component"?!h.has(k.pcb_component_id):k.type==="pcb_group"?!_.has(k.pcb_group_id):!0),x=[];for(let k of h){let C=e.toArray().find(R=>R.type==="pcb_component"&&R.pcb_component_id===k);if(!C)continue;let M=C.center.x,I=C.center.y,E=e.toArray().filter(R=>R.type==="pcb_smtpad"&&R.pcb_component_id===k);for(let R of E){let B=VLt(R);if(!B||B.width===0||B.height===0)continue;let j,U;if(R.shape==="polygon"){let V=R.points.map(et=>et.x),H=R.points.map(et=>et.y);j=M+(Math.min(...V)+Math.max(...V))/2,U=I+(Math.min(...H)+Math.max(...H))/2}else j=M+R.x,U=I+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=GLt(R);if(!B||B.width===0||B.height===0)continue;let j=M+R.x,U=I+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),C=D.parse(t.height);v={minX:-k/2,maxX:k/2,minY:-C/2,maxY:C/2}}let P={...lQ(cQ(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},w=XLt(n,P);Fet.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:P}));let T=Ew(P);if(Fet.enabled&&global?.debugGraphics){let k=oA(T);k.title=`packOutput-${n.name}`,global.debugGraphics?.push(k)}ULt(n,T,w)},qLt=n=>{let{db:e}=n.root,{_parsedProps:t}=n,i=n.children.filter(C=>C.pcb_component_id||C.pcb_group_id);if(i.some(C=>{let M=C._parsedProps;return M?.pcbX!==void 0||M?.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 h=0,d=0;typeof a=="object"?(h=a.y??0,d=a.x??0):typeof a=="number"?(h=a,d=a):typeof a=="string"&&(h=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)&&(_=ES(i.map(C=>C._getMinimumFlexContainerSize()).filter(C=>C!==null),{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d}),g=_.width,x=_.height);let P=new Nw(g,x,{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d});for(let C of i){let M=C._getMinimumFlexContainerSize();P.addChild({metadata:C,width:M?.width??0,height:M?.height??0,flexBasis:M?c==="row"?M.width:M.height:void 0})}P.build();let w={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let C of P.children)w.minX=Math.min(w.minX,C.position.x),w.minY=Math.min(w.minY,C.position.y),w.maxX=Math.max(w.maxX,C.position.x+C.size.width),w.maxY=Math.max(w.maxY,C.position.y+C.size.height);w.width=w.maxX-w.minX,w.height=w.maxY-w.minY;let T=n._getGlobalPcbPositionBeforeLayout(),k={x:T.x-(w.maxX+w.minX)/2,y:T.y-(w.maxY+w.minY)/2};for(let C of P.children)C.metadata._repositionOnPcb({x:C.position.x+C.size.width/2+k.x,y:C.position.y+C.size.height/2+k.y});e.pcb_group.update(n.pcb_group_id,{width:w.width,height:w.height,center:T})};function ZLt(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=[],h=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}),V=e.schematic_port.list({schematic_component_id:R.schematic_component_id});for(let H of V){let et=`${U?.name??R.schematic_component_id}.${H.pin_number}`;h.set(et,H.schematic_port_id),d.set(H.schematic_port_id,et)}for(let H of V){let et=d.get(H.schematic_port_id);j.push({pinId:et,x:H.center.x,y:H.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 P=new Set;n.subcircuit_id&&P.add(n.subcircuit_id);for(let R of a)R.subcircuit_id&&P.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&&P.add(B.subcircuit_id)}let k=[],C=new Map;for(let R of e.source_trace.list()){if(R.subcircuit_id&&!P.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),V=[j,U].sort().join("::");if(!C.has(V)){C.set(V,R.source_trace_id);let H=R.display_name??R.source_trace_id;R.subcircuit_connectivity_map_key&&(r.add(R.subcircuit_connectivity_map_key),v.set(H,R.subcircuit_connectivity_map_key),i.set(R.subcircuit_connectivity_map_key,H)),k.push({pinIds:[j,U].map(et=>d.get(et)),netId:H})}}}let M=[];for(let R of e.source_net.list().filter(B=>!B.subcircuit_id||P.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 I=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),I.has(U)||I.set(U,[]),I.get(U).push(R)}for(let[R,B]of I){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 H=.1*(.18/.18),et=Number((String(U).length*H).toFixed(2));M.push({netId:U,pinIds:B.map(tt=>d.get(tt)),netLabelWidth:et})}}let E=(()=>{let R={},B=new Set(M.map(j=>j.netId));for(let j of e.source_net.list().filter(U=>!U.subcircuit_id||P.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:M,availableNetLabelOrientations:E,maxMspPairDistance:n._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:h,pairKeyToSourceTraceId:C,sckToSourceNet:t,sckToUserNetId:i,userNetIdToSck:v,allSourceAndSchematicPortIdsInScope:_,schPortIdToSourcePortId:g,displayLabelTraces:o,allScks:r}}var _r=1e-6;function zet(n){let e=Math.abs(n.to.x-n.from.x),t=Math.abs(n.to.y-n.from.y);return e>=t}function eP(n,e){return Math.hypot(e.x-n.x,e.y-n.y)}function $et(n,e,t){return{x:n.x+(e.x-n.x)*t,y:n.y+(e.y-n.y)*t}}function Det(n,e,t){let i=eP(n,e);if(i<_r)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 Hw(n,e,t,i){return n*i-e*t}function KLt(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=Hw(r.x,r.y,s.x,s.y),a={x:t.x-n.x,y:t.y-n.y},c=Hw(a.x,a.y,r.x,r.y);if(Math.abs(o)<_r&&Math.abs(c)<_r||Math.abs(o)<_r&&Math.abs(c)>=_r)return null;let l=Hw(a.x,a.y,s.x,s.y)/o,u=Hw(a.x,a.y,r.x,r.y)/o;return l<-_r||l>1+_r||u<-_r||u>1+_r?null:{x:n.x+l*r.x,y:n.y+l*r.y}}function JLt(n,e=_r){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 QLt(n,e,t){let i=eP(n.from,n.to);if(i<_r||e.length===0)return[n];let r=t/2,s=e.map(h=>({start:Math.max(0,h-r),end:Math.min(i,h+r)})).filter(h=>h.end-h.start>_r),o=JLt(s),a=[],c=0,l={x:n.to.x-n.from.x,y:n.to.y-n.from.y},u=(h,d,_)=>{if(d-h<=_r)return;let g=h/i,x=d/i;a.push({from:$et(n.from,n.to,g),to:$et(n.from,n.to,x),..._?{is_crossing:!0}:{}})};for(let h of o)h.start-c>_r&&u(c,h.start,!1),u(h.start,h.end,!0),c=h.end;return i-c>_r&&u(c,i,!1),a.length>0?a:[n]}function t7t(n,e={}){let t=e.crossSegmentLength??.075,i=e.tolerance??_r,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 h=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=KLt(h.from,h.to,x.from,x.to);if(!v)continue;let P=eP(h.from,h.to),w=eP(x.from,x.to);if(P<i||w<i)continue;let T=Det(h.from,h.to,v),k=Det(x.from,x.to,v),C=T<=i||Math.abs(P-T)<=i||Number.isNaN(T),M=k<=i||Math.abs(w-k)<=i||Number.isNaN(k);if(!C&&!M){let I=zet(h),E=zet(x),A;if(I!==E)A=I;else{let j=Math.abs(h.to.x-h.from.x),U=Math.abs(h.to.y-h.from.y),V=Math.abs(x.to.x-x.from.x),H=Math.abs(x.to.y-x.from.y),et=j-U,tt=V-H;A=et===tt?!0:et>tt}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 h=s({traceIdx:c,edgeIdx:u}),d=r.get(h)??[];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=QLt(l.edges[u],_,t);a[c].edges.push(...g)}}return a}var Ho=1e-6;function nP(n,e,t=Ho){return Math.abs(n-e)<=t}function W_(n,e,t=Ho){return nP(n.x,e.x,t)&&nP(n.y,e.y,t)}function jet(n,e,t,i=Ho){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 Bet(n,e=Ho){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 Yet(n){return{x:n.to.x-n.from.x,y:n.to.y-n.from.y}}function JA(n,e,t=Ho){let i=Yet(n),r=Yet(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 D1(n,e,t=Ho){return n.edges.filter(i=>W_(i.from,e,t)||W_(i.to,e,t))}function Xet(n,e,t=Ho){for(let i of n.edges){if(W_(i.from,e,t))return i.from;if(W_(i.to,e,t))return i.to}return null}function e7t(n,e,t=Ho){let i=W_(n.from,e,t)||nP(n.from.x,e.x,t)&&nP(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 Y_(n,e,t=Ho){let i=D1(n,e,t);if(i.length<2)return null;let r=i.map(h=>e7t(h,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 n7t(n,e={}){let t=e.tolerance??Ho,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 Bet(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 h of a)for(let d of u)if(W_(h,d,t)){let _=D1(o,h,t),g=D1(l,d,t),x=_.some(T=>g.some(k=>!JA(T,k,t))),v=Y_(o,h,t),P=Y_(l,d,t);x&&!(v!==null&&P!==null&&v===P)&&(i[o.source_trace_id].push(h),o.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(d))}for(let h of a)for(let d of l.edges)if(jet(h,d.from,d.to,t)){let g=D1(o,h,t).some(T=>!JA(T,d,t)),x=Y_(o,h,t),v=Xet(l,h,t*1e3),P=v?Y_(l,v,t):null;g&&!(x!==null&&P!==null&&x===P)&&(i[o.source_trace_id].push(h),o.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(h))}for(let h of u)for(let d of o.edges)if(jet(h,d.from,d.to,t)){let g=D1(l,h,t).some(T=>!JA(d,T,t)),x=Y_(l,h,t),v=Xet(o,h,t*1e3),P=v?Y_(o,v,t):null;g&&!(P!==null&&x!==null&&P===x)&&(i[l.source_trace_id].push(h),o.source_trace_id!==l.source_trace_id&&i[o.source_trace_id].push(h))}}}for(let s of Object.keys(i))i[s]=Bet(i[s],t);return i}var QA=(0,vnt.default)("Group_doInitialSchematicTraceRender");function i7t(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=[];QA(`Traces inside SchematicTraceSolver output: ${(o??[]).length}`);for(let u of o??[]){let h=u?.tracePath;if(!Array.isArray(h)||h.length<2){QA(`Skipping trace ${u?.pinIds.join(",")} because it has less than 2 points`);continue}let d=[];for(let x=0;x<h.length-1;x++)d.push({from:{x:h[x].x,y:h[x].y},to:{x:h[x+1].x,y:h[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 P of[x,v])s.schematic_port.get(P)&&s.schematic_port.update(P,{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})}QA(`Applying ${a.length} traces from SchematicTraceSolver output`);let c=t7t(a.map(u=>({source_trace_id:u.source_trace_id,edges:u.edges}))),l=n7t(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(h=>h.source_trace_id===u.source_trace_id)?.subcircuit_connectivity_map_key})}var r7t=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"}},s7t=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}},t9=(0,Snt.default)("Group_doInitialSchematicTraceRender");function o7t(n){let{group:e,solver:t,sckToSourceNet:i,allScks:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,userNetIdToSck:a,pinIdToSchematicPortId:c,schematicPortIdsWithPreExistingNetLabels:l,schematicPortIdsWithRoutedTraces:u}=n,{db:h}=e.root,d=t.netLabelPlacementSolver?.netLabelPlacements??t.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],_=t.mspConnectionPairSolver.globalConnMap;for(let g of d){t9(`processing placement: ${g.netId}`);let x=_.getIdsConnectedToNet(g.globalConnNetId).find(R=>a.get(R)),v=a.get(x),P=g.anchorPoint,w=g.orientation,T=r7t(w),k=v?i.get(v):void 0,C=g.pinIds.map(R=>c.get(R));if(C.some(R=>l.has(R))){t9(`skipping net label placement for "${g.netId}" REASON:schematic port has pre-existing net label`);continue}if(k){let R=k.name,B=_l({anchor_position:P,anchor_side:T,text:R});h.schematic_net_label.insert({text:R,anchor_position:P,center:B,anchor_side:T,...k?.source_net_id?{source_net_id:k.source_net_id}:{}});continue}let M=e.selectAll("port").filter(R=>R._getSubcircuitConnectivityKey()===v),{name:I,wasAssignedDisplayLabel:E}=s7t(M);if(!E&&C.some(R=>u.has(R))){t9(`skipping net label placement for "${g.netId}" REASON:schematic port has routed traces and no display label`);continue}let A=_l({anchor_position:P,anchor_side:T,text:I});h.schematic_net_label.insert({text:I,anchor_position:P,center:A,anchor_side:T})}}var a7t=({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 h=o.source_port.get(l)?.subcircuit_connectivity_map_key;if(!h)continue;let d=i.get(h);if(!d||o.schematic_net_label.list().some(P=>Math.abs(P.anchor_position.x-c.center.x)<.1&&Math.abs(P.anchor_position.y-c.center.y)<.1?d.source_net_id&&P.source_net_id?P.source_net_id===d.source_net_id:P.text===(d.name||h):!1))continue;let g=d.name||d.source_net_id||h,x=X1(c.facing_direction||"right")||"right",v=_l({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}:{}})}},c7t=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},l7t=({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},u7t=(0,bnt.default)("Group_doInitialSchematicTraceRender"),p7t=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}=ZLt(n),u=c7t(n);u7t.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(e,null,2)});let h=new $Q(e);h.solve();let d=l7t({solver:h,pinIdToSchematicPortId:t});i7t({group:n,solver:h,pinIdToSchematicPortId:t,userNetIdToSck:l}),o7t({group:n,solver:h,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,pinIdToSchematicPortId:t,allScks:c,userNetIdToSck:l,schematicPortIdsWithPreExistingNetLabels:u,schematicPortIdsWithRoutedTraces:d}),a7t({group:n,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,sckToSourceNet:r,pinIdToSchematicPortId:t,schematicPortIdsWithPreExistingNetLabels:u})},h7t=()=>({async simulate(n){let e="spice-experiment-1",{circuit:t,tran:i}=YQ(n);return{simulationResultCircuitJson:XQ(i,t,e)}}}),Uet=["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)"],Zw=new Map,Kw=0;function d7t(n){if(Zw.has(n))return Zw.get(n);let e=Uet[Kw];return Kw=(Kw+1)%Uet.length,Zw.set(n,e),e}function f7t(){Zw.clear(),Kw=0}var Xa=(0,wnt.default)("tscircuit:core:Group_doInitialSimulationSpiceEngineRender");function m7t(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");f7t();let r={...e.platform?.spiceEngineMap};r.spicey||(r.spicey=h7t());let s=e.db.toArray(),o,a;try{a=jQ(s),o=a.toSpiceString(),Xa(`Generated SPICE string:
250
250
  ${o}`)}catch(c){Xa(`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 h=`spice-simulation-${l}-${c.source_component_id}`;Xa(`Queueing simulation for spice engine: ${l} (id: ${h})`),n._queueAsyncEffect(h,async()=>{try{Xa(`Running simulation with engine: ${l}`);let d=await u.simulate(o);Xa(`Simulation completed, received ${d.simulationResultCircuitJson.length} elements`);let _=e.db.simulation_experiment.list()[0];if(!_){Xa("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(P=>P.finalProbeName===g.name);v&&(g.color=v.color)}let x=g.type;x&&e.db[x]?(e.db[x].insert(g),Xa(`Inserted ${x} into database`)):(Xa(`Warning: Unknown element type ${x}, adding to raw db`),e.db._addElement(g))}n._markDirty("SimulationSpiceEngineRender")}catch(d){Xa(`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 _7t(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=Oo(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},h={...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=h;break;case"top_left":d={x:u.left,y:u.top};break;case"top_center":d={x:h.x,y:u.top};break;case"top_right":d={x:u.right,y:u.top};break;case"center_left":d={x:u.left,y:h.y};break;case"center_right":d={x:u.right,y:h.y};break;case"bottom_left":d={x:u.left,y:u.bottom};break;case"bottom_center":d={x:h.x,y:u.bottom};break;case"bottom_right":d={x:u.right,y:u.bottom};break}if(!d)return;let g={...h};t.x!==void 0&&(g.x+=t.x-d.x),t.y!==void 0&&(g.y+=t.y-d.y),(Math.abs(g.x-h.x)>1e-6||Math.abs(g.y-h.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 yl=class extends Gn{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:IH,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:Y.parse(a.x),y:Y.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 h=t.outline.map(v=>({x:Y.parse(v.x),y:Y.parse(v.y)})),d=Oo(h);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=sP(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:h,padRight:d,padTop:_,padBottom:g}=this._resolvePcbPadding();o+=h+d,a+=_+g,c+=(d-h)/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=h=>{let d=t?.[h],_=e[h];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 g9({for:s.pcb_port_selector,offsets:s.offsets}))}doInitialSourceAddConnectivityMapKey(){CLt(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,X_.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,X_.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),i=this._parsedProps,r=this._getAutorouterConfig(),s=r.serverUrl,o=r.serverMode,a=(u,h)=>(t("fetching",u),h.headers&&(h.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(u,h)),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:h}=await a(`${s}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:l9({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=h,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(h=>h.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(h=>h.json());if(u.is_finished){let{autorouting_job_output:h}=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:h.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(u.has_error){let h=new z1(`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:h.message}),h}await new Promise(h=>setTimeout(h,100))}}async _runLocalAutorouting(){let{db:e}=this.root,t=this._parsedProps,i=(0,X_.default)("tscircuit:core:_runLocalAutorouting");i(`[${this.getString()}] starting local autorouting`);let r=this._getAutorouterConfig(),s=this._isLaserPrefabAutorouter(r),{simpleRouteJson:o}=l9({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=Vg(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 bLt(o,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity,useAssignableViaSolver:s});let c=new Promise((l,u)=>{a.on("complete",h=>{i(`[${this.getString()}] local autorouting complete`),l(h.traces)}),a.on("error",h=>{i(`[${this.getString()}] local autorouting error: ${h.error.message}`),u(h.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,X_.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(){p7t(this)}updatePcbTraceRender(){let e=(0,X_.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}=y9(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(){TLt(this)}_doInitialSchematicLayoutMatchpack(){ELt(this)}_doInitialSchematicLayoutGrid(){ILt(this)}_doInitialSchematicLayoutFlex(){NLt(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(){ALt(this)}_doInitialPcbLayoutPack(){WLt(this)}_doInitialPcbLayoutFlex(){qLt(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 h=u?.center??this._getGlobalSchematicPositionBeforeLayout(),d=h.x-i/2-o,_=h.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 YLt(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(){m7t(this)}doInitialPcbComponentAnchorAlignment(){_7t(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(e){return super._repositionOnPcb(e)}},y7t=.01,Vet=(n,e,t)=>{let i=n/2,r=e/2,s=Math.min(t,i,r);if(s<y7t)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 h=-Math.PI/2+u*c;l.push({x:i-s+s*Math.cos(h),y:-r+s+s*Math.sin(h)})}l.push({x:i,y:r-s});for(let u=1;u<=a;u++){let h=0+u*c;l.push({x:i-s+s*Math.cos(h),y:r-s+s*Math.sin(h)})}l.push({x:-i+s,y:r});for(let u=1;u<=a;u++){let h=Math.PI/2+u*c;l.push({x:-i+s+s*Math.cos(h),y:r-s+s*Math.sin(h)})}l.push({x:-i,y:-r+s});for(let u=1;u<=a;u++){let h=Math.PI+u*c;l.push({x:-i+s+s*Math.cos(h),y:-r+s+s*Math.sin(h)})}return l},b9=class extends yl{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:u4}}get boardThickness(){let{_parsedProps:e}=this;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}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db:e}=this.root,{_parsedProps:t}=this;if(t.width&&t.height||t.outline)return;let i=1/0,r=1/0,s=-1/0,o=-1/0,a=_nt(e,this.subcircuit_id),c=new Set([this.subcircuit_id,...a]),l=e.pcb_component.list().filter(C=>C.subcircuit_id&&c.has(C.subcircuit_id)),u=e.pcb_group.list().filter(C=>C.subcircuit_id&&c.has(C.subcircuit_id)),h=!1,d=(C,M,I)=>{M===0||I===0||(h=!0,i=Math.min(i,C.x-M/2),r=Math.min(r,C.y-I/2),s=Math.max(s,C.x+M/2),o=Math.max(o,C.y+I/2))};for(let C of l)d(C.center,C.width,C.height);for(let C of u){let M=C.width??0,I=C.height??0;if(C.outline&&C.outline.length>0){let E=Oo(C.outline);E&&(M=E.maxX-E.minX,I=E.maxY-E.minY)}d(C.center,M,I)}if(t.boardAnchorPosition){let{x:C,y:M}=t.boardAnchorPosition;i=Math.min(i,C),r=Math.min(r,M),s=Math.max(s,C),o=Math.max(o,M)}let _=2,g=h?s-i+_*2:0,x=h?o-r+_*2:0,v={x:h?(i+s)/2+(t.outlineOffsetX??0):t.outlineOffsetX??0,y:h?(r+o)/2+(t.outlineOffsetY??0):t.outlineOffsetY??0},P=t.width??g,w=t.height??x,T=t.outline;!T&&t.borderRadius!=null&&P>0&&w>0&&(T=Vet(P,w,t.borderRadius));let k={width:P,height:w,center:v};T&&(k.outline=T.map(C=>({x:C.x+(t.outlineOffsetX??0),y:C.y+(t.outlineOffsetY??0)}))),e.pcb_board.update(this.pcb_board_id,k)}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(`
251
251
  `),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}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=t.width??0,r=t.height??0,s={x:(t.pcbX??0)+(t.outlineOffsetX??0),y:(t.pcbY??0)+(t.outlineOffsetY??0)},{boardAnchorPosition:o,boardAnchorAlignment:a}=t;if(o&&(s=xLt({boardAnchorPosition:o,boardAnchorAlignment:a??"center",width:i,height:r})),t.outline){let u=t.outline.map(v=>v.x),h=t.outline.map(v=>v.y),d=Math.min(...u),_=Math.max(...u),g=Math.min(...h),x=Math.max(...h);i=_-d,r=x-g,s={x:(d+_)/2+(t.outlineOffsetX??0),y:(g+x)/2+(t.outlineOffsetY??0)}}let c=t.outline;!c&&t.borderRadius!=null&&i>0&&r>0&&(c=Vet(i,r,t.borderRadius));let l=e.pcb_board.insert({center:s,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:r,outline:c?.map(u=>({x:u.x+(t.outlineOffsetX??0),y:u.y+(t.outlineOffsetY??0)})),material:t.material});this.pcb_board_id=l.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=HQ(e.toArray());for(let u of t)e.pcb_trace_error.insert(u);let i=GQ(e.toArray());for(let u of i)e.pcb_port_not_connected_error.insert(u);let r=ZQ(e.toArray());for(let u of r)e.pcb_component_outside_board_error.insert(u);let s=QQ(e.toArray());for(let u of s)e.pcb_trace_error.insert(u);let o=JQ(e.toArray());for(let u of o)e.pcb_via_clearance_error.insert(u);let a=KQ(e.toArray());for(let u of a)e.pcb_via_clearance_error.insert(u);let c=ttt(e.toArray());for(let u of c)e.pcb_footprint_overlap_error.insert(u);let l=ett(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})}},Get=5,g7t=5,Het=2;function x7t(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 b7t(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 v7t({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,h;e==="top"||e==="bottom"?(l=n.width,u=!0,h=e==="top"?c:a):(l=n.height,u=!1,h=e==="right"?o:s);let d=i.tabLength,_=i.boardGap;if(i.mouseBites){let w=i.tabWidth*.45,T=w*.1,k=Math.max(2,Math.ceil(i.tabLength/2));_=(k*w+(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,P=l/2;for(let w=0;w<g;w++){let T=v+x+w*(d+x)+d/2,k=w===0,C=w===g-1,M=k||C,I=T-d/2,E=T+d/2;if(M&&(k&&(I=v),C&&(E=P)),I=Math.max(I,v),E=Math.min(E,P),M&&(k&&(I-=i.tabWidth),C&&(E+=i.tabWidth)),E<=I)continue;let A=(I+E)/2,R=E-I,B=e==="top"||e==="right"?i.tabWidth/2:-i.tabWidth/2,j=u?{x:n.center.x+A,y:h+B}:{x:h+B,y:n.center.y+A},U=u?R:i.tabWidth,V=u?i.tabWidth:R,H={center:j,width:U,height:V,boardId:`${n.center.x}_${n.center.y}`},et=!1;for(let tt of t){if(!tt.width||!tt.height)continue;let mt={center:tt.center,width:tt.width,height:tt.height};if(x7t(H,mt)){et=!0;break}}et&&!M||r.push(H)}return r}function S7t({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",h=r.tabWidth*.45,d=h*.1,_=Math.max(2,Math.ceil(r.tabLength/2)),g,x=h/2;e==="top"?g=l:e==="bottom"?g=c:e==="right"?g=a:g=o;let v=[...t].sort((P,w)=>u?P.center.x-w.center.x:P.center.y-w.center.y);for(let P=0;P<v.length-1;P++){let w=v[P],T=v[P+1],k,C;u?(k=w.center.x+w.width/2,C=T.center.x-T.width/2):(k=w.center.y+w.height/2,C=T.center.y-T.height/2);let M=C-k,I=_*h,E=(_-1)*d;if(M<I+E)continue;let A=(k+C)/2;for(let R=0;R<_;R++){let B=(R-(_-1)/2)*(h+d),j=u?{x:A+B,y:g}:{x:g,y:A+B},U=h/2,V=!1;for(let H of i){if(!H.width||!H.height)continue;let et={center:H.center,width:H.width,height:H.height};if(b7t(j,U,et)){V=!0;break}}V||s.push(j)}}return s}function w7t(n,e){let t=[],i=[];for(let a=0;a<n.length;a++){let c=n[a],l=n.filter((u,h)=>h!==a);for(let u of["top","bottom","left","right"]){let h=v7t({board:c,edge:u,otherBoards:l,options:e});if(t.push(...h),e.mouseBites){let d=S7t({board:c,edge:u,edgeTabs:h,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 Pnt=class extends yl{constructor(){super(...arguments);f(this,"pcb_panel_id",null);f(this,"_tabsAndMouseBitesGenerated",!1)}get config(){return{componentName:"Panel",zodProps:NH}}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)}doInitialPcbComponentAnchorAlignment(){if(this.root?.pcbDisabled)return;super.doInitialPcbComponentAnchorAlignment();let{db:e}=this.root,t=this.children.filter(a=>a instanceof b9),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??Het,c=this._parsedProps.boardGap??a,l=Math.ceil(Math.sqrt(r.length)),u=Math.ceil(r.length/l),h=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||(h[B]=Math.max(h[B],U.width),d[j]=Math.max(d[j],U.height))});let _=h.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,P=[-g/2];for(let A=0;A<u-1;A++)P.push(P[A]+d[A]+c);let w=[x];for(let A=0;A<l-1;A++)w.push(w[A]+h[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 V=w[B]+h[B]/2,H=P[j]+d[j]/2;A._repositionOnPcb({x:V,y:H}),e.pcb_board.update(A.pcb_board_id,{center:{x:V,y:H}})});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)),C=1/0,M=1/0,I=-1/0,E=-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;C=Math.min(C,R),I=Math.max(I,B),M=Math.min(M,j),E=Math.max(E,U)}if(isFinite(C)){let A=I-C,R=E-M,B=A+2*Get,j=R+2*Get;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??Het,u=s.boardGap??l,{tabCutouts:h,mouseBiteHoles:d}=w7t(c,{boardGap:u,tabWidth:l,tabLength:s.tabLength??g7t,mouseBites:s.mouseBites??!0});for(let _ of h)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:Y.parse(t.width),height:Y.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:Y.parse(t.width),height:Y.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)}},P7t=new Proxy({},{get:(n,e)=>e}),Ga=P7t,oP="rgba(132, 0, 0)",aP=.12,v9=class extends Gn{constructor(){super(...arguments);f(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:BH,sourceFtype:Ga.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:`${gi(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${t}/${gi(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 Fs({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new Fs({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}},U1=class extends Gn{constructor(e){super(e);f(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:n_,shouldRenderAsSchematicBox:!0}}initPorts(e={}){super.initPorts(e);let{_parsedProps:t}=this;if(t.externallyConnectedPins){let i=new Set;for(let[r,s]of t.externallyConnectedPins)i.add(r),i.add(s);for(let r of i)if(!this.children.find(o=>o instanceof Vi&&o.isMatchingAnyOf([r]))){let o=r.match(/^pin(\d+)$/);if(o){let a=parseInt(o[1]);this.add(new Vi({pinNumber:a,aliases:[r]}))}else this.add(new Vi({name:r,aliases:[r]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:e}=this;e?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=t.layer??"top";if(i!=="top"&&i!=="bottom"){let s=this.getSubcircuit(),o=Om.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${i}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:i,subcircuit_id:s.subcircuit_id??void 0});e.pcb_component_invalid_layer_error.insert(o)}let r=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},width:2,height:3,layer:i==="top"||i==="bottom"?i:"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=r.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:e}=this;if(e.externallyConnectedPins)for(let[t,i]of e.externallyConnectedPins)this.add(new Fs({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 h of o)for(let d of h.getNameAndAliases())if(t[d]){let _=t[d];_.providesPower&&(i=h,s=_.providesVoltage),_.providesGround&&(r=h)}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})}},knt=class extends U1{constructor(n){super(n)}get config(){return{...super.config,componentName:"Pinout",zodProps:AH}}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}},S9=class extends Gn{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:rW,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}},Tnt=class extends Gn{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:OH,sourceFtype:Ga.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`${gi(t)}A / ${gi(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:Ga.simple_fuse,current_rating_amps:t,voltage_rating_volts:i,display_current_rating:`${gi(t)}A`,display_voltage_rating:`${gi(i)}V`});this.source_component_id=r.source_component_id}},Mnt=class extends Gn{constructor(){super(...arguments);f(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:p4,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,i=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=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},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=i.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(h=>/^(pin)?\d+$/.test(h));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))}},Ent=class extends Gn{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:RH,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,i=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=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},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=i.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(h=>/^(pin)?\d+$/.test(h));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))}},Cnt=class extends Gn{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:oW,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}},Int=class extends Gn{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:bW,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Vi({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Vi({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}},Nnt=class extends Gn{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:vW,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})}},w9=class extends Gn{constructor(){super(...arguments);f(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:FH,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${gi(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 Fs({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new Fs({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new Fs({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new Fs({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}},k7t=["leftedge","rightedge","topedge","bottomedge","center"],Ant=class extends Me{get config(){return{componentName:"Constraint",zodProps:XH}}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=k7t.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}}},Rnt=class extends Me{constructor(){super(...arguments);f(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:uW}}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 FabricationNoteRect. Must be "top" or "bottom".`);let s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,o=this.getSubcircuit(),a=t.hasStroke??(t.strokeWidth!==void 0&&t.strokeWidth!==null),c=e.pcb_fabrication_note_rect.insert({pcb_component_id:s,layer:r,color:t.color,center:{x:t.pcbX??0,y:t.pcbY??0},width:t.width,height:t.height,stroke_width:t.strokeWidth??1,is_filled:t.isFilled??!1,has_stroke:a,is_stroke_dashed:t.isStrokeDashed??!1,subcircuit_id:o?.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=c.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},Ont=class extends Me{constructor(){super(...arguments);f(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:pW}}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=$e(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}},Lnt=class extends Me{get config(){return{componentName:"FabricationNoteText",zodProps:lW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:n}=this.root,{_parsedProps:e}=this,t=this.getPrimitiveContainer(),i=this.getSubcircuit();n.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:e.pcbX??0,y:e.pcbY??0},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:e.text??"",pcb_component_id:t.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},Fnt=class extends Me{constructor(){super(...arguments);f(this,"fabrication_note_dimension_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:hW}}_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}"`),$e(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 $e(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,h=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:h,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}`}},znt=class extends Me{constructor(){super(...arguments);f(this,"pcb_note_line_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:BW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=this.getGroup(),s=this._computePcbGlobalTransformBeforeLayout(),o=$e(s,{x:t.x1,y:t.y1}),a=$e(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)}}},$nt=class extends Me{constructor(){super(...arguments);f(this,"pcb_note_rect_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:DW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=$e(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}}},Dnt=class extends Me{constructor(){super(...arguments);f(this,"pcb_note_text_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:$W}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=$e(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: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}}},jnt=class extends Me{constructor(){super(...arguments);f(this,"pcb_note_path_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:jW}}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:h,...d}=l,_=typeof u=="string"?parseFloat(u):u,g=typeof h=="string"?parseFloat(h):h,x=$e(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}}},Bnt=class extends Me{constructor(){super(...arguments);f(this,"pcb_note_dimension_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:YW}}_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}"`),$e(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 $e(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}`}},q_=(n,e)=>{let{injectionDb:t,normalComponent:i}=e;if(!i)return;let r=G_({componentName:i.name,componentRotation:"0deg"},t.toArray().filter(s=>"pcb_component_id"in s&&s.pcb_component_id===n.pcb_component_id));i.addAll(r)};function T7t(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 w9({name:n.name,resistance:n.resistance});s&&q_(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 M7t(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 Vi({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}}function E7t(n,e){let{subcircuit:t,groupsMap:i}=e,r=new yl({name:n.name});return r.source_group_id=n.source_group_id,t.add(r),i&&i.set(n.source_group_id,r),r}var C7t=(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},I7t=(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=C7t(n.internally_connected_source_port_ids,e),l=new U1({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&&q_(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)};function N7t(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 v9({name:n.name,capacitance:n.capacitance});s&&q_(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 P9=class extends Gn{constructor(){super(...arguments);f(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:iW,sourceFtype:Ga.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${gi(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:Ga.simple_inductor,inductance:t.inductance,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function A7t(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 P9({name:n.name,inductance:n.inductance});s&&q_(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 R7t(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 S9({name:n.name});s&&q_(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 O7t=(n,e)=>{let t=[],i=n.source_group_id;for(;i;){let r=e.source_group.get(i);if(!r)break;t.unshift(`.${r.name}`),i=r.parent_source_group_id}return t.push(`.${n.name}`),t.join(" > ")};function L7t(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=`${O7t({name:l.name,source_group_id:l.source_group_id},t)} > .${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 Fs({path:r});s.source_trace_id=n.source_trace_id,i.add(s)}var k9=class extends Gn{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:eW,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 F7t(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 k9({name:n.name,type:n.transistor_type});s&&q_(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 Ynt=class extends yl{constructor(n){super({...n,subcircuit:!0})}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:n,children:e}=this._parsedProps;if(!n)return;let t=Ze(n);if(n&&e?.length>0)throw new Error("Subcircuit cannot have both circuitJson and children");let r={injectionDb:t,subcircuit:this,groupsMap:new Map},s=t.source_group.list();for(let l of s)E7t(l,r);let o=t.source_component.list();for(let l of o)switch(l.ftype){case"simple_resistor":T7t(l,r);break;case"simple_capacitor":N7t(l,r);break;case"simple_inductor":A7t(l,r);break;case"simple_diode":R7t(l,r);break;case"simple_chip":I7t(l,r);break;case"simple_transistor":F7t(l,r);break;default:throw new Error(`No inflator implemented for source component ftype: "${l.ftype}"`)}let a=t.source_port.list();for(let l of a)M7t(l,r);let c=t.source_trace.list();for(let l of c)L7t(l,r)}},Xnt=class extends yl{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}})}},Unt=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:mW}}_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=0,pcbY:i=0}=this._parsedProps,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=0,pcbY:t=0}=this._parsedProps;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}}},Vnt=class extends Me{constructor(){super(...arguments);f(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:JH}}_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=$e(this.parent?.computeSchematicGlobalTransform?.()??Sr(),{x:0,y:0});return An(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=_l({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&&iP(this,[`net.${e.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let e=this._resolveConnectsTo();if(e)for(let t of e)this.add(new Fs({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 P=e.source_trace.list().find(w=>w.connected_source_net_ids?.includes(a.source_net_id)&&w.connected_source_port_ids?.includes(l.source_port_id??""));if(P&&(u=e.schematic_trace.list().some(w=>w.source_trace_id===P.source_trace_id)),u)continue}let h=l._getGlobalSchematicPositionAfterLayout(),d=r9(l.facingDirection??"right")??"x+",_=qc({x:h.x,y:h.y,facingDirection:d},{x:i.x,y:i.y,facingDirection:o});if(!Array.isArray(_)||_.length<2)continue;let g=[];for(let P=0;P<_.length-1;P++)g.push({from:{x:_[P].x,y:_[P].y},to:{x:_[P+1].x,y:_[P+1].y}});let x,v;if(a?.source_net_id&&l.source_port_id){let P=e.source_trace.list().find(w=>w.connected_source_net_ids?.includes(a.source_net_id)&&w.connected_source_port_ids?.includes(l.source_port_id));x=P?.source_trace_id,v=P?.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})}}},Gnt=class extends Me{constructor(){super(...arguments);f(this,"pcb_silkscreen_circle_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:FW}}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 SilkscreenCircle. 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_circle.insert({pcb_component_id:a,layer:r,center:{x:t.pcbX??0,y:t.pcbY??0},radius:t.radius,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:e}=this,t=e.radius*2;return{width:t,height:t}}},Hnt=class extends Me{constructor(){super(...arguments);f(this,"pcb_silkscreen_rect_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:LW}}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(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=e.pcb_silkscreen_rect.insert({pcb_component_id:o,layer:r,center:{x:t.pcbX??0,y:t.pcbY??0},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=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},Wnt=class extends Me{constructor(){super(...arguments);f(this,"pcb_silkscreen_line_id",null);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:OW}}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}}},qnt=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:dW}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}_getResolvedViaDiameters(e){return tLt({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 Vi({name:i,layer:i});r.registerMatch(this),this.add(r)}let t=new Vi({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}},Znt=class extends Me{constructor(){super(...arguments);f(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:yW}}getPcbSize(){return{width:0,height:0}}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;iP(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(h=>h.type==="source_net"&&h.name===i.name)[0]||"",o=t.clearance??.2,a=rtt(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 itt(a),{brep_shapes:l}=c.getOutput(),u=t.coveredWithSolderMask??!1;for(let h of l)e.pcb_copper_pour.insert({shape:"brep",layer:t.layer,brep_shape:h,source_net_id:i.source_net_id,subcircuit_id:r?.subcircuit_id??void 0,covered_with_solder_mask:u})})}},Knt=class extends Gn{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:ZH,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}},Jnt=class extends Gn{_getPcbRotationBeforeLayout(){let n=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+n}get config(){return{componentName:"PinHeader",zodProps:KH,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;if(n>0){let s;if(i)!e&&!t?s=`pinrow${n}_p${i}`:s=`pinrow${n}_p${i}_id${e}_od${t}`;else if(!e&&!t)s=`pinrow${n}`;else return null;return r!==!0&&(s+="_nopinlabels"),s}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 Vi({pinNumber:e,name:i,aliases:[`pin${e}`,...r]}))}else this.add(new Vi({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 z7t(n){switch(n){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var Qnt=class extends Gn{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??z7t(this.props.pinVariant),zodProps:jH,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=`${gi(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${gi(this._parsedProps.loadCapacitance)}F`:n}};function $7t(n){switch(n){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var tit=class extends Gn{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??$7t(this.props.pinVariant),zodProps:$H,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${gi(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}},eit=class extends Gn{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:QH,sourceFtype:Ga.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let n=_i[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 h=c?.find(([_,g])=>_===`pin${l}`||g===`pin${l}`);if(!h){u.schematicSymbolPortDef=t;break}(h?.[0]===`pin${l}`?h[1]:h?.[0])!=="pin1"&&(u.schematicSymbolPortDef=t)}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:Ga.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}},nit=class extends Gn{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:DH,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=`${gi(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${gi(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}},iit=class extends Gn{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:nW,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 D7t(n){return n.simSwitchFrequency!==void 0||n.simCloseAt!==void 0||n.simOpenAt!==void 0||n.simStartClosed!==void 0||n.simStartOpen!==void 0}var rit=class extends Gn{_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:cW,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(!D7t(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=Fr.parse(n.simSwitchFrequency)),n.simCloseAt!==void 0&&(t.closes_at=ur.parse(n.simCloseAt)),n.simOpenAt!==void 0&&(t.opens_at=ur.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)}},e9={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},sit=class extends Gn{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:fW,sourceFtype:Ga.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=e9.SMT_CIRCLE_DIAMETER):n==="rect"&&(r??(r=e9.SMT_RECT_SIZE),s??(s=r)):t==="through_hole"&&(e??(e=e9.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:Ga.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}},oit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:EW}}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: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:MW}}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??aP,color:t.color??oP,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=s.schematic_line_id}},cit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:TW}}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??aP,color:t.color??oP,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}},lit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:wW}}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??aP,color:t.color??oP,is_dashed:t.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=s.schematic_arc_id}},uit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:kW}}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??aP,color:t.color??oP,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 j7t({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 pit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:PW,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",h,d,_,g,x,v;if(l){let w=t.overlay.map(nt=>({selector:nt,port:this.getSubcircuit().selectOne(nt,{type:"port"})})).filter(({port:nt})=>nt!=null).map(({port:nt})=>({position:nt._getGlobalSchematicPositionAfterLayout()}));if(w.length===0)return;let T=w.map(nt=>nt.position.x),k=w.map(nt=>nt.position.y),C=Math.min(...T),M=Math.max(...T),I=Math.min(...k),E=Math.max(...k),A=M-C,R=E-I,B=A===0?i:0,j=R===0?i:0,U=a+B/2,V=c+B/2,H=s+j/2,et=o+j/2,tt=C-U,mt=M+V,G=I-et,Q=E+H;h=mt-tt,d=Q-G,_=tt+(t.schX??0),g=G+(t.schY??0),x=_+h/2,v=g+d/2}else if(u){h=t.width,d=t.height;let P=this._getGlobalSchematicPositionBeforeLayout();x=P.x,v=P.y,_=x-h/2,g=v-d/2}else return;if(e.schematic_box.insert({height:d,width:h,x:_,y:g,is_dashed:t.strokeStyle==="dashed"}),t.title){let P=t.titleInside,w=.1,T=t.titleAlignment,k=j7t({anchor:T,x:_,y:g,width:h,height:d,isInside:P}),C,M,I=k.textAnchor;P?(C=T.includes("top")?-w:T.includes("bottom")?w:0,M=T.includes("left")?w:T.includes("right")?-w:0):(C=T.includes("top")?w:T.includes("bottom")?-w:0,M=T.includes("center_left")?-w:T.includes("center_right")?w:0);let E=k.x+M,A=k.y+C;e.schematic_text.insert({anchor:I,text:t.title,font_size:t.titleFontSize??.18,color:t.titleColor??"#000000",position:{x:E,y:A},rotation:0})}}},hit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:CW}}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 P=g[v],w=P._parsedProps.colSpan??1,T=P._parsedProps.rowSpan??1;for(let k=0;k<T;k++)for(let C=0;C<w;C++)r[d+k]||(r[d+k]=[]),r[d+k][x+C]=P;x+=w}}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 P=v._parsedProps.text??v._parsedProps.children,w=v._parsedProps.width??(P?.length??2)*.5;w>g&&(g=w)}}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,h=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,P=v.rowSpan??1,w=v.colSpan??1,T=0;for(let C=0;C<w;C++)T+=a[g+C];let k=0;for(let C=0;C<P;C++)k+=o[d+C];e.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:d,end_row_index:d+P-1,start_column_index:g,end_column_index:g+w-1,text:v.text??v.children,center:{x:c.x+_+T/2,y:c.y-h-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])}h+=o[d]}}},dit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:IW}}},fit=class extends Me{constructor(){super(...arguments);f(this,"isSchematicPrimitive",!0);f(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:NW}}},mit=class extends Me{constructor(){super(...arguments);f(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:qH}}},_it=class extends Me{get config(){return{componentName:"AnalogSimulation",zodProps:tW}}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:SW}}doInitialSimulationRender(){let{db:e}=this.root,{connectsTo:t,name:i}=this._parsedProps,r=this.getSubcircuit();if(!r){this.renderError("VoltageProbe must be inside a subcircuit");return}let s=Array.isArray(t)?t:[t];if(s.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let o=s[0],a=r.selectOne(o,{type:"port"}),c=a?null:r.selectOne(o,{type:"net"});if(c&&c.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${o}" resolved to a non-net component "${c.componentName}".`);return}if(!a&&!c){this.renderError(`VoltageProbe could not find connection target "${o}"`);return}let l=a?.source_port_id??c?.source_net_id;if(!l){this.renderError("Could not identify connected source for VoltageProbe");return}this.color=d7t(l);let u=i;u||(u=s[0].split(" > ").map(d=>d.replace(/^\./,"")).join(".")),this.finalProbeName=u??null;let{simulation_voltage_probe_id:h}=e.simulation_voltage_probe.insert({name:u,signal_input_source_port_id:a?.source_port_id??void 0,signal_input_source_net_id:c?.source_net_id??void 0,subcircuit_id:r.subcircuit_id||void 0,color:this.color});this.simulation_voltage_probe_id=h}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,h=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=h.schematic_voltage_probe_id}},B7t={name:"@tscircuit/core",type:"module",version:"0.0.881",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.418","@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.25","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.58","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"}},Z_=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=Ee([]),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,git.isValidElement)(n)?e=tnt(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 yl({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()?!0:n.children.some(e=>e._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(n){let e=await Promise.resolve().then(()=>(yet(),_et)).catch(t=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
252
252
 
@@ -456,9 +456,15 @@ ${u.join(" -> ")}`)}if(!e.fsMap[a])throw gy("fsPath not found in fsMap:",a),new
456
456
 
457
457
  ${e.logger.stringifyLogs()}`);return{content:await d.text(),error:null}}).catch(d=>({error:d,content:null}));if(a)throw console.error("Error fetching npm import",n,a),a;let c=uXt(s),l=$s(c),u=W1(o);for(let d of u)i[d]||await Zp(d,e,t+1,{cwd:l});let h=A0(o,c||n);try{let d=Od(h,i,l).exports;i[n]=d,i[c]=d,i[s]=d}catch(d){throw new Error(`Eval npm package error for "${n}": ${d.message}
458
458
 
459
- ${e.logger.stringifyLogs()}`)}}var Xlt=Gt(En(),1),Ylt=(0,Xlt.default)("tsci:eval:import-eval-path");async function Zp(n,e,t=0,i={}){Ylt("importEvalPath called with:",{importName:n,depth:t,opts:i}),e.logger.info(`importEvalPath("${n}", {cwd: "${i.cwd}", depth: ${t}})`),Ylt(`${" ".repeat(t)}\u27A1\uFE0F`,n);let{preSuppliedImports:r}=e;if(r[n]){e.logger.info(`Import "${n}" in preSuppliedImports[1]`);return}if(n.startsWith("./")&&r[n.slice(2)]){e.logger.info(`Import "${n}" in preSuppliedImports[2]`);return}if(t>30)throw new Error(`Max depth for imports reached (30) Import Path: ${e.importStack.join(" -> ")}`);if(n.startsWith("/npm/")){let u=n.replace(/^\/npm\//,"").replace(/\/\+esm$/,"");e.logger.info(`importNpmPackage("${u}")`),await I7(u,e,t);let h=r[u];h&&(r[n]=h);return}let s=".",o=e.tsConfig;if(e.tsConfig&&i.cwd){let u=i.cwd.match(/^(node_modules\/[^\/]+)/);u&&(s=u[1],o=null)}let a=H1(n,e.fsMap,i.cwd,{tsConfig:o,tsconfigDir:s});if(a){e.logger.info(`importLocalFile("${a}")`),await j0(a,e,t),n!==a&&(r[n]=r[a]);return}let c=e.tsConfig??G1(e.fsMap);if(!e.tsConfig&&c&&(e.tsConfig=c),Hit(n,c))throw new Error(`Import "${n}" matches a tsconfig path alias but could not be resolved to an existing file${i.cwd?` from directory "${i.cwd}"`:""}
459
+ ${e.logger.stringifyLogs()}`)}}var Xlt=Gt(En(),1),Ylt=(0,Xlt.default)("tsci:eval:import-eval-path");async function Zp(n,e,t=0,i={}){Ylt("importEvalPath called with:",{importName:n,depth:t,opts:i}),e.logger.info(`importEvalPath("${n}", {cwd: "${i.cwd}", depth: ${t}})`),Ylt(`${" ".repeat(t)}\u27A1\uFE0F`,n);let{preSuppliedImports:r}=e,s=e.disableCdnLoading||globalThis.__DISABLE_CDN_LOADING__;if(r[n]){e.logger.info(`Import "${n}" in preSuppliedImports[1]`);return}if(n.startsWith("./")&&r[n.slice(2)]){e.logger.info(`Import "${n}" in preSuppliedImports[2]`);return}if(t>30)throw new Error(`Max depth for imports reached (30) Import Path: ${e.importStack.join(" -> ")}`);if(n.startsWith("/npm/")){let h=n.replace(/^\/npm\//,"").replace(/\/\+esm$/,"");if(s)throw new Error(`Cannot find module "${h}". The package is not available in the local environment.
460
460
 
461
- ${e.logger.stringifyLogs()}`);let l=ty(n,e.fsMap,i.cwd||"");if(l)return e.logger.info(`resolvedNodeModulePath="${l}"`),e.logger.info(`importNodeModule("${n}")`),C7(n,e,t);if(!n.startsWith(".")&&!n.startsWith("/")&&!n.startsWith("@tsci/")&&e.circuit?.platform?.nodeModulesResolver){e.logger.info(`importNodeModule("${n}") via nodeModulesResolver`);try{await C7(n,e,t);return}catch{e.logger.info(`nodeModulesResolver failed for "${n}", falling back to npm CDN`)}}if(n.startsWith("@tsci/"))return e.logger.info(`importSnippet("${n}")`),Dlt(n,e,t);if(!n.startsWith(".")&&!n.startsWith("/"))return e.logger.info(`importNpmPackage("${n}")`),I7(n,e,t);throw new Error(`Unresolved import "${n}" ${i.cwd?`from directory "${i.cwd}"`:""}
461
+ ${e.logger.stringifyLogs()}`);e.logger.info(`importNpmPackage("${h}")`),await I7(h,e,t);let d=r[h];d&&(r[n]=d);return}let o=".",a=e.tsConfig;if(e.tsConfig&&i.cwd){let h=i.cwd.match(/^(node_modules\/[^\/]+)/);h&&(o=h[1],a=null)}let c=H1(n,e.fsMap,i.cwd,{tsConfig:a,tsconfigDir:o});if(c){e.logger.info(`importLocalFile("${c}")`),await j0(c,e,t),n!==c&&(r[n]=r[c]);return}let l=e.tsConfig??G1(e.fsMap);if(!e.tsConfig&&l&&(e.tsConfig=l),Hit(n,l))throw new Error(`Import "${n}" matches a tsconfig path alias but could not be resolved to an existing file${i.cwd?` from directory "${i.cwd}"`:""}
462
+
463
+ ${e.logger.stringifyLogs()}`);let u=ty(n,e.fsMap,i.cwd||"");if(u)return e.logger.info(`resolvedNodeModulePath="${u}"`),e.logger.info(`importNodeModule("${n}")`),C7(n,e,t);if(!n.startsWith(".")&&!n.startsWith("/")&&!n.startsWith("@tsci/")&&e.circuit?.platform?.nodeModulesResolver){e.logger.info(`importNodeModule("${n}") via nodeModulesResolver`);try{await C7(n,e,t);return}catch{if(e.logger.info(`nodeModulesResolver failed for "${n}", falling back to npm CDN`),s)throw new Error(`Cannot find module "${n}". The package is not available in the local environment and automatic npm resolution is disabled.
464
+
465
+ ${e.logger.stringifyLogs()}`)}}if(n.startsWith("@tsci/"))return e.logger.info(`importSnippet("${n}")`),Dlt(n,e,t);if(!n.startsWith(".")&&!n.startsWith("/")){if(s)throw new Error(`Cannot find module "${n}". The package is not available in the local environment.
466
+
467
+ ${e.logger.stringifyLogs()}`);return e.logger.info(`importNpmPackage("${n}")`),I7(n,e,t)}throw new Error(`Unresolved import "${n}" ${i.cwd?`from directory "${i.cwd}"`:""}
462
468
 
463
469
  ${e.logger.stringifyLogs()}`)}var Ult=Gt(En(),1),pXt=(0,Ult.default)("tsci:eval:setupDefaultEntrypointIfNeeded"),Vlt=n=>{if(!n.entrypoint&&!n.mainComponentPath)if("index.tsx"in n.fsMap)n.mainComponentPath="index.tsx";else if("index.ts"in n.fsMap)n.mainComponentPath="index.ts";else if(Object.keys(n.fsMap).filter(e=>e.endsWith(".tsx")).length===1)n.mainComponentPath=Object.keys(n.fsMap)[0];else if("tscircuit.config.json"in n.fsMap){let e=n.fsMap["tscircuit.config.json"];try{let t=JSON.parse(e);t.mainEntrypoint&&(n.entrypoint=t.mainEntrypoint)}catch(t){console.warn("Failed to parse tscircuit.config.json:",t)}}else throw new Error("Either entrypoint or mainComponentPath must be provided (no index file, could not infer entrypoint)");if(!n.entrypoint&&n.mainComponentPath){if(n.entrypoint="entrypoint.tsx",!n.fsMap[gP(n.mainComponentPath,n.fsMap)])throw new Error(`Main component path "${n.mainComponentPath}" not found in fsMap. Available paths: ${Object.keys(n.fsMap).join(", ")}`);n.fsMap[n.entrypoint]=`
464
470
  import * as UserComponents from "./${n.mainComponentPath}";
@@ -478,7 +484,7 @@ ${e.logger.stringifyLogs()}`)}var Ult=Gt(En(),1),pXt=(0,Ult.default)("tsci:eval:
478
484
  circuit.add(
479
485
  <ComponentToRender ${n.mainComponentProps?`{...${JSON.stringify(n.mainComponentProps,null,2)}}`:""} />
480
486
  );
481
- `}!n.name&&n.mainComponentName&&(n.name=n.mainComponentName)};var N7=(n,e)=>{if(n instanceof Error&&e&&n.message.includes("RootCircuit has no children")&&!n.message.includes('"entrypoint":')){let t=e.startsWith("./")?e.slice(2):e;n.message=`${n.message}. "entrypoint": "${t}" is set in the runner configuration, entrypoints must contain "circuit.add(...)", you might be looking to use mainComponentPath instead if your file exports a component.`}return n};var Glt=()=>{let n=new Map,e=0;function t(r,s){let o=++e;return new Promise((a,c)=>{n.set(o,{resolve:a,reject:c});let l,u=s?{...s}:{};if(typeof r=="string"||r instanceof URL?l=r.toString():(l=r.url,u={...u,method:r.method,headers:(()=>{let h={};return r.headers.forEach((d,_)=>{h[_]=d}),h})(),body:r.bodyUsed?void 0:r.body}),u.headers instanceof Headers){let h={};u.headers.forEach((d,_)=>{h[_]=d}),u.headers=h}globalThis.postMessage({type:"worker_fetch",requestId:o,input:l,init:u})})}function i(r){let s=r.data;if(s){if(s.type==="override_global_fetch"){globalThis.fetch=t;return}if(s.type==="worker_fetch_result"){let o=n.get(s.requestId);if(!o)return;if(n.delete(s.requestId),s.success){let a=new Response(s.response.body,{status:s.response.status,statusText:s.response.statusText,headers:s.response.headers});o.resolve(a)}else{let a=new Error(s.error.message);s.error.name&&(a.name=s.error.name),s.error.stack&&(a.stack=s.error.stack),o.reject(a)}}}}globalThis.addEventListener("message",i)};function A7(n,e,t){let i=e.split("."),r=n;for(let s=0;s<i.length;s++){let o=i[s];s===i.length-1?r[o]=t:((!Object.prototype.hasOwnProperty.call(r,o)||typeof r[o]!="object"||r[o]===null||Array.isArray(r[o]))&&(r[o]={}),r=r[o])}}globalThis.React=L7;Glt();globalThis.global=globalThis.global||globalThis;var fn=null,fT,Ei={snippetsApiBaseUrl:"https://registry-api.tscircuit.com",cjsRegistryUrl:"https://cjs.tscircuit.com",verbose:!1,platform:void 0,projectConfig:void 0},ia={};function O7(n){if(!n||typeof n!="object")return n;if(n.__isSerializedReactElement){let e=hXt(n.props);return L7.createElement(n.type,e)}return n}function hXt(n){if(!n||typeof n!="object")return n;let e={};for(let[t,i]of Object.entries(n))t==="children"?Array.isArray(i)?e.children=i.map(O7):e.children=O7(i):e[t]=i;return e}function R7(n){for(let e in ia)for(let t of ia[e])n.on(e,t)}var dXt={setSnippetsApiBaseUrl:async n=>{Ei.snippetsApiBaseUrl=n},setPlatformConfig:async n=>{throw new Error("setPlatformConfig can't be used against the webworker directly due to comlink limitations, use setPlatformConfigProperty instead (or a wrapper)")},setPlatformConfigProperty:async(n,e)=>{Ei.platform||(Ei.platform={}),A7(Ei.platform,n,e)},setProjectConfig:async n=>{throw new Error("setProjectConfig can't be used against the webworker directly due to comlink limitations, use setProjectConfigProperty instead (or a wrapper)")},setProjectConfigProperty:async(n,e)=>{Ei.projectConfig||(Ei.projectConfig={}),A7(Ei.projectConfig,n,e)},enableDebug:async n=>{fT=n,fn&&fn.circuit.enableDebug?.(n)},version:async()=>"0.0.0",async executeWithFsMap(n){Ei.verbose&&console.log("[Worker] executeWithFsMap called with:",{entrypoint:n.entrypoint,fsMapKeys:Object.keys(n.fsMap),name:n.name}),Vlt(n);let e=n.entrypoint;if(fn=mP(Ei,{name:n.name,platform:Ei.platform,projectConfig:Ei.projectConfig,debugNamespace:fT}),R7(fn.circuit),fn.entrypoint=e,fn.fsMap=Vit(n.fsMap),fn.tsConfig=G1(fn.fsMap),!fn.fsMap[e])throw new Error(`Entrypoint "${n.entrypoint}" not found`);globalThis.__tscircuit_circuit=fn.circuit,e.startsWith("./")||(e=`./${e}`),await Zp(e,fn)},async execute(n,e={}){Ei.verbose&&console.log("[Worker] execute called with code length:",n.length),fn=mP(Ei,{...e,platform:Ei.platform,projectConfig:Ei.projectConfig,debugNamespace:fT}),R7(fn.circuit),fn.fsMap["entrypoint.tsx"]=n,fn.tsConfig=G1(fn.fsMap),globalThis.__tscircuit_circuit=fn.circuit,await Zp("./entrypoint.tsx",fn)},async executeComponent(n,e={}){Ei.verbose&&console.log("[Worker] executeComponent called"),fn=mP(Ei,{...e,platform:Ei.platform,projectConfig:Ei.projectConfig,debugNamespace:fT}),R7(fn.circuit),globalThis.__tscircuit_circuit=fn.circuit,fn.tsConfig=null;let t;typeof n=="function"?t=n():n?.__isSerializedReactElement?t=O7(n):t=n,fn.circuit.add(t)},on:(n,e)=>{ia[n]??(ia[n]=[]),ia[n].push(e),fn?.circuit.on(n,e)},renderUntilSettled:async()=>{if(!fn)throw new Error("No circuit has been created");try{await fn.circuit.renderUntilSettled()}catch(n){throw N7(n,fn.entrypoint)}},getCircuitJson:async()=>{if(!fn)throw new Error("No circuit has been created");try{return fn.circuit.getCircuitJson()}catch(n){throw N7(n,fn.entrypoint)}},clearEventListeners:()=>{if(fn?.circuit)for(let n in ia)for(let e of ia[n]){let t=fn.circuit;t.removeListener&&t.removeListener(n,e)}for(let n in ia)delete ia[n]},kill:async()=>{}};Rx(dXt);
487
+ `}!n.name&&n.mainComponentName&&(n.name=n.mainComponentName)};var N7=(n,e)=>{if(n instanceof Error&&e&&n.message.includes("RootCircuit has no children")&&!n.message.includes('"entrypoint":')){let t=e.startsWith("./")?e.slice(2):e;n.message=`${n.message}. "entrypoint": "${t}" is set in the runner configuration, entrypoints must contain "circuit.add(...)", you might be looking to use mainComponentPath instead if your file exports a component.`}return n};var Glt=()=>{let n=new Map,e=0;function t(r,s){let o=++e;return new Promise((a,c)=>{n.set(o,{resolve:a,reject:c});let l,u=s?{...s}:{};if(typeof r=="string"||r instanceof URL?l=r.toString():(l=r.url,u={...u,method:r.method,headers:(()=>{let h={};return r.headers.forEach((d,_)=>{h[_]=d}),h})(),body:r.bodyUsed?void 0:r.body}),u.headers instanceof Headers){let h={};u.headers.forEach((d,_)=>{h[_]=d}),u.headers=h}globalThis.postMessage({type:"worker_fetch",requestId:o,input:l,init:u})})}function i(r){let s=r.data;if(s){if(s.type==="override_global_fetch"){globalThis.fetch=t;return}if(s.type==="disable_cdn_loading"){globalThis.__DISABLE_CDN_LOADING__=s.value;return}if(s.type==="worker_fetch_result"){let o=n.get(s.requestId);if(!o)return;if(n.delete(s.requestId),s.success){let a=new Response(s.response.body,{status:s.response.status,statusText:s.response.statusText,headers:s.response.headers});o.resolve(a)}else{let a=new Error(s.error.message);s.error.name&&(a.name=s.error.name),s.error.stack&&(a.stack=s.error.stack),o.reject(a)}}}}globalThis.addEventListener("message",i)};function A7(n,e,t){let i=e.split("."),r=n;for(let s=0;s<i.length;s++){let o=i[s];s===i.length-1?r[o]=t:((!Object.prototype.hasOwnProperty.call(r,o)||typeof r[o]!="object"||r[o]===null||Array.isArray(r[o]))&&(r[o]={}),r=r[o])}}globalThis.React=L7;Glt();globalThis.global=globalThis.global||globalThis;var fn=null,fT,bi={snippetsApiBaseUrl:"https://registry-api.tscircuit.com",cjsRegistryUrl:"https://cjs.tscircuit.com",verbose:!1,platform:void 0,projectConfig:void 0},ia={};function O7(n){if(!n||typeof n!="object")return n;if(n.__isSerializedReactElement){let e=hXt(n.props);return L7.createElement(n.type,e)}return n}function hXt(n){if(!n||typeof n!="object")return n;let e={};for(let[t,i]of Object.entries(n))t==="children"?Array.isArray(i)?e.children=i.map(O7):e.children=O7(i):e[t]=i;return e}function R7(n){for(let e in ia)for(let t of ia[e])n.on(e,t)}var dXt={setSnippetsApiBaseUrl:async n=>{bi.snippetsApiBaseUrl=n},setDisableCdnLoading:async n=>{bi.disableCdnLoading=n},setPlatformConfig:async n=>{throw new Error("setPlatformConfig can't be used against the webworker directly due to comlink limitations, use setPlatformConfigProperty instead (or a wrapper)")},setPlatformConfigProperty:async(n,e)=>{bi.platform||(bi.platform={}),A7(bi.platform,n,e)},setProjectConfig:async n=>{throw new Error("setProjectConfig can't be used against the webworker directly due to comlink limitations, use setProjectConfigProperty instead (or a wrapper)")},setProjectConfigProperty:async(n,e)=>{bi.projectConfig||(bi.projectConfig={}),A7(bi.projectConfig,n,e)},enableDebug:async n=>{fT=n,fn&&fn.circuit.enableDebug?.(n)},version:async()=>"0.0.0",async executeWithFsMap(n){bi.verbose&&console.log("[Worker] executeWithFsMap called with:",{entrypoint:n.entrypoint,fsMapKeys:Object.keys(n.fsMap),name:n.name}),Vlt(n);let e=n.entrypoint;if(fn=mP(bi,{name:n.name,platform:bi.platform,projectConfig:bi.projectConfig,debugNamespace:fT}),R7(fn.circuit),fn.entrypoint=e,fn.fsMap=Vit(n.fsMap),fn.tsConfig=G1(fn.fsMap),!fn.fsMap[e])throw new Error(`Entrypoint "${n.entrypoint}" not found`);globalThis.__tscircuit_circuit=fn.circuit,e.startsWith("./")||(e=`./${e}`),await Zp(e,fn)},async execute(n,e={}){bi.verbose&&console.log("[Worker] execute called with code length:",n.length),fn=mP(bi,{...e,platform:bi.platform,projectConfig:bi.projectConfig,debugNamespace:fT}),R7(fn.circuit),fn.fsMap["entrypoint.tsx"]=n,fn.tsConfig=G1(fn.fsMap),globalThis.__tscircuit_circuit=fn.circuit,await Zp("./entrypoint.tsx",fn)},async executeComponent(n,e={}){bi.verbose&&console.log("[Worker] executeComponent called"),fn=mP(bi,{...e,platform:bi.platform,projectConfig:bi.projectConfig,debugNamespace:fT}),R7(fn.circuit),globalThis.__tscircuit_circuit=fn.circuit,fn.tsConfig=null;let t;typeof n=="function"?t=n():n?.__isSerializedReactElement?t=O7(n):t=n,fn.circuit.add(t)},on:(n,e)=>{ia[n]??(ia[n]=[]),ia[n].push(e),fn?.circuit.on(n,e)},renderUntilSettled:async()=>{if(!fn)throw new Error("No circuit has been created");try{await fn.circuit.renderUntilSettled()}catch(n){throw N7(n,fn.entrypoint)}},getCircuitJson:async()=>{if(!fn)throw new Error("No circuit has been created");try{return fn.circuit.getCircuitJson()}catch(n){throw N7(n,fn.entrypoint)}},clearEventListeners:()=>{if(fn?.circuit)for(let n in ia)for(let e of ia[n]){let t=fn.circuit;t.removeListener&&t.removeListener(n,e)}for(let n in ia)delete ia[n]},kill:async()=>{}};Rx(dXt);
482
488
  /*! Bundled license information:
483
489
 
484
490
  react/cjs/react.production.js: