@tscircuit/eval 0.0.331 → 0.0.332

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.
@@ -224,7 +224,7 @@ ${y.join(`
224
224
  </div>`},R_t=e=>{let t=e.layout(),n={title:"CssGrid",coordinateSystem:"screen",lines:[],circles:[],points:[],rects:[],texts:[]},{cells:i}=t;for(let r of i){let{x:o,y:s,width:a,height:c,key:l}=r;n.rects.push({center:{x:o+a/2,y:s+c/2},width:a,height:c,fill:G$(l),label:l})}return n};function Kg(e){return e.replace(/repeat\((\d+),\s*([^)]+)\)/g,(t,n,i)=>Array(Number(n)).fill(i.trim()).join(" "))}function Jg(e){return e.trim().split(/\s+/).filter(Boolean)}function X$(e){return e?Jg(Kg(e)).length:0}function V$(e,t){if(e==="auto")return{fr:1};if(e.endsWith("%")){let i=parseFloat(e);return t!=null?t*i/100:0}if(e.endsWith("px"))return parseFloat(e);if(e.endsWith("em"))return parseFloat(e)*16;if(e.endsWith("fr"))return{fr:parseFloat(e)};let n=parseFloat(e);return Number.isNaN(n)?0:n}function H$(e,t){return e>0?e:t+2+e}var O_t=e=>{let t=e.opts,n=t.children,i,r;if("gridTemplate"in t&&typeof t.gridTemplate=="string"){let[I,A]=t.gridTemplate.split("/");i=I?.trim(),r=A?.trim()}else i=typeof t.gridTemplateRows=="string"?t.gridTemplateRows:void 0,r=typeof t.gridTemplateColumns=="string"?t.gridTemplateColumns:void 0;let o=X$(r),s=X$(i);function a(I,A,M,k){if(!I)return 0;let z=Kg(I),B=Jg(z),j=B.length,q=0,G=!1;for(let tt=0;tt<B.length;tt++){let J=B[tt];if(J.endsWith("px"))q+=parseFloat(J);else if(J.endsWith("em"))q+=parseFloat(J)*16;else if(J.endsWith("fr")||J==="auto"){G=!0;let bt=0;for(let ct of A){let rt=M?ct.columnStart||ct.column:ct.rowStart||ct.row,it=M?ct.columnSpan||1:ct.rowSpan||1,wt=M?ct.contentWidth:ct.contentHeight,yt=(typeof rt=="number"?rt:parseInt(rt||"1"))-1,Mt=typeof it=="number"?it:parseInt(it.toString());if(yt<=tt&&tt<yt+Mt&&wt){let zt=typeof wt=="string"&&wt.endsWith("px")?parseFloat(wt):typeof wt=="number"?wt:0;bt=Math.max(bt,zt/Mt)}}q+=bt}}let K=k*(j-1);return q+K}function c(I,A,M,k=!0,z=1){if(!I)return[];if(A==null){let it=Kg(I),wt=Jg(it),yt=wt.length,Mt=$=>$===void 0?0:typeof $=="number"?$:($.endsWith("px"),parseFloat($)),zt=new Array(yt).fill(0),ht=0;for(let $ of n){let U=k?typeof $.columnSpan=="number"?$.columnSpan:$.columnSpan?parseInt($.columnSpan.toString()):1:typeof $.rowSpan=="number"?$.rowSpan:$.rowSpan?parseInt($.rowSpan.toString()):1,Y=k?$.contentWidth:$.contentHeight,et=Mt(Y)/U,lt;k?($.columnStart!==void 0||$.column!==void 0)&&(lt=parseInt($.columnStart??$.column)-1):($.rowStart!==void 0||$.row!==void 0)&&(lt=parseInt($.rowStart??$.row)-1),(lt===void 0||Number.isNaN(lt))&&(k?lt=ht%yt:lt=Math.floor(ht/z),ht+=U);for(let ut=0;ut<U&&lt+ut<yt;ut++)zt[lt+ut]=Math.max(zt[lt+ut],et)}return wt.forEach(($,U)=>{let Y=V$($,void 0);typeof Y=="number"&&(zt[U]=Y)}),zt}let B=Kg(I),j=Jg(B),q=j.length,G=A;G==null&&(G=a(I,n,k,M));let K=G-M*(q-1),tt=0,J=0,bt=[],ct=[];j.forEach((it,wt)=>{let yt=V$(it,K);typeof yt=="number"?(ct.push(yt),tt+=yt):yt&&typeof yt=="object"&&"fr"in yt?(ct.push(yt),J+=yt.fr,bt.push({idx:wt,fr:yt.fr})):(ct.push(0),tt+=0)});let rt=Math.max(K-tt,0);return ct.map(it=>typeof it=="number"?it:J>0?rt/J*it.fr:0)}let l=typeof t.gap=="number"?t.gap:Array.isArray(t.gap)?t.gap[0]:0,u=typeof t.gap=="number"?t.gap:Array.isArray(t.gap)?t.gap[1]:0,h=c(i,t.containerHeight,l,!1,o||1),m=c(r,t.containerWidth,u,!0,s||1),y=h.length,g=m.length;g===0&&n.length>0&&(g=1);let x=[],v=0;for(let I of n){let A=I.rowStart!==void 0?I.rowStart:I.row,M=I.columnStart!==void 0?I.columnStart:I.column,k=I.rowSpan!==void 0?typeof I.rowSpan=="string"?parseInt(I.rowSpan):I.rowSpan:1,z=I.columnSpan!==void 0?typeof I.columnSpan=="string"?parseInt(I.columnSpan):I.columnSpan:1;if(I.rowEnd!==void 0){let q=typeof I.rowEnd=="string"?parseInt(I.rowEnd):I.rowEnd;A!==void 0?k=q-(typeof A=="string"?parseInt(A):A):A=q-k}if(I.columnEnd!==void 0){let q=typeof I.columnEnd=="string"?parseInt(I.columnEnd):I.columnEnd;M!==void 0?z=q-(typeof M=="string"?parseInt(M):M):M=q-z}if(typeof A=="string"&&(A=parseInt(A)),typeof M=="string"&&(M=parseInt(M)),typeof A=="number"&&A<0&&(A=H$(A,y)),typeof M=="number"&&M<0&&(M=H$(M,g)),A===void 0&&M!==void 0)A=1;else if(M===void 0&&A!==void 0)M=1;else if(A===void 0&&M===void 0){let q=v;A=Math.floor(q/g)+1,M=q%g+1}let B=A-1,j=M-1;k=Math.max(1,k),z=Math.max(1,z),x.push({key:I.key,row:B,column:j,rowSpan:k,columnSpan:z,x:0,y:0,width:0,height:0}),v+=z}let w=h.length,P=m.length;for(let I of x)I.row+I.rowSpan>w&&(w=I.row+I.rowSpan),I.column+I.columnSpan>P&&(P=I.column+I.columnSpan);if(h.length===0&&w>0&&t.containerHeight){let I=w,M=(t.containerHeight-l*(I-1))/I;for(let k=0;k<I;k++)h.push(M)}else for(;h.length<w;)h.push(0);if(m.length===0&&P>0&&t.containerWidth){let I=P,M=(t.containerWidth-u*(I-1))/I;for(let k=0;k<I;k++)m.push(M)}else if(m.length===0&&n.length>0&&t.containerWidth)m.push(t.containerWidth);else for(;m.length<P;)m.push(0);let N=(I,A,M)=>{let k=0;for(let z=0;z<I;z++)k+=A[z]||0,k+=M;return k},E=(I,A,M,k)=>{let z=0;for(let B=I;B<I+A;B++)z+=M[B]||0,B>I&&(z+=k);return z},R={};for(let I of x){let A=n.find(ct=>ct.key===I.key),M=N(I.column,m,u),k=N(I.row,h,l),z=E(I.column,I.columnSpan,m,u),B=E(I.row,I.rowSpan,h,l),j=ct=>ct===void 0?0:typeof ct=="string"?ct.endsWith("px")?parseFloat(ct):ct.endsWith("%")?0:parseFloat(ct):ct,q=j(A?.contentWidth),G=j(A?.contentHeight),K=z,tt=B,J=M,bt=k;if(q>0)switch(K=q,t.justifyItems||"stretch"){case"start":J=M;break;case"end":J=M+z-K;break;case"center":J=M+(z-K)/2;break;case"stretch":K=z,J=M;break}if(G>0)switch(tt=G,t.alignItems||"stretch"){case"start":bt=k;break;case"end":bt=k+B-tt;break;case"center":bt=k+(B-tt)/2;break;case"stretch":tt=B,bt=k;break}I.x=J,I.y=bt,I.width=K,I.height=tt,R[I.key]={x:J,y:bt,width:K,height:tt}}return{cells:x,rowSizes:h,columnSizes:m,rowGap:l,columnGap:u,itemCoordinates:R}},U$=class{constructor(e){T(this,"opts");this.opts=e}layout(){return O_t(this)}convertToHtml(){return N_t(this)}visualize(){return R_t(this)}};St();var Xj=Zt(Nn(),1);Be();Be();St();var Q4=class{constructor(e){T(this,"netMap");T(this,"idToNetMap");this.netMap=e,this.idToNetMap={};for(let[t,n]of Object.entries(e))for(let i of n)this.idToNetMap[i]=t}addConnections(e){for(let t of e){let n=new Set;for(let r of t){let o=this.idToNetMap[r];o&&n.add(o)}let i;if(n.size===0)i=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[i]=[];else if(n.size===1)i=n.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{i=n.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(let r of n)if(r!==i){let o=this.netMap[i],s=this.netMap[r];if(o&&s){o.push(...s),this.netMap[r]=o;for(let a of o)this.idToNetMap[a]=i}}}for(let r of t){let o=this.netMap[i];o&&!o.includes(r)&&o.push(r),this.idToNetMap[r]=i}}}getIdsConnectedToNet(e){return this.netMap[e]||[]}getNetConnectedToId(e){return this.idToNetMap[e]}areIdsConnected(e,t){if(e===t)return!0;let n=this.getNetConnectedToId(e);if(!n)return!1;let i=this.getNetConnectedToId(t);return i?n===i||i===e||i===e:!1}areAllIdsConnected(e){if(e.length===0)return!0;let t=this.getNetConnectedToId(e[0]);if(!t)return!1;for(let n of e){let i=this.getNetConnectedToId(n);if(i===void 0||i!==t)return!1}return!0}};var nf=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(t,n){let i=this.length++;for(;i>0;){let r=i-1>>1,o=this.values[r];if(n>=o)break;this.ids[i]=this.ids[r],this.values[i]=o,i=r}this.ids[i]=t,this.values[i]=n}pop(){if(this.length===0)return;let t=this.ids,n=this.values,i=t[0],r=--this.length;if(r>0){let o=t[r],s=n[r],a=0,c=r>>1;for(;a<c;){let l=(a<<1)+1,u=l+1,h=l+(+(u<r)&+(n[u]<n[l]));if(n[h]>=s)break;t[a]=t[h],n[a]=n[h],a=h}t[a]=o,n[a]=s}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 q$=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],tT=3,rf=class e{static from(t,n=0){if(n%8!==0)throw new Error("byteOffset must be 8-byte aligned.");if(!t||t.byteLength===void 0||t.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[i,r]=new Uint8Array(t,n+0,2);if(i!==251)throw new Error("Data does not appear to be in a Flatbush format.");let o=r>>4;if(o!==tT)throw new Error(`Got v${o} data when expected v${tT}.`);let s=q$[r&15];if(!s)throw new Error("Unrecognized array type.");let[a]=new Uint16Array(t,n+2,1),[c]=new Uint32Array(t,n+4,1);return new e(c,a,s,void 0,t,n)}constructor(t,n=16,i=Float64Array,r=ArrayBuffer,o,s=0){if(t===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(t)||t<=0)throw new Error(`Unexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+n,2),65535),this.byteOffset=s;let a=t,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=q$.indexOf(i),u=c*4*i.BYTES_PER_ELEMENT;if(l<0)throw new Error(`Unexpected typed array class: ${i}.`);if(o)this.data=o,this._boxes=new i(o,s+8,c*4),this._indices=new this.IndexArrayType(o,s+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,(tT<<4)+l]),new Uint16Array(h,2,1)[0]=n,new Uint32Array(h,4,1)[0]=t}this._queue=new nf}add(t,n,i=t,r=n){let o=this._pos>>2,s=this._boxes;return this._indices[o]=o,s[this._pos++]=t,s[this._pos++]=n,s[this._pos++]=i,s[this._pos++]=r,t<this.minX&&(this.minX=t),n<this.minY&&(this.minY=n),i>this.maxX&&(this.maxX=i),r>this.maxY&&(this.maxY=r),o}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let t=this._boxes;if(this.numItems<=this.nodeSize){t[this._pos++]=this.minX,t[this._pos++]=this.minY,t[this._pos++]=this.maxX,t[this._pos++]=this.maxY;return}let n=this.maxX-this.minX||1,i=this.maxY-this.minY||1,r=new Uint32Array(this.numItems),o=65535;for(let s=0,a=0;s<this.numItems;s++){let c=t[a++],l=t[a++],u=t[a++],h=t[a++],m=Math.floor(o*((c+u)/2-this.minX)/n),y=Math.floor(o*((l+h)/2-this.minY)/i);r[s]=z_t(m,y)}eT(r,t,this._indices,0,this.numItems-1,this.nodeSize);for(let s=0,a=0;s<this._levelBounds.length-1;s++){let c=this._levelBounds[s];for(;a<c;){let l=a,u=t[a++],h=t[a++],m=t[a++],y=t[a++];for(let g=1;g<this.nodeSize&&a<c;g++)u=Math.min(u,t[a++]),h=Math.min(h,t[a++]),m=Math.max(m,t[a++]),y=Math.max(y,t[a++]);this._indices[this._pos>>2]=l,t[this._pos++]=u,t[this._pos++]=h,t[this._pos++]=m,t[this._pos++]=y}}}search(t,n,i,r,o){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=[],c=[];for(;s!==void 0;){let l=Math.min(s+this.nodeSize*4,W$(s,this._levelBounds));for(let u=s;u<l;u+=4){let h=this._boxes[u];if(i<h)continue;let m=this._boxes[u+1];if(r<m)continue;let y=this._boxes[u+2];if(t>y)continue;let g=this._boxes[u+3];if(n>g)continue;let x=this._indices[u>>2]|0;s>=this.numItems*4?a.push(x):(o===void 0||o(x,h,m,y,g))&&c.push(x)}s=a.pop()}return c}neighbors(t,n,i=1/0,r=1/0,o){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=this._queue,c=[],l=r*r;t:for(;s!==void 0;){let u=Math.min(s+this.nodeSize*4,W$(s,this._levelBounds));for(let h=s;h<u;h+=4){let m=this._indices[h>>2]|0,y=this._boxes[h],g=this._boxes[h+1],x=this._boxes[h+2],v=this._boxes[h+3],w=t<y?y-t:t>x?t-x:0,P=n<g?g-n:n>v?n-v:0,N=w*w+P*P;N>l||(s>=this.numItems*4?a.push(m<<1,N):(o===void 0||o(m))&&a.push((m<<1)+1,N))}for(;a.length&&a.peek()&1;)if(a.peekValue()>l||(c.push(a.pop()>>1),c.length===i))break t;s=a.length?a.pop()>>1:void 0}return a.clear(),c}};function W$(e,t){let n=0,i=t.length-1;for(;n<i;){let r=n+i>>1;t[r]>e?i=r:n=r+1}return t[n]}function eT(e,t,n,i,r,o){if(Math.floor(i/o)>=Math.floor(r/o))return;let s=e[i],a=e[i+r>>1],c=e[r],l=c,u=Math.max(s,a);c>u?l=u:u===s?l=Math.max(a,c):u===a&&(l=Math.max(s,c));let h=i-1,m=r+1;for(;;){do h++;while(e[h]<l);do m--;while(e[m]>l);if(h>=m)break;L_t(e,t,n,h,m)}eT(e,t,n,i,m,o),eT(e,t,n,m+1,r,o)}function L_t(e,t,n,i,r){let o=e[i];e[i]=e[r],e[r]=o;let s=4*i,a=4*r,c=t[s],l=t[s+1],u=t[s+2],h=t[s+3];t[s]=t[a],t[s+1]=t[a+1],t[s+2]=t[a+2],t[s+3]=t[a+3],t[a]=c,t[a+1]=l,t[a+2]=u,t[a+3]=h;let m=n[i];n[i]=n[r],n[r]=m}function z_t(e,t){let n=e^t,i=65535^n,r=65535^(e|t),o=e&(t^65535),s=n|i>>1,a=n>>1^n,c=r>>1^i&o>>1^r,l=n&r>>1^o>>1^o;n=s,i=a,r=c,o=l,s=n&n>>2^i&i>>2,a=n&i>>2^i&(n^i)>>2,c^=n&r>>2^i&o>>2,l^=i&r>>2^(n^i)&o>>2,n=s,i=a,r=c,o=l,s=n&n>>4^i&i>>4,a=n&i>>4^i&(n^i)>>4,c^=n&r>>4^i&o>>4,l^=i&r>>4^(n^i)&o>>4,n=s,i=a,r=c,o=l,c^=n&r>>8^i&o>>8,l^=i&r>>8^(n^i)&o>>8,n=c^c>>1,i=l^l>>1;let u=e^t,h=i|65535^(u|n);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 Ts=class{constructor(){T(this,"MAX_ITERATIONS",1e5);T(this,"solved",!1);T(this,"failed",!1);T(this,"iterations",0);T(this,"progress",0);T(this,"error",null);T(this,"activeSubSolver");T(this,"failedSubSolvers");T(this,"timeToSolve");T(this,"stats",{})}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e){throw this.error=`${this.constructor.name} error: ${e}`,this.failed=!0,e}!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 e=Date.now();for(;!this.solved&&!this.failed;)this.step();let t=Date.now();this.timeToSolve=t-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}},eB=e=>{let t=new Q4({});for(let i of e.directConnections)t.addConnections([i.netId?[i.netId,...i.pinIds]:i.pinIds]);let n=new Q4(t.netMap);for(let i of e.netConnections)n.addConnections([[i.netId,...i.pinIds]]);return{directConnMap:t,netConnMap:n}};function F_t(e,t={}){let n=e.length,i=t?.maxDistance??Number.POSITIVE_INFINITY;if(n<=1)return[];{let u=new Set;for(let h of e){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),o=new Array(n).fill(!1),s=new Array(n).fill(Number.POSITIVE_INFINITY),a=new Array(n).fill(-1),c=0;for(let u=1;u<n;u++)e[u].pinId<e[c].pinId&&(c=u);s[c]=0;let l=[];for(let u=0;u<n;u++){let h=-1,m=Number.POSITIVE_INFINITY,y="";for(let g=0;g<n;g++)if(!o[g]){let x=s[g];(x<m||x===m&&(y===""||e[g].pinId<y))&&(m=x,y=e[g].pinId,h=g)}o[h]=!0,a[h]!==-1&&l.push([e[h].pinId,e[a[h]].pinId]);for(let g=0;g<n;g++)if(!o[g]){let x=r(e[h],e[g]),v=t?.forbidEdge?.(e[h],e[g])??!1,w=x>i||v?Number.POSITIVE_INFINITY:x;(w<s[g]||w===s[g]&&e[h].pinId<e[a[g]]?.pinId)&&(s[g]=w,a[g]=h)}}return l}var sf=(e,t)=>{let{x:n,y:i}=e,{center:r,width:o,height:s}=t,a=r.y+s/2,c=r.y-s/2,l=r.x+o/2,u=r.x-o/2,h=a-i,m=i-c,y=l-n,g=n-u,x=Math.min(h,m,y,g);return x===h?"y+":x===m?"y-":x===y?"x+":"x-"},D_t=e=>{let{pins:t,inputProblem:n,pinIdMap:i,chipMap:r}=e,o=m=>{let y=new Set,g=[m];y.add(m);let x=n.directConnections||[];for(;g.length;){let v=g.shift();for(let w of x)if(w.pinIds.includes(v))for(let P of w.pinIds)y.has(P)||(y.add(P),g.push(P))}return y},s=t[0].pinId,a=t[1].pinId,c=new Set([...o(s),...o(a)]),l=new Map,u=new Map,h=new Set(t.map(m=>m.chipId));for(let m of c){let y=i.get(m);if(!y)continue;let g=r[y.chipId];if(!g)continue;let x=y._facingDirection??sf(y,g),v=u.get(g.chipId);if(!v){v={center:g.center};let w={xPos:0,xNeg:0,yPos:0,yNeg:0};for(let P of g.pins){let N=P._facingDirection??sf(P,g);N==="x+"&&w.xPos++,N==="x-"&&w.xNeg++,N==="y+"&&w.yPos++,N==="y-"&&w.yNeg++}v.counts=w,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[m,y]of u){let g=new Set,x={axes:g},v=y.counts;!!!(v&&(v.xPos>1||v.xNeg>1||v.yPos>1||v.yNeg>1))&&h.has(m)||(y.hasXPos&&y.hasXNeg&&(x.x=y.center.x,g.add("x")),y.hasYPos&&y.hasYNeg&&(x.y=y.center.y,g.add("y"))),g.size>0&&l.set(m,x)}return l},nT=e=>{let{inputProblem:t,chipMap:n,pinIdMap:i,p1:r,p2:o}=e,s=D_t({pins:[r,o],inputProblem:t,pinIdMap:i,chipMap:n});if(s.size===0)return!1;let a=1e-9,c=(y,g)=>{for(let[,x]of s)if(x.axes.has("x")&&typeof x.x=="number"&&(y.x-x.x)*(g.x-x.x)<-a||x.axes.has("y")&&typeof x.y=="number"&&(y.y-x.y)*(g.y-x.y)<-a)return!0;return!1};if(Math.abs(r.x-o.x)<a||Math.abs(r.y-o.y)<a)return c({x:r.x,y:r.y},{x:o.x,y:o.y});let l={x:o.x,y:r.y},u={x:r.x,y:o.y},h=c({x:r.x,y:r.y},l)||c(l,{x:o.x,y:o.y}),m=c({x:r.x,y:r.y},u)||c(u,{x:o.x,y:o.y});return h&&m},Ur=(e,t=1)=>`hsl(${e.split("").reduce((i,r)=>i*31+r.charCodeAt(0),0)%360}, 100%, 50%, ${t})`,Da=(e,t={})=>{let{connectionAlpha:n=.8,chipAlpha:i=.8}=t,r={lines:[],points:[],rects:[]},o=new Map;for(let s of e.chips)for(let a of s.pins)o.set(a.pinId,a);for(let s of e.chips){r.rects.push({label:s.chipId,center:s.center,width:s.width,height:s.height,fill:Ur(s.chipId,i)});for(let a of s.pins)r.points.push({label:`${a.pinId}
225
225
  ${a._facingDirection??sf(a,s)}`,x:a.x,y:a.y,color:Ur(a.pinId,.8)})}for(let s of e.directConnections){let[a,c]=s.pinIds,l=o.get(a),u=o.get(c);r.lines.push({points:[{x:l.x,y:l.y},{x:u.x,y:u.y}],strokeColor:Ur(s.netId??`${a}-${c}`,n)})}for(let s of e.netConnections){let a=s.pinIds.map(c=>o.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:Ur(s.netId,n),strokeDash:"4 2"})}}return r},$_t=class extends Ts{constructor({inputProblem:t}){super();T(this,"inputProblem");T(this,"mspConnectionPairs",[]);T(this,"dcConnMap");T(this,"globalConnMap");T(this,"queuedDcNetIds");T(this,"chipMap");T(this,"maxMspPairDistance");T(this,"pinMap");T(this,"userNetIdByPinId");this.inputProblem=t,this.maxMspPairDistance=t.maxMspPairDistance??1;let{directConnMap:n,netConnMap:i}=eB(t);this.dcConnMap=n,this.globalConnMap=i,this.pinMap={};for(let r of t.chips)for(let o of r.pins)this.pinMap[o.pinId]={...o,chipId:r.chipId};this.chipMap={};for(let r of t.chips)this.chipMap[r.chipId]=r;this.userNetIdByPinId={};for(let r of t.directConnections)if(r.netId){let[o,s]=r.pinIds;this.userNetIdByPinId[o]=r.netId,this.userNetIdByPinId[s]=r.netId}for(let r of t.netConnections)for(let o of r.pinIds)this.userNetIdByPinId[o]=r.netId;this.queuedDcNetIds=Object.keys(i.netMap)}getConstructorParams(){return{inputProblem:this.inputProblem}}_step(){if(this.queuedDcNetIds.length===0){this.solved=!0;return}let t=this.queuedDcNetIds.shift(),i=this.globalConnMap.getIdsConnectedToNet(t).filter(s=>!!this.pinMap[s]);if(i.length<=1)return;if(i.length===2){let[s,a]=i,c=this.pinMap[s],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(nT({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:h,p1:c,p2:l}))return;let m=this.globalConnMap.getNetConnectedToId(s),y=this.userNetIdByPinId[s]??this.userNetIdByPinId[a];this.mspConnectionPairs.push({mspPairId:`${s}-${a}`,dcConnNetId:t,globalConnNetId:m,userNetId:y,pins:[c,l]});return}let r=new Map(Object.entries(this.pinMap)),o=F_t(i.map(s=>this.pinMap[s]).filter(Boolean),{maxDistance:this.maxMspPairDistance,forbidEdge:(s,a)=>nT({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:r,p1:s,p2:a})});for(let[s,a]of o){let c=this.pinMap[s],l=this.pinMap[a];if(nT({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:r,p1:c,p2:l}))continue;let u=this.globalConnMap.getNetConnectedToId(s),h=this.userNetIdByPinId[s]??this.userNetIdByPinId[a];this.mspConnectionPairs.push({mspPairId:`${s}-${a}`,dcConnNetId:t,globalConnNetId:u,userNetId:h,pins:[c,l]})}}visualize(){let t=Da(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let n of this.mspConnectionPairs)t.lines.push({points:[{x:n.pins[0].x,y:n.pins[0].y},{x:n.pins[1].x,y:n.pins[1].y}],strokeColor:Ur(n.mspPairId,.75)});return t}};function aT(e){let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,maxX:e.center.x+t,minY:e.center.y-n,maxY:e.center.y+n}}var B_t=e=>{let t=aT(e);return{chipId:e.chipId,...t}},tx=e=>e.chips.map(B_t),cT=1e-9,Ps=(e,t,n=cT)=>Math.abs(e.x-t.x)<n,za=(e,t,n=cT)=>Math.abs(e.y-t.y)<n,kp=(e,t,n,i=cT)=>{let r=Ps(e,t,i),o=za(e,t,i);if(!r&&!o)return!1;if(r){let s=e.x;if(s<n.minX-i||s>n.maxX+i)return!1;let a=Math.min(e.y,t.y),c=Math.max(e.y,t.y);return Math.min(c,n.maxY)-Math.max(a,n.minY)>i}else{let s=e.y;if(s<n.minY-i||s>n.maxY+i)return!1;let a=Math.min(e.x,t.x),c=Math.max(e.x,t.x);return Math.min(c,n.maxX)-Math.max(a,n.minX)>i}},j_t=(e,t,n={})=>{for(let i=0;i<e.length-1;i++){let r=e[i],o=e[i+1],s=n.excludeRectIdsForSegment?.(i)??new Set;for(let a of t)if(!s.has(a.chipId)&&kp(r,o,a))return{segIndex:i,rect:a}}return null},Qg=(e,t)=>{for(let n=0;n<e.length-1;n++)for(let i of t)if(kp(e[n],e[n+1],i))return!0;return!1},nB=1e-9,Y_t=(e,t)=>({minX:Math.min(e.x,t.x),maxX:Math.max(e.x,t.x),minY:Math.min(e.y,t.y),maxY:Math.max(e.y,t.y)}),Z$=(e,t,n,i=nB)=>e==="x"?t.x<n.minX-i?[(t.x+n.minX)/2]:t.x>n.maxX+i?[(t.x+n.maxX)/2]:[n.minX-.2,n.maxX+.2]:t.y<n.minY-i?[(t.y+n.minY)/2]:t.y>n.maxY+i?[(t.y+n.maxY)/2]:[n.minY-.2,n.maxY+.2],X_t=(e,t,n,i,r,o=nB)=>{let s=[...i].map(a=>n.get(a)).filter(a=>!!a);if(e==="x"){let a=[r.minX,...s.map(m=>m.maxX)].filter(m=>m<t.minX-o),c=[r.maxX,...s.map(m=>m.minX)].filter(m=>m>t.maxX+o),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+t.minX)/2),u!==void 0&&h.push((t.maxX+u)/2),h}else{let a=[r.minY,...s.map(m=>m.maxY)].filter(m=>m<t.minY-o),c=[r.maxY,...s.map(m=>m.minY)].filter(m=>m>t.maxY+o),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+t.minY)/2),u!==void 0&&h.push((t.maxY+u)/2),h}},V_t=1e-9,H_t=(e,t,n,i,r=V_t)=>{if(t<0||t>=e.length-1)return null;let o=e[t],s=e[t+1],a=Ps(o,s,r),c=za(o,s,r);if(!a&&!c||a&&n!=="x"||c&&n!=="y")return null;let l=e.map(u=>({...u}));if(n==="x"){if(Math.abs(o.x-i)<r&&Math.abs(s.x-i)<r)return null;l[t]={...l[t],x:i},l[t+1]={...l[t+1],x:i}}else{if(Math.abs(o.y-i)<r&&Math.abs(s.y-i)<r)return null;l[t]={...l[t],y:i},l[t+1]={...l[t+1],y:i}}if(t-1>=0){let u=l[t-1],h=l[t];if(Math.abs(u.x-h.x)+Math.abs(u.y-h.y)<r)return null}if(t+2<=l.length-1){let u=l[t+1],h=l[t+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],m=l[u+1];if(!za(h,m,r)&&!Ps(h,m,r))return null}return l},K$=(e,t=6)=>e.map(i=>`${i.x.toFixed(t)},${i.y.toFixed(t)}`).join("|"),G_t=class extends Ts{constructor(t){super();T(this,"pins");T(this,"inputProblem");T(this,"chipMap");T(this,"obstacles");T(this,"rectById");T(this,"aabb");T(this,"baseElbow");T(this,"solvedTracePath",null);T(this,"queue",[]);T(this,"visited",new Set);this.pins=t.pins,this.inputProblem=t.inputProblem,this.chipMap=t.chipMap;for(let r of this.pins)if(!r._facingDirection){let o=this.chipMap[r.chipId];r._facingDirection=sf(r,o)}this.obstacles=tx(this.inputProblem),this.rectById=new Map(this.obstacles.map(r=>[r.chipId,r]));let[n,i]=this.pins;this.baseElbow=rp({x:n.x,y:n.y,facingDirection:n._facingDirection},{x:i.x,y:i.y,facingDirection:i._facingDirection},{overshoot:.2}),this.aabb=Y_t({x:n.x,y:n.y},{x:i.x,y:i.y}),this.queue.push({path:this.baseElbow,collisionChipIds:new Set}),this.visited.add(K$(this.baseElbow))}getConstructorParams(){return{chipMap:this.chipMap,pins:this.pins,inputProblem:this.inputProblem}}axisOfSegment(t,n){return Ps(t,n)?"x":za(t,n)?"y":null}pathLength(t){let n=0;for(let i=0;i<t.length-1;i++)n+=Math.abs(t[i+1].x-t[i].x)+Math.abs(t[i+1].y-t[i].y);return n}_step(){if(this.solvedTracePath){this.solved=!0;return}let t=this.queue.shift();if(!t){this.failed=!0,this.error="No collision-free path found";return}let{path:n,collisionChipIds:i}=t,[r,o]=this.pins,s=j_t(n,this.obstacles);if(!s){let v=n[0],w=n[n.length-1],P=1e-9,N=(E,R)=>Math.abs(E.x-R.x)<P&&Math.abs(E.y-R.y)<P;N(v,{x:r.x,y:r.y})&&N(w,{x:o.x,y:o.y})&&(this.solvedTracePath=n,this.solved=!0);return}let{segIndex:a,rect:c}=s,l=a===0,u=a===n.length-2;if(l){if(n.length<3)return;a=1}else if(u){if(n.length<3)return;a=n.length-3}let h=n[a],m=n[a+1],y=this.axisOfSegment(h,m);if(!y)return;let g=[];if(i.size===0){let v=Z$(y,{x:r.x,y:r.y},c),w=Z$(y,{x:o.x,y:o.y},c),P=[...v,...w],N=[...new Set(P)];g.push(...N)}else{let v=X_t(y,c,this.rectById,i,this.aabb);g.push(...v)}let x=[];for(let v of g){let w=H_t(n,a,y,v);if(!w)continue;let P=K$(w);if(this.visited.has(P))continue;this.visited.add(P);let N=new Set(i);N.add(c.chipId);let E=this.pathLength(w);x.push({path:w,collisionRectIds:N,len:E})}x.sort((v,w)=>v.len-w.len);for(let v of x)this.queue.push({path:v.path,collisionChipIds:v.collisionRectIds})}visualize(){let t=Da(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});t.lines.push({points:this.baseElbow,strokeColor:"red",strokeDash:"4 4"});let[n,i]=this.pins;t.lines.push({points:[{x:n.x,y:n.y},{x:i.x,y:i.y}],strokeColor:"blue",strokeDash:"5 5"});for(let{path:r,collisionChipIds:o}of this.queue)t.lines.push({points:r,strokeColor:"teal",strokeDash:"2 2"});return this.solvedTracePath?t.lines.push({points:this.solvedTracePath,strokeColor:"green"}):this.queue.length>0&&t.lines.push({points:this.queue[0].path,strokeColor:"orange"}),t}},U_t=class extends Ts{constructor(t){super();T(this,"inputProblem");T(this,"mspConnectionPairs");T(this,"dcConnMap");T(this,"globalConnMap");T(this,"queuedConnectionPairs");T(this,"chipMap");T(this,"currentConnectionPair",null);T(this,"solvedTracePaths",[]);T(this,"failedConnectionPairs",[]);this.inputProblem=t.inputProblem,this.mspConnectionPairs=t.mspConnectionPairs,this.dcConnMap=t.dcConnMap,this.globalConnMap=t.globalConnMap,this.chipMap=t.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 t=this.queuedConnectionPairs.shift();if(!t){this.solved=!0;return}this.currentConnectionPair=t;let{pins:n}=t;this.activeSubSolver=new G_t({inputProblem:this.inputProblem,pins:n,chipMap:this.chipMap})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let t=Da(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let{mspPairId:n,tracePath:i}of this.solvedTracePaths)t.lines.push({points:i,strokeColor:"green"});for(let n of this.failedConnectionPairs)t.lines.push({points:[{x:n.pins[0].x,y:n.pins[0].y},{x:n.pins[1].x,y:n.pins[1].y}],strokeColor:"red",strokeDash:"4 2"});return t}},q_t=({pts:e,segmentIndex:t,offset:n,JOG_SIZE:i,EPS:r=1e-6})=>{if(t!==0&&t!==e.length-2)return;let o=e[t],s=e[t+1],a=Math.abs(o.x-s.x)<r,c=Math.abs(o.y-s.y)<r;if(!a&&!c)return;let l=a?s.y>o.y?1:-1:s.x>o.x?1:-1;if(t===0)if(a){let u=o.y+l*i;e.splice(1,1,{x:o.x,y:u},{x:o.x+n,y:u},{x:s.x+n,y:s.y})}else{let u=o.x+l*i;e.splice(1,1,{x:u,y:o.y},{x:u,y:o.y+n},{x:s.x,y:s.y+n})}else if(a){let u=s.y-l*i;e.splice(t,1,{x:o.x+n,y:o.y},{x:s.x+n,y:u},{x:s.x,y:u})}else{let u=s.x-l*i;e.splice(t,1,{x:o.x,y:o.y+n},{x:u,y:s.y+n},{x:u,y:s.y})}},W_t=class extends Ts{constructor(t){super();T(this,"overlappingTraceSegments");T(this,"traceNetIslands");T(this,"SHIFT_DISTANCE",.1);T(this,"correctedTraceMap",{});this.overlappingTraceSegments=t.overlappingTraceSegments,this.traceNetIslands=t.traceNetIslands;for(let{connNetId:n,pathsWithOverlap:i}of this.overlappingTraceSegments)for(let{solvedTracePathIndex:r,traceSegmentIndex:o}of i){let s=this.traceNetIslands[n][r].mspPairId;this.correctedTraceMap[s]=this.traceNetIslands[n][r]}}_step(){let n=this.overlappingTraceSegments.map((o,s)=>{let a=Math.floor(s/2)+1;return(s%2===0?-a:a)*this.SHIFT_DISTANCE}),i=(o,s)=>Math.abs(o-s)<1e-6,r=(o,s)=>!!o&&!!s&&i(o.x,s.x)&&i(o.y,s.y);this.overlappingTraceSegments.forEach((o,s)=>{let a=n[s],c=new Map;for(let l of o.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[o.connNetId][l],m=this.correctedTraceMap[h.mspPairId]??h,y=m.tracePath.map(P=>({...P})),g=Array.from(u).sort((P,N)=>P-N),x=Array.from(u).sort((P,N)=>P-N).reverse(),v=this.SHIFT_DISTANCE;for(let P of x)if(!(P<0||P>=y.length-1))if(P===0||P===y.length-2)q_t({pts:y,segmentIndex:P,offset:a,JOG_SIZE:v,EPS:1e-6});else{let N=y[P],E=y[P+1],R=Math.abs(N.x-E.x)<1e-6,I=Math.abs(N.y-E.y)<1e-6;if(!R&&!I)continue;R?(N.x+=a,E.x+=a):(N.y+=a,E.y+=a)}let w=[];for(let P of y)(w.length===0||!r(w[w.length-1],P))&&w.push(P);this.correctedTraceMap[h.mspPairId]={...m,tracePath:w}}}),this.solved=!0}visualize(){let t={lines:[],points:[],rects:[],circles:[]};for(let n of this.overlappingTraceSegments)for(let{solvedTracePathIndex:i,traceSegmentIndex:r}of n.pathsWithOverlap){let o=this.traceNetIslands[n.connNetId][i],s=o.tracePath[r],a=o.tracePath[r+1];t.lines.push({points:[s,a],strokeColor:"red"})}for(let n of Object.values(this.correctedTraceMap))t.lines.push({points:n.tracePath,strokeColor:"blue",strokeDash:"4 2"});return t}},Z_t=class extends Ts{constructor(t){super();T(this,"inputProblem");T(this,"inputTracePaths");T(this,"globalConnMap");T(this,"traceNetIslands",{});T(this,"correctedTraceMap",{});this.inputProblem=t.inputProblem,this.inputTracePaths=t.inputTracePaths,this.globalConnMap=t.globalConnMap;for(let n of this.inputTracePaths){let{mspPairId:i}=n;this.correctedTraceMap[i]=n}this.traceNetIslands=this.computeTraceNetIslands()}getConstructorParams(){return{inputProblem:this.inputProblem,inputTracePaths:this.inputTracePaths,globalConnMap:this.globalConnMap}}computeTraceNetIslands(){let t={};for(let n of this.inputTracePaths){let i=this.correctedTraceMap[n.mspPairId]??n,r=i.globalConnNetId;t[r]||(t[r]=[]),t[r].push(i)}return t}findNextOverlapIssue(){let n=Object.keys(this.traceNetIslands);for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let o=n[i],s=n[r],a=this.traceNetIslands[o]||[],c=this.traceNetIslands[s]||[],l=[],u=[],h=new Set,m=new Set,y=(g,x,v,w)=>{let P=Math.min(g,x),N=Math.max(g,x),E=Math.min(v,w),R=Math.max(v,w);return Math.min(N,R)-Math.max(P,E)>.002};for(let g=0;g<a.length;g++){let v=a[g].tracePath;for(let w=0;w<v.length-1;w++){let P=v[w],N=v[w+1],E=Math.abs(P.x-N.x)<.002,R=Math.abs(P.y-N.y)<.002;if(!(!E&&!R))for(let I=0;I<c.length;I++){let M=c[I].tracePath;for(let k=0;k<M.length-1;k++){let z=M[k],B=M[k+1],j=Math.abs(z.x-B.x)<.002,q=Math.abs(z.y-B.y)<.002;if(!(!j&&!q)){if(E&&j){if(Math.abs(P.x-z.x)<.002&&y(P.y,N.y,z.y,B.y)){let G=`${g}:${w}`,K=`${I}:${k}`;h.has(G)||(l.push({solvedTracePathIndex:g,traceSegmentIndex:w}),h.add(G)),m.has(K)||(u.push({solvedTracePathIndex:I,traceSegmentIndex:k}),m.add(K))}}else if(R&&q&&Math.abs(P.y-z.y)<.002&&y(P.x,N.x,z.x,B.x)){let G=`${g}:${w}`,K=`${I}:${k}`;h.has(G)||(l.push({solvedTracePathIndex:g,traceSegmentIndex:w}),h.add(G)),m.has(K)||(u.push({solvedTracePathIndex:I,traceSegmentIndex:k}),m.add(K))}}}}}}if(l.length>0&&u.length>0)return{overlappingTraceSegments:[{connNetId:o,pathsWithOverlap:l},{connNetId:s,pathsWithOverlap:u}]}}return null}_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 t=this.findNextOverlapIssue();if(t===null){this.solved=!0;return}let{overlappingTraceSegments:n}=t;this.activeSubSolver=new W_t({overlappingTraceSegments:n,traceNetIslands:this.traceNetIslands})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let t=Da(this.inputProblem);for(let n of Object.values(this.correctedTraceMap))t.lines.push({points:n.tracePath,strokeColor:"purple"});return t}},K_t=class{constructor(e){T(this,"chips");T(this,"spatialIndex");T(this,"spatialIndexIdToChip");this.chips=e.map(t=>({...t,bounds:aT(t),spatialIndexId:null})),this.spatialIndexIdToChip=new Map,this.spatialIndex=new rf(e.length);for(let t of this.chips)t.spatialIndexId=this.spatialIndex.add(t.bounds.minX,t.bounds.minY,t.bounds.maxX,t.bounds.maxY),this.spatialIndexIdToChip.set(t.spatialIndexId,t);this.spatialIndex.finish()}getChipsInBounds(e){return this.spatialIndex.search(e.minX,e.minY,e.maxX,e.maxY).map(n=>this.spatialIndexIdToChip.get(n))}doesOrthogonalLineIntersectChip(e,t={}){let n=t.excludeChipIds??[],[i,r]=e,{x:o,y:s}=i,{x:a,y:c}=r;return this.getChipsInBounds({minX:Math.min(o,a),minY:Math.min(s,c),maxX:Math.max(o,a),maxY:Math.max(s,c)}).filter(u=>!n.includes(u.chipId)).length>0}},J_t=.45,J$=.2;function oT(e){let{orientation:t,netLabelWidth:n}=e,i=typeof n=="number"?n:J_t;return t==="y+"||t==="y-"?{width:J$,height:i}:{width:i,height:J$}}function sT(e,t,n,i){switch(t){case"x+":return{x:e.x+n/2,y:e.y};case"x-":return{x:e.x-n/2,y:e.y};case"y+":return{x:e.x,y:e.y+i/2};case"y-":return{x:e.x,y:e.y-i/2}}}function Ap(e,t,n){return{minX:e.x-t/2,minY:e.y-n/2,maxX:e.x+t/2,maxY:e.y+n/2}}function iB(e,t,n,i=1e-9){let r=Math.abs(e.x-t.x)<i,o=Math.abs(e.y-t.y)<i;if(!r&&!o)return!1;if(r){let s=e.x;if(s<n.minX-i||s>n.maxX+i)return!1;let a=Math.min(e.y,t.y),c=Math.max(e.y,t.y);return Math.min(c,n.maxY)-Math.max(a,n.minY)>i}else{let s=e.y;if(s<n.minY-i||s>n.maxY+i)return!1;let a=Math.min(e.x,t.x),c=Math.max(e.x,t.x);return Math.min(c,n.maxX)-Math.max(a,n.minX)>i}}function rB(e,t,n,i){for(let[r,o]of Object.entries(t)){let s=o.tracePath;for(let a=0;a<s.length-1;a++)if(!(r===n&&a===i)&&iB(s[a],s[a+1],e))return{hasIntersection:!0,mspPairId:r,segIndex:a}}return{hasIntersection:!1}}function Q$(e){let t=0,n=e.tracePath;for(let i=0;i<n.length-1;i++)t+=Math.abs(n[i+1].x-n[i].x)+Math.abs(n[i+1].y-n[i].y);return t}function oB(e){let{inputProblem:t,inputTraceMap:n,globalConnNetId:i,fallbackTrace:r,mspConnectionPairIds:o}=e,s=Object.fromEntries(t.chips.map(m=>[m.chipId,m])),a=Object.values(n).filter(m=>m.globalConnNetId===i);if(o&&o.length>0){let m=new Set(o);a=a.filter(y=>y.mspConnectionPairIds.some(g=>m.has(g)))}let c=new Set;for(let m of a)c.add(m.pins[0].chipId),c.add(m.pins[1].chipId);let l=null,u=-1;for(let m of c){let g=s[m]?.pins?.length??0;g>u&&(u=g,l=m)}let h=l==null?[]:a.filter(m=>m.pins[0].chipId===l||m.pins[1].chipId===l);return h.length>0?h.reduce((m,y)=>Q$(m)>=Q$(y)?m:y):r}function Q_t(e,t){return[{x:e.x,y:e.y},{x:(e.x+t.x)/2,y:(e.y+t.y)/2},{x:t.x,y:t.y}]}function tgt(e){let{inputProblem:t,inputTraceMap:n,chipObstacleSpatialIndex:i,overlappingSameNetTraceGroup:r,availableOrientations:o,netLabelWidth:s}=e,a=r.portOnlyPinId;if(!a)return{placement:null,testedCandidates:[],error:"No portOnlyPinId provided"};let c=null,l=null;for(let I of t.chips){let A=I.pins.find(M=>M.pinId===a);if(A){c={x:A.x,y:A.y},l=A._facingDirection||sf(A,I);break}}if(!c||!l)return{placement:null,testedCandidates:[],error:`Port-only pin not found: ${a}`};let u=o.length>0?o:["x+","x-","y+","y-"],h={x:c.x,y:c.y},m=I=>I==="x+"?{x:1,y:0}:I==="x-"?{x:-1,y:0}:I==="y+"?{x:0,y:1}:{x:0,y:-1},y=[];for(let I of u){let{width:A,height:M}=oT({orientation:I,netLabelWidth:s}),k=sT(h,I,A,M),z=m(I),B=.001,j={x:k.x+z.x*B,y:k.y+z.y*B},q=Ap(j,A,M);if(i.getChipsInBounds(q).length>0){y.push({center:j,width:A,height:M,bounds:q,anchor:h,orientation:I,status:"chip-collision",hostSegIndex:-1});continue}if(rB(q,n,"",-1).hasIntersection){y.push({center:j,width:A,height:M,bounds:q,anchor:h,orientation:I,status:"trace-collision",hostSegIndex:-1});continue}return y.push({center:j,width:A,height:M,bounds:q,anchor:h,orientation:I,status:"ok",hostSegIndex:-1}),{placement:{globalConnNetId:r.globalConnNetId,dcConnNetId:void 0,netId:r.netId,mspConnectionPairIds:[],pinIds:[a],orientation:I,anchorPoint:h,width:A,height:M,center:j},testedCandidates:y}}let g=l,{width:x,height:v}=oT({orientation:g,netLabelWidth:s}),w=sT(h,g,x,v),P=m(g),N=.001,E={x:w.x+P.x*N,y:w.y+P.y*N};return{placement:{globalConnNetId:r.globalConnNetId,dcConnNetId:void 0,netId:r.netId,mspConnectionPairIds:[],pinIds:[a],orientation:g,anchorPoint:h,width:x,height:v,center:E},testedCandidates:y}}function egt(e){let t=Da(e.inputProblem),n=e.overlappingSameNetTraceGroup.globalConnNetId,i=oB({inputProblem:e.inputProblem,inputTraceMap:e.inputTraceMap,globalConnNetId:n,fallbackTrace:e.overlappingSameNetTraceGroup.overlappingTraces}),r=Ur(n,.9),o=Ur(n,.5);for(let s of Object.values(e.inputTraceMap)){let a=i?s.mspPairId===i.mspPairId:!1;t.lines.push({points:s.tracePath})}for(let s of e.testedCandidates){let a=s.status==="ok"?"rgba(0, 180, 0, 0.25)":s.status==="chip-collision"?"rgba(220, 0, 0, 0.25)":s.status==="trace-collision"?"rgba(220, 140, 0, 0.25)":"rgba(120, 120, 120, 0.15)",c=s.status==="ok"?"green":s.status==="chip-collision"?"red":s.status==="trace-collision"?"orange":"gray";t.rects.push({center:{x:(s.bounds.minX+s.bounds.maxX)/2,y:(s.bounds.minY+s.bounds.maxY)/2},width:s.width,height:s.height,fill:a,strokeColor:c}),t.points.push({x:s.anchor.x,y:s.anchor.y,color:c})}if(e.netLabelPlacement){let s=e.netLabelPlacement;t.rects.push({center:s.center,width:s.width,height:s.height,fill:"rgba(0, 128, 255, 0.35)",strokeColor:"blue"}),t.points.push({x:s.anchorPoint.x,y:s.anchorPoint.y,color:"blue"})}return t}var tB=class extends Ts{constructor(t){super();T(this,"inputProblem");T(this,"inputTraceMap");T(this,"overlappingSameNetTraceGroup");T(this,"availableOrientations");T(this,"chipObstacleSpatialIndex");T(this,"netLabelWidth");T(this,"netLabelPlacement",null);T(this,"testedCandidates",[]);this.inputProblem=t.inputProblem,this.inputTraceMap=t.inputTraceMap,this.overlappingSameNetTraceGroup=t.overlappingSameNetTraceGroup,this.availableOrientations=t.availableOrientations,this.netLabelWidth=t.netLabelWidth,this.chipObstacleSpatialIndex=t.inputProblem._chipObstacleSpatialIndex??new K_t(t.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 m=tgt({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,chipObstacleSpatialIndex:this.chipObstacleSpatialIndex,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth});if(this.testedCandidates.push(...m.testedCandidates),m.placement){this.netLabelPlacement=m.placement,this.solved=!0;return}this.failed=!0,this.error=m.error??"Could not place net label at port without collisions";return}let t=this.overlappingSameNetTraceGroup.globalConnNetId,n=oB({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,globalConnNetId:t,fallbackTrace:this.overlappingSameNetTraceGroup.overlappingTraces,mspConnectionPairIds:this.overlappingSameNetTraceGroup.mspConnectionPairIds});if(!n){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(m=>m.globalConnNetId===t&&(i.size===0||m.mspConnectionPairIds.some(y=>i.has(y)))),o=this.availableOrientations.length===1?[n,...r.filter(m=>m.mspPairId!==n.mspPairId)]:[n],s=this.availableOrientations.length>0?this.availableOrientations:["x+","x-","y+","y-"],a=this.availableOrientations.length===1,c=(m,y)=>{switch(m){case"y+":return y.y;case"y-":return-y.y;case"x+":return y.x;case"x-":return-y.x}},l=null,u=-1/0,h=1e-6;for(let m of o){let y=m.tracePath.slice();for(let g=0;g<y.length-1;g++){let x=y[g],v=y[g+1],w=Math.abs(x.y-v.y)<h,P=Math.abs(x.x-v.x)<h;if(!w&&!P)continue;let N=w?["y+","y-"]:["x+","x-"],E=s.filter(I=>N.includes(I));if(E.length===0)continue;let R=Q_t(x,v);for(let I of R)for(let A of E){let{width:M,height:k}=oT({orientation:A,netLabelWidth:this.netLabelWidth}),z=sT(I,A,M,k),B=A==="x+"?{x:1,y:0}:A==="x-"?{x:-1,y:0}:A==="y+"?{x:0,y:1}:{x:0,y:-1},j=1e-4,q={x:z.x+B.x*j,y:z.y+B.y*j},G=Ap(q,M,k);if(this.chipObstacleSpatialIndex.getChipsInBounds(G).length>0){this.testedCandidates.push({center:q,width:M,height:k,bounds:G,anchor:I,orientation:A,status:"chip-collision",hostSegIndex:g});continue}if(rB(G,this.inputTraceMap,m.mspPairId,g).hasIntersection){this.testedCandidates.push({center:q,width:M,height:k,bounds:G,anchor:I,orientation:A,status:"trace-collision",hostSegIndex:g});continue}if(this.testedCandidates.push({center:q,width:M,height:k,bounds:G,anchor:I,orientation:A,status:"ok",hostSegIndex:g}),a){let J=c(A,I);J>u+1e-9&&(u=J,l={anchor:I,orientation:A,width:M,height:k,center:z,hostSegIndex:g,dcConnNetId:m.dcConnNetId,mspPairId:m.mspPairId,pinIds:[m.pins[0].pinId,m.pins[1].pinId]});continue}this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:m.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[m.mspPairId],pinIds:[m.pins[0].pinId,m.pins[1].pinId],orientation:A,anchorPoint:I,width:M,height:k,center:z},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 egt(this)}},sB=class extends Ts{constructor(t){super();T(this,"inputProblem");T(this,"inputTraceMap");T(this,"overlappingSameNetTraceGroups");T(this,"queuedOverlappingSameNetTraceGroups");T(this,"netLabelPlacements",[]);T(this,"currentGroup",null);T(this,"triedAnyOrientationFallbackForCurrentGroup",!1);this.inputProblem=t.inputProblem,this.inputTraceMap=t.inputTraceMap,this.overlappingSameNetTraceGroups=this.computeOverlappingSameNetTraceGroups(),this.queuedOverlappingSameNetTraceGroups=[...this.overlappingSameNetTraceGroups]}computeOverlappingSameNetTraceGroups(){let t={};for(let c of Object.values(this.inputTraceMap)){let l=c.globalConnNetId;t[l]||(t[l]=[]),t[l].push(c)}let{netConnMap:n}=eB(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 o=[],s=this.inputProblem.chips.flatMap(c=>c.pins.map(l=>l.pinId)),a=new Set;for(let c of s){let l=n.getNetConnectedToId(c);l&&a.add(l)}for(let c of a){let u=n.getIdsConnectedToNet(c).filter(y=>i.has(y)),h={};for(let y of u)h[y]=new Set;for(let y of t[c]??[]){let g=y.pins[0].pinId,x=y.pins[1].pinId;h[g]&&h[x]&&(h[g].add(x),h[x].add(g))}let m=new Set;for(let y of u){if(m.has(y))continue;let g=[y],x=new Set;for(m.add(y);g.length>0;){let w=g.pop();x.add(w);for(let P of h[w]??[])m.has(P)||(m.add(P),g.push(P))}let v=(t[c]??[]).filter(w=>x.has(w.pins[0].pinId)&&x.has(w.pins[1].pinId));if(v.length>0){let w=A=>{let M=0,k=A.tracePath;for(let z=0;z<k.length-1;z++)M+=Math.abs(k[z+1].x-k[z].x)+Math.abs(k[z+1].y-k[z].y);return M},P=v[0],N=w(P);for(let A=1;A<v.length;A++){let M=w(v[A]);M>N&&(P=v[A],N=M)}let E=v.find(A=>A.userNetId!=null)?.userNetId;if(!E){for(let A of x)if(r[A]){E=r[A];break}}let R=Array.from(new Set(v.flatMap(A=>A.mspConnectionPairIds??[A.mspPairId]))),I={globalConnNetId:c,netId:E,overlappingTraces:P,mspConnectionPairIds:R};o.push(I)}else for(let w of x){let P=r[w];P&&o.push({globalConnNetId:c,netId:P,portOnlyPinId:w})}}}return o}_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-"],o=this.activeSubSolver.availableOrientations,s=o.length===4&&r.every(a=>o.includes(a));if(!this.triedAnyOrientationFallbackForCurrentGroup&&!s&&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 tB({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 t=this.queuedOverlappingSameNetTraceGroups.shift();if(!t){this.solved=!0;return}let n=t.netId??t.globalConnNetId;this.currentGroup=t,this.triedAnyOrientationFallbackForCurrentGroup=!1;let i=this.currentGroup.netId?this.inputProblem.netConnections.find(r=>r.netId===this.currentGroup.netId)?.netLabelWidth:void 0;this.activeSubSolver=new tB({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:t,availableOrientations:this.inputProblem.availableNetLabelOrientations[n]??["x+","x-","y+","y-"],netLabelWidth:i})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let t=Da(this.inputProblem);for(let n of Object.values(this.inputTraceMap))t.lines.push({points:n.tracePath,strokeColor:"purple"});for(let n of this.netLabelPlacements)t.rects.push({center:n.center,width:n.width,height:n.height,fill:Ur(n.globalConnNetId,.35),strokeColor:Ur(n.globalConnNetId,.9)}),t.points.push({x:n.anchorPoint.x,y:n.anchorPoint.y,color:Ur(n.globalConnNetId,.9)});return t}},ngt=(e,t)=>{let n=[];for(let i of e)for(let r of t){let o=Ap(r.center,r.width,r.height);for(let s=0;s<i.tracePath.length-1;s++){let a=i.tracePath[s],c=i.tracePath[s+1];if(iB(a,c,o)){if(i.globalConnNetId===r.globalConnNetId)break;n.push({trace:i,label:r});break}}}return n},igt=(e,t)=>{let n=o=>o.x>t.minX&&o.x<t.maxX&&o.y>t.minY&&o.y<t.maxY,i=-1,r=-1;for(let o=0;o<e.length;o++)n(e[o])&&(i===-1&&(i=o),r=o);return{firstInsideIndex:i,lastInsideIndex:r}},Fa=e=>{if(e.length<3)return e;let t=[e[0]];for(let i=1;i<e.length-1;i++){let r=t[t.length-1],o=e[i],s=e[i+1];Ps(r,o)&&Ps(o,s)||za(r,o)&&za(o,s)||t.push(o)}if(t.push(e[e.length-1]),t.length<3)return t;let n=[t[0]];for(let i=1;i<t.length-1;i++){let r=n[n.length-1],o=t[i],s=t[i+1];Ps(r,o)&&Ps(o,s)||za(r,o)&&za(o,s)||n.push(o)}return n.push(t[t.length-1]),n},rgt=({initialTrace:e,firstInsideIndex:t,lastInsideIndex:n,labelBounds:i,obstacles:r})=>{if(t<=0||n>=e.tracePath.length-1)return null;let o=e.tracePath[t-1],s=e.tracePath[n+1],a=e.tracePath.slice(0,t),c=e.tracePath.slice(n+1),l=[];if(o.x!==s.x&&o.y!==s.y)l.push([{x:s.x,y:o.y}]),l.push([{x:o.x,y:s.y}]);else if(o.x===s.x||o.y===s.y){let x=[...a,...c],v=Fa(x);if(!Qg(v,r))return{...e,tracePath:v}}for(let x=0;x<l.length;x++){let v=l[x],w=[...a,...v,...c],P=Fa(w);if(!Qg(P,r))return{...e,tracePath:P}}l.length=0;let u=.1,h=i.minX-u,m=i.maxX+u,y=i.maxY+u,g=i.minY-u;(o.x<=i.minX||s.x<=i.minX)&&o.x<i.maxX&&s.x<i.maxX&&l.push([{x:h,y:o.y},{x:h,y:s.y}]),(o.x>=i.maxX||s.x>=i.maxX)&&o.x>i.minX&&s.x>i.minX&&l.push([{x:m,y:o.y},{x:m,y:s.y}]),(o.y>=i.maxY||s.y>=i.maxY)&&o.y>i.minY&&s.y>i.minY&&l.push([{x:o.x,y},{x:s.x,y}]),(o.y<=i.minY||s.y<=i.minY)&&o.y<i.maxY&&s.y<i.maxY&&l.push([{x:o.x,y:g},{x:s.x,y:g}]);for(let x=0;x<l.length;x++){let v=l[x],w=[...a,...v,...c],P=Fa(w);if(!Qg(P,r))return{...e,tracePath:P}}return null},ogt=({initialTrace:e,label:t,labelBounds:n,obstacles:i,paddingBuffer:r,detourCount:o})=>{let s=-1;for(let m=0;m<e.tracePath.length-1;m++)if(kp(e.tracePath[m],e.tracePath[m+1],n)){s=m;break}if(s===-1)return e;let a=e.tracePath[s],c=e.tracePath[s+1];if(!a||!c)return null;let l=[],u=Ap(t.center,t.width,t.height),h=r+o*r;if(Ps(a,c)){let m=[u.maxX+h,u.minX-h];for(let y of m)l.push(c.y>a.y?[{x:a.x,y:u.minY-h},{x:y,y:u.minY-h},{x:y,y:u.maxY+h},{x:c.x,y:u.maxY+h}]:[{x:a.x,y:u.maxY+h},{x:y,y:u.maxY+h},{x:y,y:u.minY-h},{x:c.x,y:u.minY-h}])}else{let m=[u.maxY+h,u.minY-h];for(let y of m)l.push(c.x>a.x?[{x:u.minX-h,y:a.y},{x:u.minX-h,y},{x:u.maxX+h,y},{x:u.maxX+h,y:c.y}]:[{x:u.maxX+h,y:a.y},{x:u.maxX+h,y},{x:u.minX-h,y},{x:u.minX-h,y:c.y}])}for(let m of l){let y=[...e.tracePath.slice(0,s+1),...m,...e.tracePath.slice(s+1)],g=Fa(y);if(!Qg(g,i))return{...e,tracePath:g}}return null},sgt=({trace:e,label:t,problem:n,paddingBuffer:i,detourCount:r})=>{let o={...e,tracePath:Fa(e.tracePath)};if(e.globalConnNetId===t.globalConnNetId)return o;let s=tx(n),a=i,c=Ap(t.center,t.width,t.height),l={minX:c.minX-a,minY:c.minY-a,maxX:c.maxX+a,maxY:c.maxY+a,chipId:`netlabel-${t.netId}`},u=ogt({initialTrace:o,label:t,labelBounds:l,obstacles:s,paddingBuffer:i,detourCount:r});u&&(o.tracePath=u.tracePath);let{firstInsideIndex:h,lastInsideIndex:m}=igt(o.tracePath,l),y=rgt({initialTrace:o,firstInsideIndex:h,lastInsideIndex:m,labelBounds:l,obstacles:s});return y||u||o},iT=(e,t)=>{for(let n=0;n<e.length-1;n++){let i=e[n],r=e[n+1];for(let o of t)if(kp(i,r,o))return!0}return!1},rT=e=>{let t=0;for(let n=1;n<e.length-1;n++){let i=e[n-1],r=e[n],o=e[n+1],s=i.x===r.x,a=r.x===o.x;s!==a&&t++}return t},agt=({path:e,obstacles:t,labelBounds:n})=>{if(e.length<=2)return e;let i=(u,h)=>{for(let m=0;m<u.length-1;m++){let y=u[m],g=u[m+1];for(let x of h)if(kp(y,g,x))return!0}return!1},r=(u,h)=>{let m=[];return u.x===h.x||u.y===h.y?m.push([u,h]):(m.push([u,{x:h.x,y:u.y},h]),m.push([u,{x:u.x,y:h.y},h])),m},o=(u,h)=>{if(h>=u.length-3)return-1;let m=h,y=!0;for(let g=h;g<u.length-2&&g<h+10&&!(g+2>=u.length);g++){let x=u[g],v=u[g+1],w=u[g+2],P=x.x===v.x,N=v.x===w.x;if(P===N)break;let E=Math.sign(P?v.y-x.y:v.x-x.x);if(g>h){let R=u[g-1],I=R.x===x.x,A=Math.sign(I?x.y-R.y:x.x-R.x);if(P&&I&&E!==A||!P&&!I&&E!==A){y=!1;break}}m=g+2}return y&&m-h>=3?m:-1},s=[...e],a=rT(s),c=!0;for(;c;){c=!1;for(let u=0;u<s.length-3;u++){let h=o(s,u);if(h>0){let m=s[u],y=s[h],g=r(m,y);for(let x of g){let v=[...s.slice(0,u+1),...x.slice(1,-1),...s.slice(h)],w=iT(x,t),P=i(x,n);if(!w&&!P){let N=rT(v),E=h-u-1;s=v,a=N,c=!0;break}}if(c)break}}if(!c)for(let u=0;u<s.length-2;u++){let h=Math.min(s.length-u-2,s.length-2);for(let m=1;m<=h;m++){let y=u+m+1;if(y>=s.length)continue;let g=s[u],x=s[y],v=r(g,x);for(let w of v){let P=[...s.slice(0,u+1),...w.slice(1,-1),...s.slice(y)],N=w,E=iT(N,t),R=i(N,n);if(!E&&!R){let I=rT(P);if(I<a||I===a&&P.length<s.length){s=P,a=I,c=!0;break}}}if(c)break}if(c)break}if(!c)for(let u=0;u<s.length-2;u++){let h=s[u],m=s[u+1],y=s[u+2],g=h.x===m.x&&m.x===y.x,x=h.y===m.y&&m.y===y.y;if(g||x){let v=[...s.slice(0,u+1),...s.slice(u+2)],w=iT([h,y],t),P=i([h,y],n);if(!w&&!P){s=v,c=!0;break}}}}return Fa(s)},cgt=({traces:e,problem:t,allLabelPlacements:n,mergedLabelNetIdMap:i,paddingBuffer:r})=>{let o=!1,s=tx(t),a=e.map(c=>{let l=c.tracePath,h=n.filter(y=>{let g=i.get(y.globalConnNetId);return g?!g.has(c.globalConnNetId):y.globalConnNetId!==c.globalConnNetId}).map(y=>({minX:y.center.x-y.width/2-r,maxX:y.center.x+y.width/2+r,minY:y.center.y-y.height/2-r,maxY:y.center.y+y.height/2+r})),m=agt({path:l,obstacles:s,labelBounds:h});return(m.length!==l.length||m.some((y,g)=>y.x!==l[g].x||y.y!==l[g].y))&&(o=!0),{...c,tracePath:m}});return o?a:null},lgt=({traces:e,problem:t,allLabelPlacements:n})=>{let r=!1;for(let l of e)if(l.tracePath.length===4){let[u,h,m,y]=l.tracePath,g=u.y===h.y&&h.x===m.x&&m.y===y.y,x=u.x===h.x&&h.y===m.y&&m.x===y.x,v=u.y===h.y&&h.y===m.y&&m.y===y.y,w=u.x===h.x&&h.x===m.x&&m.x===y.x,P=v||w,N=!1;if(g?N=Math.sign(h.x-u.x)===Math.sign(y.x-m.x):x&&(N=Math.sign(h.y-u.y)===Math.sign(y.y-m.y)),!((g||x)&&!P&&N))return null}let o=tx(t).map(l=>({...l,minX:l.minX+1e-5,maxX:l.maxX-1e-5,minY:l.minY+1e-5,maxY:l.maxY-1e-5})),s=(l,u,h)=>{for(let m of h)if(kp(l,u,m))return!0;return!1},a=(l,u)=>l.filter(m=>m.globalConnNetId!==u).map(m=>({minX:m.center.x-m.width/2+1e-5,maxX:m.center.x+m.width/2-1e-5,minY:m.center.y-m.height/2+1e-5,maxY:m.center.y+m.height/2-1e-5})),c=e.map(l=>{let u=[...l.tracePath];if(u.length<4)return{...l};let h=a(n,l.globalConnNetId);if(u.length===4){let[y,g,x,v]=u,w,P;if(y.y===g.y&&g.x===x.x&&x.y===v.y){let R=(y.x+v.x)/2;w={x:R,y:g.y},P={x:R,y:x.y}}else{let R=(y.y+v.y)/2;w={x:g.x,y:R},P={x:x.x,y:R}}return s(y,w,o)||s(w,P,o)||s(P,v,o)||s(y,w,h)||s(w,P,h)||s(P,v,h)||(u[1]=w,u[2]=P,r=!0),{...l,tracePath:Fa(u)}}for(let y=1;y<u.length-4;y++){let g=u[y],x=u[y+1],v=u[y+2],w=u[y+3],P=g.y===x.y&&x.x===v.x&&v.y===w.y,N=g.x===x.x&&x.y===v.y&&v.x===w.x,E=g.y===x.y&&x.y===v.y&&v.y===w.y,R=g.x===x.x&&x.x===v.x&&v.x===w.x,I=E||R,A=!1;if(P?A=Math.sign(x.x-g.x)===Math.sign(w.x-v.x):N&&(A=Math.sign(x.y-g.y)===Math.sign(w.y-v.y)),!((P||N)&&!I&&A))continue;let k,z,B=Math.abs(P?g.x-x.x:g.y-x.y),j=Math.abs(P?v.x-w.x:v.y-w.y);if(Math.abs(B-j)<.001)continue;if(P){let G=(g.x+w.x)/2;k={x:G,y:x.y},z={x:G,y:v.y}}else{let G=(g.y+w.y)/2;k={x:x.x,y:G},z={x:v.x,y:G}}s(g,k,o)||s(k,z,o)||s(z,w,o)||s(g,k,h)||s(k,z,h)||s(z,w,h)||(u[y+1]=k,u[y+2]=z,r=!0,y=0)}let m=Fa(u);return{...l,tracePath:m}});return r?c:null},ugt=class extends Ts{constructor(t){super();T(this,"problem");T(this,"traces");T(this,"netTempLabelPlacements");T(this,"netLabelPlacements");T(this,"updatedTraces");T(this,"updatedTracesMap");T(this,"mergedLabelNetIdMap");T(this,"detourCountByLabel");T(this,"PADDING_BUFFER",.1);this.problem=t.inputProblem,this.traces=t.traces,this.updatedTraces=[...t.traces],this.updatedTracesMap=new Map,this.mergedLabelNetIdMap=new Map,this.detourCountByLabel=new Map;let n=t.netLabelPlacements;if(this.netLabelPlacements=n,!n||n.length===0){this.netTempLabelPlacements=[];return}let i=new Map;for(let o of n){if(o.pinIds.length===0)continue;let s=o.pinIds[0].split(".")[0];if(!s)continue;let a=`${s}-${o.orientation}`;i.has(a)||i.set(a,[]),i.get(a).push(o)}let r=[];for(let[o,s]of i.entries()){if(s.length<=1){r.push(...s);continue}let a=1/0,c=1/0,l=-1/0,u=-1/0;for(let v of s){let w=Ap(v.center,v.width,v.height);a=Math.min(a,w.minX),c=Math.min(c,w.minY),l=Math.max(l,w.maxX),u=Math.max(u,w.maxY)}let h=l-a,m=u-c,y=s[0],g=`merged-group-${o}`,x=new Set(s.map(v=>v.globalConnNetId));this.mergedLabelNetIdMap.set(g,x),r.push({...y,globalConnNetId:g,width:h,height:m,center:{x:a+h/2,y:c+m/2},pinIds:[...new Set(s.flatMap(v=>v.pinIds))],mspConnectionPairIds:[...new Set(s.flatMap(v=>v.mspConnectionPairIds))]})}this.netTempLabelPlacements=r}_step(){if(!this.traces||this.traces.length===0||!this.netTempLabelPlacements||this.netTempLabelPlacements.length===0){this.solved=!0;return}this.detourCountByLabel.clear();let t=ngt(this.traces,this.netTempLabelPlacements);if(t.length===0){this.solved=!0;return}let n=t.filter(c=>{let l=this.mergedLabelNetIdMap.get(c.label.globalConnNetId);return l?!l.has(c.trace.globalConnNetId):c.trace.globalConnNetId!==c.label.globalConnNetId});if(n.length===0){this.solved=!0;return}let i=new Map;for(let c of this.traces)i.set(c.mspPairId,c);let r=new Set;for(let c of n){if(r.has(c.trace.mspPairId))continue;let l=i.get(c.trace.mspPairId),u=c.label.globalConnNetId,h=this.detourCountByLabel.get(u)||0,m=sgt({trace:l,label:c.label,problem:this.problem,paddingBuffer:this.PADDING_BUFFER,detourCount:h});m.tracePath!==l.tracePath&&this.detourCountByLabel.set(u,h+1),i.set(l.mspPairId,m),r.add(l.mspPairId)}this.updatedTraces=Array.from(i.values());let o=cgt({traces:this.updatedTraces,problem:this.problem,allLabelPlacements:this.netTempLabelPlacements,mergedLabelNetIdMap:this.mergedLabelNetIdMap,paddingBuffer:this.PADDING_BUFFER});o&&(this.updatedTraces=o);let s=lgt({traces:this.updatedTraces,problem:this.problem,allLabelPlacements:this.netLabelPlacements});s&&(this.updatedTraces=s),this.updatedTracesMap.clear();for(let c of this.updatedTraces)this.updatedTracesMap.set(c.mspPairId,c);let a=new sB({inputProblem:this.problem,inputTraceMap:Object.fromEntries(this.updatedTracesMap)});a.solve(),this.netLabelPlacements=a.netLabelPlacements,this.solved=!0}getOutput(){return{traceMap:this.updatedTracesMap,netLabelPlacements:this.netLabelPlacements}}visualize(){let t=Da(this.problem);t.lines||(t.lines=[]),t.circles||(t.circles=[]),t.texts||(t.texts=[]),t.rects||(t.rects=[]);for(let n of Object.values(this.updatedTraces))t.lines.push({points:n.tracePath,strokeColor:"purple"});for(let n of this.netLabelPlacements)t.rects.push({center:n.center,width:n.width,height:n.height,fill:Ur(n.globalConnNetId,.35)}),t.points.push({x:n.anchorPoint.x,y:n.anchorPoint.y,color:Ur(n.globalConnNetId,.9)});return t}},pgt=e=>{for(let t of e.chips){let n=aT(t);for(let i of t.pins){if(!(i.x>n.minX&&i.x<n.maxX&&i.y>n.minY&&i.y<n.maxY))continue;let o=i.x-n.minX,s=n.maxX-i.x,a=i.y-n.minY,c=n.maxY-i.y,l=Math.min(o,s,a,c);l===o?i.x=n.minX:l===s?i.x=n.maxX:l===a?i.y=n.minY:i.y=n.maxY,i._facingDirection=void 0}}},hgt=e=>{for(let t of e.chips){let n=t.width/2,i=t.height/2,r=0,o=0;for(let c of t.pins){let l=Math.abs(c.x-t.center.x),u=Math.abs(c.y-t.center.y);l>r&&(r=l),u>o&&(o=u)}let s=Math.max(n,r),a=Math.max(i,o);if(s>n||a>i){t.width=s*2,t.height=a*2;for(let c of t.pins)c._facingDirection=void 0}}};function of(e,t,n,i={}){return{solverName:e,solverClass:t,getConstructorParams:n,onSolved:i.onSolved}}var aB=class extends Ts{constructor(t){super();T(this,"mspConnectionPairSolver");T(this,"schematicTraceLinesSolver");T(this,"traceOverlapShiftSolver");T(this,"netLabelPlacementSolver");T(this,"traceLabelOverlapAvoidanceSolver");T(this,"startTimeOfPhase");T(this,"endTimeOfPhase");T(this,"timeSpentOnPhase");T(this,"firstIterationOfPhase");T(this,"inputProblem");T(this,"pipelineDef",[of("mspConnectionPairSolver",$_t,()=>[{inputProblem:this.inputProblem}],{onSolved:t=>{}}),of("schematicTraceLinesSolver",U_t,()=>[{mspConnectionPairs:this.mspConnectionPairSolver.mspConnectionPairs,dcConnMap:this.mspConnectionPairSolver.dcConnMap,globalConnMap:this.mspConnectionPairSolver.globalConnMap,inputProblem:this.inputProblem,chipMap:this.mspConnectionPairSolver.chipMap}],{onSolved:t=>{}}),of("traceOverlapShiftSolver",Z_t,()=>[{inputProblem:this.inputProblem,inputTracePaths:this.schematicTraceLinesSolver.solvedTracePaths,globalConnMap:this.mspConnectionPairSolver.globalConnMap}],{onSolved:t=>{}}),of("netLabelPlacementSolver",sB,()=>[{inputProblem:this.inputProblem,inputTraceMap:this.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(this.schematicTraceLinesSolver.solvedTracePaths.map(t=>[t.mspPairId,t]))}],{onSolved:t=>{}}),of("traceLabelOverlapAvoidanceSolver",ugt,t=>{let n=t.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(t.schematicTraceLinesSolver.solvedTracePaths.map(o=>[o.mspPairId,o])),i=Object.values(n),r=t.netLabelPlacementSolver.netLabelPlacements;return[{inputProblem:t.inputProblem,traces:i,netLabelPlacements:r}]},{onSolved:t=>{if(t.traceLabelOverlapAvoidanceSolver&&t.netLabelPlacementSolver){let{netLabelPlacements:n}=t.traceLabelOverlapAvoidanceSolver.getOutput();t.netLabelPlacementSolver.netLabelPlacements=n}}})]);T(this,"currentPipelineStepIndex",0);this.inputProblem=this.cloneAndCorrectInputProblem(t),this.MAX_ITERATIONS=1e6,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={},this.firstIterationOfPhase={}}getConstructorParams(){return this.inputProblem}cloneAndCorrectInputProblem(t){let n=structuredClone({...t,_chipObstacleSpatialIndex:void 0});return hgt(n),pgt(n),n}_step(){let t=this.pipelineDef[this.currentPipelineStepIndex];if(!t){this.solved=!0;return}if(this.activeSubSolver){this.activeSubSolver.step(),this.activeSubSolver.solved?(this.endTimeOfPhase[t.solverName]=performance.now(),this.timeSpentOnPhase[t.solverName]=this.endTimeOfPhase[t.solverName]-this.startTimeOfPhase[t.solverName],t.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++):this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let n=t.getConstructorParams(this);this.activeSubSolver=new t.solverClass(...n),this[t.solverName]=this.activeSubSolver,this.timeSpentOnPhase[t.solverName]=0,this.startTimeOfPhase[t.solverName]=performance.now(),this.firstIterationOfPhase[t.solverName]=this.iterations}solveUntilPhase(t){for(;this.getCurrentPhase().toLowerCase()!==t.toLowerCase();)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let t=[Da(this.inputProblem),...this.pipelineDef.map(n=>this[n.solverName]?.visualize()).filter(Boolean).map((n,i)=>{for(let r of n.rects??[])r.step=i;for(let r of n.points??[])r.step=i;for(let r of n.circles??[])r.step=i;for(let r of n.texts??[])r.step=i;for(let r of n.lines??[])r.step=i;return n})];return t.length===1?t[0]:{points:t.flatMap(n=>n.points||[]),rects:t.flatMap(n=>n.rects||[]),lines:t.flatMap(n=>n.lines||[]),circles:t.flatMap(n=>n.circles||[]),texts:t.flatMap(n=>n.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}};var Vj=Zt(Nn(),1);var Hj=Zt(Nn(),1);var Gj=Zt(Nn(),1);ji();Be();ji();Be();Be();St();Be();Be();To();Be();ji();Be();function cB(e,t,n,i){return Math.sqrt((n-e)**2+(i-t)**2)}var dgt=e=>{let t=e.filter(o=>o.type==="pcb_port"),n=e.filter(o=>o.type==="pcb_smtpad"),i=e.filter(o=>o.type==="pcb_trace");function r(o,s={}){let a=s.traceWidth||0,c=t.find(l=>cB(l.x,l.y,o.x,o.y)<.01);if(c)return c.pcb_port_id;if(s.isFirstOrLastPoint){let l=n.find(u=>{if(u.shape==="rect")return Math.abs(o.x-u.x)<u.width/2+a/2&&Math.abs(o.y-u.y)<u.height/2+a/2;if(u.shape==="circle")return cB(o.x,o.y,u.x,u.y)<u.radius});if(l)return l.pcb_port_id??null}return null}for(let o of i)for(let s=0;s<o.route.length;s++){let a=o.route[s],c=s===0||s===o.route.length-1;if(a.route_type==="wire"){if(!a.start_pcb_port_id&&s===0){let l=r(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.start_pcb_port_id=l)}if(!a.end_pcb_port_id&&s===o.route.length-1){let l=r(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.end_pcb_port_id=l)}}}};function uB(e){dgt(e);let t=e.filter(s=>s.type==="source_trace"),n=e.filter(s=>s.type==="pcb_port"),i=[],r=ir(e),o=new Map;for(let s of n)o.set(s.source_port_id,s);for(let s of t){let a=s.connected_source_port_ids;if(a.length<2)continue;let c=[],l=[];for(let g of a){let x=o.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=>e.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),pcb_port_not_connected_error_id:`pcb_port_not_connected_error_trace_${s.source_trace_id}`})}return i}var fgt=class{constructor({objects:e,getBounds:t,getId:n,CELL_SIZE:i}){T(this,"buckets");T(this,"objectsById");T(this,"getBounds");T(this,"getId");T(this,"CELL_SIZE",.4);T(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=t,this.getId=n??(()=>this._getNextId()),this.CELL_SIZE=i??this.CELL_SIZE;for(let r of e)this.addObject(r)}_getNextId(){return`${this._idCounter++}`}addObject(e){let t=this.getBounds(e),n=this.getId(e),i={...e,spatialIndexId:n};this.objectsById.set(n,i);let r=Math.floor(t.minX/this.CELL_SIZE),o=Math.floor(t.minY/this.CELL_SIZE),s=Math.floor(t.maxX/this.CELL_SIZE),a=Math.floor(t.maxY/this.CELL_SIZE);for(let c=r;c<=s;c++)for(let l=o;l<=a;l++){let u=`${c}x${l}`,h=this.buckets.get(u);h?h.push(i):this.buckets.set(u,[i])}}removeObject(e){let t=this.objectsById.get(e);if(!t)return!1;this.objectsById.delete(e);let n=this.getBounds(t),i=Math.floor(n.minX/this.CELL_SIZE),r=Math.floor(n.minY/this.CELL_SIZE),o=Math.floor(n.maxX/this.CELL_SIZE),s=Math.floor(n.maxY/this.CELL_SIZE);for(let a=i;a<=o;a++)for(let c=r;c<=s;c++){let l=`${a}x${c}`,u=this.buckets.get(l);if(u){let h=u.findIndex(m=>m.spatialIndexId===e);h!==-1&&(u.splice(h,1),u.length===0&&this.buckets.delete(l))}}return!0}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getObjectsInBounds(e,t=0){let n=[],i=new Set,r=Math.floor((e.minX-t)/this.CELL_SIZE),o=Math.floor((e.minY-t)/this.CELL_SIZE),s=Math.floor((e.maxX+t)/this.CELL_SIZE),a=Math.floor((e.maxY+t)/this.CELL_SIZE);for(let c=r;c<=s;c++)for(let l=o;l<=a;l++){let u=`${c}x${l}`,h=this.buckets.get(u)||[];for(let m of h){let y=m.spatialIndexId;i.has(y)||(i.add(y),n.push(m))}}return n}},af=e=>e.type==="pcb_trace_segment"?{minX:Math.min(e.x1,e.x2),minY:Math.min(e.y1,e.y2),maxX:Math.max(e.x1,e.x2),maxY:Math.max(e.y1,e.y2)}:rz([e]),lT=.1,mgt=.15;var uT=.005;function ygt(e){let t=new Set;for(let n of e.route)n.route_type==="wire"&&(n.start_pcb_port_id&&t.add(n.start_pcb_port_id),n.end_pcb_port_id&&t.add(n.end_pcb_port_id));return Array.from(t)}function pT(e){let t=new Set;for(let n of e)for(let i of ygt(n))t.add(i);return Array.from(t)}var _gt=(e,t)=>{let n={x:e.x1,y:e.y1},i={x:e.x2,y:e.y2},r={x:t.x1,y:t.y1},o={x:t.x2,y:t.y2},s={x:i.x-n.x,y:i.y-n.y},a={x:o.x-r.x,y:o.y-r.y},c=s.x*s.x+s.y*s.y,l=a.x*a.x+a.y*a.y;if(c===0||l===0){if(c===0&&l===0)return{x:(n.x+r.x)/2,y:(n.y+r.y)/2};if(c===0){let B=zo(((n.x-r.x)*a.x+(n.y-r.y)*a.y)/l,0,1),j={x:r.x+B*a.x,y:r.y+B*a.y};return{x:(n.x+j.x)/2,y:(n.y+j.y)/2}}let k=zo(((r.x-n.x)*s.x+(r.y-n.y)*s.y)/c,0,1),z={x:n.x+k*s.x,y:n.y+k*s.y};return{x:(z.x+r.x)/2,y:(z.y+r.y)/2}}let u={x:n.x-r.x,y:n.y-r.y},h=s.x*s.x+s.y*s.y,m=s.x*a.x+s.y*a.y,y=s.x*u.x+s.y*u.y,g=a.x*a.x+a.y*a.y,x=a.x*u.x+a.y*u.y,v=h*g-m*m;if(v<1e-10)return ggt(n,i,r,o,s,a,c,l);let w=(m*x-g*y)/v,P=(h*x-m*y)/v;w=zo(w,0,1),P=zo(P,0,1),P=(w*m+x)/g,P=zo(P,0,1),w=(P*m-y)/h,w=zo(w,0,1);let N={x:n.x+w*s.x,y:n.y+w*s.y},E={x:r.x+P*a.x,y:r.y+P*a.y},R=N.x-E.x,I=N.y-E.y,A=Math.sqrt(R*R+I*I);return{x:(N.x+E.x)/2,y:(N.y+E.y)/2}},ggt=(e,t,n,i,r,o,s,a)=>{let c=((n.x-e.x)*r.x+(n.y-e.y)*r.y)/s;c=zo(c,0,1);let l={x:e.x+c*r.x,y:e.y+c*r.y},u=((i.x-e.x)*r.x+(i.y-e.y)*r.y)/s;u=zo(u,0,1);let h={x:e.x+u*r.x,y:e.y+u*r.y},m=((e.x-n.x)*o.x+(e.y-n.y)*o.y)/a;m=zo(m,0,1);let y={x:n.x+m*o.x,y:n.y+m*o.y},g=((t.x-n.x)*o.x+(t.y-n.y)*o.y)/a;g=zo(g,0,1);let x={x:n.x+g*o.x,y:n.y+g*o.y},w=[{pointA:l,pointB:n,distance:Math.sqrt((l.x-n.x)**2+(l.y-n.y)**2)},{pointA:h,pointB:i,distance:Math.sqrt((h.x-i.x)**2+(h.y-i.y)**2)},{pointA:e,pointB:y,distance:Math.sqrt((e.x-y.x)**2+(e.y-y.y)**2)},{pointA:t,pointB:x,distance:Math.sqrt((t.x-x.x)**2+(t.y-x.y)**2)}].reduce((P,N)=>N.distance<P.distance?N:P);return{x:(w.pointA.x+w.pointB.x)/2,y:(w.pointA.y+w.pointB.y)/2}},zo=(e,t,n)=>Math.max(t,Math.min(n,e)),xgt=e=>{if(e.type==="pcb_via"||e.type==="pcb_plated_hole"&&e.shape==="circle")return e.outer_diameter/2;if(e.type==="pcb_hole"&&e.hole_shape==="circle")return e.hole_diameter/2;if(e.type==="pcb_smtpad"&&e.shape==="circle")return e.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(e)}`)},lB=(e,t)=>{let n={x:e.x1,y:e.y1},i={x:e.x2,y:e.y2},r=t.minX,o=t.minY,s=t.maxX,a=t.maxY;if(n.x===i.x&&n.y===i.y){let M=Math.max(r,Math.min(s,n.x)),k=Math.max(o,Math.min(a,n.y));return M===n.x&&k===n.y?{x:n.x,y:n.y}:{x:M,y:k}}let c=i.x-n.x,l=i.y-n.y,u=c!==0?(r-n.x)/c:Number.NEGATIVE_INFINITY,h=c!==0?(s-n.x)/c:Number.POSITIVE_INFINITY,m=l!==0?(o-n.y)/l:Number.NEGATIVE_INFINITY,y=l!==0?(a-n.y)/l:Number.POSITIVE_INFINITY,g=Math.max(Math.min(u,h),Math.min(m,y)),x=Math.min(Math.max(u,h),Math.max(m,y));if(g<=x&&x>=0&&g<=1){let M=Math.max(0,Math.min(1,g));return{x:n.x+M*c,y:n.y+M*l}}let v={x:Math.max(r,Math.min(s,n.x)),y:Math.max(o,Math.min(a,n.y))},w={x:Math.max(r,Math.min(s,i.x)),y:Math.max(o,Math.min(a,i.y))},P=(v.x-n.x)**2+(v.y-n.y)**2,N=(w.x-i.x)**2+(w.y-i.y)**2,E=[{start:{x:r,y:o},end:{x:s,y:o}},{start:{x:s,y:o},end:{x:s,y:a}},{start:{x:s,y:a},end:{x:r,y:a}},{start:{x:r,y:a},end:{x:r,y:o}}],R=Math.min(P,N),I=P<=N?v:w,A=(M,k,z)=>Math.max(k,Math.min(z,M));for(let M of E){let k={x:i.x-n.x,y:i.y-n.y},z={x:M.end.x-M.start.x,y:M.end.y-M.start.y},B={x:n.x-M.start.x,y:n.y-M.start.y},j=k.x*k.x+k.y*k.y,q=k.x*z.x+k.y*z.y,G=k.x*B.x+k.y*B.y,K=z.x*z.x+z.y*z.y,tt=z.x*B.x+z.y*B.y,J=j*K-q*q;if(Math.abs(J)<1e-10)continue;let bt=(q*tt-K*G)/J,ct=(j*tt-q*G)/J;bt=A(bt,0,1),ct=A(ct,0,1);let rt={x:n.x+bt*k.x,y:n.y+bt*k.y},it={x:M.start.x+ct*z.x,y:M.start.y+ct*z.y},wt=rt.x-it.x,yt=rt.y-it.y,Mt=wt*wt+yt*yt;Mt<R&&(R=Mt,I={x:(rt.x+it.x)/2,y:(rt.y+it.y)/2})}return I};function bgt(e){return e.type==="pcb_trace_segment"?[e.layer]:e.type==="pcb_smtpad"?[e.layer]:e.type==="pcb_plated_hole"?Array.isArray(e.layers)?e.layers:[...Ru]:e.type==="pcb_hole"?[...Ru]:e.type==="pcb_via"?Array.isArray(e.layers)?e.layers:[...Ru]:e.type==="pcb_keepout"?Array.isArray(e.layers)?e.layers:[]:[]}function pB(e,{connMap:t}={}){let n=[];t??(t=ir(e));let r=mn(e).pcb_trace.list().flatMap(g=>{let x=[];for(let v=0;v<g.route.length-1;v++){let w=g.route[v],P=g.route[v+1];w.route_type==="wire"&&P.route_type==="wire"&&w.layer===P.layer&&x.push({type:"pcb_trace_segment",pcb_trace_id:g.pcb_trace_id,_pcbTrace:g,thickness:"width"in w?w.width:"width"in P?P.width:mgt,layer:w.layer,x1:w.x,y1:w.y,x2:P.x,y2:P.y})}return x}),o=mn(e).pcb_smtpad.list(),s=mn(e).pcb_plated_hole.list(),a=mn(e).pcb_hole.list(),c=mn(e).pcb_via.list(),l=mn(e).pcb_keepout.list(),u=[...r,...o,...s,...a,...c,...l],h=new fgt({objects:u,getBounds:af}),m=g=>el(e,g),y=new Set;for(let g of r){let x=lT,v=af(g),w=h.getObjectsInBounds(v,x+g.thickness/2);if(!(g.x1===g.x2&&g.y1===g.y2))for(let P of w){if(!bgt(P).includes(g.layer))continue;if(P.type==="pcb_trace_segment"){let I=P;if(g.layer!==I.layer||t.areIdsConnected(g.pcb_trace_id,I.pcb_trace_id))continue;let A=V_({x:g.x1,y:g.y1},{x:g.x2,y:g.y2},{x:I.x1,y:I.y1},{x:I.x2,y:I.y2})-g.thickness/2-I.thickness/2;if(A>lT-uT)continue;let M=`overlap_${g.pcb_trace_id}_${I.pcb_trace_id}`,k=`overlap_${I.pcb_trace_id}_${g.pcb_trace_id}`;if(y.has(M)||y.has(k))continue;y.add(M),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${m(g.pcb_trace_id)} overlaps with ${m(I.pcb_trace_id)} ${A<0?"(accidental contact)":`(gap: ${A.toFixed(3)}mm)`}`,pcb_trace_id:g.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:M,pcb_component_ids:[],center:_gt(g,I),pcb_port_ids:pT([g._pcbTrace,I._pcbTrace])});continue}let N=q_(P);if(t.areIdsConnected(g.pcb_trace_id,"pcb_trace_id"in P?P.pcb_trace_id:N))continue;if(P.type==="pcb_via"||P.type==="pcb_plated_hole"&&P.shape==="circle"||P.type==="pcb_hole"||P.type==="pcb_smtpad"&&P.shape==="circle"){let I=xgt(P),M=H_({x:g.x1,y:g.y1},{x:g.x2,y:g.y2},{x:P.x,y:P.y,radius:I})-g.thickness/2;if(M>lT-uT)continue;let k=`overlap_${g.pcb_trace_id}_${N}`;if(y.has(k))continue;y.add(k),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${m(g.pcb_trace_id)} overlaps with ${P.type} "${m(q_(P))}" ${M<0?"(accidental contact)":`(gap: ${M.toFixed(3)}mm)`}`,pcb_trace_id:g.pcb_trace_id,center:lB(g,af(P)),source_trace_id:"",pcb_trace_error_id:k,pcb_component_ids:["pcb_component_id"in P?P.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...pT([g._pcbTrace]),"pcb_port_id"in P?P.pcb_port_id:void 0].filter(Boolean)})}let R=_d({x:g.x1,y:g.y1},{x:g.x2,y:g.y2},af(P))-g.thickness/2;if(R+uT<x){let I=`overlap_${g.pcb_trace_id}_${N}`;if(y.has(I))continue;y.add(I),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${m(g.pcb_trace_id)} overlaps with ${P.type} "${m(q_(P))}" ${R<0?"(accidental contact)":`(gap: ${R.toFixed(3)}mm)`}`,pcb_trace_id:g.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:I,pcb_component_ids:["pcb_component_id"in P?P.pcb_component_id:void 0].filter(Boolean),center:lB(g,af(P)),pcb_port_ids:[...pT([g._pcbTrace]),"pcb_port_id"in P?P.pcb_port_id:void 0].filter(Boolean)})}}}return n}function hB(e){return e.area()>=0}function dB({center:e,size:t,rotationDeg:n=0}){let i=e.x,r=e.y,o=t.width/2,s=t.height/2,a=[new Lo(i-o,r-s),new Lo(i+o,r-s),new Lo(i+o,r+s),new Lo(i-o,r+s)],c=new tf(a);if(n){let l=M_(n,i,r),u=a.map(h=>{let m=cn(l,{x:h.x,y:h.y});return new Lo(m.x,m.y)});c=new tf(u)}return hB(c)||c.reverse(),c}function vgt({board:e}){if(e.outline&&e.outline.length>0){let t=e.outline.map(i=>new Lo(i.x,i.y)),n=new tf(t);return hB(n)||n.reverse(),n}return e.center&&typeof e.width=="number"&&typeof e.height=="number"?dB({center:e.center,size:{width:e.width,height:e.height},rotationDeg:0}):null}function wgt({circuitJson:e,component:t}){if(t.source_component_id){let n=e.find(i=>i.type==="source_component"&&i.source_component_id===t.source_component_id);if(n&&"name"in n&&n.name)return n.name}return el(e,t.pcb_component_id)||"Unknown"}function Sgt(e,t,n,i,r,o){let s=new Lo(n.x,n.y);if(!t.contains(s)){let x=t.distanceTo(s);return Array.isArray(x)?x[0]:Number(x)||0}let a=i/2,c=r/2,l=[{x:n.x-a,y:n.y-c},{x:n.x+a,y:n.y-c},{x:n.x+a,y:n.y+c},{x:n.x-a,y:n.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=M_(o,n.x,n.y),m=x=>{let v=cn(h,x);return new Lo(v.x,v.y)},y=l.concat(u).map(m),g=0;for(let x of y)if(!t.contains(x)){let v=t.distanceTo(x),w=Array.isArray(v)?v[0]:Number(v)||0;w>g&&(g=w)}if(g>0)return g;try{let x=j4.intersect(e,t),v=0;x?Array.isArray(x)?v=x.reduce((P,N)=>P+(typeof N.area=="function"?N.area():0),0):typeof x.area=="function"?v=x.area():v=0:v=0;let w=e.area();if(v>0&&v<w){let P=1-v/w,N=Math.abs(i),E=Math.abs(r);return Math.min(N,E)*P}else return .1}catch{return .1}}function fB(e){let t=e.find(o=>o.type==="pcb_board");if(!t)return[];let n=vgt({board:t});if(!n)return[];let i=e.filter(o=>o.type==="pcb_component");if(i.length===0)return[];let r=[];for(let o of i){if(!o.center||typeof o.width!="number"||typeof o.height!="number"||o.width<=0||o.height<=0)continue;let s=dB({center:o.center,size:{width:o.width,height:o.height},rotationDeg:o.rotation||0});if(s.area()===0||n.contains(s))continue;let c=Sgt(s,n,o.center,o.width,o.height,o.rotation||0),l=wgt({circuitJson:e,component:o}),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_${o.pcb_component_id}`,message:`Component ${l} (${o.pcb_component_id}) extends outside board boundaries by ${u}mm`,pcb_component_id:o.pcb_component_id,pcb_board_id:t.pcb_board_id,component_center:o.center,component_bounds:{min_x:s.box.xmin,max_x:s.box.xmax,min_y:s.box.ymin,max_y:s.box.ymax},subcircuit_id:o.subcircuit_id,source_component_id:o.source_component_id})}return r}var hT=[{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 Un(e){if(e==null)return"";if(e===0)return"0";let t=Math.abs(e),n=hT.find(o=>{let s=t/o.value;return s>=1&&s<1e3})||hT[hT.length-1],r=(e/n.value).toPrecision(3);return r.includes(".")&&!/\.0+$/.test(r)&&(r=r.replace(/0+$/,"")),r=r.replace(/\.0+$/,""),`${r}${n.symbol}`}St();W();ji();ds();Be();var FY=Zt(io(),1);var zT=Zt(Nn(),1),jp=Zt(io(),1),yHt=Zt(io(),1);var xl=Zt(ml(),1);var DY=Zt(ml(),1),$Y=Zt(ml(),1);var BY=Zt(ml(),1);var jY=Zt(ml(),1);var YY=Zt(ml(),1),XY=Zt(io(),1);var Kxt=Object.defineProperty,Jxt=(e,t)=>{for(var n in t)Kxt(e,n,{get:t[n],enumerable:!0})},wj={};Jxt(wj,{Battery:()=>gY,Board:()=>Uj,Breakout:()=>uY,BreakoutPoint:()=>pY,CadAssembly:()=>Lj,CadModel:()=>Oj,Capacitor:()=>Zj,Chip:()=>Sx,Constraint:()=>sY,CopperPour:()=>_Y,Crystal:()=>PY,Cutout:()=>xf,Diode:()=>Jj,FabricationNotePath:()=>aY,FabricationNoteText:()=>cY,Footprint:()=>Rj,Fuse:()=>Qj,Group:()=>Vp,Hole:()=>XT,Inductor:()=>vY,Jumper:()=>tY,Keepout:()=>yx,Led:()=>nY,Mosfet:()=>IY,Net:()=>$T,NetLabel:()=>hY,NormalComponent:()=>Pn,PcbTrace:()=>YT,PinHeader:()=>xY,Pinout:()=>Kj,PlatedHole:()=>Yp,Port:()=>Mi,Potentiometer:()=>wY,PowerSource:()=>iY,PrimitiveComponent:()=>Ne,PushButton:()=>SY,Renderable:()=>FT,Resistor:()=>oY,Resonator:()=>bY,SchematicBox:()=>NY,SchematicCell:()=>LY,SchematicLine:()=>kY,SchematicRect:()=>AY,SchematicRow:()=>OY,SchematicTable:()=>RY,SchematicText:()=>CY,SilkscreenCircle:()=>dY,SilkscreenLine:()=>mY,SilkscreenPath:()=>jT,SilkscreenRect:()=>fY,SilkscreenText:()=>vx,SmtPad:()=>mx,SolderJumper:()=>eY,Subcircuit:()=>lY,Switch:()=>MY,Symbol:()=>zY,TestPoint:()=>EY,Trace:()=>uo,TraceHint:()=>GT,Transistor:()=>TY,Via:()=>yY,VoltageSource:()=>rY});var Qxt=(0,Tj.default)("tscircuit:renderable"),Es=["ReactSubtreesRender","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"],tbt={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"]},ebt=0,FT=class{constructor(e){T(this,"renderPhaseStates");T(this,"shouldBeRemoved",!1);T(this,"children");T(this,"isPcbPrimitive",!1);T(this,"isSchematicPrimitive",!1);T(this,"_renderId");T(this,"_currentRenderPhase",null);T(this,"_asyncEffects",[]);T(this,"parent",null);this._renderId=`${ebt++}`,this.children=[],this.renderPhaseStates={};for(let t of Es)this.renderPhaseStates[t]={initialized:!1,dirty:!1}}_markDirty(e){this.renderPhaseStates[e].dirty=!0;let t=Es.indexOf(e);for(let n=t+1;n<Es.length;n++)this.renderPhaseStates[Es[n]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(e)}_queueAsyncEffect(e,t){let n={promise:t(),phase:this._currentRenderPhase,effectName:e,complete:!1};this._asyncEffects.push(n),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:e,componentDisplayName:this.getString(),phase:n.phase}),n.promise.then(()=>{n.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:n.phase})}).catch(i=>{console.error(`Async effect error in ${n.phase} "${e}":
226
226
  ${i.stack}`),n.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:n.phase,error:i.toString()})})}_emitRenderLifecycleEvent(e,t){Qxt(`${e}:${t} ${this.getString()}`);let n=`renderable:renderLifecycle:${e}:${t}`,i={renderId:this._renderId,componentDisplayName:this.getString(),type:n};"root"in this&&this.root&&(this.root.emit(n,i),this.root.emit("renderable:renderLifecycle:anyEvent",{...i,type:n}))}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())}}runRenderCycle(){for(let e of Es)this.runRenderPhaseForChildren(e),this.runRenderPhase(e)}runRenderPhase(e){this._currentRenderPhase=e;let t=this.renderPhaseStates[e],n=t.initialized,i=t.dirty;if(!n&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&n){this._emitRenderLifecycleEvent(e,"start"),this?.[`remove${e}`]?.(),t.initialized=!1,t.dirty=!1,this._emitRenderLifecycleEvent(e,"end");return}let r=Es.indexOf(e)-1;if(r>=0){let s=Es[r];if(this._asyncEffects.filter(c=>c.phase===s).some(c=>!c.complete))return}let o=tbt[e]||[];for(let s of o)if(this._hasIncompleteAsyncEffectsInSubtreeForPhase(s))return;if(this._emitRenderLifecycleEvent(e,"start"),n){i&&(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))}},fx={},Ij=e=>{let t=Object.fromEntries(Object.entries(e).map(([n,i])=>[n.toLowerCase(),i]));Object.assign(fx,e),Object.assign(fx,t)},nbt=class extends Error{constructor(e,t,n){let i,r=Object.keys(n).filter(c=>c!=="_errors"),o=[],s=t.pinLabels;if(s)for(let[c,l]of Object.entries(s)){let u=Array.isArray(l)?l:[l];for(let h of u)typeof h=="string"&&(h.startsWith(" ")||h.endsWith(" "))&&o.push(`pinLabels.${c} ("${h}" has leading or trailing spaces)`)}let a=r.map(c=>c==="pinLabels"&&o.length>0?o.join(", "):n[c]._errors[0]?`${c} (${n[c]._errors[0]})`:`${c} (${JSON.stringify(n[c])})`).join(", ");"name"in t?i=`Invalid props for ${e} "${t.name}": ${a}`:"footprint"in t&&typeof t.footprint=="string"?i=`Invalid props for ${e} (unnamed ${t.footprint} component): ${a}`:i=`Invalid props for ${e} (unnamed): ${a}`,super(i),this.componentName=e,this.originalProps=t,this.formattedError=n}};function wT(e,t){let n=t.match(/^#(\w+)/);if(n)return e.props.id===n[1];let i=t.match(/^\.(\w+)/);if(i)return e.isMatchingNameOrAlias(i[1]);let[r,...o]=t.split(/(?=[#.[])/);return r==="pin"&&(r="port"),r&&r!=="*"&&e.lowercaseComponentName!==r.toLowerCase()?!1:o.every(s=>{if(s.startsWith("#"))return e.props.id===s.slice(1);if(s.startsWith("."))return e.isMatchingNameOrAlias(s.slice(1));let a=s.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!a)return!0;let[,c,l]=a;return e.props[c].toString()===l})}var DT={isTag:e=>!0,getParent:e=>e.parent,getChildren:e=>e.children,getName:e=>e.lowercaseComponentName,getAttributeValue:(e,t)=>{if(t==="class"&&"getNameAndAliases"in e)return e.getNameAndAliases().join(" ");if(t==="name"&&e._parsedProps?.name)return e._parsedProps.name;if(e._parsedProps&&t in e._parsedProps){let i=e._parsedProps[t];return typeof i=="string"?i:i!=null?String(i):null}if(t in e){let i=e[t];return typeof i=="string"?i:i!=null?String(i):null}let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e){let r=e[i];return typeof r=="string"?r:r!=null?String(r):null}}return null},hasAttrib:(e,t)=>{if(t==="class")return!!e._parsedProps?.name;if(e._parsedProps&&t in e._parsedProps||t in e)return!0;let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e)return!0}return!1},getSiblings:e=>e.parent?e.parent.children:[],prevElementSibling:e=>{if(!e.parent)return null;let t=e.parent.children,n=t.indexOf(e);return n>0?t[n-1]:null},getText:()=>"",removeSubsets:e=>e.filter((t,n)=>!e.some((i,r)=>n!==r&&i!==t&&i.getDescendants().includes(t))),existsOne:(e,t)=>t.some(e),findAll:(e,t)=>{let n=[],i=r=>{e(r)&&n.push(r);for(let o of r.children)i(o)};for(let r of t)i(r);return n},findOne:(e,t)=>{for(let n of t){if(e(n))return n;let i=n.children;if(i.length>0){let r=DT.findOne(e,i);if(r)return r}}return null},equals:(e,t)=>e._renderId===t._renderId,isHovered:e=>!1,isVisited:e=>!1,isActive:e=>!1},ibt={...DT,getChildren:e=>e.children.filter(t=>!t.isSubcircuit)},QB={...DT,getChildren:e=>e.children.filter(t=>t.isSubcircuit)},tj=e=>{if(/net\.[^\s>]*\./.test(e))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(e))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(e)){let t=e.match(/net\.([^ >]+)/),n=t?t[1]:"";throw new Error(`Net name "${n}" cannot start with a number, try using a prefix like "VBUS1"`)}return e.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,n,i,r)=>{let o=/^\d+$/.test(r)?`pin${r}`:r;return`${n}.${i} > .${o}`}).trim()},ST={adapter:ibt,cacheResults:!0},Ne=class extends FT{constructor(t){super(t);T(this,"parent",null);T(this,"children");T(this,"childrenPendingRemoval");T(this,"props");T(this,"_parsedProps");T(this,"externallyAddedAliases");T(this,"isPrimitiveContainer",!1);T(this,"canHaveTextChildren",!1);T(this,"source_group_id",null);T(this,"source_component_id",null);T(this,"schematic_component_id",null);T(this,"pcb_component_id",null);T(this,"cad_component_id",null);T(this,"fallbackUnassignedName");T(this,"_cachedSelectAllQueries",new Map);T(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=t??{},this.externallyAddedAliases=[];let i=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(t??{});if(i.success)this._parsedProps=i.data;else throw new nbt(this.lowercaseComponentName,this.props,i.error.format())}get config(){return{componentName:"",zodProps:p.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(t){let n=this;for(;n;){if(n._parsedProps&&t in n._parsedProps)return n._parsedProps[t];n=n.parent}if(this.root?.platform&&t in this.root.platform)return this.root.platform[t]}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(t){let n=this.config.zodProps.parse({...this.props,...t}),i=this.props;this.props=n,this._parsedProps=this.config.zodProps.parse(t),this.onPropsChange({oldProps:i,newProps:n,changedProps:Object.keys(t)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation:t}=this.props;return typeof t=="string"?parseFloat(t):t??null}computePcbPropsTransform(){let{_parsedProps:t}=this,n=this._getPcbRotationBeforeLayout()??0;return Hn(dn(t.pcbX??0,t.pcbY??0),ma(n*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let t=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(t&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let n=this._getPcbRotationBeforeLayout()??0;return Hn(this.parent?._computePcbGlobalTransformBeforeLayout()??xi(),Hn(dn(t.x,t.y),ma(n*Math.PI/180)))}if(this.isPcbPrimitive){let n=this.getPrimitiveContainer();if(n&&n._parsedProps.layer==="bottom")return Hn(this.parent?._computePcbGlobalTransformBeforeLayout()??xi(),cN(),this.computePcbPropsTransform())}return Hn(this.parent?._computePcbGlobalTransformBeforeLayout()??xi(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let t=this.getPrimitiveContainer(),n=t?t._parsedProps.layer==="bottom":!1;return{isFlipped:n,maybeFlipLayer:r=>n?r==="top"?"bottom":"top":r}}_setPositionFromLayout(t){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:t}=this;return Hn(dn(t.schX??0,t.schY??0))}computeSchematicGlobalTransform(){let t=this._getSchematicGlobalManualPlacementTransform(this);return t||Hn(this.parent?.computeSchematicGlobalTransform?.()??xi(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:t}=this,n=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=t.schOrientation!==void 0?i[t.schOrientation]:t.schRotation;if(r===void 0&&(r=0),r=r%360,r<0&&(r+=360),t.schRotation!==void 0&&r%90!==0)throw new Error(`Schematic rotation ${t.schRotation} is not supported for ${this.componentName}`);let o=`${n}_horz`,s=`${n}_vert`,a=`${n}_up`,c=`${n}_down`,l=`${n}_left`,u=`${n}_right`;if(u in Gn&&r===0)return u;if(a in Gn&&r===90)return a;if(l in Gn&&r===180)return l;if(c in Gn&&r===270)return c;if(o in Gn&&(r===0||r===180))return o;if(s in Gn&&(r===90||r===270))return s;if(n in Gn)return n}_getSchematicSymbolNameOrThrow(){let t=this._getSchematicSymbolName();if(!t)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return t}getSchematicSymbol(){let t=this._getSchematicSymbolName();return t?Gn[t]??null:null}_getPcbManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n?.pcb_placements;if(!i)return null;for(let r of i)if(wT(t,r.selector)||t.props.name===r.selector)return En(this._computePcbGlobalTransformBeforeLayout(),r.center);return null}_getSchematicManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n.schematic_placements;if(!i)return null;for(let r of i)if(wT(t,r.selector)||t.props.name===r.selector)return En(this.computeSchematicGlobalTransform(),r.center);return null}_getSchematicGlobalManualPlacementTransform(t){let n=this.getSubcircuit()?._parsedProps.manualEdits;if(!n)return null;for(let i of n.schematic_placements??[])if((wT(t,i.selector)||t.props.name===i.selector)&&i.relative_to==="group_center")return Hn(this.parent?._computePcbGlobalTransformBeforeLayout()??xi(),dn(i.center.x,i.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return En(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return En(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(t){this.parent=t}onPropsChange(t){}onChildChanged(t){this.parent?.onChildChanged?.(t)}add(t){let n=t.__text;if(typeof n=="string"){if(this.canHaveTextChildren||n.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${n}"`)}if(Object.keys(t).length!==0){if(this.lowercaseComponentName==="board"&&t.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(!t.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(t)}"`);t.onAddToParent(this),t.parent=this,this.children.push(t)}}addAll(t){for(let n of t)this.add(n)}remove(t){this.children=this.children.filter(n=>n!==t),this.childrenPendingRemoval.push(t),t.shouldBeRemoved=!0}getSubcircuitSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?n:`${this.parent.getSubcircuitSelector()} > ${n}`}getFullPathSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName,i=this.parent?.getFullPathSelector?.();return i?`${i} > ${n}`:n}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(t){return this.getNameAndAliases().includes(t)}isMatchingAnyOf(t){return this.getNameAndAliases().some(n=>t.map(i=>i.toString()).includes(n))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(t){let n=[this.componentName,this.lowercaseComponentName],i=[this.name].filter(Boolean),r=t.trim().split(/\> /)[0],o=r[0];return r.length>1?!1:!!(t==="*"||t[0]==="#"&&t.slice(1)===this.props.id||t[0]==="."&&i.includes(t.slice(1))||/^[a-zA-Z0-9_]/.test(o)&&n.includes(o))}getSubcircuit(){if(this.isSubcircuit)return this;let t=this.parent?.getSubcircuit?.();if(!t)throw new Error("Component is not inside an opaque group (no board?)");return t}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 t=this.selectAll("port");for(let n of t){let i=n.parent?.getNameAndAliases(),r=n.getNameAndAliases();if(i)for(let o of i)for(let s of r){let a=[`.${o} > .${s}`,`.${o} .${s}`];for(let c of a){let l=this._cachedSelectAllQueries.get(c);l?l.push(n):this._cachedSelectAllQueries.set(c,[n])}}}for(let[n,i]of this._cachedSelectAllQueries.entries())i.length===1&&this._cachedSelectOneQueries.set(n,i[0])}selectAll(t){if(this._cachedSelectAllQueries.has(t))return this._cachedSelectAllQueries.get(t);let n=tj(t),i=BP(n,this,ST);if(i.length>0)return this._cachedSelectAllQueries.set(t,i),i;let[r,...o]=n.split(" "),s=T_(r,this,{adapter:QB});if(!s)return[];let a=s.selectAll(o.join(" "));return this._cachedSelectAllQueries.set(t,a),a}selectOne(t,n){if(this._cachedSelectOneQueries.has(t))return this._cachedSelectOneQueries.get(t);let i=tj(t);n?.port&&(n.type="port");let r=null;if(n?.type&&(r=BP(i,this,ST).find(l=>l.lowercaseComponentName===n.type)),r??(r=T_(i,this,ST)),r)return this._cachedSelectOneQueries.set(t,r),r;let[o,...s]=i.split(" "),a=T_(o,this,{adapter:QB});return a?(r=a.selectOne(s.join(" "),n),this._cachedSelectOneQueries.set(t,r),r):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:t}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[t(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?this.root?._getBoard()?.allLayers??["top","bottom"]:[]}return[]}getDescendants(){let t=[];for(let n of this.children)t.push(n),t.push(...n.getDescendants());return t}getSelectableDescendants(){let t=[];for(let n of this.children)n.isSubcircuit?t.push(n):(t.push(n),t.push(...n.getSelectableDescendants()));return t}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this;return{schWidth:t.schWidth,schHeight:t.schHeight}}renderError(t){if(typeof t=="string")return super.renderError(t);this.root?.db.pcb_placement_error.insert(t)}getString(){let{lowercaseComponentName:t,_parsedProps:n,parent:i}=this;return n?.pinNumber!==void 0&&i?.props?.name&&n?.name?`<${t}#${this._renderId}(pin:${n.pinNumber} .${i?.props.name}>.${n.name}) />`:i?.props?.name&&n?.name?`<${t}#${this._renderId}(.${i?.props.name}>.${n?.name}) />`:n?.from&&n?.to?`<${t}#${this._renderId}(from:${n.from} to:${n?.to}) />`:n?.name?`<${t}#${this._renderId} name=".${n?.name}" />`:n?.portHints?`<${t}#${this._renderId}(${n.portHints.map(r=>`.${r}`).join(", ")}) />`:`<${t}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},rbt=class extends Ne{constructor(e,t){super(e),this._parsedProps={...e,error:t,type:e.type||"unknown",component_name:e.name,error_type:"source_failed_to_create_component_error",message:t instanceof Error?t.message:String(t),pcbX:e.pcbX,pcbY:e.pcbY,schX:e.schX,schY:e.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:p.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let e=this._getGlobalPcbPositionBeforeLayout(),t=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:e,schematic_center:t})}}};function obt(e,t){return new rbt(e,t)}function sbt(e,t){let n=e;return n.__tsci={...t},e}var abt={supportsMutation:!0,createInstance(e,t){let n=fx[e];if(!n)throw Object.keys(fx).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 "${e}". 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 sbt(new n(t),{})}catch(i){return obt({...t,componentType:e},i)}},createTextInstance(e){return{__text:e}},appendInitialChild(e,t){e.add(t)},appendChild(e,t){e.add(t)},appendChildToContainer(e,t){e.add(t)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(e){return e},preparePortalMount(e){throw new Error("Function not implemented.")},scheduleTimeout(e,t){throw new Error("Function not implemented.")},cancelTimeout(e){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(e){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(e,t)=>{throw new Error("Function not implemented.")},getInstanceFromScope:e=>{throw new Error("Function not implemented.")},detachDeletedInstance:e=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>px.DefaultEventPriority,getCurrentUpdatePriority:()=>px.DefaultEventPriority,resolveUpdatePriority:()=>px.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},cx=(0,Pj.default)(abt),Mj=e=>{let t={children:[],props:{name:"$root"},add(o){o.parent=this,this.children.push(o)},computePcbGlobalTransform(){return xi()}},n=[],i=cx.createContainer(t,0,null,!1,null,"tsci",o=>{console.log("Error in createContainer"),console.error(o),n.push(o)},null);if(cx.updateContainerSync(e,i,null,()=>{}),cx.flushSyncWork(),n.length>0)throw n[0];let r=cx.getPublicRootInstance(i);return r||t.children[0]},bf=(e,t)=>{if(typeof e=="number")return e;if(e.startsWith("pin"))return Number(e.slice(3));if(!t)throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`);for(let n in t)if((Array.isArray(t[n])?t[n]:[t[n]]).includes(e))return Number(n.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`)},cbt=(e,t)=>{if(!e)return;let n={},i={};for(let[r,o]of Object.entries(e)){let s=bf(r,t);i[s]={...i[s],...o}}for(let[r,o]of Object.entries(i)){let s=`pin${r}`;n[s]={bottom_margin:o.bottomMargin,left_margin:o.leftMargin,right_margin:o.rightMargin,top_margin:o.topMargin}}return n},lbt=e=>{if(e){if("leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e)return{left_side:e.leftSide,right_side:e.rightSide,top_side:e.topSide,bottom_side:e.bottomSide};if("leftPinCount"in e||"rightPinCount"in e||"topPinCount"in e||"bottomPinCount"in e)return{left_size:e.leftPinCount,right_size:e.rightPinCount,top_size:e.topPinCount,bottom_size:e.bottomPinCount};if("leftSize"in e||"rightSize"in e||"topSize"in e||"bottomSize"in e)return{left_size:e.leftSize,right_size:e.rightSize,top_size:e.topSize,bottom_size:e.bottomSize}}};function Ej(e){let t=[];for(let n=0;n<e.length-1;n++)t.push([e[n],e[n+1]]);return t}var ubt=p.object({name:p.string().refine(e=>!/[+-]/.test(e),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),$T=class extends Ne{constructor(){super(...arguments);T(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:ubt}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=n.name.startsWith("GND"),r=n.name.startsWith("V"),o=t.source_net.insert({name:n.name,member_source_group_ids:[],is_ground:i,is_power:r,is_positive_voltage_source:r});this.source_net_id=o.source_net_id}doInitialSourceParentAttachment(){let t=this.getSubcircuit();if(!t)return;let{db:n}=this.root;n.source_net.update(this.source_net_id,{subcircuit_id:t.subcircuit_id})}getAllConnectedPorts(){let t=this.getSubcircuit().selectAll("port"),n=[];for(let i of t){let r=i._getDirectlyConnectedTraces();for(let o of r)if(o._isExplicitlyConnectedToNet(this)){n.push(i);break}}return n}_getAllDirectlyConnectedTraces(){let t=this.getSubcircuit().selectAll("trace"),n=[];for(let i of t)i._isExplicitlyConnectedToNet(this)&&n.push(i);return n}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getAllDirectlyConnectedTraces().filter(s=>(s._portsRoutedOnPcb?.length??0)>0),r=[];for(let s of i){let a=s._portsRoutedOnPcb,c=r.find(l=>a.some(u=>l.ports.includes(u)));if(!c){r.push({ports:[...a],traces:[s]});continue}c.traces.push(s),c.ports.push(...a)}if(r.length===0)return;let o=Ej(r);for(let[s,a]of o){let c=s.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),l=a.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),u=1/0,h=[-1,-1];for(let w=0;w<c.length;w++){let P=c[w];for(let N=0;N<l.length;N++){let E=l[N],R=Math.sqrt((P.x-E.x)**2+(P.y-E.y)**2);R<u&&(u=R,h=[w,N])}}let m=s.ports[h[0]],y=a.ports[h[1]],g=t.toArray().filter(w=>w.type==="pcb_smtpad"||w.type==="pcb_trace"||w.type==="pcb_plated_hole"||w.type==="pcb_hole"||w.type==="source_port"||w.type==="pcb_port"),{solution:x}=EO(g.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[m.source_port_id,y.source_port_id]}])),v=x[0];if(!v){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[m.pcb_component_id,y.pcb_component_id].filter(Boolean),pcb_port_ids:[m.pcb_port_id,y.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}t.pcb_trace.insert(v)}}renderError(t){if(typeof t=="string")return super.renderError(t);this.root?.db.pcb_trace_error.insert(t)}},BT=(e,t)=>{for(let n of t)if(typeof n=="string"&&n.startsWith("net.")){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('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(n)){let r=n.split("net.")[1];throw new Error(`Net name "${r}" cannot start with a number, try using a prefix like "VBUS1"`)}let i=e.getSubcircuit();if(!i.selectOne(n)){let r=new $T({name:n.split("net.")[1]});i.add(r)}}},mx=class extends Ne{constructor(){super(...arguments);T(this,"pcb_smtpad_id",null);T(this,"matchedPort",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:KO}}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="polygon"){let n=t.points,i=n.map(l=>l.x),r=n.map(l=>l.y),o=Math.min(...i),s=Math.max(...i),a=Math.min(...r),c=Math.max(...r);return{width:s-o,height:c-a}}if(t.shape==="pill")return{width:t.width,height:t.height};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this;if(!n.portHints)return;let i=this.getPrimitiveContainer(),r=this.getSubcircuit(),o=this._getGlobalPcbPositionBeforeLayout(),s=i?._getGlobalPcbPositionBeforeLayout(),a=A1(this._computePcbGlobalTransformBeforeLayout()),c=Math.abs(a.rotation.angle*(180/Math.PI)-90)%180<.01,{maybeFlipLayer:l}=this._getPcbPrimitiveFlippedHelpers(),u=i?._parsedProps.pcbRotation??0,h=null,m=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;n.shape==="circle"?(h=t.pcb_smtpad.insert({pcb_component_id:m,pcb_port_id:this.matchedPort?.pcb_port_id,layer:l(n.layer??"top"),shape:"circle",radius:n.radius,port_hints:n.portHints.map(y=>y.toString()),is_covered_with_solder_mask:n.coveredWithSolderMask??!1,x:o.x,y:o.y,subcircuit_id:r?.subcircuit_id??void 0}),t.pcb_solder_paste.insert({layer:h.layer,shape:"circle",radius:h.radius*.7,x:h.x,y:h.y,pcb_component_id:h.pcb_component_id,pcb_smtpad_id:h.pcb_smtpad_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):n.shape==="rect"?(h=u===0||c?t.pcb_smtpad.insert({pcb_component_id:m,pcb_port_id:this.matchedPort?.pcb_port_id,layer:l(n.layer??"top"),shape:"rect",width:c?n.height:n.width,height:c?n.width:n.height,port_hints:n.portHints.map(y=>y.toString()),is_covered_with_solder_mask:n.coveredWithSolderMask??!1,x:o.x,y:o.y,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):t.pcb_smtpad.insert({pcb_component_id:m,layer:l(n.layer??"top"),shape:"rotated_rect",width:n.width,height:n.height,x:o.x,y:o.y,ccw_rotation:u,port_hints:n.portHints.map(y=>y.toString()),is_covered_with_solder_mask:n.coveredWithSolderMask??!1,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),h.shape==="rect"&&t.pcb_solder_paste.insert({layer:l(n.layer??"top"),shape:"rect",width:h.width*.7,height:h.height*.7,x:h.x,y:h.y,pcb_component_id:h.pcb_component_id,pcb_smtpad_id:h.pcb_smtpad_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),h.shape==="rotated_rect"&&t.pcb_solder_paste.insert({layer:l(n.layer??"top"),shape:"rotated_rect",width:h.width*.7,height:h.height*.7,x:h.x,y:h.y,ccw_rotation:u,pcb_component_id:h.pcb_component_id,pcb_smtpad_id:h.pcb_smtpad_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):n.shape==="polygon"?h=t.pcb_smtpad.insert({pcb_component_id:m,pcb_port_id:this.matchedPort?.pcb_port_id,layer:l(n.layer??"top"),shape:"polygon",points:n.points.map(y=>({x:y.x+o.x,y:y.y+o.y})),port_hints:n.portHints.map(y=>y.toString()),is_covered_with_solder_mask:n.coveredWithSolderMask??!1,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):n.shape==="pill"&&(h=t.pcb_smtpad.insert({pcb_component_id:m,pcb_port_id:this.matchedPort?.pcb_port_id,layer:l(n.layer??"top"),shape:"pill",x:o.x,y:o.y,radius:n.radius,height:n.height,width:n.width,port_hints:n.portHints.map(y=>y.toString()),is_covered_with_solder_mask:n.coveredWithSolderMask??!1,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})),h&&(this.pcb_smtpad_id=h.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_smtpad.get(this.pcb_smtpad_id);if(n.shape==="rect")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.width/2,top:n.y+n.height/2,right:n.x+n.width/2,bottom:n.y-n.height/2},width:n.width,height:n.height};if(n.shape==="rotated_rect"){let i=n.ccw_rotation*Math.PI/180,r=Math.cos(i),o=Math.sin(i),s=n.width/2,a=n.height/2,c=Math.abs(s*r)+Math.abs(a*o),l=Math.abs(s*o)+Math.abs(a*r);return{center:{x:n.x,y:n.y},bounds:{left:n.x-c,right:n.x+c,top:n.y-l,bottom:n.y+l},width:c*2,height:l*2}}if(n.shape==="circle")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.radius,top:n.y-n.radius,right:n.x+n.radius,bottom:n.y+n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){let i=n.points,r=i.map(u=>u.x),o=i.map(u=>u.y),s=Math.min(...r),a=Math.max(...r),c=Math.min(...o),l=Math.max(...o);return{center:{x:(s+a)/2,y:(c+l)/2},bounds:{left:s,top:l,right:a,bottom:c},width:a-s,height:l-c}}if(n.shape==="pill"){let i=n.width/2,r=n.height/2;return{center:{x:n.x,y:n.y},bounds:{left:n.x-i,top:n.y-r,right:n.x+i,bottom:n.y+r},width:n.width,height:n.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${n.shape}"`)}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_smtpad.update(this.pcb_smtpad_id,{x:t.x,y:t.y});let i=n.pcb_solder_paste.list().find(r=>r.pcb_smtpad_id===this.pcb_smtpad_id);n.pcb_solder_paste.update(i?.pcb_solder_paste_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}},jT=class extends Ne{constructor(){super(...arguments);T(this,"pcb_silkscreen_path_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:NL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_path.insert({pcb_component_id:a,layer:r,route:n.route.map(l=>{let u=En(o,{x:l.x,y:l.y});return{...l,x:u.x,y:u.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:s?.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(t){let{db:n}=this.root,{_parsedProps:i}=this,r=n.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!r)return;let o=0,s=0;for(let u of r.route)o+=u.x,s+=u.y;o/=r.route.length,s/=r.route.length;let a=t.x-o,c=t.y-s,l=r.route.map(u=>({...u,x:u.x+a,y:u.y+c}));n.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:l})}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-r}}},pbt=p.object({route:p.array(f1),source_trace_id:p.string().optional()}),YT=class extends Ne{constructor(){super(...arguments);T(this,"pcb_trace_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:pbt}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),r=this.getSubcircuit(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),s=this._computePcbGlobalTransformBeforeLayout(),a=n.route.map(l=>{let{x:u,y:h,...m}=l,y=En(s,{x:u,y:h});return l.route_type==="wire"&&l.layer?{...y,...m,layer:o(l.layer)}:{...y,...m}}),c=t.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:n.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:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y),s.route_type==="wire"&&(n=Math.min(n,s.x-s.width/2),i=Math.max(i,s.x+s.width/2),r=Math.min(r,s.y-s.width/2),o=Math.max(o,s.y+s.width/2));return n===1/0||i===-1/0||r===1/0||o===-1/0?{width:0,height:0}:{width:i-n,height:o-r}}},Yp=class extends Ne{constructor(){super(...arguments);T(this,"pcb_plated_hole_id",null);T(this,"matchedPort",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:jO}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.outerDiameter,height:t.outerDiameter};if(t.shape==="oval"||t.shape==="pill")return{width:t.outerWidth,height:t.outerHeight};if(t.shape==="circular_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};if(t.shape==="pill_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_plated_hole.get(this.pcb_plated_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y+i.height/2,right:n.x+i.width/2,bottom:n.y-i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,o=this.getSubcircuit();if(n.shape==="circle"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:n.outerDiameter,hole_diameter:n.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="pill"&&n.rectPad){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.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"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:n.pcbRotation??0,rect_ccw_rotation:n.pcbRotation??0,rect_pad_width:n.outerWidth,rect_pad_height:n.outerHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill"||n.shape==="oval"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:n.shape,port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:n.pcbRotation??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="circular_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:n.holeDiameter,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,rect_border_radius:n.rectBorderRadius??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:n.holeWidth,hole_height:n.holeHeight,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},yx=class extends Ne{constructor(){super(...arguments);T(this,"pcb_keepout_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:xL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let t=this.getSubcircuit(),{db:n}=this.root,{_parsedProps:i}=this,r=this._getGlobalPcbPositionBeforeLayout(),o=A1(this._computePcbGlobalTransformBeforeLayout()),s=Math.abs(o.rotation.angle*(180/Math.PI)-90)%180<.01,a=null;i.shape==="circle"?a=n.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:r.x,y:r.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0}):i.shape==="rect"&&(a=n.pcb_keepout.insert({layers:["top"],shape:"rect",...s?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:r.x,y:r.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0})),a&&(this.pcb_keepout_id=a.pcb_keepout_id)}},XT=class extends Ne{constructor(){super(...arguments);T(this,"pcb_hole_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:JO}}getPcbSize(){let{_parsedProps:t}=this,n=t.shape==="pill";return{width:n?t.width:t.diameter,height:n?t.height:t.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this._getGlobalPcbPositionBeforeLayout(),o=t.pcb_hole.insert({hole_shape:"circle",hole_diameter:n.diameter,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=o.pcb_hole_id}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_hole.get(this.pcb_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_hole.update(this.pcb_hole_id,{x:t.x,y:t.y})}},vx=class extends Ne{constructor(){super(...arguments);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:AL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),r=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),s=this.getSubcircuit(),a=new Set(n.layers);n.layer&&a.add(n.layer);let c=a.size>0?Array.from(a):["top"];for(let l of c)t.pcb_silkscreen_text.insert({anchor_alignment:n.anchorAlignment,anchor_position:{x:r.x,y:r.y},font:n.font??"tscircuit2024",font_size:n.fontSize??1,layer:o(l),text:n.text??"",ccw_rotation:n.pcbRotation,pcb_component_id:i.pcb_component_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:t}=this,n=t.fontSize??1,r=(t.text??"").length*n,o=n;return{width:r*n,height:o*n}}},xf=class extends Ne{constructor(){super(...arguments);T(this,"pcb_cutout_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:ZO}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this.getGroup()?.pcb_group_id??void 0,o=this._getGlobalPcbPositionBeforeLayout(),a=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,c;if(n.shape==="rect"){let l=typeof a=="string"?parseInt(a.replace("deg",""),10):a,u=Math.abs(l%180)===90,h={shape:"rect",center:o,width:u?n.height:n.width,height:u?n.width:n.height,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(h)}else if(n.shape==="circle"){let l={shape:"circle",center:o,radius:n.radius,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(l)}else if(n.shape==="polygon"){let l=this._computePcbGlobalTransformBeforeLayout(),h={shape:"polygon",points:n.points.map(m=>En(l,m)),subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(h)}c&&(this.pcb_cutout_id=c.pcb_cutout_id)}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){if(t.points.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.points)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-r}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_cutout.get(this.pcb_cutout_id);if(!n)return super._getPcbCircuitJsonBounds();if(n.shape==="rect")return{center:n.center,bounds:{left:n.center.x-n.width/2,top:n.center.y+n.height/2,right:n.center.x+n.width/2,bottom:n.center.y-n.height/2},width:n.width,height:n.height};if(n.shape==="circle")return{center:n.center,bounds:{left:n.center.x-n.radius,top:n.center.y+n.radius,right:n.center.x+n.radius,bottom:n.center.y-n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){if(n.points.length===0)return super._getPcbCircuitJsonBounds();let i=1/0,r=-1/0,o=1/0,s=-1/0;for(let a of n.points)i=Math.min(i,a.x),r=Math.max(r,a.x),o=Math.min(o,a.y),s=Math.max(s,a.y);return{center:{x:(i+r)/2,y:(o+s)/2},bounds:{left:i,top:s,right:r,bottom:o},width:r-i,height:s-o}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(t){if(!this.pcb_cutout_id)return;let{db:n}=this.root,i=n.pcb_cutout.get(this.pcb_cutout_id);if(i){if(i.shape==="rect"||i.shape==="circle")n.pcb_cutout.update(this.pcb_cutout_id,{...i,center:t});else if(i.shape==="polygon"){let r=this._getPcbCircuitJsonBounds().center,o=t.x-r.x,s=t.y-r.y,a=i.points.map(c=>({x:c.x+o,y:c.y+s}));n.pcb_cutout.update(this.pcb_cutout_id,{...i,points:a})}}}},hbt=({elm:e,pinLabels:t,layer:n,readableRotation:i,anchorAlignment:r})=>{let o=e.text.replace(/[{}]/g,"").toLowerCase(),s=o;if(Array.isArray(t)){let a=parseInt(o.replace(/[^\d]/g,""),10)-1;s=String(t[a]??o)}else typeof t=="object"&&(s=String(t[o]??o));return new vx({anchorAlignment:r||"center",text:s??o,layer:n||"top",fontSize:e.font_size+.2,pcbX:isNaN(e.anchor_position.x)?0:e.anchor_position.x,pcbY:e.anchor_position.y,pcbRotation:i??0})},dbt=(e,t)=>((-parseInt(e||"0",10)+(t??0))%360+360)%360,hx=({componentName:e,componentRotation:t,footprint:n,pinLabels:i,pcbPinLabels:r},o)=>{let s=[];for(let a of o)if(a.type==="pcb_smtpad"&&a.shape==="rect")s.push(new mx({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")s.push(new mx({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"circle",radius:a.radius,portHints:a.port_hints}));else if(a.type==="pcb_silkscreen_path")s.push(new jT({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?s.push(new Yp({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"?s.push(new Yp({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"?s.push(new Yp({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"&&s.push(new Yp({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}));else if(a.type==="pcb_keepout"&&a.shape==="circle")s.push(new yx({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius}));else if(a.type==="pcb_keepout"&&a.shape==="rect")s.push(new yx({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")s.push(new XT({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_cutout")a.shape==="rect"?s.push(new xf({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height})):a.shape==="circle"?s.push(new xf({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius})):a.shape==="polygon"&&s.push(new xf({shape:"polygon",points:a.points}));else if(a.type==="pcb_silkscreen_text"){let c=dbt(t,a.ccw_rotation);n.includes("pinrow")&&a.text.includes("PIN")?s.push(hbt({elm:a,pinLabels:r??i,layer:a.layer,readableRotation:c,anchorAlignment:a.anchor_alignment})):s.push(new vx({anchorAlignment:a.anchor_alignment||"center",text:e,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"&&s.push(new YT({route:a.route}));return s};function wx(e){let t=1/0,n=1/0,i=-1/0,r=-1/0,o=!1;for(let c of e)if(c.isPcbPrimitive&&!c.componentName.startsWith("Silkscreen")){let{x:l,y:u}=c._getGlobalPcbPositionBeforeLayout(),{width:h,height:m}=c.getPcbSize();t=Math.min(t,l-h/2),n=Math.min(n,u-m/2),i=Math.max(i,l+h/2),r=Math.max(r,u+m/2),o=!0}else if(c.children.length>0){let l=wx(c.children);(l.width>0||l.height>0)&&(t=Math.min(t,l.minX),n=Math.min(n,l.minY),i=Math.max(i,l.maxX),r=Math.max(r,l.maxY),o=!0)}if(!o)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let s=i-t,a=r-n;return s<0&&(s=0),a<0&&(a=0),{minX:t,minY:n,maxX:i,maxY:r,width:s,height:a}}function Cj(e){let t=1/0,n=1/0,i=-1/0,r=-1/0;for(let o of e){let s,a,c,l;if(o.type==="schematic_component")s=o.center?.x,a=o.center?.y,c=o.size?.width,l=o.size?.height;else if(o.type==="schematic_box")s=o.x,a=o.y,c=o.width,l=o.height;else if(o.type==="schematic_port")s=o.center?.x,a=o.center?.y,c=.2,l=.2;else if(o.type==="schematic_text")s=o.position?.x,a=o.position?.y,c=(o.text?.length??0)*.1,l=.2;else if(o.type==="schematic_line"){let u=o.x1??0,h=o.y1??0,m=o.x2??0,y=o.y2??0;s=(u+m)/2,a=(h+y)/2,c=Math.abs(m-u),l=Math.abs(y-h)}else o.type==="schematic_rect"&&(s=o.center?.x,a=o.center?.y,c=o.width,l=o.height);typeof s=="number"&&typeof a=="number"&&typeof c=="number"&&typeof l=="number"&&(t=Math.min(t,s-c/2),i=Math.max(i,s+c/2),n=Math.min(n,a-l/2),r=Math.max(r,a+l/2))}return{minX:t,maxX:i,minY:n,maxY:r}}function fbt(e,t){let n=t.x-e.x,i=t.y-e.y;return Math.abs(n)>Math.abs(i)?n>=0?"right":"left":i>=0?"up":"down"}var ej=e=>{if(e.length<=1)return!0;let t=e.map(o=>{let s=o._getPcbCircuitJsonBounds();return{left:s.bounds.left,right:s.bounds.right,top:s.bounds.top,bottom:s.bounds.bottom}}),n=Array(t.length).fill(!1).map(()=>Array(t.length).fill(!1));for(let o=0;o<t.length;o++)for(let s=o+1;s<t.length;s++){let a=t[o],c=t[s];n[o][s]=n[s][o]=!(a.right<c.left||a.left>c.right||a.bottom>c.top||a.top<c.bottom)}let i=new Set,r=o=>{i.add(o);for(let s=0;s<t.length;s++)n[o][s]&&!i.has(s)&&r(s)};return r(0),i.size===t.length},nj=e=>{if(e.length===0)throw new Error("Cannot get center of empty PCB primitives array");let t=e.map(r=>r._getPcbCircuitJsonBounds().center).filter(Boolean),n=t.reduce((r,o)=>r+o.x,0),i=t.reduce((r,o)=>r+o.y,0);return{x:n/t.length,y:i/t.length}},mbt=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()}),Mi=class extends Ne{constructor(t,n={}){if(!t.name&&t.pinNumber!==void 0&&(t.name=`pin${t.pinNumber}`),!t.name)throw new Error("Port must have a name or a pinNumber");super(t);T(this,"source_port_id",null);T(this,"pcb_port_id",null);T(this,"schematic_port_id",null);T(this,"schematicSymbolPortDef",null);T(this,"matchedComponents");T(this,"facingDirection",null);T(this,"originDescription",null);n.originDescription&&(this.originDescription=n.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:mbt}}_isBoardPinoutFromAttributes(){let t=this.parent;if(t?._parsedProps?.pinAttributes){let n=t._parsedProps.pinAttributes;for(let i of this.getNameAndAliases())if(n[i]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let t=this.matchedComponents.find(i=>i.isPcbPrimitive),n=this.parent;if(n&&!n.props.footprint)throw new Error(`${n.componentName} "${n.props.name}" does not have a footprint. Add a footprint prop, e.g. <${n.componentName.toLowerCase()} footprint="..." />`);if(!t)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return t?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_port.get(this.pcb_port_id);return{center:{x:n.x,y:n.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let t=this.parent;if(!t||!t._getInternallyConnectedPins)return[];let n=t._getInternallyConnectedPins();for(let i of n)if(i.some(r=>r===this))return i;return[]}_hasSchematicPort(){if(this.parent?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(r=>r.schematicSymbolPortDef));let n=this?.parent?._getSchematicBoxDimensions();return!!(n&&this.props.pinNumber!==void 0&&n.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let t=this.parent?.getSchematicSymbol();if(t){let i=this.schematicSymbolPortDef;if(!i&&(i=this._getPortsInternallyConnectedToThisPort().find(o=>o.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!i))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 r=Hn(this.parent.computeSchematicGlobalTransform(),dn(-t.center.x,-t.center.y));return En(r,i)}let n=this?.parent?._getSchematicBoxDimensions();if(n&&this.props.pinNumber!==void 0){let i=n.getPortPositionByPinNumber(this.props.pinNumber);if(!i)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return En(this.parent.computeSchematicGlobalTransform(),i)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:t}=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 n=t.schematic_port.get(this.schematic_port_id);if(!n)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return n.center}registerMatch(t){this.matchedComponents.push(t)}getNameAndAliases(){let{_parsedProps:t}=this;return Array.from(new Set([...t.name?[t.name]:[],...t.aliases??[],...typeof t.pinNumber=="number"?[`pin${t.pinNumber}`,t.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let t=this.parent?._parsedProps?.pinAttributes;if(!t)return[];let n=[];for(let i of this.getNameAndAliases()){let r=t[i];r&&n.push(r)}return n}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(t=>t.includeInBoardPinout===!0)}isMatchingPort(t){return this.isMatchingAnyOf(t.getNameAndAliases())}getPortSelector(){return`.${this.parent?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:t,layers:n}=this._parsedProps;return n||(t?[t]: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:t}=this.root,{_parsedProps:n}=this,i=this.getNameAndAliases(),r=t.source_port.insert({name:n.name,pin_number:n.pinNumber,port_hints:i,source_component_id:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=r.source_port_id}doInitialSourceParentAttachment(){let{db:t}=this.root;if(!this.parent?.source_component_id)throw new Error(`${this.getString()} has no parent source component (parent: ${this.parent?.getString()})`);t.source_port.update(this.source_port_id,{source_component_id:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=this.parent?.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{matchedComponents:n}=this;if(!this.parent?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()})`);let i=n.filter(o=>o.isPcbPrimitive);if(i.length===0)return;let r=null;if(i.length===1&&(r=i[0]._getPcbCircuitJsonBounds().center),i.length>1){if(!ej(i))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${i.map(o=>o.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)`);r=nj(i)}if(r){let o=this.getSubcircuit(),s=this._shouldIncludeInBoardPinout(),a=t.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...s?{is_board_pinout:!0}:{},...r,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=a.pcb_port_id}else{let o=i[0];throw new Error(`${o.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;if(this.pcb_port_id)return;let n=this.matchedComponents.filter(a=>a.isPcbPrimitive);if(n.length===0)return;let i=null;if(n.length===1&&(i=n[0]._getPcbCircuitJsonBounds().center),n.length>1)try{ej(n)&&(i=nj(n))}catch{}if(!i)return;let r=this.getSubcircuit(),o=this._shouldIncludeInBoardPinout(),s=t.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...o?{is_board_pinout:!0}:{},...i,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=s.pcb_port_id}doInitialSchematicPortRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer();if(!i||!this._hasSchematicPort())return;let r=i._getGlobalSchematicPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout(),s=null,a=i._getSchematicBoxDimensions();a&&n.pinNumber!==void 0&&(s=a.getPortPositionByPinNumber(n.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&t.schematic_debug_object.insert({shape:"rect",center:o,size:{width:.1,height:.1},label:"obstacle"}),s?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[s.side]:this.facingDirection=fbt(r,o);let c=t.source_port.get(this.source_port_id),l=[];for(let g of c?.port_hints??[])g.match(/^(pin)?\d+$/)||g.match(/^(left|right)/)&&!c?.name.match(/^(left|right)/)||l.push(g);let u;this.parent?.props?.showPinAliases&&l.length>0?u=l.join("/"):l.length>0&&(u=l[0]);let m={type:"schematic_port",schematic_component_id:this.parent?.schematic_component_id,center:o,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:s?.side,pin_number:n.pinNumber,true_ccw_index:s?.trueIndex,display_pin_label:u,is_connected:!1};for(let g of this._getMatchingPinAttributes())g.requiresPower&&(m.has_input_arrow=!0),g.providesPower&&(m.has_output_arrow=!0);let y=t.schematic_port.insert(m);this.schematic_port_id=y.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_port_id&&n.pcb_port.update(this.pcb_port_id,{x:t.x,y:t.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(t=>t.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},kj=e=>{let t=e.find(n=>/^(pin)?\d+$/.test(n));return t?Number.parseInt(t.replace(/^pin/,"")):null};function mf(e,t){let n=kj(e);if(!n)return null;let r=[...e.filter(o=>o.toString()!==n.toString()&&o!==`pin${n}`),...t?.additionalAliases?.[`pin${n}`]??[]];return new Mi({pinNumber:n,aliases:r})}var ybt=e=>{for(let t of["leftSide","rightSide","topSide","bottomSide"])if(t in e&&typeof e[t]=="number")throw new Error(`A number was specified for "${t}", you probably meant to use "size" not "side"`);return"leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e},_bt=e=>{if(ybt(e))return{leftSize:e.leftSide?.pins.length??0,rightSize:e.rightSide?.pins.length??0,topSize:e.topSide?.pins.length??0,bottomSize:e.bottomSide?.pins.length??0};let{leftSize:t=0,rightSize:n=0,topSize:i=0,bottomSize:r=0}=e;return{leftSize:t,rightSize:n,topSize:i,bottomSize:r}};function Aj(e){let t=e;return t.leftSide!==void 0||t.rightSide!==void 0||t.topSide!==void 0||t.bottomSide!==void 0}var gbt=e=>{let t=e.portDistanceFromEdge??.4,n=e.schPortArrangement?_bt(e.schPortArrangement):null,i={left:0,right:0,top:0,bottom:0},r=e.pinCount??null;if(r===null)if(n)r=n.leftSize+n.rightSize+n.topSize;else throw new Error("Could not determine pin count for the schematic box");if(r&&!n){let g=Math.floor(r/2);n={leftSize:r-g,rightSize:g,topSize:0,bottomSize:0}}n||(n={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let o=({side:g,sideIndex:x,truePinIndex:v})=>{if(!e.schPortArrangement||!Aj(e.schPortArrangement))return v+1;let w={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[g],P=e.schPortArrangement?.[`${g}Side`]?.direction??w,N=e.schPortArrangement?.[`${g}Side`]?.pins,E=x;return P!==w&&(E=N.length-x-1),bf(N[E],e.pinLabels)},s=[],a=0,c=0;for(let g=0;g<n.leftSize;g++){let x=o({side:"left",sideIndex:g,truePinIndex:c}),v=e.numericSchPinStyle?.[`pin${x}`]??e.numericSchPinStyle?.[x];v?.topMargin&&(a+=v.topMargin),s.push({trueIndex:c,pinNumber:x,side:"left",distanceFromOrthogonalEdge:a}),v?.bottomMargin&&(a+=v.bottomMargin),g===n.leftSize-1?i.left=a:a+=e.schPinSpacing,c++}a=0;for(let g=0;g<n.bottomSize;g++){let x=o({side:"bottom",sideIndex:g,truePinIndex:c}),v=e.numericSchPinStyle?.[`pin${x}`]??e.numericSchPinStyle?.[x];v?.leftMargin&&(a+=v.leftMargin),s.push({trueIndex:c,pinNumber:x,side:"bottom",distanceFromOrthogonalEdge:a}),v?.rightMargin&&(a+=v.rightMargin),g===n.bottomSize-1?i.bottom=a:a+=e.schPinSpacing,c++}a=0;for(let g=0;g<n.rightSize;g++){let x=o({side:"right",sideIndex:g,truePinIndex:c}),v=e.numericSchPinStyle?.[`pin${x}`]??e.numericSchPinStyle?.[x];v?.bottomMargin&&(a+=v.bottomMargin),s.push({trueIndex:c,pinNumber:x,side:"right",distanceFromOrthogonalEdge:a}),v?.topMargin&&(a+=v.topMargin),g===n.rightSize-1?i.right=a:a+=e.schPinSpacing,c++}a=0;for(let g=0;g<n.topSize;g++){let x=o({side:"top",sideIndex:g,truePinIndex:c}),v=e.numericSchPinStyle?.[`pin${x}`]??e.numericSchPinStyle?.[x];v?.rightMargin&&(a+=v.rightMargin),s.push({trueIndex:c,pinNumber:x,side:"top",distanceFromOrthogonalEdge:a}),v?.leftMargin&&(a+=v.leftMargin),g===n.topSize-1?i.top=a:a+=e.schPinSpacing,c++}let l=e.schWidth;if(l===void 0){l=Math.max(i.top+e.schPinSpacing*2,i.bottom+e.schPinSpacing*2);let g=e.pinLabels?Math.max(...Object.values(e.pinLabels).map(v=>v.length*.1)):0,x=g>0?1.1:0;l=Math.max(l,g+x)}let u=e.schHeight;u||(u=Math.max(i.left+e.schPinSpacing*2,i.right+e.schPinSpacing*2));let h={left:{x:-l/2-t,y:i.left/2},bottom:{x:-i.bottom/2,y:-u/2-t},right:{x:l/2+t,y:-i.right/2},top:{x:i.top/2,y:u/2+t}},m={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},y=s.map(g=>{let{distanceFromOrthogonalEdge:x,side:v}=g,w=h[v],P=m[v];return{x:w.x+x*P.x,y:w.y+x*P.y,...g}});return{getPortPositionByPinNumber(g){let x=y.find(v=>v.pinNumber.toString()===g.toString());return x||null},getSize(){return{width:l,height:u}},getSizeIncludingPins(){return{width:l+(n.leftSize||n.rightSize?.4:0),height:u+(n.topSize||n.bottomSize?.4:0)}},pinCount:r}},xbt=(0,Nj.default)("tscircuit:core:footprint"),Rj=class extends Ne{get config(){return{componentName:"Footprint",zodProps:tL}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let e=this.children.filter(h=>h.componentName==="Constraint");if(e.length===0)return;let{isFlipped:t}=this._getPcbPrimitiveFlippedHelpers(),n=h=>t&&"left"in h&&"right"in h?{...h,left:h.right,right:h.left}:h,i=e.flatMap(h=>h._getAllReferencedComponents().componentsWithSelectors).map(({component:h,selector:m,componentSelector:y,edge:g})=>({component:h,selector:m,componentSelector:y,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:m})=>m===h)}let o=new ep,s={};function a(h){return h in s||(s[h]=new gs(h),o.addEditVariable(s[h],fn.weak)),s[h]}for(let{selector:h,bounds:m}of i){let y=a(`${h}_x`),g=a(`${h}_y`);o.suggestValue(y,m.center.x),o.suggestValue(g,m.center.y)}for(let h of e){let m=h._parsedProps;if("xDist"in m){let{xDist:y,left:g,right:x,edgeToEdge:v,centerToCenter:w}=n(m),P=a(`${g}_x`),N=a(`${x}_x`),E=r(g)?.bounds,R=r(x)?.bounds;if(w){let I=new xn(N,[-1,P]);o.addConstraint(new Qn(I,zn.Eq,m.xDist,fn.required))}else if(v){let I=new xn(N,-R.width/2,[-1,P],-E.width/2);o.addConstraint(new Qn(I,zn.Eq,m.xDist,fn.required))}}else if("yDist"in m){let{yDist:y,top:g,bottom:x,edgeToEdge:v,centerToCenter:w}=m,P=a(`${g}_y`),N=a(`${x}_y`),E=r(g)?.bounds,R=r(x)?.bounds;if(w){let I=new xn(P,[-1,N]);o.addConstraint(new Qn(I,zn.Eq,m.yDist,fn.required))}else if(v){let I=new xn(P,E.height/2,[-1,N],-R.height/2);o.addConstraint(new Qn(I,zn.Eq,m.yDist,fn.required))}}else if("sameY"in m){let{for:y}=m;if(y.length<2)continue;let g=y.map(v=>a(`${v}_y`)),x=new xn(...g.slice(1));o.addConstraint(new Qn(x,zn.Eq,g[0],fn.required))}else if("sameX"in m){let{for:y}=m;if(y.length<2)continue;let g=y.map(v=>a(`${v}_x`)),x=new xn(...g.slice(1));o.addConstraint(new Qn(x,zn.Eq,g[0],fn.required))}}o.updateVariables(),xbt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(s).map(([h,m])=>({var:h,val:m.value()}))));let c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:h,bounds:{width:m,height:y}}of i){let g=a(`${h}_x`),x=a(`${h}_y`),v=g.value()-m/2,w=g.value()+m/2,P=x.value()+y/2,N=x.value()-y/2;c.left=Math.min(c.left,v),c.right=Math.max(c.right,w),c.top=Math.max(c.top,P),c.bottom=Math.min(c.bottom,N)}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:m}of i){let y=a(`${m}_x`),g=a(`${m}_y`);h._setPositionFromLayout({x:y.value()+l.x,y:g.value()+l.y})}}},PT=p.union([p.number(),p.string()]),ij=p.object({x:PT,y:PT,z:PT}),Oj=class extends Ne{get config(){return{componentName:"CadModel",zodProps:wL}}doInitialCadModelRender(){let e=this._findParentWithPcbComponent();if(!e||!e.pcb_component_id)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=e._getPcbCircuitJsonBounds(),r=t.pcb_component.get(e.pcb_component_id),o=this._parsedProps;if(!o||typeof o.modelUrl!="string")return;let s=ij.parse({x:0,y:0,z:0});if(typeof o.rotationOffset=="number")s.z=Number(o.rotationOffset);else if(typeof o.rotationOffset=="object"){let m=ij.parse(o.rotationOffset);s.x=Number(m.x),s.y=Number(m.y),s.z=Number(m.z)}let a=L_.parse({x:o.pcbX??0,y:o.pcbY??0,z:o.pcbZ??0,...typeof o.positionOffset=="object"?o.positionOffset:{}}),c=e.props.layer==="bottom"?"bottom":"top",l=new URL(o.modelUrl).pathname.split(".").pop()?.toLowerCase(),u={};l==="stl"?u.model_stl_url=this._addCachebustToModelUrl(o.modelUrl):l==="obj"?u.model_obj_url=this._addCachebustToModelUrl(o.modelUrl):l==="gltf"?u.model_gltf_url=this._addCachebustToModelUrl(o.modelUrl):l==="glb"?u.model_glb_url=this._addCachebustToModelUrl(o.modelUrl):l==="step"||l==="stp"?u.model_step_url=this._addCachebustToModelUrl(o.modelUrl):l==="wrl"||l==="vrml"?u.model_wrl_url=this._addCachebustToModelUrl(o.modelUrl):u.model_stl_url=this._addCachebustToModelUrl(o.modelUrl);let h=t.cad_component.insert({position:{x:i.center.x+Number(a.x),y:i.center.y+Number(a.y),z:(c==="bottom"?-n/2:n/2)+Number(a.z)},rotation:{x:Number(s.x),y:(c==="top"?0:180)+Number(s.y),z:c==="bottom"?-((r?.rotation??0)+Number(s.z))+180:(r?.rotation??0)+Number(s.z)},pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,model_unit_to_mm_scale_factor:typeof o.modelUnitToMmScale=="number"?o.modelUnitToMmScale:void 0,...u});this.cad_component_id=h.cad_component_id}_findParentWithPcbComponent(){let e=this.parent;for(;e&&!e.pcb_component_id;)e=e.parent;return e}_addCachebustToModelUrl(e){if(!e||!e.includes("modelcdn.tscircuit.com"))return e;let t=this.root?.getClientOrigin()??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(t)}`}},Lj=class extends Ne{constructor(){super(...arguments);T(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:vL}}},bbt=(e,t)=>{if(!e)return;let n={};for(let[i,r]of Object.entries(e)){let o=bf(i,t),s={leftMargin:r.marginLeft??r.leftMargin,rightMargin:r.marginRight??r.rightMargin,topMargin:r.marginTop??r.topMargin,bottomMargin:r.marginBottom??r.bottomMargin};n[`pin${o}`]={...n[`pin${o}`],...s}}return n},rj=class{constructor({input:e}){T(this,"input");this.input=e}solveAndMapToTraces(){let e=[];for(let t of this.input.connections){if(t.pointsToConnect.length!==2)continue;let[n,i]=t.pointsToConnect,r={type:"pcb_trace",pcb_trace_id:"",connection_name:t.name,route:[{route_type:"wire",x:n.x,y:n.y,layer:"top",width:.1},{route_type:"wire",x:i.x,y:i.y,layer:"top",width:.1}]};e.push(r)}return e}},vbt=e=>{let t=Math.min(...e.map(o=>o.center.x)),n=Math.max(...e.map(o=>o.center.x)),i=Math.min(...e.map(o=>o.center.y)),r=Math.max(...e.map(o=>o.center.y));return{minX:t,maxX:n,minY:i,maxY:r}},oj=["top","bottom","inner1","inner2"],dx=(e,t=[])=>{let n=[];if(t.length===0){let a=e[0].layers;for(let c of a)n.push(...dx(e.slice(1),[c]));return n}if(e.length===0)return[];let i=e[0],r=i.via||i.optional_via,o=t[t.length-1];if(e.length===1){let a=i;return a.layers&&r?a.layers.map(c=>({layer_path:[...t,c]})):a.layers?.includes(o)?[{layer_path:[...t,o]}]:[]}if(!r)return i.layers&&!i.layers.includes(o)?[]:dx(e.slice(1),t.concat([o]));let s=(i.optional_via?oj:oj.filter(a=>a!==o)).filter(a=>!i.layers||i.layers?.includes(a));for(let a of s)n.push(...dx(e.slice(1),t.concat(a)));return n};function sj(e){let t={x:e.to.x-e.from.x,y:e.to.y-e.from.y},n=Math.abs(t.x),i=Math.abs(t.y);return n>i?t.x>0?"right":"left":t.y>0?"down":"up"}function Fp(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}var wbt=e=>{if(e.length===1)return e[0];if(e.some(c=>c.length===0))throw new Error("Cannot merge routes with zero length");let t=[],n=e[0][0],i=e[0][e[0].length-1],r=e[1][0],o=e[1][e[1].length-1],s=Math.min(Fp(n,r),Fp(n,o)),a=Math.min(Fp(i,r),Fp(i,o));s<a?t.push(...e[0].reverse()):t.push(...e[0]);for(let c=1;c<e.length;c++){let l=t[t.length-1],u=e[c],h=u[0],m=u[u.length-1],y=Fp(l,h),g=Fp(l,m);y<g?t.push(...u):t.push(...u.reverse())}for(let c=1;c<t.length-1;c++){let l=t[c-1],u=t[c];l.route_type==="wire"&&u.route_type==="wire"&&l.layer!==u.layer&&t.splice(c,0,{x:l.x,y:l.y,from_layer:l.layer,to_layer:u.layer,route_type:"via"})}return t},Sbt=(e,t)=>{let n="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e,i="_getGlobalPcbPositionBeforeLayout"in t?t._getGlobalPcbPositionBeforeLayout():t;return Math.sqrt((n.x-i.x)**2+(n.y-i.y)**2)};function Pbt(e,t){if(t.length===0)throw new Error("No candidates given to getClosest method");let n=t[0],i=1/0;for(let r of t){let o=Sbt(e,r);o<i&&(n=r,i=o)}return n}var Tbt=(e,t)=>{let n=0;n+=e.length??0,n+=t.filter(i=>i.is_crossing).length;for(let i=1;i<t.length;i++){let r=t[i-1],o=t[i],s=Math.abs(r.from.x-r.to.x)<.01,a=Math.abs(o.from.x-o.to.x)<.01;s!==a&&n++}return n},vf=e=>({up:"bottom",down:"top",left:"right",right:"left"})[e]??null,kT=({firstEdge:e,firstEdgePort:t,firstDominantDirection:n,lastEdge:i,lastEdgePort:r,lastDominantDirection:o})=>{if(e&&t)return kT({lastEdge:{from:e.to,to:e.from},lastEdgePort:t,lastDominantDirection:n}).reverse().map(a=>({from:a.to,to:a.from}));let s=[];if(i&&r){let a={x:i.to.x,y:i.to.y};o==="left"||o==="right"?(a.x=r.position.x,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...r.position}})):(a.y=r.position.y,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...r.position}}))}return s=s.filter(a=>vi(a.from,a.to)>.01),s};function Ibt(e){try{return[e(),null]}catch(t){return[null,t]}}var Mbt=(e,{db:t})=>{let n=e.map(i=>{let r=t.source_port.get(i.source_port_id);if(!r?.source_component_id)return null;let o=t.source_component.get(r.source_component_id);return o?.ftype==="simple_capacitor"?o.max_decoupling_trace_length:null}).filter(i=>i!==null);if(n.length!==0)return Math.min(...n)};function Ebt({ports:e,nets:t}){if(e.length>=2)return`${e[0]?.selector} to ${e[1]?.selector}`;if(e.length===1&&t.length===1)return`${e[0]?.selector} to net.${t[0]._parsedProps.name}`}var Cbt=(e,{db:t})=>{let n=t.pcb_board.list()[0];if(n.outline){let c=n.outline,l=(u,h)=>{let m=!1;for(let y=0,g=h.length-1;y<h.length;g=y++){let x=h[y].x,v=h[y].y,w=h[g].x,P=h[g].y;v>u.y!=P>u.y&&u.x<(w-x)*(u.y-v)/(P-v)+x&&(m=!m)}return m};return e.some(u=>!l(u,c))}let i=n.width,r=n.height,o=n.center.x,s=n.center.y;return e.some(c=>c.x<o-i/2||c.y<s-r/2||c.x>o+i/2||c.y>s+r/2)},aj=(e,t)=>Math.abs(e-t)<1e-4,kbt=(e,t,{viaDiameter:n=.5}={})=>{let i=[];for(let r=0;r<e.length-1;r++){let[o,s]=[e[r],e[r+1]],a=r-1>=0?e[r-1]:null,c=aj(o.y,s.y),l=aj(o.x,s.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${t}, start: (${o.x}, ${o.y}), end: (${s.x}, ${s.y})`);let u={type:"rect",layers:[o.layer],center:{x:(o.x+s.x)/2,y:(o.y+s.y)/2},width:c?Math.abs(o.x-s.x):.1,height:l?Math.abs(o.y-s.y):.1,connectedTo:[t]};if(i.push(u),a&&a.layer===o.layer&&o.layer!==s.layer){let h={type:"rect",layers:[o.layer,s.layer],center:{x:o.x,y:o.y},connectedTo:[t],width:n,height:n};i.push(h)}}return i};function zj(e,t=4){let{center:n,width:i,height:r,rotation:o}=e,s=[],a=o*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(o%360+360)%360;if(r<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let m=i/t;for(let y=0;y<t;y++){let g=(y-t/2+.5)*m,x=-g*c,v=-g*l,w=m*1.1,P=Math.abs(r*c)+Math.abs(m*l);s.push({center:{x:n.x+x,y:n.y+v},width:w,height:P})}}else{let m=r/t;for(let y=0;y<t;y++){let g=(y-t/2+.5)*m,x=-g*l,v=g*c,w=Math.abs(i*c)+Math.abs(m*l),P=m*1.1;s.push({center:{x:n.x+x,y:n.y+v},width:w,height:P})}}return s}function Abt(e,t={}){if(e.length<3)return[];let{rectHeight:n=.1}=t,i=[],r=e.map(a=>a.y),o=Math.min(...r),s=Math.max(...r);for(let a=o;a<s;a+=n){let c=a+n/2,l=[];for(let u=0;u<e.length;u++){let h=e[u],m=e[(u+1)%e.length];if(h.y<=c&&m.y>c||m.y<=c&&h.y>c){let y=(c-h.y)*(m.x-h.x)/(m.y-h.y)+h.x;l.push(y)}}l.sort((u,h)=>u-h);for(let u=0;u<l.length;u+=2)if(u+1<l.length){let h=l[u],y=l[u+1]-h;y>1e-6&&i.push({center:{x:h+y/2,y:c},width:y,height:n})}}return i}function Nbt(e,t={}){let{center:n,radius:i}=e,{rectHeight:r=.1}=t,o=[],s=Math.ceil(i*2/r);for(let a=0;a<s;a++){let c=n.y-i+(a+.5)*r,l=c-n.y,u=Math.sqrt(i*i-l*l);u>0&&o.push({center:{x:n.x,y:c},width:u*2,height:r})}return o}var ja=["top","inner1","inner2","bottom"],VT=(e,t)=>{let n=r=>t?r.concat(r.map(o=>t?.getNetConnectedToId(o)).filter(Boolean)):r,i=[];for(let r of e)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:n([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:n([r.pcb_smtpad_id])});else if(r.shape==="rotated_rect"){let o={center:{x:r.x,y:r.y},width:r.width,height:r.height,rotation:r.ccw_rotation},s=zj(o);for(let a of s)i.push({type:"rect",layers:[r.layer],center:a.center,width:a.width,height:a.height,connectedTo:n([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:ja,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.shape==="circle"){let o=Nbt({center:r.center,radius:r.radius},{rectHeight:.6});for(let s of o)i.push({type:"rect",layers:ja,center:s.center,width:s.width,height:s.height,connectedTo:[]})}else if(r.shape==="polygon"){let o=Abt(r.points,{rectHeight:.6});for(let s of o)i.push({type:"rect",layers:ja,center:s.center,width:s.width,height:s.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:ja,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:ja,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:ja,center:{x:r.x,y:r.y},width:r.outer_diameter,height:r.outer_diameter,connectedTo:n([r.pcb_plated_hole_id])}):r.shape==="circular_hole_with_rect_pad"?i.push({type:"rect",layers:ja,center:{x:r.x,y:r.y},width:r.rect_pad_width,height:r.rect_pad_height,connectedTo:n([r.pcb_plated_hole_id])}):(r.shape==="oval"||r.shape==="pill")&&i.push({type:"oval",layers:ja,center:{x:r.x,y:r.y},width:r.outer_width,height:r.outer_height,connectedTo:n([r.pcb_plated_hole_id])});else if(r.type==="pcb_trace"){let o=kbt(r.route.map(s=>({x:s.x,y:s.y,layer:"layer"in s?s.layer:s.from_layer})),r.source_trace_id);i.push(...o)}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},Xa=({anchor_position:e,anchor_side:t,text:n,font_size:i=.18})=>{let r=.1*(i/.18),o=n.length*r,s=i,a={...e};switch(t){case"right":a.x-=o/2;break;case"left":a.x+=o/2;break;case"top":a.y-=s/2;break;case"bottom":a.y+=s/2;break}return a},HT=({db:e,source_trace_id:t,sameNetOnly:n,differentNetOnly:i})=>{!n&&!i&&(i=!0);let r=e.source_trace.get(t),o=[];for(let s of e.schematic_trace.list()){if(s.source_trace_id===t)continue;let c=e.source_trace.get(s.source_trace_id)?.subcircuit_connectivity_map_key===r.subcircuit_connectivity_map_key;i&&c||n&&!c||o.push(s)}return o},Rbt=({edges:e,otherEdges:t})=>{let n=[...e];for(let i=0;i<n.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=n[i],o=Math.abs(r.from.x-r.to.x)<.01?"vertical":r.from.y===r.to.y?"horizontal":"not-orthogonal";if(o==="not-orthogonal")continue;let s=[];for(let x of t){let v=x.from.x===x.to.x?"vertical":x.from.y===x.to.y?"horizontal":"not-orthogonal";if(v==="not-orthogonal"||o===v)continue;if(Sa([r.from,r.to],[x.from,x.to],{lineThickness:.01})){let P=o==="vertical"?r.from.x:x.from.x,N=o==="vertical"?x.from.y:r.from.y,E={x:P,y:N};s.push({otherEdge:x,crossingPoint:E,distanceFromEdgeFrom:vi(r.from,E)})}}if(s.length===0)continue;let a=s[0];for(let x of s)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=G_(r.from,c),h={x:c.x-u.x*l/2,y:c.y-u.y*l/2},m={x:c.x+u.x*l/2,y:c.y+u.y*l/2},y=vi(m,r.to)<l,g=[{from:r.from,to:h},{from:h,to:m,is_crossing:!0},{from:m,to:r.to}];n.splice(i,1,...g),i+=g.length-2,y&&i++}return n},AT=.001,Dp=(e,t)=>{let n=Math.min(t.from.x,t.to.x),i=Math.max(t.from.x,t.to.x),r=Math.min(t.from.y,t.to.y),o=Math.max(t.from.y,t.to.y);return e.x>=n&&e.x<=i&&e.y>=r&&e.y<=o},cj=e=>{let t=Math.abs(e.from.x-e.to.x)<AT,n=Math.abs(e.from.y-e.to.y)<AT;return t?"vertical":n?"horizontal":"diagonal"},Obt=(e,t)=>{let n=cj(e),i=cj(t);if(n===i)return null;if(n==="vertical"&&i==="horizontal"||n==="horizontal"&&i==="vertical"){let h=n==="vertical"?e:t,m=n==="horizontal"?e:t,y=h.from.x,g=m.from.y,x={x:y,y:g};return Dp(x,e)&&Dp(x,t)?x:null}if(n==="vertical"||i==="vertical"){let h=n==="vertical"?e:t,m=n==="vertical"?t:e,y=h.from.x,g=(m.to.y-m.from.y)/(m.to.x-m.from.x),x=m.from.y-g*m.from.x,v=g*y+x,w={x:y,y:v};return Dp(w,e)&&Dp(w,t)?w:null}let r=(e.to.y-e.from.y)/(e.to.x-e.from.x),o=e.from.y-r*e.from.x,s=(t.to.y-t.from.y)/(t.to.x-t.from.x),a=t.from.y-s*t.from.x;if(Math.abs(r-s)<AT)return null;let c=(a-o)/(r-s),l=r*c+o,u={x:c,y:l};return Dp(u,e)&&Dp(u,t)?u:null},Lbt=({edges:e,db:t,source_trace_id:n})=>{let i=HT({db:t,source_trace_id:n,sameNetOnly:!0}).flatMap(o=>o.edges),r=new Map;for(let o of e)for(let s of i){let a=Obt(o,s);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 zbt(e,t={}){let{minX:n,maxX:i,minY:r,maxY:o}=e,s=t.padding??1;if(!isFinite(n)||!isFinite(i)||!isFinite(r)||!isFinite(o))return[];let a=n-s,c=i+s,l=o+s,u=r-s,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 Fbt=e=>{let t=e.root.db,n=e._findConnectedPorts().ports??[],i=new Set(n.map(s=>s.schematic_port_id)),r=[];for(let s of t.toArray()){if(s.type==="schematic_component"){let a=!!s.symbol_name,c=s.size.width>s.size.height?"horz":"vert";r.push({type:"rect",layers:["top"],center:s.center,width:s.size.width+(a&&c==="horz"?-.5:0),height:s.size.height+(a&&c==="vert"?-.5:0),connectedTo:[]})}if(s.type==="schematic_port"){if(i.has(s.schematic_port_id))continue;let a=s.facing_direction?U_(s.facing_direction):{x:0,y:0};r.push({type:"rect",layers:["top"],center:{x:s.center.x-a.x*.1,y:s.center.y-a.y*.1},width:.1+Math.abs(a.x)*.3,height:.1+Math.abs(a.y)*.3,connectedTo:[]})}s.type==="schematic_text"&&r.push({type:"rect",layers:["top"],center:s.position,width:(s.text?.length??0)*.1,height:.2,connectedTo:[]}),s.type==="schematic_box"&&r.push({type:"rect",layers:["top"],center:{x:s.x,y:s.y},width:s.width,height:s.height,connectedTo:[]})}let o=Cj(t.toArray());return r.push(...zbt(o,{padding:1})),r},Dbt=({edges:e,db:t,source_trace_id:n})=>{let i=t.source_trace.get(n),r=HT({db:t,source_trace_id:n,differentNetOnly:!0}).flatMap(s=>s.edges),o=s=>{let{from:a,to:c}=s;return a.x===c.x?"vertical":"horizontal"};for(let s of e){let a=o(s),c=()=>r.find(u=>o(u)===a&&Sa([s.from,s.to],[u.from,u.to],{lineThickness:.05})),l=c();for(;l;)a==="horizontal"?(s.from.y+=.1,s.to.y+=.1):(s.from.x+=.1,s.to.x+=.1),l=c()}},NT=e=>{switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},$bt=KL.version??"unknown",yf=class extends Error{constructor(e){super(`${e} (capacity-autorouter@${$bt})`),this.name="AutorouterError"}},_x=class extends Error{constructor(e){super(e.message),this.errorData=e,this.name="TraceConnectionError"}},Bbt=e=>{if(e.root?._featureMspSchematicTraceRouting||e._couldNotFindPort||e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let r,o;try{let G=e._findConnectedPorts();r=G.allPortsFound,o=G.portsWithSelectors??[]}catch(G){if(G instanceof _x){t.source_trace_not_connected_error.insert({...G.errorData,error_type:"source_trace_not_connected_error"});return}throw G}let{netsWithSelectors:s}=e._findConnectedNets();if(!r)return;let c=o.map(G=>G.port.schematic_port_id).sort().join(","),l=e.root?._getBoard();if(l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.has(c))return;let u={name:e.source_trace_id,pointsToConnect:[]},h=Fbt(e),m=o.filter(({port:G})=>G.schematic_port_id!==null).map(({port:G})=>({port:G,position:G._getGlobalSchematicPositionAfterLayout(),schematic_port_id:G.schematic_port_id??void 0,facingDirection:G.facingDirection}));if(m.length===1&&s.length===1){let G=s[0].net,{port:K,position:tt}=m[0],J=e.getSubcircuit().selectAll("netlabel").find(rt=>{let it=rt._parsedProps.connection??rt._parsedProps.connectsTo;return it?Array.isArray(it)?it.some(yt=>e.getSubcircuit().selectOne(yt,{port:!0})===K):e.getSubcircuit().selectOne(it,{port:!0})===K:!1});if(!J){let rt=t.schematic_net_label.getWhere({source_trace_id:e.source_trace_id});rt&&(J=rt)}if(J){let rt="_getGlobalSchematicPositionBeforeLayout"in J?J._getGlobalSchematicPositionBeforeLayout():J.anchor_position,it=[];tt.x===rt.x||tt.y===rt.y?it.push({from:tt,to:rt}):(it.push({from:tt,to:{x:rt.x,y:tt.y}}),it.push({from:{x:rt.x,y:tt.y},to:rt}));let wt=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:it,junctions:[],subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=wt.schematic_trace_id;return}if(e.props.schDisplayLabel){let rt=vf(K.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel,source_net_id:G.source_net_id,anchor_position:tt,center:Xa({anchor_position:tt,anchor_side:rt,text:e.props.schDisplayLabel}),anchor_side:rt});return}let bt=vf(K.facingDirection)??"bottom",ct=t.schematic_net_label.insert({text:G._parsedProps.name,source_net_id:G.source_net_id,anchor_position:tt,center:Xa({anchor_position:tt,anchor_side:bt,text:G._parsedProps.name}),anchor_side:bt});return}if(e.props.schDisplayLabel&&("from"in e.props&&"to"in e.props||"path"in e.props)){e._doInitialSchematicTraceRenderWithDisplayLabel();return}if(m.length<2)return;let x=(()=>{let G=[];for(let tt=0;tt<m.length-1;tt++){let J=m[tt],bt=m[tt+1],ct=rp({x:J.position.x,y:J.position.y,facingDirection:NT(J.facingDirection)},{x:bt.position.x,y:bt.position.y,facingDirection:NT(bt.facingDirection)});for(let rt=0;rt<ct.length-1;rt++)G.push({from:ct[rt],to:ct[rt+1]})}let K=(tt,J)=>{let bt=J.width/2,ct=J.height/2,rt=J.center.x-bt,it=J.center.x+bt,wt=J.center.y-ct,yt=J.center.y+ct,Mt=ht=>ht.x>=rt&&ht.x<=it&&ht.y>=wt&&ht.y<=yt;return Mt(tt.from)||Mt(tt.to)?!0:[[{x:rt,y:wt},{x:it,y:wt}],[{x:it,y:wt},{x:it,y:yt}],[{x:it,y:yt},{x:rt,y:yt}],[{x:rt,y:yt},{x:rt,y:wt}]].some(ht=>Sa([tt.from,tt.to],ht,{lineThickness:0}))};for(let tt of G)for(let J of h)if(K(tt,J))return null;return G})();x&&x.length===0&&(x=null),u.pointsToConnect=m.map(({position:G})=>({...G,layer:"top"}));let v=vbt(h),w=2,P={minTraceWidth:.1,obstacles:h,connections:[u],bounds:{minX:v.minX-w,maxX:v.maxX+w,minY:v.minY-w,maxY:v.maxY+w},layerCount:1},N=N_,E=!1;if(e.getSubcircuit().props._schDirectLineRoutingEnabled&&(N=rj,E=!0),!x){let K=new N({input:P,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(K.length===0){if(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection()){e._doInitialSchematicTraceRenderWithDisplayLabel();return}K=new rj({input:P}).solveAndMapToTraces(),E=!0}let[{route:tt}]=K;x=[];for(let J=0;J<tt.length-1;J++)x.push({from:tt[J],to:tt[J+1]})}let R=e.source_trace_id,I=[];if(!E){Dbt({edges:x,db:t,source_trace_id:R});let G=HT({db:t,source_trace_id:R,differentNetOnly:!0}).flatMap(K=>K.edges);x=Rbt({edges:x,otherEdges:G}),I=Lbt({edges:x,db:t,source_trace_id:e.source_trace_id})}if(!x||x.length===0)return;let A=x[x.length-1],M=m[m.length-1],k=sj(A);x.push(...kT({lastEdge:A,lastEdgePort:M,lastDominantDirection:k}));let z=x[0],B=m[0],j=sj(z);if(x.unshift(...kT({firstEdge:z,firstEdgePort:B,firstDominantDirection:j})),!e.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(e.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&Tbt(I,x)>=5&&(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection())){e._doInitialSchematicTraceRenderWithDisplayLabel();return}let q=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:x,junctions:I,subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=q.schematic_trace_id;for(let{port:G}of o)G.schematic_port_id&&t.schematic_port.update(G.schematic_port_id,{is_connected:!0});l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.add(c)};function Fj(e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];if(i.route_type==="wire"){let r=e[n+1];if(r){let o=r.x-i.x,s=r.y-i.y;t+=Math.sqrt(o*o+s*s)}}else i.route_type==="via"&&(t+=1.6)}return t}var lx=e=>({...e._getGlobalPcbPositionAfterLayout(),layers:e.getAvailablePcbLayers()}),jbt=!1;function Ybt(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e,r=e.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(r._parsedProps.routingDisabled)return;let o=r._parsedProps.pcbRouteCache?.pcbTraces;if(o){let k=t.pcb_trace.insert({route:o.flatMap(z=>z.route),source_trace_id:e.source_trace_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});e.pcb_trace_id=k.pcb_trace_id;return}if(n.pcbPath&&n.pcbPath.length>0||!r._shouldUseTraceByTraceRouting())return;let{allPortsFound:s,ports:a}=e._findConnectedPorts(),c=[];if(!s)return;let l=[];for(let k of a)k._hasMatchedPcbPrimitive()||l.push(k);if(l.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.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, ${e} wasn't routed. Missing ports: ${l.map(k=>k.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(k=>k.pcb_port_id).filter(Boolean)});return}let u=e._findConnectedNets().netsWithSelectors;if(a.length===0&&u.length===2){e.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 k=a[0],B=u[0].net.getAllConnectedPorts().filter(q=>q!==k);if(B.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let j=Pbt(k,B);c.push(j),a.push(j)}else if(a.length>1&&u.length>=1){e.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(k=>k.matchedComponents.filter(z=>z.componentName==="TraceHint")),m=(e._parsedProps.pcbRouteHints??[]).concat(h.flatMap(k=>k.getPcbRouteHints()));if(a.length>2){e.renderError(`Trace has more than two ports (${a.map(k=>k.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(e.getSubcircuit().selectAll("trace").filter(k=>k.renderPhaseStates.PcbTraceRender.initialized).some(k=>k._portsRoutedOnPcb.length===a.length&&k._portsRoutedOnPcb.every(z=>a.includes(z))))return;let x=[];m.length===0?x=[lx(a[0]),lx(a[1])]:x=[lx(a[0]),...m,lx(a[1])];let v=dx(x);if(jbt&&v.length===0){e.renderError(`Could not find a common layer (using hints) for trace ${e.getString()}`);return}let w=ir(e.root.db.toArray()),[P,N]=Ibt(()=>VT(e.root.db.toArray()));if(N){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Error getting obstacles for autorouting: ${N.message}`,source_trace_id:e.source_trace_id,center:{x:0,y:0},pcb_port_ids:a.map(k=>k.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[]});return}for(let k of P)if(k.connectedTo.length>0){let B=w.getNetConnectedToId(k.connectedTo[0]);B&&k.connectedTo.push(B)}let E=[];if(v.length===0)E=x;else{let k=v[0].layer_path;E=x.map((z,B)=>z.via?{...z,via_to_layer:k[B]}:{...z,layers:[k[B]]})}E[0].pcb_port_id=a[0].pcb_port_id,E[E.length-1].pcb_port_id=a[1].pcb_port_id;let R=[];for(let[k,z]of Ej(E)){let B="via_to_layer"in k?k.via_to_layer:null,j=2,q="layers"in k&&k.layers.length===1?k.layers[0]:B??"top",G="layers"in z&&z.layers.length===1?z.layers[0]:B??"top",K="pcb_port_id"in k?k.pcb_port_id:null,tt="pcb_port_id"in z?z.pcb_port_id:null,J=e.getSubcircuit()._parsedProps.minTraceWidth??.16,bt=new N_({OBSTACLE_MARGIN:J*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(K&&tt),connMap:w,input:{obstacles:P,minTraceWidth:J,connections:[{name:e.source_trace_id,pointsToConnect:[{...k,layer:q,pcb_port_id:K},{...z,layer:G,pcb_port_id:tt}]}],layerCount:e.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(k.x,z.x)-j,maxX:Math.max(k.x,z.x)+j,minY:Math.min(k.y,z.y)-j,maxY:Math.max(k.y,z.y)+j}}}),ct=null;try{ct=bt.solveAndMapToTraces()}catch(wt){e.renderError({type:"pcb_trace_error",pcb_trace_error_id:e.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${wt.message}`,source_trace_id:e.pcb_trace_id,center:{x:(k.x+z.x)/2,y:(k.y+z.y)/2},pcb_port_ids:a.map(yt=>yt.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(yt=>yt.pcb_component_id)})}if(!ct)return;if(ct.length===0){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Could not find a route for ${e}`,source_trace_id:e.source_trace_id,center:{x:(k.x+z.x)/2,y:(k.y+z.y)/2},pcb_port_ids:a.map(wt=>wt.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(wt=>wt.pcb_component_id)});return}let[rt]=ct;B&&(rt.route=rt.route.map(wt=>(wt.route_type==="wire"&&!wt.layer&&(wt.layer=B),wt))),K&&rt.route[0].route_type==="wire"&&(rt.route[0].start_pcb_port_id=K);let it=rt.route[rt.route.length-1];tt&&it.route_type==="wire"&&(it.end_pcb_port_id=tt),R.push(rt.route)}let I=wbt(R),A=Fj(I),M=t.pcb_trace.insert({route:I,source_trace_id:e.source_trace_id,subcircuit_id:e.getSubcircuit()?.subcircuit_id,trace_length:A});e._portsRoutedOnPcb=a,e.pcb_trace_id=M.pcb_trace_id;for(let k of I)k.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:M.pcb_trace_id,x:k.x,y:k.y,hole_diameter:.3,outer_diameter:.6,layers:[k.from_layer,k.to_layer],from_layer:k.from_layer,to_layer:k.to_layer});e._insertErrorIfTraceIsOutsideBoard(I,a)}function Xbt(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n}=e,i=e.getSubcircuit();if(!n.pcbPath||n.pcbPath.length===0)return;let{allPortsFound:r,ports:o,portsWithSelectors:s}=e._findConnectedPorts();if(!r)return;let a=[];for(let P of o)P._hasMatchedPcbPrimitive()||a.push(P);if(a.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.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, ${e} wasn't routed. Missing ports: ${a.map(P=>P.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:a.map(P=>P.pcb_port_id).filter(Boolean)});return}let c;n.pcbPathRelativeTo&&(c=s.find(P=>P.selector===n.pcbPathRelativeTo)?.port,c||(c=e.getSubcircuit().selectOne(n.pcbPathRelativeTo))),c||(c=o[0]);let l=o.find(P=>P!==c)??o[1],u=c.getAvailablePcbLayers()[0]||"top",h=n.thickness??e.getSubcircuit()._parsedProps.minTraceWidth??.16,m=c._getGlobalPcbPositionAfterLayout(),y=l._getGlobalPcbPositionAfterLayout(),g=[];g.push({route_type:"wire",x:m.x,y:m.y,width:h,layer:u,start_pcb_port_id:c.pcb_port_id});let x=c?._computePcbGlobalTransformBeforeLayout?.()||xi();for(let P of n.pcbPath){let N=En(x,{x:P.x,y:P.y});g.push({route_type:"wire",x:N.x,y:N.y,width:h,layer:u})}g.push({route_type:"wire",x:y.x,y:y.y,width:h,layer:u,end_pcb_port_id:l.pcb_port_id});let v=Fj(g),w=t.pcb_trace.insert({route:g,source_trace_id:e.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,trace_length:v});e._portsRoutedOnPcb=o,e.pcb_trace_id=w.pcb_trace_id,e._insertErrorIfTraceIsOutsideBoard(g,o)}function Vbt(e){if(e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let{allPortsFound:r,portsWithSelectors:o}=e._findConnectedPorts();if(!r)return;let s=o.map(({port:E})=>({port:E,position:E._getGlobalSchematicPositionAfterLayout(),schematic_port_id:E.schematic_port_id,facingDirection:E.facingDirection}));if(s.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let a,c,l=s[0].position,u=s[0].port;if("path"in e.props){if(e.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[a,c]=e.props.path}else{if(!("from"in e.props&&"to"in e.props))throw new Error("Missing 'from' or 'to' properties in props.");a=e.props.from,c=e.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${a}).`);let h=s[1].position,m=s[1].port;if(!m.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);let y=t.schematic_net_label.list().find(E=>E.source_net_id===u.source_port_id),g=t.schematic_net_label.list().find(E=>E.source_net_id===m.source_port_id),[x,v]=o.map(({port:E})=>E),P=x.parent?.config.shouldRenderAsSchematicBox?`${x?.parent?.props.name}_${x?.props.name}`:`${v?.parent?.props.name}_${v?.props.name}`,N=e.props.schDisplayLabel??P;if(y&&y.text!==N&&(y.text=`${N} / ${y.text}`),g&&g?.text!==N&&(g.text=`${N} / ${g.text}`),!g){let E=vf(m.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??P,source_net_id:m.source_port_id,anchor_position:h,center:Xa({anchor_position:h,anchor_side:E,text:e.props.schDisplayLabel??P}),anchor_side:E})}if(!y){let E=vf(u.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??P,source_net_id:u.source_port_id,anchor_position:l,center:Xa({anchor_position:l,anchor_side:E,text:e.props.schDisplayLabel??P}),anchor_side:E})}}function Hbt(e){let{_parsedProps:t,parent:n}=e;if(!n)throw new Error("Trace has no parent");let r=e.getTracePortPathSelectors().map(o=>({selector:o,port:e.getSubcircuit().selectOne(o,{type:"port"})??null}));for(let{selector:o,port:s}of r)if(!s){let a,c,l=o.lastIndexOf(".");if(l!==-1&&l>o.lastIndexOf(" "))a=o.slice(0,l),c=o.slice(l+1);else{let E=o.match(/^(.*[ >])?([^ >]+)$/);a=E?.[1]?.trim()??"",c=E?.[2]??o}let u=a?e.getSubcircuit().selectOne(a):null;if(!u&&a&&!/[.#\[]/.test(a)&&(u=e.getSubcircuit().selectOne(`.${a}`)),!u){let E=a?`Could not find port for selector "${o}". Component "${a}" not found`:`Could not find port for selector "${o}"`,R=e.getSubcircuit(),I=R.getGroup();throw new _x({error_type:"source_trace_not_connected_error",message:E,subcircuit_id:R.subcircuit_id??void 0,source_group_id:I?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[o]})}let h=u.children.filter(E=>E.componentName==="Port"),m=c.includes(".")?c.split(".").pop()??"":c,y=h.flatMap(E=>E.getNameAndAliases()),g=y.some(E=>!/^(pin\d+|\d+)$/.test(E)),x=Array.from(new Set(y)).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 w=`Could not find port for selector "${o}". Component "${u.props.name??a}" found, but does not have pin "${m}". ${v}`,P=e.getSubcircuit(),N=P.getGroup();throw new _x({error_type:"source_trace_not_connected_error",message:w,subcircuit_id:P.subcircuit_id??void 0,source_group_id:N?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[o]})}return r.some(o=>!o.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:r,ports:r.map(({port:o})=>o)}}var uo=class extends Ne{constructor(t){super(t);T(this,"source_trace_id",null);T(this,"pcb_trace_id",null);T(this,"schematic_trace_id",null);T(this,"_portsRoutedOnPcb");T(this,"subcircuit_connectivity_map_key",null);T(this,"_traceConnectionHash",null);T(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}get config(){return{zodProps:QO,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(t=>typeof t=="string"?t:t.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(t=>!t.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(t=>t.includes("net."))}_findConnectedPorts(){return Hbt(this)}_resolveNet(t){let n=this.getSubcircuit().selectOne(t,{type:"net"});if(n)return n;let i=t.match(/^net\.(.+)$/),r=i?i[1]:null;return r&&this.root._getBoard().getDescendants().find(s=>s.componentName==="Net"&&s._parsedProps.name===r)||null}_findConnectedNets(){let t=this.getTracePathNetSelectors().map(i=>({selector:i,net:this._resolveNet(i)})),n=t.filter(i=>!i.net);return n.length>0&&this.renderError(`Could not find net for selector "${n[0].selector}" inside ${this}`),{netsWithSelectors:t,nets:t.map(i=>i.net)}}_getAllTracesConnectedToSameNet(){let t=this.getSubcircuit().selectAll("trace"),n=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return t.filter(r=>{if(r===this)return!1;let o=r._findConnectedNets().nets,s=r._findConnectedPorts().ports??[];return o.some(a=>n.includes(a))||s.some(a=>i.includes(a))})}_isExplicitlyConnectedToPort(t){let{allPortsFound:n,portsWithSelectors:i}=this._findConnectedPorts();return n?i.map(o=>o.port).includes(t):!1}_isExplicitlyConnectedToNet(t){return this._findConnectedNets().nets.includes(t)}doInitialCreateNetsFromProps(){BT(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();return!t||!n?null:[...n].sort((o,s)=>(o.pcb_port_id||"").localeCompare(s.pcb_port_id||"")).map(o=>o.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}let r,o;try{let h=this._findConnectedPorts();r=h.allPortsFound,o=h.portsWithSelectors??[]}catch(h){if(h instanceof _x){t.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=t.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=Ebt({ports:o,nets:c}),u=t.source_trace.insert({connected_source_port_ids:o.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:Mbt(o.map(h=>h.port),{db:t})??n.maxLength,display_name:l,min_trace_thickness:n.thickness});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(t,n){let{db:i}=this.root;Cbt(t,{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:n.map(o=>o.pcb_port_id)})}doInitialPcbManualTraceRender(){Xbt(this)}doInitialPcbTraceRender(){Ybt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){Vbt(this)}_isSymbolToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=i.parent.config.shouldRenderAsSchematicBox,s=r.parent.config.shouldRenderAsSchematicBox;return o&&!s||!o&&s}_isSymbolToSymbolConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=!i.parent.config.shouldRenderAsSchematicBox,s=!r.parent.config.shouldRenderAsSchematicBox;return o&&s}_isChipToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=i.parent.config.shouldRenderAsSchematicBox,s=r.parent.config.shouldRenderAsSchematicBox;return o&&s}doInitialSchematicTraceRender(){Bbt(this)}},Gbt=e=>{let{db:t}=e.root;if(e.pcb_component_id){let n=t.pcb_component.get(e.pcb_component_id);return n?{width:n.width,height:n.height}:null}if(e.pcb_group_id){let n=t.pcb_group.get(e.pcb_group_id);return n?{width:n.width,height:n.height}:null}return null},Ubt=(e,t)=>{let{db:n}=e.root,i=n.toArray();if(e.pcb_component_id){W_(i,e.pcb_component_id,t);return}if(e.source_group_id){Z_(i,e.source_group_id,t);return}throw new Error(`Cannot reposition component ${e.getString()}: no pcb_component_id or source_group_id`)},qbt=e=>{let{db:t}=e.root;if(!e.source_component_id)return;let n=e.selectAll("port"),i=t.source_trace.list(),r=new Set;for(let s of i)for(let a of s.connected_source_port_ids)r.add(a);let o=e._getInternallyConnectedPins();for(let s of o)if(s.some(a=>a.source_port_id&&r.has(a.source_port_id)))for(let a of s)a.source_port_id&&r.add(a.source_port_id);for(let s of n)s.source_port_id&&Wbt(e,s)&&(r.has(s.source_port_id)||t.source_pin_missing_trace_warning.insert({message:`Port ${s.getNameAndAliases()[0]} on ${e.props.name} is missing a trace`,source_component_id:e.source_component_id,source_port_id:s.source_port_id,subcircuit_id:e.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},Wbt=(e,t)=>{if(e.config.componentName==="Chip"){let n=e.props.pinAttributes;if(!n)return!1;for(let i of t.getNameAndAliases()){let r=n[i];if(r?.requiresPower||r?.requiresGround||r?.requiresVoltage!==void 0)return!0}return!1}return!0};function Zbt(e){let t=e.font_size,n=e.text.length*t*.6,i=t,r=e.anchor_alignment||"center",o=e.anchor_position.x,s=e.anchor_position.y;switch(r){case"top_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y+i/2;break;case"top_center":o=e.anchor_position.x,s=e.anchor_position.y+i/2;break;case"top_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y+i/2;break;case"center_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y;break;case"center":o=e.anchor_position.x,s=e.anchor_position.y;break;case"center_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y;break;case"bottom_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y-i/2;break;case"bottom_center":o=e.anchor_position.x,s=e.anchor_position.y-i/2;break;case"bottom_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y-i/2;break;default:o=e.anchor_position.x,s=e.anchor_position.y;break}return{x:o-n/2,y:s-i/2,width:n,height:i}}function Kbt(e){if(!e._adjustSilkscreenTextAutomatically||e.root?.pcbDisabled||!e.pcb_component_id)return;let{db:t}=e.root,i=e._getPcbCircuitJsonBounds().center,r=t.pcb_silkscreen_text.list({pcb_component_id:e.pcb_component_id}).filter(c=>c.text===e.name);if(r.length===0)return;let a=e.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(c=>c!==e&&c.pcb_component_id).map(c=>{let l=c._getPcbCircuitJsonBounds(),u={center:l.center,width:l.width,height:l.height};return _s(u)});for(let c of r){let l=c.anchor_position,u=Zbt(c),h={center:{x:u.x+u.width/2,y:u.y+u.height/2},width:u.width,height:u.height},m=_s(h);if(!a.some(N=>gd(m,N)))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},w=_s(v);a.some(N=>gd(w,N))||t.pcb_silkscreen_text.update(c.pcb_silkscreen_text_id,{anchor_position:{x:g,y:x}})}}function Jbt(e){if(!e)return{validPinLabels:e,invalidPinLabelsMessages:[]};let t={},n=[];for(let[i,r]of Object.entries(e)){let o=Array.isArray(r)?r.slice():[r],s=[];for(let a of o)Qbt(i,a)?s.push(a):n.push(`Invalid pin label: ${i} = '${a}' - excluding from component. Please use a valid pin label.`);s.length>0&&(t[i]=Array.isArray(r)?s:s[0])}return{validPinLabels:Object.keys(t).length>0?t:void 0,invalidPinLabelsMessages:n}}function Qbt(e,t){try{let n={name:"test",footprint:"test",pinLabels:{[e]:t}};return tp.safeParse(n).success}catch{return!1}}var gx=e=>e.startsWith("http://")||e.startsWith("https://"),OT=e=>{if(gx(e))return null;let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t),i=e.slice(t+1);return!n||!i?null:{footprintLib:n,footprintName:i}};function t2t(e,t){let{footprint:n}=e.props;if(n??(n=e._getImpliedFootprintString?.()),!n)return;let{pcbRotation:i,pinLabels:r,pcbPinLabels:o}=e.props;if(typeof n=="string"&&gx(n)){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let s=n;t("load-footprint-url",async()=>{try{let a=await fetch(s);if(!a.ok)throw new Error(`Failed to fetch footprint: ${a.status}`);let c=await a.json(),l=hx({componentName:e.name,componentRotation:i,footprint:s,pinLabels:r,pcbPinLabels:o},c);e.addAll(l),e._markDirty("InitializePortsFromChildren")}catch(a){let c=e.root?.db;if(c&&e.source_component_id&&e.pcb_component_id){let l=e.getSubcircuit(),u=`${e.getString()} failed to load external footprint "${s}": `+(a instanceof Error?a.message:String(a)),h=Vh.parse({type:"external_footprint_load_error",message:u,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:l.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:s});c.external_footprint_load_error.insert(h)}throw a}});return}if(typeof n=="string"){let s=OT(n);if(!s||e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let c=e.root?.platform?.footprintLibraryMap?.[s.footprintLib],l;if(typeof c=="function"&&(l=c),!l)return;t("load-lib-footprint",async()=>{try{let u=await l(s.footprintName),h=null;if(Array.isArray(u)?h=u:Array.isArray(u.footprintCircuitJson)&&(h=u.footprintCircuitJson),!h)return;let m=hx({componentName:e.name,componentRotation:i,footprint:n,pinLabels:r,pcbPinLabels:o},h);e.addAll(m),!Array.isArray(u)&&u.cadModel&&(e._asyncFootprintCadModel=u.cadModel);for(let y of e.children)y.componentName==="Port"&&y._markDirty?.("PcbPortRender");e._markDirty("InitializePortsFromChildren")}catch(u){let h=e.root?.db;if(h&&e.source_component_id&&e.pcb_component_id){let m=e.getSubcircuit(),y=`${e.getString()} failed to load external footprint "${n}": `+(u instanceof Error?u.message:String(u)),g=Vh.parse({type:"external_footprint_load_error",message:y,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:m.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:n});h.external_footprint_load_error.insert(g)}throw u}});return}if(!(0,RT.isValidElement)(n)&&n.componentName==="Footprint"&&e.add(n),Array.isArray(n)&&!(0,RT.isValidElement)(n)&&n.length>0){try{let s=hx({componentName:e.name,componentRotation:i,footprint:"",pinLabels:r,pcbPinLabels:o},n);e.addAll(s)}catch(s){let a=e.root?.db;if(a&&e.source_component_id&&e.pcb_component_id){let c=e.getSubcircuit(),l=`${e.getString()} failed to load json footprint: `+(s instanceof Error?s.message:String(s)),u=m1.parse({type:"circuit_json_footprint_load_error",message:l,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:c.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});a.circuit_json_footprint_load_error.insert(u)}throw s}return}}function e2t(e){if(e.root?.pcbDisabled||!e.pcb_component_id)return;let{pcbX:t,pcbY:n}=e._parsedProps,i=e.props?.pcbPositionAnchor;if(!i||t===void 0&&n===void 0)return;let r=wx(e.children);if(r.width===0||r.height===0)return;let s={...{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=s;break;case"top_left":a={x:u.left,y:u.top};break;case"top_center":a={x:s.x,y:u.top};break;case"top_right":a={x:u.right,y:u.top};break;case"center_left":a={x:u.left,y:s.y};break;case"center_right":a={x:u.right,y:s.y};break;case"bottom_left":a={x:u.left,y:u.bottom};break;case"bottom_center":a={x:s.x,y:u.bottom};break;case"bottom_right":a={x:u.right,y:u.bottom};break}}else try{let u=e.portMap[i];u&&(a=u._getGlobalPcbPositionBeforeLayout())}catch{}if(!a)return;let l={...s};t!==void 0&&(l.x+=t-a.x),n!==void 0&&(l.y+=n-a.y),(Math.abs(l.x-s.x)>1e-6||Math.abs(l.y-s.y)>1e-6)&&e._repositionOnPcb(l)}var n2t=(0,Sj.default)("tscircuit:core"),i2t=p.object({x:Oe,y:Oe,z:Oe}),Pn=class extends Ne{constructor(t){let n={...t},i=[];if(n.pinLabels&&!Array.isArray(n.pinLabels)){let{validPinLabels:r,invalidPinLabelsMessages:o}=Jbt(n.pinLabels);n.pinLabels=r,i=o}super(n);T(this,"reactSubtrees",[]);T(this,"_impliedFootprint");T(this,"isPrimitiveContainer",!0);T(this,"_isNormalComponent",!0);T(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});T(this,"_asyncSupplierPartNumbers");T(this,"_asyncFootprintCadModel");T(this,"_isCadModelChild");T(this,"pcb_missing_footprint_error_id");T(this,"_hasStartedFootprintUrlLoad",!1);T(this,"_invalidPinLabelMessages",[]);T(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=i,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(n=>n.map(i=>typeof i=="number"?`pin${i}`:i))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let t=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(r=>r!==this&&r._isNormalComponent&&r.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let r=this._getGlobalPcbPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout();t.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:o}),this.shouldBeRemoved=!0;let s=[...this.children];for(let a of s)this.remove(a)}}initPorts(t={}){if(this.root?.schematicDisabled)return;let{config:n}=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 m=bf(h,this._parsedProps.pinLabels);i.push(new Mi({pinNumber:m,aliases:t.additionalAliases?.[`pin${m}`]??[]},{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 Mi({pinNumber:c++,aliases:t.additionalAliases?.[`pin${c}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let o=this._parsedProps.pinLabels;if(o)for(let[a,c]of Object.entries(o)){a=a.replace("pin","");let l=i.find(m=>m._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 Mi({pinNumber:parseInt(a),name:u,aliases:[...h,...t.additionalAliases?.[`pin${parseInt(a)}`]??[]]},{originDescription:`pinLabels:pin${a}`}),i.push(l))}if(n.schematicSymbolName&&!t.ignoreSymbolPorts){let a=Gn[this._getSchematicSymbolNameOrThrow()];if(!a)return;for(let c of a.ports){let l=kj(c.labels);if(!l)continue;let u=i.find(h=>h._parsedProps.pinNumber===Number(l));if(u)u.schematicSymbolPortDef=c;else{let h=mf(c.labels.concat(t.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(t);for(let c of a)i.some(l=>l.isMatchingAnyOf(c.getNameAndAliases()))||i.push(c)}let s=t.pinCount??this._getPinCount()??0;for(let a=1;a<=s;a++){if(i.find(l=>l._parsedProps.pinNumber===a))continue;if(!r){i.push(new Mi({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]}));continue}let c=[...r.leftSide?.pins??[],...r.rightSide?.pins??[],...r.topSide?.pins??[],...r.bottomSide?.pins??[]].map(l=>bf(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 Mi({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${a}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:t,pinLabels:n,pcbPinLabels:i}=this.props,{footprint:r}=this.props;if(r??(r=this._getImpliedFootprintString?.()),!!r&&typeof r=="string"){if(gx(r)||OT(r))return;let o=bv.string(r).soup(),s=hx({componentName:this.name??this.componentName,componentRotation:t,footprint:r,pinLabels:n,pcbPinLabels:i},o);this.addAll(s)}}get portMap(){return new Proxy({},{get:(t,n)=>{let i=this.children.find(r=>r.componentName==="Port"&&r.isMatchingNameOrAlias(n));if(!i)throw new Error(`There was an issue finding the port "${n.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return i}})}getInstanceForReactElement(t){for(let n of this.reactSubtrees)if(n.element===t)return n.component;return null}doInitialSourceRender(){let t=this.config.sourceFtype;if(!t)return;let{db:n}=this.root,{_parsedProps:i}=this,r=n.source_component.insert({ftype:t,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:t}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let o of this._invalidPinLabelMessages){let s="pinLabels",a=o.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);a&&(s=`pinLabels['${a[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:s,message:o,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:n}=this.config,{_parsedProps:i}=this;i.symbol&&(0,Ya.isValidElement)(i.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(i.symbol):n?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 o=d1.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});t.schematic_manual_edit_conflict_warning.insert(o)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let t=[];for(let n of this.internallyConnectedPinNames){let i=[];for(let r of n)i.push(this.portMap[r]);t.push(i)}return t}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicSymbolNameOrThrow(),r=Gn[i],o=this._getGlobalSchematicPositionBeforeLayout();if(r){let s=t.schematic_component.insert({center:o,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=s.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(t){if(this.root?.schematicDisabled)return;let{db:n}=this.root,i=this._getGlobalSchematicPositionBeforeLayout(),r=n.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,this.add(t)}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicBoxDimensions(),r={};if(Array.isArray(n.pinLabels))n.pinLabels.forEach((y,g)=>{r[String(g+1)]=y});else for(let[y,g]of Object.entries(n.pinLabels??{}))r[y]=Array.isArray(g)?g[0]:g;let o=this._getGlobalSchematicPositionBeforeLayout(),s=this._getSchematicPortArrangement(),a=t.schematic_component.insert({center:o,rotation:n.schRotation??0,size:i.getSize(),port_arrangement:lbt(s),pin_spacing:n.schPinSpacing??.2,pin_styles:cbt(n.schPinStyle,n.pinLabels),port_labels:r,source_component_id:this.source_component_id}),c=s?.topSide!==void 0||s?.bottomSide!==void 0,l=i?.getSize().width,u=i?.getSize().height,h=t.schematic_text.insert({text:n.manufacturerPartNumber??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(l??0)/2+.1:o.x-(l??0)/2,y:c?o.y+(u??0)/2+.35:o.y-(u??0)/2-.13},color:"#006464",font_size:.18}),m=t.schematic_text.insert({text:n.name??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(l??0)/2+.1:o.x-(l??0)/2,y:c?o.y+(u??0)/2+.55:o.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:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=t.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0});if(!(n.footprint??this._getImpliedFootprintString())&&!this.isGroup){let a=t.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=a.pcb_missing_footprint_error_id}this.pcb_component_id=r.pcb_component_id;let s=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&s){let a=y1.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});t.pcb_manual_edit_conflict_warning.insert(a)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:t}=this.root,{_parsedProps:n}=this,i=wx(this.children);if(i.width===0||i.height===0)return;let r={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};t.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:t}=this.root;if(!t.schematic_component.get(this.schematic_component_id))return;let i=[],r=c=>{for(let l of c){if(l.isSchematicPrimitive&&l.componentName==="SchematicLine"){let u=t.schematic_line.get(l.schematic_line_id);u&&i.push(u)}if(l.isSchematicPrimitive&&l.componentName==="SchematicRect"){let u=t.schematic_rect.get(l.schematic_rect_id);u&&i.push(u)}if(l.isSchematicPrimitive&&l.componentName==="SchematicText"){let u=t.schematic_text.get(l.schematic_text_id);u&&i.push(u)}l.children&&l.children.length>0&&r(l.children)}};if(r(this.children),i.length===0)return;let o=Cj(i),s=Math.abs(o.maxX-o.minX),a=Math.abs(o.maxY-o.minY);s===0&&a===0||t.schematic_component.update(this.schematic_component_id,{size:{width:s,height:a}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){e2t(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(t){let n=Mj(t);return{element:t,component:n}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let t=this.props.footprint;(0,Ya.isValidElement)(t)&&(this.children.some(r=>r.componentName==="Footprint")||this.add(t));let n=this.props.cadModel;if((0,Ya.isValidElement)(n)){this._isCadModelChild=!0;let i=this.children.some(o=>o.componentName==="CadAssembly"),r=this.children.some(o=>o.componentName==="CadModel");!i&&!r&&this.add(n)}}doInitialPcbFootprintStringRender(){t2t(this,(t,n)=>this._queueAsyncEffect(t,n))}_hasExistingPortExactly(t){return this.children.filter(i=>i.componentName==="Port").some(i=>{let r=t.getNameAndAliases(),o=i.getNameAndAliases();return r.length===o.length&&r.every(s=>o.includes(s))})}add(t){let n;if((0,Ya.isValidElement)(t)){let i=this._renderReactSubtree(t);this.reactSubtrees.push(i),n=i.component}else n=t;if(n.componentName==="Port"){if(this._hasExistingPortExactly(n))return;let r=this.children.filter(o=>o.componentName==="Port").find(o=>o.isMatchingAnyOf(n.getNameAndAliases()));r&&n2t(`Similar ports added. Port 1: ${r}, Port 2: ${n}`)}super.add(n)}getPortsFromFootprint(t){let{footprint:n}=this.props;if((!n||(0,Ya.isValidElement)(n))&&(n=this.children.find(r=>r.componentName==="Footprint")),typeof n=="string"){if(gx(n))return[];if(OT(n))return[];let r=bv.string(n).soup(),o=[];for(let s of r)if("port_hints"in s&&s.port_hints){let a=mf(s.port_hints,t);if(!a)continue;a.originDescription=`footprint:string:${n}:port_hints[0]:${s.port_hints[0]}`,o.push(a)}return o}if(!(0,Ya.isValidElement)(n)&&n&&n.componentName==="Footprint"){let r=n,o=1,s=[];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${o}`]),o++;let u=mf(c);u&&(u.originDescription=`footprint:${n}`,s.push(u))}return s}let i=[];if(!n){for(let r of this.children)if(r.props.portHints&&r.isPcbPrimitive){let o=mf(r.props.portHints);o&&i.push(o)}}return i}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:t}=this;if(!t.schematicSymbolName)return[];let n=Gn[t.schematicSymbolName];if(!n)return[];let i=[];for(let r of n.ports){let o=mf(r.labels);o&&(o.schematicSymbolPortDef=r,i.push(o))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:t}=this,n=[];if(t.connections)for(let[i,r]of Object.entries(t.connections)){let o=Array.isArray(r)?r:[r];for(let s of o)n.push(s)}return n}_createNetsFromProps(t){BT(this,t)}_getPcbCircuitJsonBounds(){let{db:t}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let n=t.pcb_component.get(this.pcb_component_id);return{center:{x:n.center.x,y:n.center.y},bounds:{left:n.center.x-n.width/2,top:n.center.y-n.height/2,right:n.center.x+n.width/2,bottom:n.center.y+n.height/2},width:n.width,height:n.height}}_getPinCountFromSchematicPortArrangement(){let t=this._getSchematicPortArrangement();if(!t)return 0;if(!Aj(t))return(t.leftSize??t.leftPinCount??0)+(t.rightSize??t.rightPinCount??0)+(t.topSize??t.topPinCount??0)+(t.bottomSize??t.bottomPinCount??0);let{leftSide:i,rightSide:r,topSide:o,bottomSide:s}=t;return Math.max(...i?.pins??[],...r?.pins??[],...o?.pins??[],...s?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let n=this.getPortsFromFootprint();if(n.length>0)return n.length;let{pinLabels:i}=this._parsedProps;if(i){if(Array.isArray(i))return i.length;let r=Object.keys(i).map(o=>o.startsWith("pin")?parseInt(o.slice(3)):parseInt(o)).filter(o=>!Number.isNaN(o));return r.length>0?Math.max(...r):Object.keys(i).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this,n=this._getPinCount(),i=t.schPinSpacing??.2;return gbt({schWidth:t.schWidth,schHeight:t.schHeight,schPinSpacing:i,numericSchPinStyle:bbt(t.schPinStyle,t.pinLabels),pinCount:n,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:t.pinLabels})}doInitialCadModelRender(){if(this._isCadModelChild)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=this._parsedProps.cadModel,r=i===void 0?this._asyncFootprintCadModel:i,o=this.props.footprint??this._getImpliedFootprintString();if(!this.pcb_component_id||!r&&!o||r===null)return;let s=this._getPcbCircuitJsonBounds(),a=t.pcb_component.get(this.pcb_component_id);if(typeof r=="string")throw new Error("String cadModel not yet implemented");let c=i2t.parse({x:0,y:0,z:typeof r?.rotationOffset=="number"?r.rotationOffset:0,...typeof r?.rotationOffset=="object"?r.rotationOffset??{}:{}}),l=Lc.parse({x:0,y:0,z:0,...typeof r?.positionOffset=="object"?r.positionOffset:{}}),u=this.props.layer==="bottom"?"bottom":"top",h=t.cad_component.insert({position:{x:s.center.x+l.x,y:s.center.y+l.y,z:(u==="bottom"?-n/2:n/2)+l.z},rotation:{x:c.x,y:(u==="top"?0:180)+c.y,z:u==="bottom"?-((a?.rotation??0)+c.z)+180:(a?.rotation??0)+c.z},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 o=="string"&&!r?o:void 0});this.cad_component_id=h.cad_component_id}_addCachebustToModelUrl(t){if(!t||!t.includes("modelcdn.tscircuit.com"))return t;let n=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(n)}`}_getPartsEngineCacheKey(t,n){return JSON.stringify({ftype:t.ftype,name:t.name,manufacturer_part_number:t.manufacturer_part_number,footprinterString:n})}async _getSupplierPartNumbers(t,n,i){if(this.props.doNotPlace)return{};let r=this.root?.platform?.localCacheEngine,o=this._getPartsEngineCacheKey(n,i);if(r){let c=await r.getItem(o);if(c)try{return JSON.parse(c)}catch{}}let s=await Promise.resolve(t.findPart({sourceComponent:n,footprinterString:i})),a=s==="Not found"?{}:s;if(r)try{await r.setItem(o,JSON.stringify(a))}catch{}return a}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let t=this.getInheritedProperty("partsEngine");if(!t)return;let{db:n}=this.root,i=n.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 o=this._getSupplierPartNumbers(t,i,r);if(!(o instanceof Promise)){n.source_component.update(this.source_component_id,{supplier_part_numbers:o});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await o,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(n&&!n.supplier_part_numbers&&this._asyncSupplierPartNumbers){t.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:t}=this;t.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:t}=this;if(t.connections)for(let[n,i]of Object.entries(t.connections)){let r=Array.isArray(i)?i:[i];for(let o of r)this.add(new uo({from:`${this.getSubcircuitSelector()} > port.${n}`,to:o}))}}doInitialSourceDesignRuleChecks(){qbt(this)}_getMinimumFlexContainerSize(){return Gbt(this)}_repositionOnPcb(t){return Ubt(this,t)}doInitialSilkscreenOverlapAdjustment(){return Kbt(this)}},r2t=class{constructor(e,t={}){T(this,"input");T(this,"isRouting",!1);T(this,"solver");T(this,"eventHandlers",{complete:[],error:[],progress:[]});T(this,"cycleCount",0);T(this,"stepDelay");T(this,"timeoutId");this.input=e;let{capacityDepth:n,targetMinCapacity:i,stepDelay:r=0}=t;this.solver=new sF(e,{capacityDepth:n,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 yf(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let e=Date.now(),t=this.solver.iterations;for(;Date.now()-e<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let n=(this.solver.iterations-t)/(Date.now()-e)*1e3;this.cycleCount++;let i=this.solver?.preview()||void 0,r=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,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(e){this.emitEvent({type:"error",error:e instanceof Error?new yf(e.message):new yf(String(e))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(e,t){e==="complete"?this.eventHandlers.complete.push(t):e==="error"?this.eventHandlers.error.push(t):e==="progress"&&this.eventHandlers.progress.push(t)}emitEvent(e){if(e.type==="complete")for(let t of this.eventHandlers.complete)t(e);else if(e.type==="error")for(let t of this.eventHandlers.error)t(e);else if(e.type==="progress")for(let t of this.eventHandlers.progress)t(e)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new yf(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},GT=class extends Ne{constructor(){super(...arguments);T(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:zL}}doInitialPortMatching(){let{db:t}=this.root,{_parsedProps:n,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(!n.for){this.renderError(`TraceHint has no for property (${this})`);return}let r=i.selectOne(n.for,{type:"port"});r||this.renderError(`${this} could not find port for selector "${n.for}"`),this.matchedPort=r,r.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:t}=this,n=t.offset?[t.offset]:t.offsets;if(!n)return[];let i=this._computePcbGlobalTransformBeforeLayout();return n.map(r=>({...En(i,r),via:r.via,to_layer:r.to_layer,trace_width:r.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this;t.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},Dj=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,pcb_placements:[...n.pcb_placements??[]]};for(let r of t)if(r.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:o,new_center:s}=r,a=Ve(e).pcb_component.get(o);if(!a)continue;let c=Ve(e).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:s,relative_to:"group_center"};l>=0?i.pcb_placements[l]=u:i.pcb_placements.push(u)}return i},$j=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,schematic_placements:[...n.schematic_placements??[]]};for(let r of t)if(r.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:o,new_center:s}=r,a=Ve(e).schematic_component.get(o);if(!a||!a.source_component_id)continue;let c=Ve(e).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:s,relative_to:"group_center"};l>=0?i.schematic_placements[l]=u:i.schematic_placements.push(u)}return i},o2t=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i=t.filter(s=>s.edit_event_type==="edit_schematic_component_location"),r=t.filter(s=>s.edit_event_type==="edit_pcb_component_location"),o=n;return i.length>0&&(o=$j({circuitJson:e,editEvents:i,manualEditsFile:o})),r.length>0&&(o=Dj({circuitJson:e,editEvents:r,manualEditsFile:o})),o},s2t=(e,t)=>{if(Ve(e).pcb_trace_hint.get(t.pcb_trace_hint_id))e=e.map(i=>i.pcb_trace_hint_id===t.pcb_trace_hint_id?{...i,route:t.route}:i);else{let i=Ve(e).pcb_port.get(t.pcb_port_id);e=e.filter(r=>!(r.type==="pcb_trace_hint"&&r.pcb_port_id===t.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:t.pcb_trace_hint_id,route:t.route,pcb_port_id:t.pcb_port_id,pcb_component_id:i?.pcb_component_id}])}return e},a2t=({circuitJson:e,editEvents:t})=>{e=JSON.parse(JSON.stringify(e));for(let n of t)if(n.edit_event_type==="edit_pcb_component_location"){let i=e.find(o=>o.type==="pcb_component"&&o.pcb_component_id===n.pcb_component_id);if((!i||i.center.x!==n.new_center.x||i.center.y!==n.new_center.y)&&n.original_center){let o=dn(n.new_center.x-n.original_center.x,n.new_center.y-n.original_center.y);e=e.map(s=>s.pcb_component_id!==n.pcb_component_id?s:l5(s,o))}}else n.edit_event_type==="edit_schematic_component_location"?e=e.map(i=>i.type==="schematic_component"&&i.schematic_component_id===n.schematic_component_id?{...i,center:n.new_center}:i):n.edit_event_type==="edit_pcb_trace_hint"&&(e=s2t(e,n));return e},Bj=(e,t)=>{let n=e.source_group.list(),i=[],r=o=>{let s=n.filter(a=>a.parent_subcircuit_id===o);for(let a of s)a.subcircuit_id&&(i.push(a.subcircuit_id),r(a.subcircuit_id))};return r(t),i},LT=({db:e,circuitJson:t,subcircuit_id:n,minTraceWidth:i=.1})=>{if(!e&&t&&(e=Ve(t)),!e)throw new Error("db or circuitJson is required");let r=e.pcb_trace_hint.list(),o=n?new Set([n]):null;if(n){let A=Bj(e,n);for(let M of A)o.add(M)}let s=(t??e.toArray()).filter(A=>!n||"subcircuit_id"in A&&o.has(A.subcircuit_id)),a=e.pcb_board.list()[0];e=Ve(s);let c=ir(s),l=VT([...e.pcb_component.list(),...e.pcb_smtpad.list(),...e.pcb_plated_hole.list(),...e.pcb_hole.list(),...e.pcb_via.list(),...e.pcb_cutout.list()].filter(A=>!n||o?.has(A.subcircuit_id)),c);for(let A of l){let M=A.connectedTo.flatMap(k=>c.getIdsConnectedToNet(k));A.connectedTo.push(...M)}let u=l.flatMap(A=>[{x:A.center.x-A.width/2,y:A.center.y-A.height/2},{x:A.center.x+A.width/2,y:A.center.y+A.height/2}]),h;if(a?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(A=>A.x))-1,maxX:Math.max(...u.map(A=>A.x))+1,minY:Math.min(...u.map(A=>A.y))-1,maxY:Math.max(...u.map(A=>A.y))+1},n){let A=e.pcb_group.getWhere({subcircuit_id:n});if(A){let M={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(h.minX,M.minX),maxX:Math.max(h.maxX,M.maxX),minY:Math.min(h.minY,M.minY),maxY:Math.max(h.maxY,M.maxY)}}}let m=new Set(e.pcb_trace.list().map(A=>A.source_trace_id).filter(A=>!!A)),y=e.source_trace.list().filter(A=>!m.has(A.source_trace_id)).map(A=>{let M=A.connected_source_port_ids.map(K=>{let tt=e.source_port.get(K),J=e.pcb_port.getWhere({source_port_id:K});return{...tt,...J}});if(M.length<2)return null;let[k,z]=M,B=k.layers?.[0]??"top",j=z.layers?.[0]??"top",q=r.filter(K=>K.pcb_port_id===k.pcb_port_id||K.pcb_port_id===z.pcb_port_id),G=[];for(let K of q){let J=e.pcb_port.get(K.pcb_port_id)?.layers?.[0]??"top";for(let bt of K.route)G.push({x:bt.x,y:bt.y,layer:J})}return{name:A.source_trace_id??c.getNetConnectedToId(A.source_trace_id)??"",source_trace_id:A.source_trace_id,pointsToConnect:[{x:k.x,y:k.y,layer:B,pointId:k.pcb_port_id,pcb_port_id:k.pcb_port_id},...G,{x:z.x,y:z.y,layer:j,pointId:z.pcb_port_id,pcb_port_id:z.pcb_port_id}]}}).filter(A=>A!==null),g=new Map(y.map(A=>[A.source_trace_id,A])),x=e.source_net.list().filter(A=>!n||o?.has(A.subcircuit_id)),v=[];for(let A of x){let M=e.source_trace.list().filter(k=>k.connected_source_net_ids?.includes(A.source_net_id));v.push({name:A.source_net_id??c.getNetConnectedToId(A.source_net_id),pointsToConnect:M.flatMap(k=>e.pcb_port.list().filter(B=>k.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 w=e.pcb_breakout_point.list().filter(A=>!n||o?.has(A.subcircuit_id)),P=[],N=new Map;for(let A of w){let M={x:A.x,y:A.y,layer:"top"};if(A.source_trace_id){let k=g.get(A.source_trace_id)??N.get(A.source_trace_id);if(k)k.pointsToConnect.push(M);else{let z={name:A.source_trace_id,source_trace_id:A.source_trace_id,pointsToConnect:[M]};P.push(z),N.set(A.source_trace_id,z)}}else if(A.source_net_id){let k=v.find(z=>z.name===A.source_net_id);k?k.pointsToConnect.push(M):P.push({name:A.source_net_id,pointsToConnect:[M]})}else if(A.source_port_id){let k=e.pcb_port.getWhere({source_port_id:A.source_port_id});k&&P.push({name:A.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:k.x,y:k.y,layer:k.layers?.[0]??"top",pointId:k.pcb_port_id,pcb_port_id:k.pcb_port_id},M]})}}let E=[...y,...v,...P],R=new Map;for(let A of E)for(let M of A.pointsToConnect)M.pointId&&R.set(M.pointId,A);let I=e.pcb_trace.list().filter(A=>!n||o?.has(A.subcircuit_id));for(let A of I){let M=new Set;for(let B of A.route)B.start_pcb_port_id&&M.add(B.start_pcb_port_id),B.end_pcb_port_id&&M.add(B.end_pcb_port_id);if(M.size<2)continue;let k=M.values().next().value;if(!k)continue;let z=R.get(k);z&&[...M].every(B=>R.get(B)===z)&&(z.externallyConnectedPointIds??(z.externallyConnectedPointIds=[]),z.externallyConnectedPointIds.push([...M]))}return{simpleRouteJson:{bounds:h,obstacles:l,connections:E,layerCount:a?.num_layers??2,minTraceWidth:i},connMap:c}},c2t=e=>{let t={};if(!e)return t;for(let i of Es)t[i]=0;let n=new Map;for(let i of e){let[,,r,o]=i.type.split(":");if(o==="start"){n.set(`${r}:${i.renderId}`,i);continue}if(o==="end"){let s=n.get(`${r}:${i.renderId}`);if(s){let a=i.createdAt-s.createdAt;t[r]=(t[r]||0)+a}}}return t},l2t=e=>{let t=e.map(c=>[...new Set(c)]),n=t.map(()=>[]),i=t.map(()=>null);for(let c=0;c<t.length;c++)for(let l of t[c])if(/^\d+$/.test(l)){i[c]=Number.parseInt(l);break}let r=0,o=new Set;for(let c=0;c<i.length;c++){let l=i[c];if(l===null||l<1)continue;if(!o.has(l)){o.add(l),n[c].push(`pin${l}`),r=Math.max(r,l);continue}let u=0;for(let h of n[c])h.startsWith(`pin${l}_alt`)&&u++;n[c].push(`pin${l}_alt${u+1}`)}for(let c=0;c<n.length;c++)n[c][0]?.includes("_alt")&&(r++,n[c].unshift(`pin${r}`));for(let c=0;c<n.length;c++)n[c].length===0&&(r++,n[c].push(`pin${r}`));let s={};for(let c of t)for(let l of c)/^\d+$/.test(l)||(s[l]=(s[l]??0)+1);let a={};for(let c=0;c<t.length;c++){let l=t[c];for(let u of l)/^\d+$/.test(u)||(s[u]===1?n[c].push(u):(a[u]=(a[u]??0)+1,n[c].push(`${u}${a[u]}`)))}return n},lj=(0,jj.default)("Group_doInitialSchematicLayoutMatchAdapt");function u2t(e){let{db:t}=e.root,n=xd(t.toArray(),{source_group_id:e.source_group_id}),i=D5(n);lj.enabled&&global.debugGraphics?.push(Aa(i,{title:`floatingBpcGraph-${e.name}`}));let r=D5(n),o={boxes:r.boxes,pins:r.pins.map(c=>({...c,color:c.color.replace("not_connected","normal")}))},{result:s}=LD([{variantName:"default",floatingGraph:r},{variantName:"noNotConnected",floatingGraph:o}],{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:{}});lj.enabled&&global.debugGraphics?.push(Aa(s,{title:`laidOutBpcGraph-${e.name}`}));let a=e._getGlobalSchematicPositionBeforeLayout();for(let c of s.boxes){if(!c.center)continue;let l=t.schematic_component.get(c.boxId);if(l){let h={x:c.center.x+a.x,y:c.center.y+a.y},m=t.schematic_port.list({schematic_component_id:l.schematic_component_id}),y=t.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 m)x.center.x+=g.x,x.center.y+=g.y;for(let x of y)x.position.x+=g.x,x.position.y+=g.y;l.center=h;continue}let u=t.schematic_net_label.get(c.boxId);if(u){let h=s.pins.find(y=>y.boxId===c.boxId&&y.color==="netlabel_center");if(!h)throw new Error(`No pin found for net label: ${c.boxId}`);let m={x:c.center.x+a.x,y:c.center.y+a.y};u.center=m,u.anchor_position={x:m.x+h.offset.x,y:m.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 ue=(0,Yj.default)("Group_doInitialSchematicLayoutMatchpack");function uj(e){switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function pj(e,t){let n=["right","up","left","down"],i=n.indexOf(e);if(i===-1)return e;let r=Math.round(t/90),o=(i+r)%4;return n[o<0?o+4:o]}function p2t(e,t,n){let i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};ue(`[${n.name}] Processing ${e.childNodes.length} child nodes for input problem`),e.childNodes.forEach((o,s)=>{if(ue(`[${n.name}] Processing child ${s}: nodeType=${o.nodeType}`),o.nodeType==="component"?ue(`[${n.name}] - Component: ${o.sourceComponent?.name}`):o.nodeType==="group"&&ue(`[${n.name}] - Group: ${o.sourceGroup?.name}`),o.nodeType==="component"&&o.sourceComponent){let a=o.sourceComponent.name||`chip_${s}`,c=t.schematic_component.getWhere({source_component_id:o.sourceComponent.source_component_id});if(!c)return;let l=n.children.find(P=>P.source_component_id===o.sourceComponent?.source_component_id),u=[0,90,180,270];l?._parsedProps?.schOrientation&&(u=[0]),l?._parsedProps?.schRotation!==void 0&&(u=[0]);let h=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,m=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,y=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,g=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0;l?.config.shouldRenderAsSchematicBox&&(y+=.4,g+=.4);let x=(m-h)/2,v=(y-g)/2;i.chipMap[a]={chipId:a,pins:[],size:{x:(c.size?.width||1)+h+m,y:(c.size?.height||1)+y+g},availableRotations:u};let w=t.schematic_port.list({schematic_component_id:c.schematic_component_id});for(let P of w){let N=t.source_port.get(P.source_port_id);if(!N)continue;let E=`${a}.${N.pin_number||N.name||P.schematic_port_id}`;i.chipMap[a].pins.push(E);let R=uj(P.facing_direction);i.chipPinMap[E]={pinId:E,offset:{x:(P.center?.x||0)-(c.center.x||0)+x,y:(P.center?.y||0)-(c.center.y||0)+v},side:R}}}else if(o.nodeType==="group"&&o.sourceGroup){let a=o.sourceGroup.name||`group_${s}`;ue(`[${n.name}] Processing nested group: ${a}`);let c=t.schematic_group?.getWhere?.({source_group_id:o.sourceGroup.source_group_id}),l=n.children.find(u=>u.source_group_id===o.sourceGroup?.source_group_id);if(ue(`[${n.name}] Found schematic_group for ${a}:`,c),c){ue(`[${n.name}] Treating group ${a} as composite chip`);let u=t.schematic_component.list({schematic_group_id:c.schematic_group_id});ue(`[${n.name}] Group ${a} has ${u.length} components:`,u.map(k=>k.source_component_id));let h=1/0,m=-1/0,y=1/0,g=-1/0,x=!1;for(let k of u)if(k.center&&k.size){x=!0;let z=k.size.width/2,B=k.size.height/2;h=Math.min(h,k.center.x-z),m=Math.max(m,k.center.x+z),y=Math.min(y,k.center.y-B),g=Math.max(g,k.center.y+B)}let v=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,w=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,P=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,N=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0,E=(w-v)/2,R=(P-N)/2,I=(x?m-h:2)+v+w,A=(x?g-y:2)+P+N;ue(`[${n.name}] Group ${a} computed size: ${I} x ${A}`);let M=[];for(let k of u){let z=t.schematic_port.list({schematic_component_id:k.schematic_component_id});for(let B of z){let j=t.source_port.get(B.source_port_id);if(!j)continue;let q=`${a}.${j.pin_number||j.name||B.schematic_port_id}`;M.push(q);let G=c.center||{x:0,y:0},K=uj(B.facing_direction);i.chipPinMap[q]={pinId:q,offset:{x:(B.center?.x||0)-G.x+E,y:(B.center?.y||0)-G.y+R},side:K}}}ue(`[${n.name}] Group ${a} has ${M.length} pins:`,M),i.chipMap[a]={chipId:a,pins:M,size:{x:I,y:A}},ue(`[${n.name}] Added group ${a} to chipMap`)}else ue(`[${n.name}] Warning: No schematic_group found for group ${a}`)}}),ue(`[${n.name}] Creating connections using connectivity keys`);let r=new Map;for(let[o,s]of Object.entries(i.chipMap))for(let a of s.pins){let c=a.split(".").pop(),l=e.childNodes.find(u=>u.nodeType==="component"&&u.sourceComponent?u.sourceComponent.name===o:u.nodeType==="group"&&u.sourceGroup?`group_${e.childNodes.indexOf(u)}`===o:!1);if(l?.nodeType==="group"&&l.sourceGroup){let u=t.schematic_group?.getWhere?.({source_group_id:l.sourceGroup.source_group_id});if(u){let h=t.schematic_component.list({schematic_group_id:u.schematic_group_id});for(let m of h){let y=t.source_port.list({source_component_id:m.source_component_id});for(let g of y){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),ue(`[${n.name}] \u2713 Pin ${a} has connectivity key: ${v}`)}else ue(`[${n.name}] Pin ${a} has no connectivity key`)}}}}else if(l?.nodeType==="component"&&l.sourceComponent){let u=t.source_port.list({source_component_id:l.sourceComponent.source_component_id});for(let h of u){let m=h.pin_number||h.name;if(String(m)===String(c)&&h.subcircuit_connectivity_map_key){let y=h.subcircuit_connectivity_map_key;r.has(y)||r.set(y,[]),r.get(y).push(a),ue(`[${n.name}] Pin ${a} has connectivity key: ${y}`)}}}}ue(`[${n.name}] Found ${r.size} connectivity groups:`,Array.from(r.entries()).map(([o,s])=>({key:o,pins:s})));for(let[o,s]of r)if(s.length>=2){let a=t.source_trace.list().filter(u=>u.subcircuit_connectivity_map_key===o),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(ue(`[${n.name}] Connectivity ${o}: 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 m of u.connected_source_port_ids)for(let y of s){let g=y.split(".").pop(),x=t.source_port.get(m);if(x&&String(x.pin_number||x.name)===String(g)){let v=y.split(".")[0],w=e.childNodes.find(P=>P.nodeType==="component"&&P.sourceComponent?P.sourceComponent.name===v:P.nodeType==="group"&&P.sourceGroup?`group_${e.childNodes.indexOf(P)}`===v:!1);w?.nodeType==="component"&&w.sourceComponent&&t.source_port.list({source_component_id:w.sourceComponent.source_component_id}).some(N=>N.source_port_id===m)&&h.push(y)}}for(let m=0;m<h.length;m++)for(let y=m+1;y<h.length;y++){let g=h[m],x=h[y];i.pinStrongConnMap[`${g}-${x}`]=!0,i.pinStrongConnMap[`${x}-${g}`]=!0,ue(`[${n.name}] Created strong connection: ${g} <-> ${x}`)}}}if(c){let u=t.source_net.getWhere({subcircuit_connectivity_map_key:o}),h=u?.is_ground??!1,m=u?.is_power??!1;i.netMap[o]={netId:o,isGround:h,isPositiveVoltageSource:m};for(let y of s)i.netConnMap[`${y}-${o}`]=!0;ue(`[${n.name}] Created net ${o} with ${s.length} pins:`,s)}}return i}function h2t(e){let{db:t}=e.root,n=sp(t.toArray(),{source_group_id:e.source_group_id});if(ue(`[${e.name}] Starting matchpack layout with ${n.childNodes.length} children`),ue(`[${e.name}] Tree structure:`,JSON.stringify(n,null,2)),n.childNodes.length<=1){ue(`[${e.name}] Only ${n.childNodes.length} children, skipping layout`);return}ue("Converting circuit tree to InputProblem...");let i=p2t(n,t,e);ue.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${e.name}`,content:JSON.stringify(i,null,2)});let r=new D$(i);if(ue("Starting LayoutPipelineSolver..."),ue.enabled&&global.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-initial-${e.name}`})}if(r.solve(),ue(`Solver completed in ${r.iterations} iterations`),ue(`Solved: ${r.solved}, Failed: ${r.failed}`),r.failed)throw ue(`Solver failed with error: ${r.error}`),new Error(`Matchpack layout solver failed: ${r.error}`);let o=r.getOutputLayout();if(ue("OutputLayout:",JSON.stringify(o,null,2)),ue("Solver completed successfully:",!r.failed),ue.enabled&&global.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-final-${e.name}`})}let s=r.checkForOverlaps(o);if(s.length>0){ue(`Warning: Found ${s.length} overlapping components:`);for(let c of s)ue(` ${c.chip1} overlaps ${c.chip2} (area: ${c.overlapArea})`)}let a=e._getGlobalSchematicPositionBeforeLayout();ue(`Group offset: x=${a.x}, y=${a.y}`),ue(`Applying layout results for ${Object.keys(o.chipPlacements).length} chip placements`);for(let[c,l]of Object.entries(o.chipPlacements)){ue(`Processing placement for chip: ${c} at (${l.x}, ${l.y})`);let u=n.childNodes.find(m=>{if(m.nodeType==="component"&&m.sourceComponent){let y=m.sourceComponent.name===c;return ue(` Checking component ${m.sourceComponent.name}: matches=${y}`),y}if(m.nodeType==="group"&&m.sourceGroup){let y=m.sourceGroup.name,g=`group_${n.childNodes.indexOf(m)}`,x=g===c;return ue(` Checking group ${y} (expected chipId: ${g}): matches=${x}`),x}return!1});if(!u){ue(`Warning: No tree node found for chip: ${c}`),ue("Available tree nodes:",n.childNodes.map((m,y)=>({type:m.nodeType,name:m.nodeType==="component"?m.sourceComponent?.name:m.sourceGroup?.name,expectedChipId:m.nodeType==="group"?`group_${y}`:m.sourceComponent?.name})));continue}let h={x:l.x+a.x,y:l.y+a.y};if(u.nodeType==="component"&&u.sourceComponent){let m=t.schematic_component.getWhere({source_component_id:u.sourceComponent.source_component_id});if(m){ue(`Moving component ${c} to (${h.x}, ${h.y})`);let y=t.schematic_port.list({schematic_component_id:m.schematic_component_id}),g=t.schematic_text.list({schematic_component_id:m.schematic_component_id}),x={x:h.x-m.center.x,y:h.y-m.center.y};for(let v of y)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(m.center=h,l.ccwRotationDegrees!==0){ue(`Component ${c} has rotation: ${l.ccwRotationDegrees}\xB0`);let v=l.ccwRotationDegrees*Math.PI/180,w=Math.cos(v),P=Math.sin(v);for(let N of y){let E=N.center.x-h.x,R=N.center.y-h.y,I=E*w-R*P,A=E*P+R*w;N.center.x=h.x+I,N.center.y=h.y+A;let M=N.facing_direction||"right";N.facing_direction=pj(M,l.ccwRotationDegrees)}for(let N of g){let E=N.position.x-h.x,R=N.position.y-h.y,I=E*w-R*P,A=E*P+R*w;N.position.x=h.x+I,N.position.y=h.y+A}if(m.symbol_name){let N=m.symbol_name.match(/_(right|left|up|down)$/);N&&(m.symbol_name=m.symbol_name.replace(N[0],`_${pj(N[1],l.ccwRotationDegrees)}`))}}}}else if(u.nodeType==="group"&&u.sourceGroup){let m=t.schematic_group?.getWhere?.({source_group_id:u.sourceGroup.source_group_id});if(m){ue(`Moving group ${c} to (${h.x}, ${h.y}) from (${m.center?.x}, ${m.center?.y})`);let y=t.schematic_component.list({schematic_group_id:m.schematic_group_id});ue(`Group ${c} has ${y.length} components to move`);let g=m.center||{x:0,y:0},x={x:h.x-g.x,y:h.y-g.y};ue(`Position delta for group ${c}: (${x.x}, ${x.y})`);for(let v of y)if(v.center){let w={...v.center};v.center.x+=x.x,v.center.y+=x.y,ue(`Moved component ${v.source_component_id} from (${w.x}, ${w.y}) to (${v.center.x}, ${v.center.y})`);let P=t.schematic_port.list({schematic_component_id:v.schematic_component_id}),N=t.schematic_text.list({schematic_component_id:v.schematic_component_id});for(let E of P)E.center&&(E.center.x+=x.x,E.center.y+=x.y);for(let E of N)E.position&&(E.position.x+=x.x,E.position.y+=x.y)}m.center=h,ue(`Updated group ${c} center to (${h.x}, ${h.y})`)}}}ue("Matchpack layout completed successfully")}function d2t(e){if(!e.isSubcircuit)return;let{db:t}=e.root,n=e.selectAll("trace"),i=new pd({});i.addConnections(n.map(a=>{let c=t.source_trace.get(a.source_trace_id);return c?[c.source_trace_id,...c.connected_source_port_ids,...c.connected_source_net_ids]:null}).filter(a=>a!==null));let{name:r}=e._parsedProps;for(let a of n){if(!a.source_trace_id)continue;let c=i.getNetConnectedToId(a.source_trace_id);c&&(a.subcircuit_connectivity_map_key=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`,t.source_trace.update(a.source_trace_id,{subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}))}let o=new Set;for(let a of n){if(!a.source_trace_id)continue;let c=t.source_trace.get(a.source_trace_id);if(c)for(let l of c.connected_source_port_ids)o.add(l)}for(let a of o){let c=i.getNetConnectedToId(a);if(!c)continue;let l=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`;t.source_port.update(a,{subcircuit_connectivity_map_key:l})}let s=new Set;for(let a of n){if(!a.source_trace_id)continue;let c=t.source_trace.get(a.source_trace_id);if(c)for(let l of c.connected_source_net_ids)s.add(l)}for(let a of s){let c=i.getNetConnectedToId(a);if(!c)continue;let l=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`;t.source_net.update(a,{subcircuit_connectivity_map_key:l})}}function f2t(e){let{db:t}=e.root,n=e._parsedProps,i=e.children.filter(R=>{let I=R._parsedProps?.schX!==void 0||R._parsedProps?.schY!==void 0;return R.schematic_component_id&&!I});if(i.length===0)return;let r=0,o=0;for(let R of i){let I=t.schematic_component.get(R.schematic_component_id);I?.size&&(r=Math.max(r,I.size.width),o=Math.max(o,I.size.height))}r===0&&i.length>0&&(r=1),o===0&&i.length>0&&(o=1);let s=n.gridCols,a,c=n.gridGap,l=n.gridRowGap,u=n.gridColumnGap;n.schLayout?.grid&&(s=n.schLayout.grid.cols??s,a=n.schLayout.grid.rows,c=n.schLayout.gridGap??c,l=n.schLayout.gridRowGap??l,u=n.schLayout.gridColumnGap??u);let h,m;s!==void 0&&a!==void 0?(h=s,m=a):s!==void 0?(h=s,m=Math.ceil(i.length/h)):a!==void 0?(m=a,h=Math.ceil(i.length/m)):(h=Math.ceil(Math.sqrt(i.length)),m=Math.ceil(i.length/h)),h===0&&i.length>0&&(h=1),m===0&&i.length>0&&(m=i.length);let y,g,x=R=>{if(R!==void 0)return typeof R=="number"?R:D.parse(R)};if(l!==void 0||u!==void 0){let R=typeof c=="object"&&c!==null?c.x:c,I=typeof c=="object"&&c!==null?c.y:c;y=x(u??R)??1,g=x(l??I)??1}else if(typeof c=="number")y=c,g=c;else if(typeof c=="string"){let R=D.parse(c);y=R,g=R}else if(typeof c=="object"&&c!==null){let R=c.x,I=c.y;y=typeof R=="number"?R:D.parse(R??"0mm"),g=typeof I=="number"?I:D.parse(I??"0mm")}else y=1,g=1;let v=h*r+Math.max(0,h-1)*y,w=m*o+Math.max(0,m-1)*g,P=e._getGlobalSchematicPositionBeforeLayout(),N=P.x-v/2+r/2,E=P.y+w/2-o/2;for(let R=0;R<i.length;R++){let I=i[R];if(!I.schematic_component_id)continue;let A=Math.floor(R/h),M=R%h;if(A>=m||M>=h){console.warn(`Schematic grid layout: Child ${I.getString()} at index ${R} (row ${A}, col ${M}) exceeds specified grid dimensions (${m}x${h}). Skipping placement.`);continue}let k=N+M*(r+y),z=E-A*(o+g),B=t.schematic_component.get(I.schematic_component_id);if(B){let j=B.center,q={x:k,y:z};t.schematic_component.update(I.schematic_component_id,{center:q});let G=q.x-j.x,K=q.y-j.y,tt=t.schematic_port.list({schematic_component_id:I.schematic_component_id});for(let bt of tt)t.schematic_port.update(bt.schematic_port_id,{center:{x:bt.center.x+G,y:bt.center.y+K}});let J=t.schematic_text.list({schematic_component_id:I.schematic_component_id});for(let bt of J)t.schematic_text.update(bt.schematic_text_id,{position:{x:bt.position.x+G,y:bt.position.y+K}})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:v,height:w,center:P})}var hj=(e,t)=>{let{sourceComponent:n,sourceGroup:i}=t;if(t.nodeType==="component"){let r=e.schematic_component.getWhere({source_component_id:n?.source_component_id});return r?.size?{width:r.size.width,height:r.size.height}:null}if(t.nodeType==="group"){let r=e.schematic_group.getWhere({source_group_id:i?.source_group_id});if(r?.width&&r?.height)return{width:r.width,height:r.height};let o=e.schematic_component.list({schematic_group_id:r?.schematic_group_id}),s=1/0,a=-1/0,c=1/0,l=-1/0;for(let m of o)if(m.center&&m.size){let y=m.size.width/2,g=m.size.height/2;s=Math.min(s,m.center.x-y),a=Math.max(a,m.center.x+y),c=Math.min(c,m.center.y-g),l=Math.max(l,m.center.y+g)}let u=a-s,h=l-c;return{width:u,height:h}}return null},m2t=e=>{let{db:t}=e.root,n=e._parsedProps,i=sp(t.toArray(),{source_group_id:e.source_group_id}),r=n.schJustifyContent??n.justifyContent,o=n.schAlignItems??n.alignItems,s=n.schFlexGap??n.schGap??n.gap,a=n.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"}[o??"center"];if(!c)throw new Error(`Invalid justifyContent value: "${r}"`);if(!l)throw new Error(`Invalid alignItems value: "${o}"`);let u=0,h=0;typeof s=="object"?(u=s.y??0,h=s.x??0):typeof s=="number"?(u=s,h=s):typeof s=="string"&&(u=D.parse(s),h=D.parse(s));let m,y=n.width??n.schWidth??void 0,g=n.height??n.schHeight??void 0;(y===void 0||g===void 0)&&(m=K_(i.childNodes.map(E=>hj(t,E)).filter(E=>E!==null),{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h}),y=m.width,g=m.height);let v=new Zg(y,g,{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h});for(let E of i.childNodes){let R=hj(t,E);v.addChild({metadata:E,width:R?.width??0,height:R?.height??0,flexBasis:R?a==="row"?R.width:R.height:void 0})}v.build();let w={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let E of v.children)w.minX=Math.min(w.minX,E.position.x),w.minY=Math.min(w.minY,E.position.y),w.maxX=Math.max(w.maxX,E.position.x+E.size.width),w.maxY=Math.max(w.maxY,E.position.y+E.size.height);w.width=w.maxX-w.minX,w.height=w.maxY-w.minY;let P={x:-(w.maxX+w.minX)/2,y:-(w.maxY+w.minY)/2},N=t.toArray();for(let E of v.children){let{sourceComponent:R,sourceGroup:I}=E.metadata;if(R){let A=t.schematic_component.getWhere({source_component_id:R.source_component_id});if(!A)continue;az(N,A.schematic_component_id,{x:E.position.x+E.size.width/2+P.x,y:E.position.y+E.size.height/2+P.y})}if(I){if(!t.schematic_group.getWhere({source_group_id:I.source_group_id}))continue;lz(N,I.source_group_id,{x:E.position.x+E.size.width/2+P.x,y:E.position.y+E.size.height/2+P.y})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:w.width,height:w.height})},TT=1;function y2t(e){let{db:t}=e.root,n=e._parsedProps,i=_2t(e);if(i.length===0)return;let r=g2t({db:t,pcbChildren:i}),o=x2t(n),s=b2t({props:n,pcbChildren:i,childDimensions:r,gridConfig:o}),a=S2t({pcbChildren:i,childDimensions:r,gridLayout:s,gridConfig:o}),{itemCoordinates:c}=a.layout();P2t({db:t,group:e,pcbChildren:i,itemCoordinates:c,gridLayout:s}),T2t({db:t,group:e,props:n,gridLayout:s})}function _2t(e){return e.children.filter(t=>t.pcb_component_id||t.pcb_group_id)}function g2t(e){let{db:t,pcbChildren:n}=e,i=0,r=0;for(let o of n){let s=0,a=0;if(o.pcb_group_id){let c=t.pcb_group.get(o.pcb_group_id);s=c?.width??0,a=c?.height??0}else if(o.pcb_component_id){let c=t.pcb_component.get(o.pcb_component_id);s=c?.width??0,a=c?.height??0}i=Math.max(i,s),r=Math.max(r,a)}return{width:i,height:r}}function x2t(e){let t=e.pcbGridCols??e.gridCols??e.pcbLayout?.grid?.cols,n=e.pcbGridRows??e.pcbLayout?.grid?.rows,i=e.pcbGridTemplateColumns,r=e.pcbGridTemplateRows,o=h=>h===void 0?TT:typeof h=="number"?h:D.parse(h),s=e.pcbGridGap??e.gridGap??e.pcbLayout?.gridGap,a=e.pcbGridRowGap??e.gridRowGap??e.pcbLayout?.gridRowGap,c=e.pcbGridColumnGap??e.gridColumnGap??e.pcbLayout?.gridColumnGap,l=TT,u=TT;if(a!==void 0||c!==void 0){let h=typeof s=="object"?s?.x:s,m=typeof s=="object"?s?.y:s;l=o(c??h),u=o(a??m)}else if(typeof s=="object"&&s!==null)l=o(s.x),u=o(s.y);else{let h=o(s);l=h,u=h}return{cols:t,rows:n,gapX:l,gapY:u,templateColumns:i,templateRows:r}}function b2t(e){let{props:t,pcbChildren:n,childDimensions:i,gridConfig:r}=e;return t.pcbGridTemplateColumns||t.pcbGridTemplateRows?v2t({props:t,gridConfig:r,pcbChildren:n,childDimensions:i}):w2t({gridConfig:r,pcbChildren:n,childDimensions:i})}function v2t(e){let{props:t,gridConfig:n,pcbChildren:i,childDimensions:r}=e,o=t.pcbGridTemplateColumns??"",s=t.pcbGridTemplateRows??"",a=m=>{let y=m.match(/repeat\((\d+),/);return y?parseInt(y[1]):Math.ceil(Math.sqrt(i.length))},c=t.pcbGridTemplateColumns?a(o):Math.ceil(Math.sqrt(i.length)),l=t.pcbGridTemplateRows?a(s):Math.ceil(i.length/c),u=c*r.width+Math.max(0,c-1)*n.gapX,h=l*r.height+Math.max(0,l-1)*n.gapY;return{gridTemplateColumns:o,gridTemplateRows:s,containerWidth:u,containerHeight:h}}function w2t(e){let{gridConfig:t,pcbChildren:n,childDimensions:i}=e,r,o;t.cols!==void 0&&t.rows!==void 0?(r=t.cols,o=t.rows):t.cols!==void 0?(r=t.cols,o=Math.ceil(n.length/r)):t.rows!==void 0?(o=t.rows,r=Math.ceil(n.length/o)):(r=Math.ceil(Math.sqrt(n.length)),o=Math.ceil(n.length/r)),r=Math.max(1,r),o=Math.max(1,o);let s=r*i.width+Math.max(0,r-1)*t.gapX,a=o*i.height+Math.max(0,o-1)*t.gapY,c=`repeat(${r}, ${i.width}px)`,l=`repeat(${o}, ${i.height}px)`;return{gridTemplateColumns:c,gridTemplateRows:l,containerWidth:s,containerHeight:a}}function S2t(e){let{pcbChildren:t,childDimensions:n,gridLayout:i,gridConfig:r}=e,o=t.map((s,a)=>({key:s.getString()||`child-${a}`,contentWidth:n.width,contentHeight:n.height}));return new U$({containerWidth:i.containerWidth,containerHeight:i.containerHeight,gridTemplateColumns:i.gridTemplateColumns,gridTemplateRows:i.gridTemplateRows,gap:[r.gapY,r.gapX],children:o})}function P2t(e){let{db:t,group:n,pcbChildren:i,itemCoordinates:r,gridLayout:o}=e,s=n._getGlobalPcbPositionBeforeLayout(),a=t.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 m=s.x-o.containerWidth/2+h.x+h.width/2,y=s.y+o.containerHeight/2-h.y-h.height/2;if(l.pcb_component_id)W_(a,l.pcb_component_id,{x:m,y});else{let g=l;g.pcb_group_id&&g.source_group_id&&Z_(a,g.source_group_id,{x:m,y})}}}function T2t(e){let{db:t,group:n,props:i,gridLayout:r}=e;if(n.pcb_group_id){let o=n._getGlobalPcbPositionBeforeLayout();t.pcb_group.update(n.pcb_group_id,{width:i.width??r.containerWidth,height:i.height??r.containerHeight,center:o})}}function I2t(e){let t={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof e=="object"&&!e.preset)return{local:!(e.serverUrl||e.serverMode||e.serverCacheEnabled),...t,...e};let n=typeof e=="object"?e.preset:e,i=typeof e=="object"?e:{};switch(n){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:r,local:o,groupMode:s,...a}=i;return{local:!1,groupMode:"subcircuit",...t,...a}}default:return{local:!0,groupMode:"subcircuit"}}}var M2t=(e,t)=>{let n=e.children.filter(h=>h.componentName==="Constraint"&&h._parsedProps.pcb),i=new Map,r={},o=h=>(r[h]!==h&&(r[h]=o(r[h])),r[h]),s=(h,m)=>{let y=o(h),g=o(m);y!==g&&(r[g]=y)},a=h=>{h in r||(r[h]=h)},c=h=>{let m=h.startsWith(".")?h.slice(1):h;return e.children.find(g=>g.name===m)?.pcb_component_id??void 0};for(let h of n){let m=h._parsedProps;if("left"in m&&"right"in m){let y=c(m.left),g=c(m.right);y&&g&&(a(y),a(g),s(y,g))}else if("top"in m&&"bottom"in m){let y=c(m.top),g=c(m.bottom);y&&g&&(a(y),a(g),s(y,g))}else if("for"in m&&Array.isArray(m.for)){let y=m.for.map(g=>c(g)).filter(g=>!!g);for(let g of y)a(g);for(let g=1;g<y.length;g++)s(y[0],y[g])}}for(let h of Object.keys(r)){let m=o(h);i.has(m)||i.set(m,{componentIds:[],constraints:[]}),i.get(m).componentIds.push(h)}for(let h of n){let m=h._parsedProps,y;if("left"in m?y=c(m.left):"top"in m?y=c(m.top):"for"in m&&(y=c(m.for[0])),!y)continue;let g=o(y);i.get(g)?.constraints.push(h)}let l={},u=Object.fromEntries(t.components.map(h=>[h.componentId,h]));for(let[h,m]of i.entries()){if(m.componentIds.length<=1)continue;let y=new ep,g={},x=(k,z)=>{let B=`${k}_${z}`;return g[B]||(g[B]=new gs(B)),g[B]},v=m.componentIds[0];y.addConstraint(new Qn(x(v,"x"),zn.Eq,0,fn.required)),y.addConstraint(new Qn(x(v,"y"),zn.Eq,0,fn.required));for(let k of m.constraints){let z=k._parsedProps;if("xDist"in z){let B=c(z.left),j=c(z.right);B&&j&&y.addConstraint(new Qn(new xn(x(j,"x"),[-1,x(B,"x")]),zn.Eq,z.xDist,fn.required))}else if("yDist"in z){let B=c(z.top),j=c(z.bottom);B&&j&&y.addConstraint(new Qn(new xn(x(B,"y"),[-1,x(j,"y")]),zn.Eq,z.yDist,fn.required))}else if("sameX"in z&&Array.isArray(z.for)){let B=z.for.map(j=>c(j)).filter(j=>!!j);if(B.length>1){let j=x(B[0],"x");for(let q=1;q<B.length;q++)y.addConstraint(new Qn(new xn(x(B[q],"x"),[-1,j]),zn.Eq,0,fn.required))}}else if("sameY"in z&&Array.isArray(z.for)){let B=z.for.map(j=>c(j)).filter(j=>!!j);if(B.length>1){let j=x(B[0],"y");for(let q=1;q<B.length;q++)y.addConstraint(new Qn(new xn(x(B[q],"y"),[-1,j]),zn.Eq,0,fn.required))}}}y.updateVariables();let w={};for(let k of m.componentIds)w[k]={x:x(k,"x").value(),y:x(k,"y").value()};let P=1/0,N=1/0,E=-1/0,R=-1/0;for(let k of m.componentIds){let z=u[k],B=w[k];if(z)for(let j of z.pads){let q=B.x+j.offset.x,G=B.y+j.offset.y;P=Math.min(P,q-j.size.x/2),E=Math.max(E,q+j.size.x/2),N=Math.min(N,G-j.size.y/2),R=Math.max(R,G+j.size.y/2)}}let I={x:(P+E)/2,y:(N+R)/2},A=[],M={};for(let k of m.componentIds){let z=u[k],B=w[k];if(z){M[k]={x:B.x-I.x,y:B.y-I.y};for(let j of z.pads)A.push({padId:j.padId,networkId:j.networkId,type:j.type,size:j.size,offset:{x:B.x+j.offset.x-I.x,y:B.y+j.offset.y-I.y}})}}t.components=t.components.filter(k=>!m.componentIds.includes(k.componentId)),t.components.push({componentId:m.componentIds[0],pads:A,availableRotationDegrees:[0]}),m.relativeCenters=M,l[m.componentIds[0]]=m}return l},_f=(e,t,n)=>{if(t===n)return!0;let i=e.source_group.get(t);return!i||!i.parent_source_group_id?!1:_f(e,i.parent_source_group_id,n)},E2t=(e,t,n)=>{let{db:i}=e.root;for(let r of t.components){let{center:o,componentId:s,ccwRotationOffset:a,ccwRotationDegrees:c}=r,l=n[s];if(l){let w=(c??a??0)*Math.PI/180;for(let P of l.componentIds){let N=l.relativeCenters[P];if(!N)continue;let E={x:N.x*Math.cos(w)-N.y*Math.sin(w),y:N.x*Math.sin(w)+N.y*Math.cos(w)},R=i.pcb_component.get(P);if(!R)continue;let I=R.center,A=Hn(e._computePcbGlobalTransformBeforeLayout(),dn(o.x+E.x,o.y+E.y),ma(w),dn(-I.x,-I.y)),M=i.toArray().filter(k=>"pcb_component_id"in k&&k.pcb_component_id===P);op(M,A)}continue}let u=i.pcb_component.get(s);if(u){let v=e.source_group_id,P=i.source_component.get(u.source_component_id)?.source_group_id;if(P!==void 0&&!_f(i,P,v))continue;let N=u.center,E=c??a??0,R=Hn(e._computePcbGlobalTransformBeforeLayout(),dn(o.x,o.y),ma(E*Math.PI/180),dn(-N.x,-N.y)),I=i.toArray().filter(A=>"pcb_component_id"in A&&A.pcb_component_id===s);op(I,R);continue}let h=i.pcb_group.list().find(v=>v.source_group_id===s);if(!h)continue;let m=h.center,y=c??a??0,g=Hn(e._computePcbGlobalTransformBeforeLayout(),dn(o.x,o.y),ma(y*Math.PI/180),dn(-m.x,-m.y)),x=i.toArray().filter(v=>{if("source_group_id"in v&&v.source_group_id&&(v.source_group_id===s||_f(i,v.source_group_id,s)))return!0;if("source_component_id"in v&&v.source_component_id){let w=i.source_component.get(v.source_component_id);if(w?.source_group_id&&(w.source_group_id===s||_f(i,w.source_group_id,s)))return!0}if("pcb_component_id"in v&&v.pcb_component_id){let w=i.pcb_component.get(v.pcb_component_id);if(w?.source_component_id){let P=i.source_component.get(w.source_component_id);if(P?.source_group_id&&(P.source_group_id===s||_f(i,P.source_group_id,s)))return!0}}return!1});op(x,g),i.pcb_group.update(h.pcb_group_id,{center:o})}},C2t="1mm",dj=(0,Xj.default)("Group_doInitialPcbLayoutPack"),k2t=e=>{let{db:t}=e.root,{_parsedProps:n}=e,{packOrderStrategy:i,packPlacementStrategy:r,gap:o,pcbGap:s,pcbPackGap:a}=n,c=a??s??o,l=D.parse(c??C2t),u={},h=x=>{if(x?.pcb_component_id&&x?._parsedProps){let v=x._parsedProps,w=D.parse(v.pcbMarginLeft??v.pcbMarginX??0),P=D.parse(v.pcbMarginRight??v.pcbMarginX??0),N=D.parse(v.pcbMarginTop??v.pcbMarginY??0),E=D.parse(v.pcbMarginBottom??v.pcbMarginY??0);(w||P||N||E)&&(u[x.pcb_component_id]={left:w,right:P,top:N,bottom:E})}x?.children&&x.children.forEach(h)};h(e);let m={...z$(L$(t.toArray(),{source_group_id:e.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:u})),orderStrategy:i??"largest_to_smallest",placementStrategy:r??"minimum_sum_squared_distance_to_network",minGap:l},y=M2t(e,m);dj.enabled&&(e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${e.name}`,content:JSON.stringify(t.toArray())}),e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${e.name}`,content:m}));let g=Ug(m);if(dj.enabled){let x=W4(g);x.title=`packOutput-${e.name}`,global.debugGraphics?.push(x)}E2t(e,g,y)},A2t=e=>{let{db:t}=e.root,{_parsedProps:n}=e,i=e.children.filter(R=>R.pcb_component_id||R.pcb_group_id);if(i.some(R=>{let I=R._parsedProps;return I?.pcbX!==void 0||I?.pcbY!==void 0}))return;let o=n.pcbJustifyContent??n.justifyContent,s=n.pcbAlignItems??n.alignItems,a=n.pcbFlexGap??n.pcbGap??n.gap,c=n.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"}[o??"space-between"],u={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[s??"center"];if(!l)throw new Error(`Invalid justifyContent value: "${o}"`);if(!u)throw new Error(`Invalid alignItems value: "${s}"`);let h=0,m=0;typeof a=="object"?(h=a.y??0,m=a.x??0):typeof a=="number"?(h=a,m=a):typeof a=="string"&&(h=D.parse(a),m=D.parse(a));let y,g=n.width??n.pcbWidth??void 0,x=n.height??n.pcbHeight??void 0;(g===void 0||x===void 0)&&(y=K_(i.map(R=>R._getMinimumFlexContainerSize()).filter(R=>R!==null),{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:m}),g=y.width,x=y.height);let w=new Zg(g,x,{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:m});for(let R of i){let I=R._getMinimumFlexContainerSize();w.addChild({metadata:R,width:I?.width??0,height:I?.height??0,flexBasis:I?c==="row"?I.width:I.height:void 0})}w.build();let P={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let R of w.children)P.minX=Math.min(P.minX,R.position.x),P.minY=Math.min(P.minY,R.position.y),P.maxX=Math.max(P.maxX,R.position.x+R.size.width),P.maxY=Math.max(P.maxY,R.position.y+R.size.height);P.width=P.maxX-P.minX,P.height=P.maxY-P.minY;let N=e._getGlobalPcbPositionBeforeLayout(),E={x:N.x-(P.maxX+P.minX)/2,y:N.y-(P.maxY+P.minY)/2};for(let R of w.children)R.metadata._repositionOnPcb({x:R.position.x+R.size.width/2+E.x,y:R.position.y+R.size.height/2+E.y});t.pcb_group.update(e.pcb_group_id,{width:P.width,height:P.height,center:N})};function N2t(e){let{db:t}=e.root,n=new Map,i=new Map,r=new Set,s=e.selectAll("trace").filter(z=>z._parsedProps?.schDisplayLabel),a=e.selectAll("group"),c=[e.schematic_group_id,...a.map(z=>z.schematic_group_id)],l=t.schematic_component.list().filter(z=>c.includes(z.schematic_group_id)),u=[],h=new Map,m=new Map;for(let z of l){let B=z.schematic_component_id,j=[],q=t.source_component.getWhere({source_component_id:z.source_component_id}),G=t.schematic_port.list({schematic_component_id:z.schematic_component_id});for(let K of G){let tt=`${q?.name??z.schematic_component_id}.${K.pin_number}`;h.set(tt,K.schematic_port_id),m.set(K.schematic_port_id,tt)}for(let K of G){let tt=m.get(K.schematic_port_id);j.push({pinId:tt,x:K.center.x,y:K.center.y})}u.push({chipId:B,center:z.center,width:z.size.width,height:z.size.height,pins:j})}let y=new Set,g=new Map,x=new Map,v=new Map;for(let z of l){let B=t.schematic_port.list({schematic_component_id:z.schematic_component_id});for(let j of B)y.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 w=new Set;e.subcircuit_id&&w.add(e.subcircuit_id);for(let z of a)z.subcircuit_id&&w.add(z.subcircuit_id);let N=t.source_trace.list().filter(z=>{if(z.subcircuit_id===e.subcircuit_id)return!0;for(let B of z.connected_source_port_ids)if(x.has(B))return!0;return!1}).flatMap(z=>z.connected_source_net_ids);for(let z of N){let B=t.source_net.get(z);B?.subcircuit_id&&w.add(B.subcircuit_id)}let E=[],R=new Map;for(let z of t.source_trace.list()){if(z.subcircuit_id&&!w.has(z.subcircuit_id))continue;let B=(z.connected_source_port_ids??[]).map(j=>x.get(j)).filter(j=>!!j&&y.has(j));if(B.length>=2){let[j,q]=B.slice(0,2),G=[j,q].sort().join("::");if(!R.has(G)){R.set(G,z.source_trace_id);let K=z.display_name??z.source_trace_id;z.subcircuit_connectivity_map_key&&(r.add(z.subcircuit_connectivity_map_key),v.set(K,z.subcircuit_connectivity_map_key),i.set(z.subcircuit_connectivity_map_key,K)),E.push({pinIds:[j,q].map(tt=>m.get(tt)),netId:K})}}}let I=[];for(let z of t.source_net.list().filter(B=>!B.subcircuit_id||w.has(B.subcircuit_id)))z.subcircuit_connectivity_map_key&&(r.add(z.subcircuit_connectivity_map_key),n.set(z.subcircuit_connectivity_map_key,z));let A=new Map;for(let[z,B]of g){let j=t.source_port.get(B);if(!j?.subcircuit_connectivity_map_key)continue;let q=j.subcircuit_connectivity_map_key;r.add(q),A.has(q)||A.set(q,[]),A.get(q).push(z)}for(let[z,B]of A){let j=n.get(z);if(j&&B.length>=2){let q=String(j.name||j.source_net_id||z);v.set(q,z),i.set(z,q);let K=.1*(.18/.18),tt=Number((String(q).length*K).toFixed(2));I.push({netId:q,pinIds:B.map(J=>m.get(J)),netLabelWidth:tt})}}let M=(()=>{let z={},B=new Set(I.map(j=>j.netId));for(let j of t.source_net.list().filter(q=>!q.subcircuit_id||w.has(q.subcircuit_id)))j.name&&B.has(j.name)&&(j.is_ground||j.name.toLowerCase().startsWith("gnd")?z[j.name]=["y-"]:j.is_power||j.name.toLowerCase().startsWith("v")?z[j.name]=["y+"]:z[j.name]=["x-","x+"]);return z})();return{inputProblem:{chips:u,directConnections:E,netConnections:I,availableNetLabelOrientations:M,maxMspPairDistance:e._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:h,pairKeyToSourceTraceId:R,sckToSourceNet:n,sckToUserNetId:i,userNetIdToSck:v,allSourceAndSchematicPortIdsInScope:y,schPortIdToSourcePortId:g,displayLabelTraces:s,allScks:r}}var zi=1e-6;function fj(e){let t=Math.abs(e.to.x-e.from.x),n=Math.abs(e.to.y-e.from.y);return t>=n}function xx(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function mj(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function yj(e,t,n){let i=xx(e,t);if(i<zi)return 0;let r=((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/((t.x-e.x)*(t.x-e.x)+(t.y-e.y)*(t.y-e.y));return Math.max(0,Math.min(1,r))*i}function ux(e,t,n,i){return e*i-t*n}function R2t(e,t,n,i){let r={x:t.x-e.x,y:t.y-e.y},o={x:i.x-n.x,y:i.y-n.y},s=ux(r.x,r.y,o.x,o.y),a={x:n.x-e.x,y:n.y-e.y},c=ux(a.x,a.y,r.x,r.y);if(Math.abs(s)<zi&&Math.abs(c)<zi||Math.abs(s)<zi&&Math.abs(c)>=zi)return null;let l=ux(a.x,a.y,o.x,o.y)/s,u=ux(a.x,a.y,r.x,r.y)/s;return l<-zi||l>1+zi||u<-zi||u>1+zi?null:{x:e.x+l*r.x,y:e.y+l*r.y}}function O2t(e,t=zi){if(e.length===0)return e;e.sort((r,o)=>r.start-o.start);let n=[],i={...e[0]};for(let r=1;r<e.length;r++){let o=e[r];o.start<=i.end+t?i.end=Math.max(i.end,o.end):(n.push(i),i={...o})}return n.push(i),n}function L2t(e,t,n){let i=xx(e.from,e.to);if(i<zi||t.length===0)return[e];let r=n/2,o=t.map(h=>({start:Math.max(0,h-r),end:Math.min(i,h+r)})).filter(h=>h.end-h.start>zi),s=O2t(o),a=[],c=0,l={x:e.to.x-e.from.x,y:e.to.y-e.from.y},u=(h,m,y)=>{if(m-h<=zi)return;let g=h/i,x=m/i;a.push({from:mj(e.from,e.to,g),to:mj(e.from,e.to,x),...y?{is_crossing:!0}:{}})};for(let h of s)h.start-c>zi&&u(c,h.start,!1),u(h.start,h.end,!0),c=h.end;return i-c>zi&&u(c,i,!1),a.length>0?a:[e]}function z2t(e,t={}){let n=t.crossSegmentLength??.075,i=t.tolerance??zi,r=new Map,o=c=>`${c.traceIdx}:${c.edgeIdx}`,s=c=>e[c.traceIdx].edges[c.edgeIdx];for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=l.edges[u];for(let m=c;m<e.length;m++){let y=e[m];for(let g=m===c?u+1:0;g<y.edges.length;g++){let x=y.edges[g],v=R2t(h.from,h.to,x.from,x.to);if(!v)continue;let w=xx(h.from,h.to),P=xx(x.from,x.to);if(w<i||P<i)continue;let N=yj(h.from,h.to,v),E=yj(x.from,x.to,v),R=N<=i||Math.abs(w-N)<=i||Number.isNaN(N),I=E<=i||Math.abs(P-E)<=i||Number.isNaN(E);if(!R&&!I){let A=fj(h),M=fj(x),k;if(A!==M)k=A;else{let j=Math.abs(h.to.x-h.from.x),q=Math.abs(h.to.y-h.from.y),G=Math.abs(x.to.x-x.from.x),K=Math.abs(x.to.y-x.from.y),tt=j-q,J=G-K;k=tt===J?!0:tt>J}let z=o({traceIdx:k?c:m,edgeIdx:k?u:g}),B=r.get(z)??[];B.push(k?N:E),r.set(z,B)}}}}}let a=e.map(c=>({source_trace_id:c.source_trace_id,edges:[]}));for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=o({traceIdx:c,edgeIdx:u}),m=r.get(h)??[];if(m.length===0){a[c].edges.push(l.edges[u]);continue}let y=Array.from(new Set(m.map(x=>Number(x.toFixed(6))))).sort((x,v)=>x-v),g=L2t(l.edges[u],y,n);a[c].edges.push(...g)}}return a}var Do=1e-6;function bx(e,t,n=Do){return Math.abs(e-t)<=n}function Xp(e,t,n=Do){return bx(e.x,t.x,n)&&bx(e.y,t.y,n)}function _j(e,t,n,i=Do){let r=Math.min(t.x,n.x)-i,o=Math.max(t.x,n.x)+i,s=Math.min(t.y,n.y)-i,a=Math.max(t.y,n.y)+i;return e.x<r||e.x>o||e.y<s||e.y>a?!1:Math.abs((n.x-t.x)*(e.y-t.y)-(n.y-t.y)*(e.x-t.x))<=i}function gj(e,t=Do){let n=new Map;for(let i of e){let r=`${i.x.toFixed(6)},${i.y.toFixed(6)}`;n.has(r)||n.set(r,i)}return Array.from(n.values())}function xj(e){return{x:e.to.x-e.from.x,y:e.to.y-e.from.y}}function IT(e,t,n=Do){let i=xj(e),r=xj(t),o=Math.hypot(i.x,i.y),s=Math.hypot(r.x,r.y);if(o<n||s<n)return!0;let a=i.x*r.y-i.y*r.x;return Math.abs(a)<=n*o*s}function gf(e,t,n=Do){return e.edges.filter(i=>Xp(i.from,t,n)||Xp(i.to,t,n))}function bj(e,t,n=Do){for(let i of e.edges){if(Xp(i.from,t,n))return i.from;if(Xp(i.to,t,n))return i.to}return null}function F2t(e,t,n=Do){let i=Xp(e.from,t,n)||bx(e.from.x,t.x,n)&&bx(e.from.y,t.y,n)?e.to:e.from,r=i.x-t.x,o=i.y-t.y;return Math.abs(r)<n&&Math.abs(o)<n?null:Math.abs(r)>=Math.abs(o)?r>=0?"right":"left":o>=0?"up":"down"}function $p(e,t,n=Do){let i=gf(e,t,n);if(i.length<2)return null;let r=i.map(h=>F2t(h,t,n)),o=r.includes("up"),s=r.includes("down"),a=r.includes("left"),c=r.includes("right"),l=o?"up":s?"down":null,u=c?"right":a?"left":null;return l&&u?`${l}-${u}`:null}function D2t(e,t={}){let n=t.tolerance??Do,i={};for(let o of e)i[o.source_trace_id]=[];let r=e.map(o=>{let s=[];for(let a of o.edges)s.push(a.from,a.to);return gj(s,n)});for(let o=0;o<e.length;o++){let s=e[o],a=r[o];for(let c=o+1;c<e.length;c++){let l=e[c],u=r[c];for(let h of a)for(let m of u)if(Xp(h,m,n)){let y=gf(s,h,n),g=gf(l,m,n),x=y.some(N=>g.some(E=>!IT(N,E,n))),v=$p(s,h,n),w=$p(l,m,n);x&&!(v!==null&&w!==null&&v===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(m))}for(let h of a)for(let m of l.edges)if(_j(h,m.from,m.to,n)){let g=gf(s,h,n).some(N=>!IT(N,m,n)),x=$p(s,h,n),v=bj(l,h,n*1e3),w=v?$p(l,v,n):null;g&&!(x!==null&&w!==null&&x===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(h))}for(let h of u)for(let m of s.edges)if(_j(h,m.from,m.to,n)){let g=gf(l,h,n).some(N=>!IT(m,N,n)),x=$p(l,h,n),v=bj(s,h,n*1e3),w=v?$p(s,v,n):null;g&&!(w!==null&&x!==null&&w===x)&&(i[l.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[s.source_trace_id].push(h))}}}for(let o of Object.keys(i))i[o]=gj(i[o],n);return i}var MT=(0,Hj.default)("Group_doInitialSchematicTraceRender");function $2t(e){let{group:t,solver:n,pinIdToSchematicPortId:i,userNetIdToSck:r}=e,{db:o}=t.root,s=n.traceOverlapShiftSolver?.correctedTraceMap,a=[];MT(`Traces inside SchematicTraceSolver output: ${Object.values(s??{}).length}`);for(let u of Object.values(s??{})){let h=u?.tracePath;if(!Array.isArray(h)||h.length<2){MT(`Skipping trace ${u?.pinIds.join(",")} because it has less than 2 points`);continue}let m=[];for(let x=0;x<h.length-1;x++)m.push({from:{x:h[x].x,y:h[x].y},to:{x:h[x+1].x,y:h[x+1].y}});let y=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 w of[x,v])o.schematic_port.get(w)&&o.schematic_port.update(w,{is_connected:!0});g=r.get(String(u.userNetId))}}y||(y=`solver_${u?.mspPairId}`,g=r.get(String(u.userNetId))),a.push({source_trace_id:y,edges:m,subcircuit_connectivity_map_key:g})}MT(`Applying ${a.length} traces from SchematicTraceSolver output`);let c=z2t(a.map(u=>({source_trace_id:u.source_trace_id,edges:u.edges}))),l=D2t(c);for(let u of c)o.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 B2t=e=>{switch(e){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"}},j2t=e=>{for(let n of e){let i=n._getDirectlyConnectedTraces();for(let r of i){let o=r._parsedProps.schDisplayLabel;if(o)return{name:o,wasAssignedDisplayLabel:!0}}}return{name:e.map(n=>n._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},ET=(0,Gj.default)("Group_doInitialSchematicTraceRender");function Y2t(e){let{group:t,solver:n,sckToSourceNet:i,allScks:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,userNetIdToSck:a,pinIdToSchematicPortId:c,schematicPortIdsWithPreExistingNetLabels:l,schematicPortIdsWithRoutedTraces:u}=e,{db:h}=t.root,m=n.netLabelPlacementSolver?.netLabelPlacements??[],y=n.mspConnectionPairSolver.globalConnMap;for(let g of m){ET(`processing placement: ${g.netId}`);let x=y.getIdsConnectedToNet(g.globalConnNetId).find(z=>a.get(z)),v=a.get(x),w=g.anchorPoint,P=g.orientation,N=B2t(P),E=v?i.get(v):void 0,R=g.pinIds.map(z=>c.get(z));if(R.some(z=>l.has(z))){ET(`skipping net label placement for "${g.netId}" REASON:schematic port has pre-existing net label`);continue}if(E){let z=E.name,B=Xa({anchor_position:w,anchor_side:N,text:z});h.schematic_net_label.insert({text:z,anchor_position:w,center:B,anchor_side:N,...E?.source_net_id?{source_net_id:E.source_net_id}:{}});continue}let I=t.selectAll("port").filter(z=>z._getSubcircuitConnectivityKey()===v),{name:A,wasAssignedDisplayLabel:M}=j2t(I);if(!M&&R.some(z=>u.has(z))){ET(`skipping net label placement for "${g.netId}" REASON:schematic port has routed traces and no display label`);continue}let k=Xa({anchor_position:w,anchor_side:N,text:A});h.schematic_net_label.insert({text:A,anchor_position:w,center:k,anchor_side:N})}}var X2t=({allSourceAndSchematicPortIdsInScope:e,group:t,schPortIdToSourcePortId:n,sckToSourceNet:i,pinIdToSchematicPortId:r,schematicPortIdsWithPreExistingNetLabels:o})=>{let{db:s}=t.root;for(let a of Array.from(e)){let c=s.schematic_port.get(a);if(!c||c.is_connected)continue;let l=n.get(a);if(!l)continue;let h=s.source_port.get(l)?.subcircuit_connectivity_map_key;if(!h)continue;let m=i.get(h);if(!m||s.schematic_net_label.list().some(w=>Math.abs(w.anchor_position.x-c.center.x)<.1&&Math.abs(w.anchor_position.y-c.center.y)<.1?m.source_net_id&&w.source_net_id?w.source_net_id===m.source_net_id:w.text===(m.name||h):!1))continue;let g=m.name||m.source_net_id||h,x=vf(c.facing_direction||"right")||"right",v=Xa({anchor_position:c.center,anchor_side:x,text:g});s.schematic_net_label.insert({text:g,anchor_position:c.center,center:v,anchor_side:x,...m.source_net_id?{source_net_id:m.source_net_id}:{}})}},V2t=e=>{let t=new Set,n=e.selectAll("netlabel");for(let i of n){let r=i._getConnectedPorts();for(let o of r)o.schematic_port_id&&t.add(o.schematic_port_id)}return t},H2t=({solver:e,pinIdToSchematicPortId:t})=>{let n=e.schematicTraceLinesSolver.solvedTracePaths,i=new Set;for(let r of n)for(let o of r.pinIds){let s=t.get(o);s&&i.add(s)}return i},G2t=(0,Vj.default)("Group_doInitialSchematicTraceRender"),U2t=e=>{if(!e.root?._featureMspSchematicTraceRouting||!e.isSubcircuit||e.root?.schematicDisabled)return;let{inputProblem:t,pinIdToSchematicPortId:n,pairKeyToSourceTraceId:i,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,displayLabelTraces:a,allScks:c,userNetIdToSck:l}=N2t(e),u=V2t(e);G2t.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(t,null,2)});let h=new aB(t);h.solve();let m=H2t({solver:h,pinIdToSchematicPortId:n});$2t({group:e,solver:h,pinIdToSchematicPortId:n,userNetIdToSck:l}),Y2t({group:e,solver:h,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,pinIdToSchematicPortId:n,allScks:c,userNetIdToSck:l,schematicPortIdsWithPreExistingNetLabels:u,schematicPortIdsWithRoutedTraces:m}),X2t({group:e,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,sckToSourceNet:r,pinIdToSchematicPortId:n,schematicPortIdsWithPreExistingNetLabels:u})},Vp=class extends Pn{constructor(){super(...arguments);T(this,"pcb_group_id",null);T(this,"schematic_group_id",null);T(this,"subcircuit_id",null);T(this,"_hasStartedAsyncAutorouting",!1);T(this,"_asyncAutoroutingResult",null);T(this,"unnamedElementCounter",{})}get config(){return{zodProps:FO,componentName:"Group"}}doInitialSourceGroupRender(){let{db:t}=this.root,n=t.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit});this.source_group_id=n.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${n.source_group_id}`,t.source_group.update(n.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:t}=this.root;for(let n of this.children)t.source_component.update(n.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:t}=this.root,n=this.parent?.getGroup?.();if(n?.source_group_id&&t.source_group.update(this.source_group_id,{parent_source_group_id:n.source_group_id}),!this.isSubcircuit)return;let i=this.parent?.getSubcircuit?.()?.subcircuit_id;i&&t.source_group.update(this.source_group_id,{parent_subcircuit_id:i})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:n.autorouter?{trace_clearance:n.autorouter.traceClearance}:void 0});this.pcb_group_id=i.pcb_group_id;for(let r of this.children)t.pcb_component.update(r.pcb_component_id,{pcb_group_id:i.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this._parsedProps,i=wx(this.children);if(this.pcb_group_id){let r=i.width,o=i.height,s=(i.minX+i.maxX)/2,a=(i.minY+i.maxY)/2;if(this.isSubcircuit){let{padLeft:u,padRight:h,padTop:m,padBottom:y}=this._resolvePcbPadding();r+=u+h,o+=m+y,s+=(h-u)/2,a+=(m-y)/2}let l=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0?t.pcb_group.get(this.pcb_group_id)?.center??{x:s,y:a}:{x:s,y:a};t.pcb_group.update(this.pcb_group_id,{width:Number(n.width??r),height:Number(n.height??o),center:l})}}getNextAvailableName(t){var n,i;return(n=this.unnamedElementCounter)[i=t.lowercaseComponentName]??(n[i]=1),`unnamed_${t.lowercaseComponentName}${this.unnamedElementCounter[t.lowercaseComponentName]++}`}_resolvePcbPadding(){let t=this._parsedProps,n=t.pcbLayout,i=h=>{let m=n?.[h],y=t[h];if(typeof m=="number")return m;if(typeof y=="number")return y},r=i("padding")??0,o=i("paddingX"),s=i("paddingY"),a=i("paddingLeft")??o??r,c=i("paddingRight")??o??r,l=i("paddingTop")??s??r,u=i("paddingBottom")??s??r;return{padLeft:a,padRight:c,padTop:l,padBottom:u}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:t}=this,{db:n}=this.root,i=t;if(!this.isSubcircuit)return;let r=i.manualEdits?.manual_trace_hints;if(r)for(let o of r)this.add(new GT({for:o.pcb_port_selector,offsets:o.offsets}))}doInitialSourceAddConnectivityMapKey(){d2t(this)}_areChildSubcircuitsRouted(){let t=this.selectAll("group").filter(n=>n.isSubcircuit);for(let n of t)if(n._shouldRouteAsync()&&!n._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let t=this._getAutorouterConfig();return t.groupMode==="sequential-trace"?!1:!!(t.local&&t.groupMode==="subcircuit"||!t.local)}_hasTracesToRoute(){let t=(0,Bp.default)("tscircuit:core:_hasTracesToRoute"),n=this.selectAll("trace");return t(`[${this.getString()}] has ${n.length} traces to route`),n.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:t}=this.root,n=(0,Bp.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),i=this._parsedProps,r=this._getAutorouterConfig(),o=r.serverUrl,s=r.serverMode,a=(u,h)=>(n("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(s==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:h}=await a(`${o}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:LT({db:t,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(m=>m.json());this._asyncAutoroutingResult=h,this._markDirty("PcbTraceRender");return}let{autorouting_result:u}=await a(`${o}/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(`${o}/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(`${o}/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(`${o}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(m=>m.json());this._asyncAutoroutingResult={output_pcb_traces:h.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(u.has_error){let h=new yf(`Autorouting job failed: ${JSON.stringify(u.error)}`);throw t.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:t}=this.root,n=this._parsedProps,i=(0,Bp.default)("tscircuit:core:_runLocalAutorouting");i(`[${this.getString()}] starting local autorouting`);let r=this._getAutorouterConfig(),{simpleRouteJson:o}=LT({db:t,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(i.enabled){let c=O5(o);c.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(c)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:o});let s;r.algorithmFn?s=await r.algorithmFn(o):s=new r2t(o,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity});let a=new Promise((c,l)=>{s.on("complete",u=>{i(`[${this.getString()}] local autorouting complete`),c(u.traces)}),s.on("error",u=>{i(`[${this.getString()}] local autorouting error: ${u.error.message}`),l(u.error)})});s.on("progress",c=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...c})}),s.start();try{let c=await a;this._asyncAutoroutingResult={output_pcb_traces:c},this._markDirty("PcbTraceRender")}catch(c){let{db:l}=this.root;throw l.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:c instanceof Error?c.message:String(c)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:c instanceof Error?c.message:String(c)},simpleRouteJson:o}),c}finally{s.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 t=(0,Bp.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){t(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}t(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){U2t(this)}updatePcbTraceRender(){let t=(0,Bp.default)("tscircuit:core:updatePcbTraceRender");if(t(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(t(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:n}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){t(`[${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){t(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:t}=this.root,{traces:n}=this._asyncAutoroutingResult.output_simple_route_json;if(n)for(let i of n){let r=t.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:t}=this._asyncAutoroutingResult;if(!t)return;let{db:n}=this.root;for(let i of t)if(i.type==="pcb_trace"){if(i.subcircuit_id=this.subcircuit_id,i.connection_name){let r=i.connection_name;i.source_trace_id=r}n.pcb_trace.insert(i)}for(let i of t)if(i.type!=="pcb_via"&&i.type==="pcb_trace")for(let r of i.route)r.route_type==="via"&&n.pcb_via.insert({pcb_trace_id:i.pcb_trace_id,x:r.x,y:r.y,hole_diameter:.3,outer_diameter:.6,layers:[r.from_layer,r.to_layer],from_layer:r.from_layer,to_layer:r.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.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&&t.schematic_component.update(r.schematic_component_id,{schematic_group_id:i.schematic_group_id})}_getSchematicLayoutMode(){let t=this._parsedProps;if(t.schLayout?.layoutMode==="none"||t.schLayout?.layoutMode==="relative")return"relative";if(t.schLayout?.matchAdapt)return"match-adapt";if(t.schLayout?.flex)return"flex";if(t.schLayout?.grid)return"grid";if(t.schMatchAdapt)return"match-adapt";if(t.schFlex)return"flex";if(t.schGrid)return"grid";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";if(t.relative||t.schRelative)return"relative";let n=this.children.some(r=>{let o=r._parsedProps;return o?.schX!==void 0||o?.schY!==void 0}),i=(t.manualEdits?.schematic_placements?.length??0)>0;return!n&&!i?"match-adapt":"relative"}doInitialSchematicLayout(){let t=this._getSchematicLayoutMode();t==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),t==="grid"&&this._doInitialSchematicLayoutGrid(),t==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){u2t(this)}_doInitialSchematicLayoutMatchpack(){h2t(this)}_doInitialSchematicLayoutGrid(){f2t(this)}_doInitialSchematicLayoutFlex(){m2t(this)}_getPcbLayoutMode(){let t=this._parsedProps;if(t.pcbRelative)return"none";if(t.pcbLayout?.matchAdapt)return"match-adapt";if(t.pcbLayout?.flex)return"flex";if(t.pcbLayout?.grid)return"grid";if(t.pcbLayout?.pack)return"pack";if(t.pcbFlex)return"flex";if(t.pcbGrid)return"grid";if(t.pcbPack||t.pack)return"pack";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";let n=t.pcbX!==void 0||t.pcbY!==void 0,i=(t.manualEdits?.pcb_placements?.length??0)>0;if(this.children.some(s=>{let a=s._parsedProps;return a?.pcbX!==void 0||a?.pcbY!==void 0}))return"none";let o=this.children.reduce((s,a)=>{let c=a._parsedProps,l=c?.pcbX!==void 0||c?.pcbY!==void 0;return s+(l?0:1)},0);return!n&&!i&&o>1?"pack":"none"}doInitialPcbLayout(){let t=this._getPcbLayoutMode();t==="grid"?this._doInitialPcbLayoutGrid():t==="pack"?this._doInitialPcbLayoutPack():t==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){y2t(this)}_doInitialPcbLayoutPack(){k2t(this)}_doInitialPcbLayoutFlex(){A2t(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._parsedProps;if(!n.border)return;let i=typeof n.schWidth=="number"?n.schWidth:void 0,r=typeof n.schHeight=="number"?n.schHeight:void 0,o=typeof n.schPadding=="number"?n.schPadding:0,s=typeof n.schPaddingLeft=="number"?n.schPaddingLeft:o,a=typeof n.schPaddingRight=="number"?n.schPaddingRight:o,c=typeof n.schPaddingTop=="number"?n.schPaddingTop:o,l=typeof n.schPaddingBottom=="number"?n.schPaddingBottom:o,u=this.schematic_group_id?t.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(),m=h.x-i/2-s,y=h.y-r/2-l,g=i+s+a,x=r+c+l;t.schematic_box.insert({width:g,height:x,x:m,y,is_dashed:n.border?.dashed??!1})}_determineSideFromPosition(t,n){if(!t.center||!n.center)return"left";let i=t.center.x-n.center.x,r=t.center.y-n.center.y;return Math.abs(i)>Math.abs(r)?i>0?"right":"left":r>0?"bottom":"top"}_calculateSchematicBounds(t){if(t.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let a of t)n=Math.min(n,a.centerX),i=Math.max(i,a.centerX),r=Math.min(r,a.centerY),o=Math.max(o,a.centerY);let s=2;return{minX:n-s,maxX:i+s,minY:r-s,maxY:o+s}}_getAutorouterConfig(){let t=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return I2t(t)}_getSubcircuitLayerCount(){let t=this.getInheritedProperty("layers");return typeof t=="number"?t:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(this.isSubcircuit){let n=new Map;for(let i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){let r=n.get(i._parsedProps.name)||[];r.push(i),n.set(i._parsedProps.name,r)}for(let[i,r]of n.entries())r.length>1&&t.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(o=>o.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:t}=this.root,n=t;for(let i of n.schematic_net_label.list()){let r=n.source_net.get(i.source_net_id),o=i.text||r?.name||"";if(i.anchor_side==="top"&&/^gnd/i.test(o)){n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_down"});continue}i.anchor_side==="bottom"&&/^v/i.test(o)&&n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_up"})}}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(t){return super._repositionOnPcb(t)}},vj=(e,t,n)=>{let i=Math.min(n,e/2,t/2),r=Math.max(1,Math.ceil(Math.PI/2*i)),o=Math.PI/2/r,s=e/2,a=t/2,c=[];c.push({x:-s+i,y:-a}),c.push({x:s-i,y:-a});for(let l=1;l<=r;l++){let u=-Math.PI/2+l*o;c.push({x:s-i+i*Math.cos(u),y:-a+i+i*Math.sin(u)})}c.push({x:s,y:a-i});for(let l=1;l<=r;l++){let u=0+l*o;c.push({x:s-i+i*Math.cos(u),y:a-i+i*Math.sin(u)})}c.push({x:-s+i,y:a});for(let l=1;l<=r;l++){let u=Math.PI/2+l*o;c.push({x:-s+i+i*Math.cos(u),y:a-i+i*Math.sin(u)})}c.push({x:-s,y:-a+i});for(let l=1;l<=r;l++){let u=Math.PI+l*o;c.push({x:-s+i+i*Math.cos(u),y:-a+i+i*Math.sin(u)})}return c},Uj=class extends Vp{constructor(){super(...arguments);T(this,"pcb_board_id",null);T(this,"_drcChecksComplete",!1);T(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:r5}}get boardThickness(){let{_parsedProps:t}=this;return 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:t}=this.root,{_parsedProps:n}=this;if(n.width&&n.height)return;let i=1/0,r=1/0,o=-1/0,s=-1/0,a=Bj(t,this.subcircuit_id),c=new Set([this.subcircuit_id,...a]),l=t.pcb_component.list().filter(R=>R.subcircuit_id&&c.has(R.subcircuit_id)),u=t.pcb_group.list().filter(R=>R.subcircuit_id&&c.has(R.subcircuit_id)),h=!1,m=(R,I,A)=>{I===0||A===0||(h=!0,i=Math.min(i,R.x-I/2),r=Math.min(r,R.y-A/2),o=Math.max(o,R.x+I/2),s=Math.max(s,R.y+A/2))};for(let R of l)m(R.center,R.width,R.height);for(let R of u)m(R.center,R.width,R.height);let y=2,g=h?o-i+y*2:0,x=h?s-r+y*2:0,v={x:h?(i+o)/2+(n.outlineOffsetX??0):n.outlineOffsetX??0,y:h?(r+s)/2+(n.outlineOffsetY??0):n.outlineOffsetY??0},w=n.width??g,P=n.height??x,N=n.outline;!N&&n.borderRadius!=null&&w>0&&P>0&&(N=vj(w,P,n.borderRadius));let E={width:w,height:P,center:v};N&&(E.outline=N.map(R=>({x:R.x+(n.outlineOffsetX??0),y:R.y+(n.outlineOffsetY??0)}))),t.pcb_board.update(this.pcb_board_id,E)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let t=this.root?.platform;if(!t?.printBoardInformationToSilkscreen)return;let n=this.root.db.pcb_board.get(this.pcb_board_id);if(!n)return;let i=[];if(t.projectName&&i.push(t.projectName),t.version&&i.push(`v${t.version}`),t.url&&i.push(t.url),i.length===0)return;let r=i.join(`
227
- `),a={x:n.center.x+n.width/2-.25,y:n.center.y-n.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})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.width??0,r=n.height??0,o={x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)};if(n.outline){let c=n.outline.map(g=>g.x),l=n.outline.map(g=>g.y),u=Math.min(...c),h=Math.max(...c),m=Math.min(...l),y=Math.max(...l);i=h-u,r=y-m,o={x:(u+h)/2+(n.outlineOffsetX??0),y:(m+y)/2+(n.outlineOffsetY??0)}}let s=n.outline;!s&&n.borderRadius!=null&&i>0&&r>0&&(s=vj(i,r,n.borderRadius));let a=t.pcb_board.insert({center:o,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:r,outline:s?.map(c=>({x:c.x+(n.outlineOffsetX??0),y:c.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=a.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:t}=this.root;this.pcb_board_id&&(t.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return xi()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let n=pB(t.toArray());for(let o of n)t.pcb_trace_error.insert(o);let i=uB(t.toArray());for(let o of i)t.pcb_port_not_connected_error.insert(o);let r=fB(t.toArray());for(let o of r)t.pcb_component_outside_board_error.insert(o)}_emitRenderLifecycleEvent(t,n){super._emitRenderLifecycleEvent(t,n),n==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t})}},q2t=new Proxy({},{get:(e,t)=>t}),Cs=q2t,qj="rgba(132, 0, 0)",Wj=.12,Zj=class extends Pn{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:UO,sourceFtype:Cs.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let t=this.props.capacitance,n=typeof t=="string"?t:`${Un(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${n}/${Un(this._parsedProps.maxVoltageRating)}V`:n}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new uo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new uo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,capacitance:n.capacitance,max_voltage_rating:n.maxVoltageRating,max_decoupling_trace_length:n.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!n.polarized});this.source_component_id=i.source_component_id}},Sx=class extends Pn{constructor(t){super(t);T(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:tp,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);let{_parsedProps:n}=this;if(n.externallyConnectedPins){let i=new Set;for(let[r,o]of n.externallyConnectedPins)i.add(r),i.add(o);for(let r of i)if(!this.children.find(s=>s instanceof Mi&&s.isMatchingAnyOf([r]))){let s=r.match(/^pin(\d+)$/);if(s){let a=parseInt(s[1]);this.add(new Mi({pinNumber:a,aliases:[r]}))}else this.add(new Mi({name:r,aliases:[r]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:t}=this;t?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=i.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:t}=this;if(t.externallyConnectedPins)for(let[n,i]of t.externallyConnectedPins)this.add(new uo({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:t}=this.root,{pinAttributes:n}=this.props;if(!n)return;let i=null,r=null,o,s=this.selectAll("port");for(let h of s)for(let m of h.getNameAndAliases())if(n[m]){let y=n[m];y.providesPower&&(i=h,o=y.providesVoltage),y.providesGround&&(r=h)}if(!i||!r||o===void 0)return;let a=t.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=t.source_port.get(r.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=t.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=t.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||t.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:o})}},Kj=class extends Sx{constructor(e){super(e)}get config(){return{...super.config,componentName:"Pinout",zodProps:DO}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}},Jj=class extends Pn{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"anode",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"cathode",this.portMap.pin2)}get config(){let t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},n=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"diode",componentName:"Diode",zodProps:lL,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},Qj=class extends Pn{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:BO,sourceFtype:Cs.simple_fuse}}_getSchematicSymbolDisplayValue(){let e=this._parsedProps.currentRating,t=this._parsedProps.voltageRating,n=typeof e=="string"?parseFloat(e):e,i=typeof t=="string"?parseFloat(t):t;return`${Un(n)}A / ${Un(i)}V`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=typeof t.currentRating=="string"?parseFloat(t.currentRating):t.currentRating,i=typeof t.voltageRating=="string"?parseFloat(t.voltageRating):t.voltageRating,r=e.source_component.insert({name:this.name,ftype:Cs.simple_fuse,current_rating_amps:n,voltage_rating_volts:i,display_current_rating:`${Un(n)}A`,display_voltage_rating:`${Un(i)}V`});this.source_component_id=r.source_component_id}},tY=class extends Pn{constructor(){super(...arguments);T(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:o5,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=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"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.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=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},eY=class extends Pn{constructor(){super(...arguments);T(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(t){return this.selectOne(`port.${t}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let t=this.children.filter(n=>n.componentName==="Port").map(n=>n.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){let t=this._parsedProps??this.props,n=t.pinCount;if(t.pinCount==null&&!t.footprint&&(n=2),t.pinCount==null){let o=(t.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),s=o.length>0?Math.max(...o):0,a=t.pinLabels?Object.keys(t.pinLabels).length:0,c=Math.max(s,a);(c===2||c===3)&&(n=c),n==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(n=this.getPortsFromFootprint().length)}let i="";n?i+=`solderjumper${n}`:i="solderjumper";let r=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?r=Array.from(new Set(t.bridgedPins.flat().map(o=>this._getPinNumberFromBridgedPinName(o)).filter(o=>o!==null))).sort((o,s)=>o-s):t.bridged&&n&&(r=Array.from({length:n},(o,s)=>s+1)),r.length>0&&(i+=`_bridged${r.join("")}`),{schematicSymbolName:t.symbolName??i,componentName:"SolderJumper",zodProps:$O,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);n==null&&!this._parsedProps.footprint&&(n=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.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=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},nY=class extends Pn{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"anode",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"cathode",this.portMap.pin2)}get config(){let t={laser:"laser_diode"},n=this.props.laser?"laser":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"led",componentName:"Led",zodProps:pL,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}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:n.wavelength,color:n.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},iY=class extends Pn{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"positive",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:SL,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Mi({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Mi({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},W2t=Ln.extend({voltage:Jn.optional(),frequency:so.optional(),peakToPeakVoltage:Jn.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Oe.optional(),dutyCycle:p.number().optional()}),rY=class extends Pn{constructor(){super(...arguments);T(this,"terminal1",this.portMap.terminal1);T(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:W2t,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.portMap.terminal1,r=this.portMap.terminal2;t.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:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle})}},oY=class extends Pn{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:YO,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${Un(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 uo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new uo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new uo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new uo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,resistance:n.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}},Z2t=["leftedge","rightedge","topedge","bottomedge","center"],sY=class extends Ne{get config(){return{componentName:"Constraint",zodProps:WO}}constructor(e){if(super(e),("xdist"in e||"ydist"in e)&&!("edgeToEdge"in e)&&!("centerToCenter"in e))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in e&&e.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let e=[],t=this.getPrimitiveContainer();function n(i){let r=i.split(" ").pop(),o=Z2t.includes(r)?r:void 0,s=o?i.replace(` ${o}`,""):i,a=t.selectOne(s,{pcbPrimitive:!0});a&&e.push({selector:i,component:a,componentSelector:s,edge:o})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},aY=class extends Ne{constructor(){super(...arguments);T(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:mL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=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 o=this._computePcbGlobalTransformBeforeLayout(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_fabrication_note_path.insert({pcb_component_id:s,layer:r,color:i.color,route:i.route.map(c=>{let l=En(o,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:n?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},cY=class extends Ne{get config(){return{componentName:"FabricationNoteText",zodProps:fL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this.getSubcircuit();e.pcb_fabrication_note_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:t.pcbX??0,y:t.pcbY??0},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:"top",color:t.color,text:t.text??"",pcb_component_id:n.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},lY=class extends Vp{constructor(e){super({...e,subcircuit:!0})}},uY=class extends Vp{constructor(e){super({...e,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!this.pcb_group_id)return;let n=e.pcb_group.get(this.pcb_group_id),i=t.paddingLeft??t.padding??0,r=t.paddingRight??t.padding??0,o=t.paddingTop??t.padding??0,s=t.paddingBottom??t.padding??0;e.pcb_group.update(this.pcb_group_id,{width:n.width+i+r,height:n.height+o+s,center:{x:n.center.x+(r-i)/2,y:n.center.y+(o-s)/2}})}},pY=class extends Ne{constructor(){super(...arguments);T(this,"pcb_breakout_point_id",null);T(this,"matchedPort",null);T(this,"matchedNet",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:gL}}_matchConnection(){let{connection:t}=this._parsedProps,n=this.getSubcircuit();n&&(this.matchedPort=n.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=n.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}_getSourceTraceIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;this._matchConnection();let{pcbX:n=0,pcbY:i=0}=this._parsedProps,r=this.parent?.getGroup(),o=this.getSubcircuit();if(!r||!r.pcb_group_id)return;let s=t.pcb_breakout_point.insert({pcb_group_id:r.pcb_group_id,subcircuit_id:o?.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:n,y:i});this.pcb_breakout_point_id=s.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:t=0,pcbY:n=0}=this._parsedProps;return{center:{x:t,y:n},bounds:{left:t,top:n,right:t,bottom:n},width:0,height:0}}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_breakout_point_id&&n.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:t.x,y:t.y})}getPcbSize(){return{width:0,height:0}}},hY=class extends Ne{constructor(){super(...arguments);T(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:rL}}_getAnchorSide(){let{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getConnectedPorts();if(r.length===0)return"right";let o=r[0]._getGlobalSchematicPositionBeforeLayout(),s=o.x-i.x,a=o.y-i.y;if(Math.abs(s)>Math.abs(a)){if(s>0)return"right";if(s<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let t=this._resolveConnectsTo();if(!t)return[];let n=[];for(let i of t){let r=this.getSubcircuit().selectOne(i);r&&n.push(r)}return n}computeSchematicPropsTransform(){let{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){let n=this._getConnectedPorts();if(n.length>0){let i=n[0]._getGlobalSchematicPositionBeforeLayout(),r=En(this.parent?.computeSchematicGlobalTransform?.()??xi(),{x:0,y:0});return dn(i.x-r.x,i.y-r.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),o=n.anchorSide??"right",s=Xa({anchor_position:i,anchor_side:o,text:n.net}),a=t.schematic_net_label.insert({text:n.net,source_net_id:r.source_net_id,anchor_position:i,center:s,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo??t.connection;if(Array.isArray(n))return n;if(typeof n=="string")return[n]}_getNetName(){let{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;t.net&&BT(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let t=this._resolveConnectsTo();if(t)for(let n of t)this.add(new uo({from:n,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._resolveConnectsTo();if(!n||n.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getAnchorSide(),s={left:"x-",right:"x+",top:"y+",bottom:"y-"}[r],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of n){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let w=t.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id??""));if(w&&(u=t.schematic_trace.list().some(P=>P.source_trace_id===w.source_trace_id)),u)continue}let h=l._getGlobalSchematicPositionAfterLayout(),m=NT(l.facingDirection??"right")??"x+",y=rp({x:h.x,y:h.y,facingDirection:m},{x:i.x,y:i.y,facingDirection:s});if(!Array.isArray(y)||y.length<2)continue;let g=[];for(let w=0;w<y.length-1;w++)g.push({from:{x:y[w].x,y:y[w].y},to:{x:y[w+1].x,y:y[w+1].y}});let x,v;if(a?.source_net_id&&l.source_port_id){let w=t.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id));x=w?.source_trace_id,v=w?.subcircuit_connectivity_map_key||t.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}t.schematic_trace.insert({source_trace_id:x,edges:g,junctions:[],subcircuit_connectivity_map_key:v}),t.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},dY=class extends Ne{constructor(){super(...arguments);T(this,"pcb_silkscreen_circle_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:LL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenCircle. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_circle.insert({pcb_component_id:a,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},fY=class extends Ne{constructor(){super(...arguments);T(this,"pcb_silkscreen_rect_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:OL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenRect. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_rect.insert({pcb_component_id:s,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},mY=class extends Ne{constructor(){super(...arguments);T(this,"pcb_silkscreen_line_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:RL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenLine. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_line.insert({pcb_component_id:s,layer:r,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:o?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},yY=class extends Ne{constructor(t){super(t);T(this,"pcb_via_id",null);T(this,"matchedPort",null);T(this,"isPcbPrimitive",!0);T(this,"source_manually_placed_via_id",null);let n=this._getLayers();this._parsedProps.layers=n,this.initPorts()}get config(){return{componentName:"Via",zodProps:yL}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}_getLayers(){let{fromLayer:t="top",toLayer:n="bottom"}=this._parsedProps;return t===n?[t]:[t,n]}initPorts(){let t=this._parsedProps.layers;for(let i of t){let r=new Mi({name:i,layer:i});r.registerMatch(this),this.add(r)}let n=new Mi({name:"pin1"});n.registerMatch(this),this.add(n)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_component.insert({center:i,width:n.outerDiameter,height:n.outerDiameter,layer:n.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:r?.subcircuit_id??void 0});this.pcb_component_id=o.pcb_component_id}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getGroup(),r=this.getSubcircuit(),o=t.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:n.net??"",subcircuit_id:r?.subcircuit_id??void 0});this.source_component_id=o.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_via.insert({x:i.x,y:i.y,hole_diameter:n.holeDiameter,outer_diameter:n.outerDiameter,layers:["bottom","top"],from_layer:n.fromLayer||"bottom",to_layer:n.toLayer||"top",subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_via_id=o.pcb_via_id}},_Y=class extends Ne{constructor(){super(...arguments);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:bL}}getPcbSize(){return{width:0,height:0}}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit().selectOne(n.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${n.connectsTo}" not found for copper pour`);return}let r=t.pcb_board.list()[0];if(!r){this.renderError("No board found for copper pour");return}let o;r.outline&&r.outline.length>0?o=new L.Polygon(r.outline.map(y=>L.point(y.x,y.y))):o=new L.Polygon(new L.Box(r.center.x-r.width/2,r.center.y-r.height/2,r.center.x+r.width/2,r.center.y+r.height/2).toPoints());let s=ir(t.toArray()),a=VT(t.toArray(),s).filter(y=>y.layers.includes(n.layer));for(let y of t.pcb_trace.list())if(y.route)for(let g=0;g<y.route.length-1;g++){let x=y.route[g],v=y.route[g+1];if(x.route_type!=="wire"||v.route_type!=="wire"||x.layer!==n.layer)continue;let w=x.width;if(w===0)continue;let P=Math.hypot(x.x-v.x,x.y-v.y);if(P===0)continue;let N=(x.x+v.x)/2,E=(x.y+v.y)/2,R=Math.atan2(v.y-x.y,v.x-x.x)*180/Math.PI,A=zj({center:{x:N,y:E},width:P,height:w,rotation:R});for(let M of A)a.push({type:"rect",layers:[x.layer],center:M.center,width:M.width,height:M.height,connectedTo:y.source_trace_id?[y.source_trace_id]:[],obstacle_type:"trace"})}let c=[],l=[],u=n.traceMargin??.2,h=n.padMargin??.2;for(let y of a){if(y.connectedTo.some(w=>s.areIdsConnected(w,i.source_net_id)))continue;if(y.type==="oval"&&y.width===y.height){let w=y.width/2+h;l.push({center:y.center,radius:w});continue}if(y.type==="rect"&&y.width===y.height&&y.connectedTo.length===0){let w=y.width/2;l.push({center:y.center,radius:w});continue}let x=u,v=new L.Box(y.center.x-y.width/2-x,y.center.y-y.height/2-x,y.center.x+y.width/2+x,y.center.y+y.height/2+x);c.push(new L.Polygon(v.toPoints()))}let m=o;if(c.length>0){let y=c.reduce((g,x)=>L.BooleanOperations.unify(g,x));y&&!y.isEmpty()&&(m=L.BooleanOperations.subtract(o,y))}Array.isArray(m)||(m=[m]);for(let y of m){let g=y.splitToIslands();for(let x of g){if(x.isEmpty())continue;let v=[...x.faces],w=v.find(I=>I.orientation()===L.ORIENTATION.CCW),P=v.filter(I=>I.orientation()===L.ORIENTATION.CW);if(!w)continue;if(!t.pcb_copper_pour){this.renderError("db.pcb_copper_pour not found. The database schema may be outdated.");return}let N=I=>I.edges.map(A=>{let M={x:A.start.x,y:A.start.y};if(A.isArc){let k=Math.tan(A.shape.sweep/4);Math.abs(k)>1e-9&&(M.bulge=k)}return M});w.reverse();let E=N(w),R=P.map(I=>(I.reverse(),{vertices:N(I)}));for(let I of l){let A=L.point(I.center.x,I.center.y);x.contains(A)&&R.push({vertices:[{x:I.center.x,y:I.center.y-I.radius,bulge:1},{x:I.center.x,y:I.center.y+I.radius,bulge:1}]})}t.pcb_copper_pour.insert({shape:"brep",layer:n.layer,brep_shape:{outer_ring:{vertices:E},inner_rings:R},source_net_id:i.source_net_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0})}}})}},gY=class extends Pn{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:nL,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:t.capacity,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},xY=class extends Pn{_getPcbRotationBeforeLayout(){let e=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+e}get config(){return{componentName:"PinHeader",zodProps:iL,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,r=this._parsedProps.showSilkscreenPinLabels;if(e>0){let o;if(i)!t&&!n?o=`pinrow${e}_p${i}`:o=`pinrow${e}_p${i}_id${t}_od${n}`;else if(!t&&!n)o=`pinrow${e}`;else return null;return r!==!0&&(o+="_nopinlabels"),o}return null}initPorts(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let t=1;t<=e;t++){let n=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[t-1]:this._parsedProps.pinLabels?.[`pin${t}`];if(n){let i=Array.isArray(n)?n[0]:n,r=Array.isArray(n)?n.slice(1):[];this.add(new Mi({pinNumber:t,name:i,aliases:[`pin${t}`,...r]}))}else this.add(new Mi({pinNumber:t,name:`pin${t}`}))}}_getSchematicPortArrangement(){let e=this._parsedProps.pinCount??1,t=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",n=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:n?.leftSide?.direction??"top-to-bottom",pins:n?.leftSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}:{rightSide:{direction:n?.rightSide?.direction??"top-to-bottom",pins:n?.rightSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:t.supplierPartNumbers,pin_count:t.pinCount,gender:t.gender,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function K2t(e){switch(e){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var bY=class extends Pn{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??K2t(this.props.pinVariant),zodProps:GO,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:t.frequency,load_capacitance:t.loadCapacitance,supplier_part_numbers:t.supplierPartNumbers,pin_variant:n,are_pins_interchangeable:n==="no_ground"||n==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let e=`${Un(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${Un(this._parsedProps.loadCapacitance)}F`:e}},vY=class extends Pn{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:cL,sourceFtype:Cs.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${Un(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({name:this.name,ftype:Cs.simple_inductor,inductance:n.inductance,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function J2t(e){switch(e){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var wY=class extends Pn{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??J2t(this.props.pinVariant),zodProps:VO,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${Un(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},SY=class extends Pn{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:oL,sourceFtype:Cs.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let e=Gn[this._getSchematicSymbolNameOrThrow()],t=e.ports.find(l=>l.labels.includes("1")),n=e.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),r=i.find(l=>l.props.pinNumber===1),o=i.find(l=>l.props.pinNumber===2),s=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;r.schematicSymbolPortDef=t,(!c||c.length===0)&&(o.schematicSymbolPortDef=n);for(let[l,u]of[[2,o],[3,s],[4,a]]){let h=c?.find(([y,g])=>y===`pin${l}`||g===`pin${l}`);if(!h){u.schematicSymbolPortDef=n;break}(h?.[0]===`pin${l}`?h[1]:h?.[0])!=="pin1"&&(u.schematicSymbolPortDef=n)}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:Cs.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},PY=class extends Pn{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:HO,sourceFtype:"simple_crystal"}}initPorts(){let e=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:e})}_getSchematicSymbolDisplayValue(){let e=`${Un(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${Un(this._parsedProps.loadCapacitance)}F`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:t.frequency,load_capacitance:t.loadCapacitance,pin_variant:t.pinVariant||"two_pin",are_pins_interchangeable:(t.pinVariant||"two_pin")==="two_pin"});this.source_component_id=n.source_component_id}},TY=class extends Pn{constructor(){super(...arguments);T(this,"emitter",this.portMap.pin1);T(this,"collector",this.portMap.pin2);T(this,"base",this.portMap.pin3)}get config(){let t=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??t,zodProps:sL,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let t={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},IY=class extends Pn{get config(){let e=this.props.mosfetMode==="depletion"?"d":"e",n=`${this.props.channelType}_channel_${e}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??n,zodProps:aL,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}},MY=class extends Pn{_getSwitchType(){let{spst:e,spdt:t,dpst:n,dpdt:i,type:r}=this._parsedProps??{};return i?"dpdt":e?"spst":t?"spdt":n?"dpst":r??"spst"}get config(){let e=this._getSwitchType(),{isNormallyClosed:t}=this._parsedProps??{},i={spst:t?"spst_normally_closed_switch":"spst_switch",spdt:t?"spdt_normally_closed_switch":"spdt_switch",dpst:t?"dpst_normally_closed_switch":"dpst_switch",dpdt:t?"dpdt_normally_closed_switch":"dpdt_switch"}[e]??"spst_switch";return{componentName:"Switch",schematicSymbolName:this.props.symbolName??i,zodProps:dL,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_switch",name:this.name,switch_type:t.type,is_normally_closed:t.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=n.source_component_id}},CT={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},EY=class extends Pn{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:_L,sourceFtype:Cs.simple_test_point}}_getPropsWithDefaults(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._parsedProps;return!n&&t&&(n="through_hole"),n??(n="through_hole"),e??(e="circle"),n==="pad"?e==="circle"?i??(i=CT.SMT_CIRCLE_DIAMETER):e==="rect"&&(r??(r=CT.SMT_RECT_SIZE),o??(o=r)):n==="through_hole"&&(t??(t=CT.HOLE_DIAMETER)),{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}}_getImpliedFootprintString(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._getPropsWithDefaults();if(n==="through_hole")return`platedhole_d${t}`;if(n==="pad"){if(e==="circle")return`smtpad_circle_d${i}`;if(e==="rect")return`smtpad_rect_w${r}_h${o}`}throw new Error(`Footprint variant "${n}" with pad shape "${e}" not implemented`)}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{padShape:n,holeDiameter:i,footprintVariant:r,padDiameter:o,width:s,height:a}=this._getPropsWithDefaults(),c=e.source_component.insert({ftype:Cs.simple_test_point,name:this.name,supplier_part_numbers:t.supplierPartNumbers,footprint_variant:r,pad_shape:n,pad_diameter:o,hole_diameter:i,width:s,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},CY=class extends Ne{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:ML}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout();t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:i.x,y:i.y},rotation:n.schRotation??0})}},kY=class extends Ne{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:IL}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_line.insert({schematic_component_id:r,x1:n.x1+i.x,y1:n.y1+i.y,x2:n.x2+i.x,y2:n.y2+i.y,stroke_width:Wj,color:qj,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=o.schematic_line_id}},AY=class extends Ne{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:TL}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_rect.insert({center:{x:n.center.x+i.x,y:n.center.y+i.y},width:n.width,height:n.height,stroke_width:Wj,color:qj,is_filled:n.isFilled,schematic_component_id:r,is_dashed:n.isDashed,rotation:n.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=o.schematic_rect_id}};function Q2t({anchor:e,x:t,y:n,width:i,height:r,isInside:o}){switch(e){case"top_left":return{x:t,y:n+r,textAnchor:o?"top_left":"bottom_left"};case"top_center":return{x:t+i/2,y:n+r,textAnchor:o?"top_center":"bottom_center"};case"top_right":return{x:t+i,y:n+r,textAnchor:o?"top_right":"bottom_right"};case"center_left":return{x:t,y:n+r/2,textAnchor:o?"center_left":"center_right"};case"center":return{x:t+i/2,y:n+r/2,textAnchor:"center"};case"center_right":return{x:t+i,y:n+r/2,textAnchor:o?"center_right":"center_left"};case"bottom_left":return{x:t,y:n,textAnchor:o?"bottom_left":"top_left"};case"bottom_center":return{x:t+i/2,y:n,textAnchor:o?"bottom_center":"top_center"};case"bottom_right":return{x:t+i,y:n,textAnchor:o?"bottom_right":"top_right"};default:return{x:t+i/2,y:n+r,textAnchor:"center"}}}var NY=class extends Ne{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:PL,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=.6,r=typeof n.padding=="number"?n.padding:0,o=typeof n.paddingTop=="number"?n.paddingTop:r,s=typeof n.paddingBottom=="number"?n.paddingBottom:r,a=typeof n.paddingLeft=="number"?n.paddingLeft:r,c=typeof n.paddingRight=="number"?n.paddingRight:r,l=n.overlay&&n.overlay.length>0,u=typeof n.width=="number"&&typeof n.height=="number",h,m,y,g,x,v;if(l){let P=n.overlay.map(it=>({selector:it,port:this.getSubcircuit().selectOne(it,{type:"port"})})).filter(({port:it})=>it!=null).map(({port:it})=>({position:it._getGlobalSchematicPositionAfterLayout()}));if(P.length===0)return;let N=P.map(it=>it.position.x),E=P.map(it=>it.position.y),R=Math.min(...N),I=Math.max(...N),A=Math.min(...E),M=Math.max(...E),k=I-R,z=M-A,B=k===0?i:0,j=z===0?i:0,q=a+B/2,G=c+B/2,K=o+j/2,tt=s+j/2,J=R-q,bt=I+G,ct=A-tt,rt=M+K;h=bt-J,m=rt-ct,y=J+(n.schX??0),g=ct+(n.schY??0),x=y+h/2,v=g+m/2}else if(u){h=n.width,m=n.height;let w=this._getGlobalSchematicPositionBeforeLayout();x=w.x,v=w.y,y=x-h/2,g=v-m/2}else return;if(t.schematic_box.insert({height:m,width:h,x:y,y:g,is_dashed:n.strokeStyle==="dashed"}),n.title){let w=n.titleInside,P=.1,N=n.titleAlignment,E=Q2t({anchor:N,x:y,y:g,width:h,height:m,isInside:w}),R,I,A=E.textAnchor;w?(R=N.includes("top")?-P:N.includes("bottom")?P:0,I=N.includes("left")?P:N.includes("right")?-P:0):(R=N.includes("top")?P:N.includes("bottom")?-P:0,I=N.includes("center_left")?-P:N.includes("center_right")?P:0);let M=E.x+I,k=E.y+R;t.schematic_text.insert({anchor:A,text:n.title,font_size:n.titleFontSize??.18,color:n.titleColor??"#000000",position:{x:M,y:k},rotation:0})}}},RY=class extends Ne{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:EL}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.children.filter(m=>m.componentName==="SchematicRow");if(i.length===0)return;let r=[],o=0;for(let m of i){let y=m.children.filter(g=>g.componentName==="SchematicCell");o=Math.max(o,y.length)}for(let m=0;m<i.length;m++)r[m]=[];for(let m=0;m<i.length;m++){let g=i[m].children.filter(v=>v.componentName==="SchematicCell"),x=0;for(let v=0;v<g.length;v++){for(;r[m][x];)x++;let w=g[v],P=w._parsedProps.colSpan??1,N=w._parsedProps.rowSpan??1;for(let E=0;E<N;E++)for(let R=0;R<P;R++)r[m+E]||(r[m+E]=[]),r[m+E][x+R]=w;x+=P}}o=Math.max(0,...r.map(m=>m.length));let s=i.map((m,y)=>m._parsedProps.height??1),a=Array.from({length:o},(m,y)=>{let g=0;for(let x=0;x<i.length;x++){let v=r[x]?.[y];if(v){let w=v._parsedProps.text??v._parsedProps.children,P=v._parsedProps.width??(w?.length??2)*.5;P>g&&(g=P)}}return g||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=t.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:s,cell_padding:n.cellPadding,border_width:n.borderWidth,anchor:n.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 m=0;m<i.length;m++){let y=0;for(let g=0;g<o;g++){let x=r[m]?.[g];if(x&&!u.has(x)){u.add(x);let v=x._parsedProps,w=v.rowSpan??1,P=v.colSpan??1,N=0;for(let R=0;R<P;R++)N+=a[g+R];let E=0;for(let R=0;R<w;R++)E+=s[m+R];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:m,end_row_index:m+w-1,start_column_index:g,end_column_index:g+P-1,text:v.text??v.children,center:{x:c.x+y+N/2,y:c.y-h-E/2},width:N,height:E,horizontal_align:v.horizontalAlign,vertical_align:v.verticalAlign,font_size:v.fontSize??n.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[g]&&(y+=a[g])}h+=s[m]}}},OY=class extends Ne{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:CL}}},LY=class extends Ne{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:kL}}},zY=class extends Ne{constructor(){super(...arguments);T(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:eL}}},tvt={name:"@tscircuit/core",type:"module",version:"0.0.738",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"'},devDependencies:{"@biomejs/biome":"^1.8.3","@tscircuit/capacity-autorouter":"^0.0.107","@tscircuit/checks":"^0.0.75","@tscircuit/circuit-json-util":"^0.0.67","@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.21","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"0.0.335","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^0.0.38","@tscircuit/simple-3d-svg":"^0.0.41","@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.261","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-simple-3d":"^0.0.8","circuit-to-svg":"^0.0.197",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.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",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.201","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.37","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"}},Hp=class{constructor({platform:e,projectUrl:t}={}){T(this,"firstChild",null);T(this,"children");T(this,"db");T(this,"root",null);T(this,"isRoot",!0);T(this,"schematicDisabled",!1);T(this,"pcbDisabled",!1);T(this,"pcbRoutingDisabled",!1);T(this,"_featureMspSchematicTraceRouting",!0);T(this,"name");T(this,"platform");T(this,"projectUrl");T(this,"_hasRenderedAtleastOnce",!1);T(this,"_eventListeners",{});this.children=[],this.db=Ve([]),this.root=this,this.platform=e,this.projectUrl=t,this.pcbDisabled=e?.pcbDisabled??!1}add(e){let t;(0,FY.isValidElement)(e)?t=Mj(e):t=e,this.children.push(t)}_getBoard(){return this.children.find(e=>e.componentName==="Board")}_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(...))");if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let e=new Vp({subcircuit:!0});e.parent=this,e.addAll(this.children),this.children=[e],this.firstChild=e}render(){this.firstChild||this._guessRootComponent();let{firstChild:e,db:t}=this;if(!e)throw new Error("RootCircuit has no root component");e.parent=this,e.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(t=>setTimeout(t,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(e=>e._hasIncompleteAsyncEffects()?!0:e.children.some(t=>t._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(e){let t=await Promise.resolve().then(()=>(JB(),KB)).catch(n=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
227
+ `),a={x:n.center.x+n.width/2-.25,y:n.center.y-n.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})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.width??0,r=n.height??0,o={x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)};if(n.outline){let c=n.outline.map(g=>g.x),l=n.outline.map(g=>g.y),u=Math.min(...c),h=Math.max(...c),m=Math.min(...l),y=Math.max(...l);i=h-u,r=y-m,o={x:(u+h)/2+(n.outlineOffsetX??0),y:(m+y)/2+(n.outlineOffsetY??0)}}let s=n.outline;!s&&n.borderRadius!=null&&i>0&&r>0&&(s=vj(i,r,n.borderRadius));let a=t.pcb_board.insert({center:o,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:r,outline:s?.map(c=>({x:c.x+(n.outlineOffsetX??0),y:c.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=a.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:t}=this.root;this.pcb_board_id&&(t.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return xi()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let n=pB(t.toArray());for(let o of n)t.pcb_trace_error.insert(o);let i=uB(t.toArray());for(let o of i)t.pcb_port_not_connected_error.insert(o);let r=fB(t.toArray());for(let o of r)t.pcb_component_outside_board_error.insert(o)}_emitRenderLifecycleEvent(t,n){super._emitRenderLifecycleEvent(t,n),n==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t})}},q2t=new Proxy({},{get:(e,t)=>t}),Cs=q2t,qj="rgba(132, 0, 0)",Wj=.12,Zj=class extends Pn{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:UO,sourceFtype:Cs.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let t=this.props.capacitance,n=typeof t=="string"?t:`${Un(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${n}/${Un(this._parsedProps.maxVoltageRating)}V`:n}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new uo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new uo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,capacitance:n.capacitance,max_voltage_rating:n.maxVoltageRating,max_decoupling_trace_length:n.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!n.polarized});this.source_component_id=i.source_component_id}},Sx=class extends Pn{constructor(t){super(t);T(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:tp,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);let{_parsedProps:n}=this;if(n.externallyConnectedPins){let i=new Set;for(let[r,o]of n.externallyConnectedPins)i.add(r),i.add(o);for(let r of i)if(!this.children.find(s=>s instanceof Mi&&s.isMatchingAnyOf([r]))){let s=r.match(/^pin(\d+)$/);if(s){let a=parseInt(s[1]);this.add(new Mi({pinNumber:a,aliases:[r]}))}else this.add(new Mi({name:r,aliases:[r]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:t}=this;t?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=i.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:t}=this;if(t.externallyConnectedPins)for(let[n,i]of t.externallyConnectedPins)this.add(new uo({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:t}=this.root,{pinAttributes:n}=this.props;if(!n)return;let i=null,r=null,o,s=this.selectAll("port");for(let h of s)for(let m of h.getNameAndAliases())if(n[m]){let y=n[m];y.providesPower&&(i=h,o=y.providesVoltage),y.providesGround&&(r=h)}if(!i||!r||o===void 0)return;let a=t.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=t.source_port.get(r.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=t.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=t.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||t.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:o})}},Kj=class extends Sx{constructor(e){super(e)}get config(){return{...super.config,componentName:"Pinout",zodProps:DO}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}},Jj=class extends Pn{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"anode",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"cathode",this.portMap.pin2)}get config(){let t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},n=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"diode",componentName:"Diode",zodProps:lL,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},Qj=class extends Pn{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:BO,sourceFtype:Cs.simple_fuse}}_getSchematicSymbolDisplayValue(){let e=this._parsedProps.currentRating,t=this._parsedProps.voltageRating,n=typeof e=="string"?parseFloat(e):e,i=typeof t=="string"?parseFloat(t):t;return`${Un(n)}A / ${Un(i)}V`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=typeof t.currentRating=="string"?parseFloat(t.currentRating):t.currentRating,i=typeof t.voltageRating=="string"?parseFloat(t.voltageRating):t.voltageRating,r=e.source_component.insert({name:this.name,ftype:Cs.simple_fuse,current_rating_amps:n,voltage_rating_volts:i,display_current_rating:`${Un(n)}A`,display_voltage_rating:`${Un(i)}V`});this.source_component_id=r.source_component_id}},tY=class extends Pn{constructor(){super(...arguments);T(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:o5,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=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"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.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=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},eY=class extends Pn{constructor(){super(...arguments);T(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(t){return this.selectOne(`port.${t}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let t=this.children.filter(n=>n.componentName==="Port").map(n=>n.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){let t=this._parsedProps??this.props,n=t.pinCount;if(t.pinCount==null&&!t.footprint&&(n=2),t.pinCount==null){let o=(t.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),s=o.length>0?Math.max(...o):0,a=t.pinLabels?Object.keys(t.pinLabels).length:0,c=Math.max(s,a);(c===2||c===3)&&(n=c),n==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(n=this.getPortsFromFootprint().length)}let i="";n?i+=`solderjumper${n}`:i="solderjumper";let r=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?r=Array.from(new Set(t.bridgedPins.flat().map(o=>this._getPinNumberFromBridgedPinName(o)).filter(o=>o!==null))).sort((o,s)=>o-s):t.bridged&&n&&(r=Array.from({length:n},(o,s)=>s+1)),r.length>0&&(i+=`_bridged${r.join("")}`),{schematicSymbolName:t.symbolName??i,componentName:"SolderJumper",zodProps:$O,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);n==null&&!this._parsedProps.footprint&&(n=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.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=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},nY=class extends Pn{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"anode",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"cathode",this.portMap.pin2)}get config(){let t={laser:"laser_diode"},n=this.props.laser?"laser":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"led",componentName:"Led",zodProps:pL,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}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:n.wavelength,color:n.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},iY=class extends Pn{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"positive",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:SL,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Mi({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Mi({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},W2t=Ln.extend({voltage:Jn.optional(),frequency:so.optional(),peakToPeakVoltage:Jn.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Oe.optional(),dutyCycle:p.number().optional()}),rY=class extends Pn{constructor(){super(...arguments);T(this,"terminal1",this.portMap.terminal1);T(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:W2t,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.portMap.terminal1,r=this.portMap.terminal2;t.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:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle})}},oY=class extends Pn{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:YO,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${Un(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 uo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new uo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new uo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new uo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,resistance:n.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}},Z2t=["leftedge","rightedge","topedge","bottomedge","center"],sY=class extends Ne{get config(){return{componentName:"Constraint",zodProps:WO}}constructor(e){if(super(e),("xdist"in e||"ydist"in e)&&!("edgeToEdge"in e)&&!("centerToCenter"in e))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in e&&e.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let e=[],t=this.getPrimitiveContainer();function n(i){let r=i.split(" ").pop(),o=Z2t.includes(r)?r:void 0,s=o?i.replace(` ${o}`,""):i,a=t.selectOne(s,{pcbPrimitive:!0});a&&e.push({selector:i,component:a,componentSelector:s,edge:o})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},aY=class extends Ne{constructor(){super(...arguments);T(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:mL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=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 o=this._computePcbGlobalTransformBeforeLayout(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_fabrication_note_path.insert({pcb_component_id:s,layer:r,color:i.color,route:i.route.map(c=>{let l=En(o,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:n?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},cY=class extends Ne{get config(){return{componentName:"FabricationNoteText",zodProps:fL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this.getSubcircuit();e.pcb_fabrication_note_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:t.pcbX??0,y:t.pcbY??0},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:"top",color:t.color,text:t.text??"",pcb_component_id:n.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},lY=class extends Vp{constructor(e){super({...e,subcircuit:!0})}},uY=class extends Vp{constructor(e){super({...e,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!this.pcb_group_id)return;let n=e.pcb_group.get(this.pcb_group_id),i=t.paddingLeft??t.padding??0,r=t.paddingRight??t.padding??0,o=t.paddingTop??t.padding??0,s=t.paddingBottom??t.padding??0;e.pcb_group.update(this.pcb_group_id,{width:n.width+i+r,height:n.height+o+s,center:{x:n.center.x+(r-i)/2,y:n.center.y+(o-s)/2}})}},pY=class extends Ne{constructor(){super(...arguments);T(this,"pcb_breakout_point_id",null);T(this,"matchedPort",null);T(this,"matchedNet",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:gL}}_matchConnection(){let{connection:t}=this._parsedProps,n=this.getSubcircuit();n&&(this.matchedPort=n.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=n.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}_getSourceTraceIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;this._matchConnection();let{pcbX:n=0,pcbY:i=0}=this._parsedProps,r=this.parent?.getGroup(),o=this.getSubcircuit();if(!r||!r.pcb_group_id)return;let s=t.pcb_breakout_point.insert({pcb_group_id:r.pcb_group_id,subcircuit_id:o?.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:n,y:i});this.pcb_breakout_point_id=s.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:t=0,pcbY:n=0}=this._parsedProps;return{center:{x:t,y:n},bounds:{left:t,top:n,right:t,bottom:n},width:0,height:0}}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_breakout_point_id&&n.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:t.x,y:t.y})}getPcbSize(){return{width:0,height:0}}},hY=class extends Ne{constructor(){super(...arguments);T(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:rL}}_getAnchorSide(){let{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getConnectedPorts();if(r.length===0)return"right";let o=r[0]._getGlobalSchematicPositionBeforeLayout(),s=o.x-i.x,a=o.y-i.y;if(Math.abs(s)>Math.abs(a)){if(s>0)return"right";if(s<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let t=this._resolveConnectsTo();if(!t)return[];let n=[];for(let i of t){let r=this.getSubcircuit().selectOne(i);r&&n.push(r)}return n}computeSchematicPropsTransform(){let{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){let n=this._getConnectedPorts();if(n.length>0){let i=n[0]._getGlobalSchematicPositionBeforeLayout(),r=En(this.parent?.computeSchematicGlobalTransform?.()??xi(),{x:0,y:0});return dn(i.x-r.x,i.y-r.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),o=n.anchorSide??"right",s=Xa({anchor_position:i,anchor_side:o,text:n.net}),a=t.schematic_net_label.insert({text:n.net,source_net_id:r.source_net_id,anchor_position:i,center:s,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo??t.connection;if(Array.isArray(n))return n;if(typeof n=="string")return[n]}_getNetName(){let{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;t.net&&BT(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let t=this._resolveConnectsTo();if(t)for(let n of t)this.add(new uo({from:n,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._resolveConnectsTo();if(!n||n.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getAnchorSide(),s={left:"x-",right:"x+",top:"y+",bottom:"y-"}[r],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of n){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let w=t.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id??""));if(w&&(u=t.schematic_trace.list().some(P=>P.source_trace_id===w.source_trace_id)),u)continue}let h=l._getGlobalSchematicPositionAfterLayout(),m=NT(l.facingDirection??"right")??"x+",y=rp({x:h.x,y:h.y,facingDirection:m},{x:i.x,y:i.y,facingDirection:s});if(!Array.isArray(y)||y.length<2)continue;let g=[];for(let w=0;w<y.length-1;w++)g.push({from:{x:y[w].x,y:y[w].y},to:{x:y[w+1].x,y:y[w+1].y}});let x,v;if(a?.source_net_id&&l.source_port_id){let w=t.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id));x=w?.source_trace_id,v=w?.subcircuit_connectivity_map_key||t.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}t.schematic_trace.insert({source_trace_id:x,edges:g,junctions:[],subcircuit_connectivity_map_key:v}),t.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},dY=class extends Ne{constructor(){super(...arguments);T(this,"pcb_silkscreen_circle_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:LL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenCircle. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_circle.insert({pcb_component_id:a,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},fY=class extends Ne{constructor(){super(...arguments);T(this,"pcb_silkscreen_rect_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:OL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenRect. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_rect.insert({pcb_component_id:s,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},mY=class extends Ne{constructor(){super(...arguments);T(this,"pcb_silkscreen_line_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:RL}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenLine. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_line.insert({pcb_component_id:s,layer:r,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:o?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},yY=class extends Ne{constructor(t){super(t);T(this,"pcb_via_id",null);T(this,"matchedPort",null);T(this,"isPcbPrimitive",!0);T(this,"source_manually_placed_via_id",null);let n=this._getLayers();this._parsedProps.layers=n,this.initPorts()}get config(){return{componentName:"Via",zodProps:yL}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}_getLayers(){let{fromLayer:t="top",toLayer:n="bottom"}=this._parsedProps;return t===n?[t]:[t,n]}initPorts(){let t=this._parsedProps.layers;for(let i of t){let r=new Mi({name:i,layer:i});r.registerMatch(this),this.add(r)}let n=new Mi({name:"pin1"});n.registerMatch(this),this.add(n)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_component.insert({center:i,width:n.outerDiameter,height:n.outerDiameter,layer:n.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:r?.subcircuit_id??void 0});this.pcb_component_id=o.pcb_component_id}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getGroup(),r=this.getSubcircuit(),o=t.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:n.net??"",subcircuit_id:r?.subcircuit_id??void 0});this.source_component_id=o.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_via.insert({x:i.x,y:i.y,hole_diameter:n.holeDiameter,outer_diameter:n.outerDiameter,layers:["bottom","top"],from_layer:n.fromLayer||"bottom",to_layer:n.toLayer||"top",subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_via_id=o.pcb_via_id}},_Y=class extends Ne{constructor(){super(...arguments);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:bL}}getPcbSize(){return{width:0,height:0}}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit().selectOne(n.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${n.connectsTo}" not found for copper pour`);return}let r=t.pcb_board.list()[0];if(!r){this.renderError("No board found for copper pour");return}let o;r.outline&&r.outline.length>0?o=new L.Polygon(r.outline.map(y=>L.point(y.x,y.y))):o=new L.Polygon(new L.Box(r.center.x-r.width/2,r.center.y-r.height/2,r.center.x+r.width/2,r.center.y+r.height/2).toPoints());let s=ir(t.toArray()),a=VT(t.toArray(),s).filter(y=>y.layers.includes(n.layer));for(let y of t.pcb_trace.list())if(y.route)for(let g=0;g<y.route.length-1;g++){let x=y.route[g],v=y.route[g+1];if(x.route_type!=="wire"||v.route_type!=="wire"||x.layer!==n.layer)continue;let w=x.width;if(w===0)continue;let P=Math.hypot(x.x-v.x,x.y-v.y);if(P===0)continue;let N=(x.x+v.x)/2,E=(x.y+v.y)/2,R=Math.atan2(v.y-x.y,v.x-x.x)*180/Math.PI,A=zj({center:{x:N,y:E},width:P,height:w,rotation:R});for(let M of A)a.push({type:"rect",layers:[x.layer],center:M.center,width:M.width,height:M.height,connectedTo:y.source_trace_id?[y.source_trace_id]:[],obstacle_type:"trace"})}let c=[],l=[],u=n.traceMargin??.2,h=n.padMargin??.2;for(let y of a){if(y.connectedTo.some(w=>s.areIdsConnected(w,i.source_net_id)))continue;if(y.type==="oval"&&y.width===y.height){let w=y.width/2+h;l.push({center:y.center,radius:w});continue}if(y.type==="rect"&&y.width===y.height&&y.connectedTo.length===0){let w=y.width/2;l.push({center:y.center,radius:w});continue}let x=u,v=new L.Box(y.center.x-y.width/2-x,y.center.y-y.height/2-x,y.center.x+y.width/2+x,y.center.y+y.height/2+x);c.push(new L.Polygon(v.toPoints()))}let m=o;if(c.length>0){let y=c.reduce((g,x)=>L.BooleanOperations.unify(g,x));y&&!y.isEmpty()&&(m=L.BooleanOperations.subtract(o,y))}Array.isArray(m)||(m=[m]);for(let y of m){let g=y.splitToIslands();for(let x of g){if(x.isEmpty())continue;let v=[...x.faces],w=v.find(I=>I.orientation()===L.ORIENTATION.CCW),P=v.filter(I=>I.orientation()===L.ORIENTATION.CW);if(!w)continue;if(!t.pcb_copper_pour){this.renderError("db.pcb_copper_pour not found. The database schema may be outdated.");return}let N=I=>I.edges.map(A=>{let M={x:A.start.x,y:A.start.y};if(A.isArc){let k=Math.tan(A.shape.sweep/4);Math.abs(k)>1e-9&&(M.bulge=k)}return M});w.reverse();let E=N(w),R=P.map(I=>(I.reverse(),{vertices:N(I)}));for(let I of l){let A=L.point(I.center.x,I.center.y);x.contains(A)&&R.push({vertices:[{x:I.center.x,y:I.center.y-I.radius,bulge:1},{x:I.center.x,y:I.center.y+I.radius,bulge:1}]})}t.pcb_copper_pour.insert({shape:"brep",layer:n.layer,brep_shape:{outer_ring:{vertices:E},inner_rings:R},source_net_id:i.source_net_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0})}}})}},gY=class extends Pn{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:nL,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:t.capacity,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},xY=class extends Pn{_getPcbRotationBeforeLayout(){let e=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+e}get config(){return{componentName:"PinHeader",zodProps:iL,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,r=this._parsedProps.showSilkscreenPinLabels;if(e>0){let o;if(i)!t&&!n?o=`pinrow${e}_p${i}`:o=`pinrow${e}_p${i}_id${t}_od${n}`;else if(!t&&!n)o=`pinrow${e}`;else return null;return r!==!0&&(o+="_nopinlabels"),o}return null}initPorts(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let t=1;t<=e;t++){let n=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[t-1]:this._parsedProps.pinLabels?.[`pin${t}`];if(n){let i=Array.isArray(n)?n[0]:n,r=Array.isArray(n)?n.slice(1):[];this.add(new Mi({pinNumber:t,name:i,aliases:[`pin${t}`,...r]}))}else this.add(new Mi({pinNumber:t,name:`pin${t}`}))}}_getSchematicPortArrangement(){let e=this._parsedProps.pinCount??1,t=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",n=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:n?.leftSide?.direction??"top-to-bottom",pins:n?.leftSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}:{rightSide:{direction:n?.rightSide?.direction??"top-to-bottom",pins:n?.rightSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:t.supplierPartNumbers,pin_count:t.pinCount,gender:t.gender,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function K2t(e){switch(e){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var bY=class extends Pn{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??K2t(this.props.pinVariant),zodProps:GO,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:t.frequency,load_capacitance:t.loadCapacitance,supplier_part_numbers:t.supplierPartNumbers,pin_variant:n,are_pins_interchangeable:n==="no_ground"||n==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let e=`${Un(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${Un(this._parsedProps.loadCapacitance)}F`:e}},vY=class extends Pn{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:cL,sourceFtype:Cs.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${Un(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({name:this.name,ftype:Cs.simple_inductor,inductance:n.inductance,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function J2t(e){switch(e){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var wY=class extends Pn{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??J2t(this.props.pinVariant),zodProps:VO,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${Un(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},SY=class extends Pn{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:oL,sourceFtype:Cs.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let e=Gn[this._getSchematicSymbolNameOrThrow()],t=e.ports.find(l=>l.labels.includes("1")),n=e.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),r=i.find(l=>l.props.pinNumber===1),o=i.find(l=>l.props.pinNumber===2),s=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;r.schematicSymbolPortDef=t,(!c||c.length===0)&&(o.schematicSymbolPortDef=n);for(let[l,u]of[[2,o],[3,s],[4,a]]){let h=c?.find(([y,g])=>y===`pin${l}`||g===`pin${l}`);if(!h){u.schematicSymbolPortDef=n;break}(h?.[0]===`pin${l}`?h[1]:h?.[0])!=="pin1"&&(u.schematicSymbolPortDef=n)}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:Cs.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},PY=class extends Pn{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:HO,sourceFtype:"simple_crystal"}}initPorts(){let e=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:e})}_getSchematicSymbolDisplayValue(){let e=`${Un(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${Un(this._parsedProps.loadCapacitance)}F`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:t.frequency,load_capacitance:t.loadCapacitance,pin_variant:t.pinVariant||"two_pin",are_pins_interchangeable:(t.pinVariant||"two_pin")==="two_pin"});this.source_component_id=n.source_component_id}},TY=class extends Pn{constructor(){super(...arguments);T(this,"emitter",this.portMap.pin1);T(this,"collector",this.portMap.pin2);T(this,"base",this.portMap.pin3)}get config(){let t=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??t,zodProps:sL,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let t={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},IY=class extends Pn{get config(){let e=this.props.mosfetMode==="depletion"?"d":"e",n=`${this.props.channelType}_channel_${e}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??n,zodProps:aL,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}},MY=class extends Pn{_getSwitchType(){let{spst:e,spdt:t,dpst:n,dpdt:i,type:r}=this._parsedProps??{};return i?"dpdt":e?"spst":t?"spdt":n?"dpst":r??"spst"}get config(){let e=this._getSwitchType(),{isNormallyClosed:t}=this._parsedProps??{},i={spst:t?"spst_normally_closed_switch":"spst_switch",spdt:t?"spdt_normally_closed_switch":"spdt_switch",dpst:t?"dpst_normally_closed_switch":"dpst_switch",dpdt:t?"dpdt_normally_closed_switch":"dpdt_switch"}[e]??"spst_switch";return{componentName:"Switch",schematicSymbolName:this.props.symbolName??i,zodProps:dL,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_switch",name:this.name,switch_type:t.type,is_normally_closed:t.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=n.source_component_id}},CT={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},EY=class extends Pn{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:_L,sourceFtype:Cs.simple_test_point}}_getPropsWithDefaults(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._parsedProps;return!n&&t&&(n="through_hole"),n??(n="through_hole"),e??(e="circle"),n==="pad"?e==="circle"?i??(i=CT.SMT_CIRCLE_DIAMETER):e==="rect"&&(r??(r=CT.SMT_RECT_SIZE),o??(o=r)):n==="through_hole"&&(t??(t=CT.HOLE_DIAMETER)),{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}}_getImpliedFootprintString(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._getPropsWithDefaults();if(n==="through_hole")return`platedhole_d${t}`;if(n==="pad"){if(e==="circle")return`smtpad_circle_d${i}`;if(e==="rect")return`smtpad_rect_w${r}_h${o}`}throw new Error(`Footprint variant "${n}" with pad shape "${e}" not implemented`)}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{padShape:n,holeDiameter:i,footprintVariant:r,padDiameter:o,width:s,height:a}=this._getPropsWithDefaults(),c=e.source_component.insert({ftype:Cs.simple_test_point,name:this.name,supplier_part_numbers:t.supplierPartNumbers,footprint_variant:r,pad_shape:n,pad_diameter:o,hole_diameter:i,width:s,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},CY=class extends Ne{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:ML}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout();t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:i.x,y:i.y},rotation:n.schRotation??0})}},kY=class extends Ne{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:IL}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_line.insert({schematic_component_id:r,x1:n.x1+i.x,y1:n.y1+i.y,x2:n.x2+i.x,y2:n.y2+i.y,stroke_width:Wj,color:qj,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=o.schematic_line_id}},AY=class extends Ne{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:TL}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_rect.insert({center:{x:n.center.x+i.x,y:n.center.y+i.y},width:n.width,height:n.height,stroke_width:Wj,color:qj,is_filled:n.isFilled,schematic_component_id:r,is_dashed:n.isDashed,rotation:n.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=o.schematic_rect_id}};function Q2t({anchor:e,x:t,y:n,width:i,height:r,isInside:o}){switch(e){case"top_left":return{x:t,y:n+r,textAnchor:o?"top_left":"bottom_left"};case"top_center":return{x:t+i/2,y:n+r,textAnchor:o?"top_center":"bottom_center"};case"top_right":return{x:t+i,y:n+r,textAnchor:o?"top_right":"bottom_right"};case"center_left":return{x:t,y:n+r/2,textAnchor:o?"center_left":"center_right"};case"center":return{x:t+i/2,y:n+r/2,textAnchor:"center"};case"center_right":return{x:t+i,y:n+r/2,textAnchor:o?"center_right":"center_left"};case"bottom_left":return{x:t,y:n,textAnchor:o?"bottom_left":"top_left"};case"bottom_center":return{x:t+i/2,y:n,textAnchor:o?"bottom_center":"top_center"};case"bottom_right":return{x:t+i,y:n,textAnchor:o?"bottom_right":"top_right"};default:return{x:t+i/2,y:n+r,textAnchor:"center"}}}var NY=class extends Ne{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:PL,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=.6,r=typeof n.padding=="number"?n.padding:0,o=typeof n.paddingTop=="number"?n.paddingTop:r,s=typeof n.paddingBottom=="number"?n.paddingBottom:r,a=typeof n.paddingLeft=="number"?n.paddingLeft:r,c=typeof n.paddingRight=="number"?n.paddingRight:r,l=n.overlay&&n.overlay.length>0,u=typeof n.width=="number"&&typeof n.height=="number",h,m,y,g,x,v;if(l){let P=n.overlay.map(it=>({selector:it,port:this.getSubcircuit().selectOne(it,{type:"port"})})).filter(({port:it})=>it!=null).map(({port:it})=>({position:it._getGlobalSchematicPositionAfterLayout()}));if(P.length===0)return;let N=P.map(it=>it.position.x),E=P.map(it=>it.position.y),R=Math.min(...N),I=Math.max(...N),A=Math.min(...E),M=Math.max(...E),k=I-R,z=M-A,B=k===0?i:0,j=z===0?i:0,q=a+B/2,G=c+B/2,K=o+j/2,tt=s+j/2,J=R-q,bt=I+G,ct=A-tt,rt=M+K;h=bt-J,m=rt-ct,y=J+(n.schX??0),g=ct+(n.schY??0),x=y+h/2,v=g+m/2}else if(u){h=n.width,m=n.height;let w=this._getGlobalSchematicPositionBeforeLayout();x=w.x,v=w.y,y=x-h/2,g=v-m/2}else return;if(t.schematic_box.insert({height:m,width:h,x:y,y:g,is_dashed:n.strokeStyle==="dashed"}),n.title){let w=n.titleInside,P=.1,N=n.titleAlignment,E=Q2t({anchor:N,x:y,y:g,width:h,height:m,isInside:w}),R,I,A=E.textAnchor;w?(R=N.includes("top")?-P:N.includes("bottom")?P:0,I=N.includes("left")?P:N.includes("right")?-P:0):(R=N.includes("top")?P:N.includes("bottom")?-P:0,I=N.includes("center_left")?-P:N.includes("center_right")?P:0);let M=E.x+I,k=E.y+R;t.schematic_text.insert({anchor:A,text:n.title,font_size:n.titleFontSize??.18,color:n.titleColor??"#000000",position:{x:M,y:k},rotation:0})}}},RY=class extends Ne{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:EL}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.children.filter(m=>m.componentName==="SchematicRow");if(i.length===0)return;let r=[],o=0;for(let m of i){let y=m.children.filter(g=>g.componentName==="SchematicCell");o=Math.max(o,y.length)}for(let m=0;m<i.length;m++)r[m]=[];for(let m=0;m<i.length;m++){let g=i[m].children.filter(v=>v.componentName==="SchematicCell"),x=0;for(let v=0;v<g.length;v++){for(;r[m][x];)x++;let w=g[v],P=w._parsedProps.colSpan??1,N=w._parsedProps.rowSpan??1;for(let E=0;E<N;E++)for(let R=0;R<P;R++)r[m+E]||(r[m+E]=[]),r[m+E][x+R]=w;x+=P}}o=Math.max(0,...r.map(m=>m.length));let s=i.map((m,y)=>m._parsedProps.height??1),a=Array.from({length:o},(m,y)=>{let g=0;for(let x=0;x<i.length;x++){let v=r[x]?.[y];if(v){let w=v._parsedProps.text??v._parsedProps.children,P=v._parsedProps.width??(w?.length??2)*.5;P>g&&(g=P)}}return g||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=t.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:s,cell_padding:n.cellPadding,border_width:n.borderWidth,anchor:n.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 m=0;m<i.length;m++){let y=0;for(let g=0;g<o;g++){let x=r[m]?.[g];if(x&&!u.has(x)){u.add(x);let v=x._parsedProps,w=v.rowSpan??1,P=v.colSpan??1,N=0;for(let R=0;R<P;R++)N+=a[g+R];let E=0;for(let R=0;R<w;R++)E+=s[m+R];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:m,end_row_index:m+w-1,start_column_index:g,end_column_index:g+P-1,text:v.text??v.children,center:{x:c.x+y+N/2,y:c.y-h-E/2},width:N,height:E,horizontal_align:v.horizontalAlign,vertical_align:v.verticalAlign,font_size:v.fontSize??n.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[g]&&(y+=a[g])}h+=s[m]}}},OY=class extends Ne{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:CL}}},LY=class extends Ne{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:kL}}},zY=class extends Ne{constructor(){super(...arguments);T(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:eL}}},tvt={name:"@tscircuit/core",type:"module",version:"0.0.739",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"'},devDependencies:{"@biomejs/biome":"^1.8.3","@tscircuit/capacity-autorouter":"^0.0.107","@tscircuit/checks":"^0.0.75","@tscircuit/circuit-json-util":"^0.0.67","@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.21","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"0.0.335","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^0.0.38","@tscircuit/simple-3d-svg":"^0.0.41","@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.261","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-simple-3d":"^0.0.9","circuit-to-svg":"^0.0.197",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.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",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.201","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.37","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"}},Hp=class{constructor({platform:e,projectUrl:t}={}){T(this,"firstChild",null);T(this,"children");T(this,"db");T(this,"root",null);T(this,"isRoot",!0);T(this,"schematicDisabled",!1);T(this,"pcbDisabled",!1);T(this,"pcbRoutingDisabled",!1);T(this,"_featureMspSchematicTraceRouting",!0);T(this,"name");T(this,"platform");T(this,"projectUrl");T(this,"_hasRenderedAtleastOnce",!1);T(this,"_eventListeners",{});this.children=[],this.db=Ve([]),this.root=this,this.platform=e,this.projectUrl=t,this.pcbDisabled=e?.pcbDisabled??!1}add(e){let t;(0,FY.isValidElement)(e)?t=Mj(e):t=e,this.children.push(t)}_getBoard(){return this.children.find(e=>e.componentName==="Board")}_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(...))");if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let e=new Vp({subcircuit:!0});e.parent=this,e.addAll(this.children),this.children=[e],this.firstChild=e}render(){this.firstChild||this._guessRootComponent();let{firstChild:e,db:t}=this;if(!e)throw new Error("RootCircuit has no root component");e.parent=this,e.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(t=>setTimeout(t,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(e=>e._hasIncompleteAsyncEffects()?!0:e.children.some(t=>t._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(e){let t=await Promise.resolve().then(()=>(JB(),KB)).catch(n=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
228
228
 
229
229
  "${n.message}"`)});if(e.view==="pcb")return t.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(e.view==="schematic")return t.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${e.view}`)}getCoreVersion(){let[e,t,n]=tvt.version.split(".").map(Number);return`${e}.${t}.${n+1}`}async preview(e){let t=typeof e=="object"?e:{previewName:e};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return xi()}_computePcbGlobalTransformBeforeLayout(){return xi()}selectAll(e){return this._guessRootComponent(),this.firstChild?.selectAll(e)??[]}selectOne(e,t){return this._guessRootComponent(),this.firstChild?.selectOne(e,t)??null}emit(e,...t){if(this._eventListeners[e])for(let n of this._eventListeners[e])n(...t)}on(e,t){this._eventListeners[e]||(this._eventListeners[e]=[]),this._eventListeners[e].push(t)}removeListener(e,t){this._eventListeners[e]&&(this._eventListeners[e]=this._eventListeners[e].filter(n=>n!==t))}enableDebug(e){typeof e=="string"?zT.default.enable(e):(e===null||e===!1)&&zT.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},evt=Hp,nvt=Hp,ivt=e=>{let[t,n]=jp.default.useState(!0),[i,r]=jp.default.useState(null),[o,s]=jp.default.useState(),[a,c]=jp.default.useState();return jp.default.useEffect(()=>{n(!0),r(null),e&&setTimeout(()=>{try{let l=new Hp;l.add(e),s(l),c(l.toJson())}catch(l){r(l)}n(!1)},1)},[e]),{isLoading:t,error:i,circuit:o,circuitJson:a}},Gp=(e,t)=>(n,i)=>{let r=[];Array.isArray(t)?r.push(...t.flat()):typeof t=="object"&&r.push(...Object.values(t).flat(),...Object.keys(t));let o=s=>{if(s?.name&&s.name!==n)throw new Error(`Component name mismatch. Hook name: ${n}, Component prop name: ${s.name}`);let a={...i,...s,name:n},c=[];for(let l of r)if(a[l]){let u=`.${n} > .${l}`,h=a[l];c.push({from:u,to:h}),delete a[l]}return(0,xl.jsxs)(xl.Fragment,{children:[(0,xl.jsx)(e,{...a}),c.map((l,u)=>(0,xl.jsx)("trace",{...l},u))]})};for(let s of r)o[s]=`.${n} > .${s}`;return o},rvt=Gp(e=>(0,DY.jsx)("capacitor",{...e}),qO),ovt=e=>Gp(t=>(0,$Y.jsx)("chip",{pinLabels:e,...t}),e),svt=Gp(e=>(0,BY.jsx)("diode",{...e}),uL),avt=Gp(e=>(0,jY.jsx)("led",{...e}),hL),cvt=Gp(e=>(0,YY.jsx)("resistor",{...e}),XO),lvt=new Proxy(e=>new Proxy({},{get:(t,n)=>`.${e} > .${n}`}),{get:(e,t)=>{let n=(...i)=>{let r=i[0];return new Proxy({},{get:(o,s)=>`.${t} > .${s}`})};return new Proxy(n,{get:(i,r)=>t==="net"?`net.${r}`:t==="subcircuit"?new Proxy({},{get:(o,s)=>new Proxy({},{get:(a,c)=>`subcircuit.${r} > .${s} > .${c}`})}):`.${t} > .${r}`,apply:(i,r,o)=>t==="net"?new Proxy({},{get:(s,a)=>`net.${a}`}):new Proxy({},{get:(s,a)=>{let c=`.${t} > .${a}`;return["U","J","CN"].some(u=>t.startsWith(u))?c:new Proxy(new String(c),{get:(u,h)=>typeof h=="symbol"||h==="toString"?()=>c:`.${t} > .${a} > .${h}`})}})})}});Ij(wj);Ij({Bug:Sx});var GY=Zt(io(),1);var UT=new Map,Vi=async(e,t)=>{let n=new URLSearchParams({...t,json:"true"}).toString();if(UT.has(n))return UT.get(n);let r=await(await fetch(`https://jlcsearch.tscircuit.com/${e}/list?${n}`)).json();return UT.set(n,r),r},VY={findPart:async({sourceComponent:e,footprinterString:t})=>{if(e.type==="source_component"&&e.ftype==="simple_resistor"){let{resistors:n}=await Vi("resistors",{resistance:e.display_resistance??e.resistance,package:t});return{jlcpcb:(n??[]).map(i=>`C${i.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_capacitor"){t?.includes("cap")&&(t=t.replace("cap",""));let{capacitors:n}=await Vi("capacitors",{capacitance:e.display_capacitance??e.capacitance,package:t});return{jlcpcb:(n??[]).map(i=>`C${i.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_pin_header"){let n;t?.includes("_p")&&(n=Number(t.split("_p")[1]));let{headers:i}=await Vi("headers",n?{pitch:n,num_pins:e.pin_count,gender:e.gender}:{num_pins:e.pin_count,gender:e.gender});return{jlcpcb:(i??[]).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_potentiometer"){let{potentiometers:n}=await Vi("potentiometers",{resistance:e.max_resistance,package:t});return{jlcpcb:(n??[]).map(i=>`C${i.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_diode"){let{diodes:n}=await Vi("diodes",{package:t});return{jlcpcb:(n??[]).map(i=>`C${i.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_chip"){let{chips:n}=await Vi("chips",{package:t});return{jlcpcb:(n??[]).map(i=>`C${i.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_transistor"){let{transistors:n}=await Vi("transistors",{package:t,transistor_type:e.transistor_type});return{jlcpcb:(n??[]).map(i=>`C${i.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_power_source"){let{power_sources:n}=await Vi("power_sources",{voltage:e.voltage,package:t});return{jlcpcb:(n??[]).map(i=>`C${i.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_inductor"){let{inductors:n}=await Vi("inductors",{inductance:e.inductance,package:t});return{jlcpcb:(n??[]).map(i=>`C${i.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_crystal"){let{crystals:n}=await Vi("crystals",{frequency:e.frequency,load_capacitance:e.load_capacitance,package:t});return{jlcpcb:(n??[]).map(i=>`C${i.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_mosfet"){let{mosfets:n}=await Vi("mosfets",{package:t,mosfet_mode:e.mosfet_mode,channel_type:e.channel_type});return{jlcpcb:(n??[]).map(i=>`C${i.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_resonator"){let{resonators:n}=await Vi("resonators",{frequency:e.frequency,package:t});return{jlcpcb:(n??[]).map(i=>`C${i.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_switch"){let{switches:n}=await Vi("switches",{switch_type:e.type,package:t});return{jlcpcb:(n??[]).map(i=>`C${i.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_led"){let{leds:n}=await Vi("leds",{package:t});return{jlcpcb:(n??[]).map(i=>`C${i.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_fuse"){let{fuses:n}=await Vi("fuses",{package:t});return{jlcpcb:(n??[]).map(i=>`C${i.lcsc}`).slice(0,3)}}return{}}};var uvt="https://kicad-mod-cache.tscircuit.com",HY=()=>({partsEngine:VY,footprintLibraryMap:{kicad:async e=>{let t=`${uvt}/${e}`,n=`${t}.circuit.json`,r=await(await fetch(n)).json(),o=Array.isArray(r)?r.filter(a=>a?.type==="pcb_silkscreen_text"?a?.text==="REF**":!0):r,s=`${t}.wrl`;return{footprintCircuitJson:o,cadModel:{wrlUrl:s,modelUnitToMmScale:2.54}}}}});var qT=Zt(Nn(),1),HGt=(0,qT.default)("tsci:eval:execution-context");function Tx(e,t={}){globalThis.React=GY;let n=t.platform||HY(),i=t.projectConfig?{...n,...t.projectConfig}:n,r=new Hp({platform:i});return t.name&&(r.name=t.name),t.debugNamespace&&r.enableDebug(t.debugNamespace),{fsMap:{},entrypoint:"",preSuppliedImports:{"@tscircuit/core":Px,tscircuit:Px,"@tscircuit/math-utils":a5,react:GY,debug:qT.default,"@tscircuit/props":{}},circuit:r,...e}}function wf(e){let t=e;return t=t.replace(/\\/g,"/"),t=t.trim(),t.startsWith("./")&&(t=t.slice(2)),t.startsWith("/")&&(t=t.slice(1)),t}function UY(e){let t={};for(let[n,i]of Object.entries(e))t[wf(n)]=i;return t}function po(e){if(!e)return".";let n=e.replace(/\\/g,"/").replace(/\/+$/,"");return n.indexOf("/")===-1?".":n.substring(0,n.lastIndexOf("/"))||"/"}function WT(e,t){if(e.startsWith("../")){let n=po(t);return WT(e.slice(3),n)}return e.startsWith("./")?WT(e.slice(2),t):e.startsWith("/")?e.slice(1):`${t}/${e}`}var Sf=(e,t,n)=>{let i=n?WT(e,n):e,r=new Set(Array.isArray(t)?t:Object.keys(t));if(r.has(i))return i;let o=new Map;for(let c of r)o.set(wf(c),c);let s=wf(i);if(o.has(s))return o.get(s);let a=["tsx","ts","json","js","jsx","obj","gltf","glb"];for(let c of a){let l=`${s}.${c}`;if(o.has(l))return o.get(l)}if(!e.startsWith("./")&&!e.startsWith("../")){let c=wf(e);if(o.has(c))return o.get(c);for(let l of a){let u=`${c}.${l}`;if(o.has(u))return o.get(u)}}return null},Ix=(e,t)=>{let n=Sf(e,t);if(!n)throw new Error(`File not found "${e}", available paths:
230
230