@tscircuit/runframe 0.0.551 → 0.0.553

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.
@@ -849,9 +849,9 @@ ${a.width}x${a.height}
849
849
  `);const i=BAt(n,r.connections);for(const a of i)e.push(` ${a}`)}e.push("");const t=r.connections.filter(n=>n.connectedPorts.length>2);if(e.push("Complex Connections (more than 2 points):"),t.length===0)e.push(" (none)");else for(let n=0;n<t.length;n++){const i=t[n];e.push(` - complex connection[${n}]:`);for(const a of i.connectedPorts)"boxId"in a?e.push(` - ${a.boxId}.${a.pinNumber}`):"netId"in a&&e.push(` - ${a.netId}`)}return e.join(`
850
850
  `)};function bAt(r){if(!r.isPassive)throw new Error(`Chip ${r.chipId} is not a passive component`);return r.leftPinCount>0||r.rightPinCount>0?"horizontal":"vertical"}function SAt(r,e){var i;const t={boxes:e.boxes.map(a=>({...a})),nets:((i=e.nets)==null?void 0:i.map(a=>({...a})))||[],connections:e.connections.map(a=>({...a,connectedPorts:[...a.connectedPorts]}))},n=r.chips.filter(a=>a.isPassive);for(const a of n){const o=t.boxes.find(s=>s.boxId===a.chipId);if(o)try{if(bAt(a)==="vertical"){if(o.leftPinCount>0||o.rightPinCount>0){const l=o.leftPinCount+o.rightPinCount;o.leftPinCount=0,o.rightPinCount=0,o.bottomPinCount=Math.ceil(l/2),o.topPinCount=Math.floor(l/2)}}else if(o.bottomPinCount>0||o.topPinCount>0){const l=o.bottomPinCount+o.topPinCount;o.bottomPinCount=0,o.topPinCount=0,o.leftPinCount=Math.ceil(l/2),o.rightPinCount=Math.floor(l/2)}}catch{continue}}return t}var wAt=r=>{const e=d=>{const f=new Set;for(const g of r.connections)for(const _ of g.connectedPorts)"boxId"in _&&_.boxId===d&&f.add(_.pinNumber);return Array.from(f).sort((g,_)=>g-_)},t=new Map;for(const d of r.connections)for(const f of d.connectedPorts)if("boxId"in f){const g=`${f.boxId}|${f.pinNumber}`;t.has(g)||t.set(g,[]),t.get(g).push(d)}let n="",i=-1;for(const d of r.boxes){const f=(d.leftPinCount??0)+(d.rightPinCount??0)+(d.topPinCount??0)+(d.bottomPinCount??0);(f>i||f===i&&d.boxId<n)&&(n=d.boxId,i=f)}const a={[n]:0},o=new Set([n]),s=new Set,l=new Set;let c=1;const u=[],A=d=>{const f=e(d).slice().reverse();for(const g of f)u.push({boxId:d,pinNumber:g})};for(A(n);u.length;){const{boxId:d,pinNumber:f}=u.pop(),g=`${d}|${f}`;if(l.has(g))continue;l.add(g);const _=[],I=new Set,E=t.get(g)??[];for(const P of E)for(const L of P.connectedPorts)"boxId"in L?L.boxId!==d&&_.push([L.boxId,L.pinNumber]):"netId"in L&&I.add(L.netId);const x=Array.from(I).sort();for(const P of x)s.has(P)||(a[P]=c++,s.add(P));const B={};for(const[P,L]of _)B[P]=B[P]===void 0?L:Math.min(B[P],L);for(const[P]of Object.entries(B).sort((L,U)=>{if(L[1]!==U[1])return L[1]-U[1];const H=z=>{const ae=new Set;for(const te of r.connections){const oe=te.connectedPorts.find(pe=>"boxId"in pe&&pe.boxId===z);if(oe&&"pinNumber"in oe)for(const pe of te.connectedPorts)pe!==oe&&"boxId"in pe&&"pinNumber"in pe&&ae.add(pe.pinNumber)}return Array.from(ae).sort((te,oe)=>te-oe).join(",")},G=H(L[0]),W=H(U[0]);return G.localeCompare(W)}))o.has(P)||(a[P]=c++,o.add(P),A(P))}return a},J2=r=>{const e={boxIdToBoxIndex:{},netIdToNetIndex:{},boxIndexToBoxId:{},netIndexToNetId:{}},t=wAt(r),n=r.boxes.map(l=>l.boxId).sort((l,c)=>{const u=t[l]??Number.MAX_SAFE_INTEGER,A=t[c]??Number.MAX_SAFE_INTEGER;return u!==A?u-A:l.localeCompare(c)});n.forEach((l,c)=>{e.boxIdToBoxIndex[l]=c,e.boxIndexToBoxId[c]=l});const i=n.map(l=>{const c=r.boxes.find(u=>u.boxId===l);return{boxIndex:e.boxIdToBoxIndex[l],leftPinCount:c.leftPinCount,rightPinCount:c.rightPinCount,topPinCount:c.topPinCount,bottomPinCount:c.bottomPinCount}}),a=r.nets.map(l=>l.netId).sort((l,c)=>t[l]-t[c]);a.forEach((l,c)=>{e.netIdToNetIndex[l]=c,e.netIndexToNetId[c]=l});const o=a.map(l=>({netIndex:e.netIdToNetIndex[l]})),s=r.connections.map(l=>({connectedPorts:l.connectedPorts.map(u=>"boxId"in u?{boxIndex:e.boxIdToBoxIndex[u.boxId],pinNumber:u.pinNumber}:{netIndex:e.netIdToNetIndex[u.netId]}).sort((u,A)=>{const d="boxIndex"in u,f="boxIndex"in A;return d&&!f?-1:!d&&f?1:d&&f?u.boxIndex!==A.boxIndex?u.boxIndex-A.boxIndex:u.pinNumber-A.pinNumber:u.netIndex-A.netIndex})}));return s.sort((l,c)=>{const u=A=>A.connectedPorts.map(d=>"boxIndex"in d?`b${d.boxIndex}p${d.pinNumber}`:`n${d.netIndex}`).join(",");return u(l).localeCompare(u(c))}),{normalizedNetlist:{boxes:i,nets:o,connections:s},transform:e}};function VV(r){return r.length}var KV=["left","bottom","right","top"],zb=(r,e)=>{let t=0,n=0;for(let i=0;i<r&&t<4;){const a=KV[t],o=e[`${a}PinCount`];if(o===void 0||o===0){t++;continue}if(n>=o){t++,n=0;continue}if(i+1===r){const s={side:a,indexOnSide:n};return a==="left"?s.indexFromTop=n:a==="right"&&(s.indexFromTop=e.rightPinCount-n-1),a==="bottom"?s.indexFromLeft=n:a==="top"&&(s.indexFromLeft=e.topPinCount-n-1),s}n++,i++}throw new Error(`Pin number out of bounds: ${r} with dimensions left=${e.leftPinCount}, right=${e.rightPinCount}, top=${e.topPinCount}, bottom=${e.bottomPinCount}`)},gM=.5,QAt=.3,MAt=class{constructor(){Ke(this,"obstacles",[])}addObstacle(r){this.obstacles.push(r)}clearObstacles(){this.obstacles=[]}findPath(r,e){const t=this.worldToGrid(r),n=this.worldToGrid(e),i=new Set,a=new Set,o=new Map,s={point:t,gCost:0,hCost:this.getHeuristic(t,n),fCost:0,parent:null,direction:null};s.fCost=s.gCost+s.hCost;const l=this.pointToKey(t);i.add(l),o.set(l,s);let c=0;const u=200,A=Math.min(this.getHeuristic(t,n)*2,10/gM);for(;i.size>0&&c<u;){c++;let d=Array.from(i)[0],f=o.get(d);for(const _ of i){const I=o.get(_);(I.fCost<f.fCost||I.fCost===f.fCost&&I.hCost<f.hCost)&&(d=_,f=I)}if(i.delete(d),a.add(d),f.point.x===n.x&&f.point.y===n.y)return this.reconstructPath(f);if(f.gCost>A)continue;const g=this.getNeighbors(f.point);for(const _ of g){const I=this.pointToKey(_);if(a.has(I)||this.isObstacle(_))continue;const E=this.getDirection(f.point,_);let x=1;f.direction&&f.direction!==E&&(x+=QAt);const B=f.gCost+x;if(i.has(I)){const P=o.get(I);B<P.gCost&&(P.gCost=B,P.fCost=P.gCost+P.hCost,P.parent=f,P.direction=E)}else{const P={point:_,gCost:B,hCost:this.getHeuristic(_,n),fCost:0,parent:f,direction:E};P.fCost=P.gCost+P.hCost,i.add(I),o.set(I,P)}}}return c>=u&&console.warn(`Pathfinding exceeded max iterations (${u})`),[]}worldToGrid(r){return{x:Math.round(r.x/gM),y:Math.round(r.y/gM)}}gridToWorld(r){return{x:r.x*gM,y:r.y*gM}}pointToKey(r){return`${r.x},${r.y}`}getHeuristic(r,e){return Math.abs(r.x-e.x)+Math.abs(r.y-e.y)}getNeighbors(r){return[{x:r.x,y:r.y+1},{x:r.x,y:r.y-1},{x:r.x-1,y:r.y},{x:r.x+1,y:r.y}]}getDirection(r,e){return e.y>r.y?"up":e.y<r.y?"down":e.x<r.x?"left":"right"}isObstacle(r){const e=this.gridToWorld(r);return this.obstacles.some(t=>e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)}reconstructPath(r){if(r.gCost*gM>10)return[];const e=[];let t=r;for(;t;)e.unshift(this.gridToWorld(t.point)),t=t.parent;return e}};function DAt(r,e,t,n){for(let a=1;a<10;a++){const o=a/10,s=r.x+(e.x-r.x)*o,l=r.y+(e.y-r.y)*o;if(W2(s,l,t,n))return!1}return!0}function W2(r,e,t,n){for(const i of t.chips){if(i.chipId===n)continue;const a=i.getWidth(),o=i.getHeight(),s=.1;if(r>=i.x-a/2-s&&r<=i.x+a/2+s&&e>=i.y-o/2-s&&e<=i.y+o/2+s)return!0}return!1}function RAt(r,e,t,n,i,a){let o=-1/0,s=1/0;for(const f of i.chips){if(f.chipId===a)continue;const g=f.getWidth(),_=f.getHeight(),I=.1,E=f.x-g/2-I,x=f.x+g/2+I,B=f.y+_/2+I,P=f.y-_/2-I,L=Math.min(r,t),U=Math.max(r,t);x>L&&E<U&&(o=Math.max(o,B),s=Math.min(s,P))}if(o!==-1/0){const f=o+.5;if(!W2(r,f,i,a)&&!W2(t,f,i,a))return{x:r,y:f};const g=s-.5;if(!W2(r,g,i,a)&&!W2(t,g,i,a))return{x:r,y:g}}const l={x:t,y:e};if(!W2(l.x,l.y,i,a))return l;const c={x:r,y:n};if(!W2(c.x,c.y,i,a))return c;const u=t-r,A=n-e;let d=1;for(;d<4;){const f=r+(u>0?d:-d),g=e+(A>0?d:-d);if(!W2(f,g,i,a))return{x:f,y:g};d+=.5}return{x:r,y:e}}var jV=class{constructor(r,e){Ke(this,"x",0);Ke(this,"y",0);Ke(this,"pathId",null);Ke(this,"lastConnected",null);Ke(this,"lastCreatedLine",null);Ke(this,"lastDx",0);Ke(this,"lastDy",0);Ke(this,"fromJunctionId",null);this.chip=r,this.pinNumber=e}get circuit(){return this.chip.circuit}line(r,e){this.pathId||(this.pathId=this.circuit.addPath().pathId);const t={x:this.x,y:this.y,ref:this.ref};this.x+=r,this.y+=e;const n={x:this.x,y:this.y,ref:this.ref};this.fromJunctionId&&(t.fromJunctionId=this.fromJunctionId,n.fromJunctionId=this.fromJunctionId);const i={start:t,end:n,pathId:this.pathId};return this.circuit.lines.push(i),this.lastDx=r,this.lastDy=e,this.lastCreatedLine=i,this}lineAt(r,e){const t=r-this.x,n=e-this.y;if(t===0&&n===0)return this;if(t===0||n===0)return this.line(t,n);let i;return this.lastCreatedLine===null?this.getPinDirection()==="horizontal"?i="x":i="y":this.lastDx!==0?i="y":i="x",i==="x"?this.line(t,0).line(0,n):this.line(0,n).line(t,0)}pathTo(r,e){const t={x:this.x,y:this.y},n={x:r,y:e};if(t.x===n.x&&t.y===n.y)return this;if(DAt(t,n,this.circuit,this.chip.chipId))return this.lineAt(r,e);const i=new MAt;for(const s of this.circuit.chips){if(s.chipId===this.chip.chipId)continue;const l=s.getWidth(),c=s.getHeight(),u=.1,A={minX:s.x-l/2-u,maxX:s.x+l/2+u,minY:s.y-c/2-u,maxY:s.y+c/2+u};i.addObstacle(A)}if(Math.abs(r-this.x)+Math.abs(e-this.y)<10){const s=i.findPath(t,n);if(s.length>0){for(let l=1;l<s.length;l++){const c=s[l],u=c.x-this.x,A=c.y-this.y;this.line(u,A)}return this}}const o=RAt(this.x,this.y,r,e,this.circuit,this.chip.chipId);return this.lineAt(o.x,o.y).lineAt(r,e)}getPinDirection(){const r=this.side;return r==="left"||r==="right"?"horizontal":"vertical"}get side(){const{side:r}=zb(this.pinNumber,this.chip);return r}get ref(){return{boxId:this.chip.chipId,pinNumber:this.pinNumber}}passive(r){const e=this.lastDx===0?"vertical":"horizontal",t=this.circuit.passive(r);e==="horizontal"?t.leftpins(1).rightpins(1):t.bottompins(1).toppins(1);const n=t.getWidth()/2,i=t.getHeight()/2,a=this.x+Math.sign(this.lastDx)*(Math.abs(this.lastDx)>0?n:0),o=this.y+Math.sign(this.lastDy)*(Math.abs(this.lastDy)>0?i:0);t.at(a,o);const s=this.lastDx>0?"left":this.lastDx<0?"right":this.lastDy>0?"bottom":"top",[l,c]=s==="left"||s==="bottom"?[t.pin(1),t.pin(2)]:[t.pin(2),t.pin(1)];return this.lastCreatedLine.end.ref=l.ref,this.lastCreatedLine.end.fromJunctionId=void 0,c}label(r){const e=r??this.circuit.generateAutoLabel(),t=this.circuit.addNetLabel({netId:e,x:this.x,y:this.y,anchorSide:this.lastDx>0?"left":this.lastDx<0?"right":this.lastDy>0?"bottom":"top",fromRef:this.ref});this.lastCreatedLine||this.line(0,0),this.lastCreatedLine.end.ref={netId:e,netLabelId:t.netLabelId},this.lastCreatedLine.end.fromJunctionId=void 0}connect(){return this.circuit.addJunction({pinRef:this.ref,x:this.x,y:this.y}),this}intersect(){const r=this.circuit.addJunction({pinRef:this.ref,x:this.x,y:this.y,showAsIntersection:!0});return this.lastCreatedLine.end.fromJunctionId=r.junctionId,this}intersectsAt(r,e){return this.lineAt(r,e),this.intersect()}connectToMark(r){const t=this.circuit.getMark(r).state;return this.lineAt(t.x,t.y),this.connect()}intersectAtMark(r){const t=this.circuit.getMark(r).state;return this.lineAt(t.x,t.y),this.intersect()}mark(r){return this.chip.addMark(r,this),this}getMarkableState(){return{x:this.x,y:this.y,lastConnected:this.lastConnected,lastDx:this.lastDx,lastDy:this.lastDy}}applyMarkableState(r){this.x=r.x,this.y=r.y,this.lastConnected=r.lastConnected,this.lastDx=r.lastDx,this.lastDy=r.lastDy,this.pathId=this.circuit.addPath().pathId}},JV=class{constructor(r,e,t=!1){Ke(this,"x",0);Ke(this,"y",0);Ke(this,"leftPins",[]);Ke(this,"rightPins",[]);Ke(this,"topPins",[]);Ke(this,"bottomPins",[]);Ke(this,"leftPinCount",0);Ke(this,"rightPinCount",0);Ke(this,"topPinCount",0);Ke(this,"bottomPinCount",0);Ke(this,"pinMap",{});Ke(this,"marks",{});Ke(this,"pinMargins",{});Ke(this,"pinPositionsAreSet",!1);this.circuit=r,this.chipId=e,this.isPassive=t}at(r,e){return this.x=r,this.y=e,this}makePin({side:r,indexOnSide:e,ccwPinNumber:t}){const n=new jV(this,t);return this.pinMap[`${r}${e}`]=n,n}leftpins(r){if(this.pinPositionsAreSet)throw new Error("Pin positions are already set, cannot add new pins");this.leftPinCount=r;for(let e=0;e<r;++e){const t=e+1,n=this.makePin({side:"left",indexOnSide:e,ccwPinNumber:t});this.leftPins.push(n)}return this}rightpins(r){if(this.pinPositionsAreSet)throw new Error("Pin positions are already set, cannot add new pins");this.rightPinCount=r;for(let e=0;e<r;++e){const t=this.leftPinCount+this.bottomPinCount+e+1,n=this.makePin({side:"right",indexOnSide:e,ccwPinNumber:t});this.rightPins.push(n)}return this}toppins(r){if(this.pinPositionsAreSet)throw new Error("Pin positions are already set, cannot add new pins");this.topPinCount=r;for(let e=0;e<r;++e){const t=this.leftPinCount+this.bottomPinCount+this.rightPinCount+e+1,n=this.makePin({side:"top",indexOnSide:e,ccwPinNumber:t});this.topPins.push(n)}return this}bottompins(r){if(this.pinPositionsAreSet)throw new Error("Pin positions are already set, cannot add new pins");this.bottomPinCount=r;for(let e=0;e<r;++e){const t=this.leftPinCount+e+1,n=this.makePin({side:"bottom",indexOnSide:e,ccwPinNumber:t});this.bottomPins.push(n)}return this}getWidth(){return this.isPassive?this.leftPinCount>0||this.rightPinCount>0?this.circuit.defaultPassiveWidth:this.circuit.defaultPassiveHeight:[this.leftPinCount>0?1:0,this.rightPinCount>0?1:0,this.topPinCount>0?1:0,this.bottomPinCount>0?1:0].reduce((e,t)=>e+t,0)===1?this.circuit.defaultSingleSidedChipWidth:this.circuit.defaultChipWidth}getHeight(){return this.isPassive?this.leftPinCount>0||this.rightPinCount>0?this.circuit.defaultPassiveHeight:this.circuit.defaultPassiveWidth:Math.max(this.leftPinCount,this.rightPinCount)*this.circuit.defaultPinSpacing+this.circuit.defaultPinSpacing*2}getCenter(){return this.isPassive?{x:this.x,y:this.y}:{x:this.x+this.getWidth()/2,y:this.y+this.getHeight()/2}}get totalPinCount(){return this.leftPinCount+this.rightPinCount+this.topPinCount+this.bottomPinCount}setPinPositions(){for(let r=1;r<=this.totalPinCount;r++){const e=this._getPin(r),t=this.getPinLocation(r);e.x=t.x,e.y=t.y}this.pinPositionsAreSet=!0}_getPin(r){let e=r;if(e<=this.leftPins.length)return this.leftPins[e-1];if(e-=this.leftPins.length,e<=this.bottomPins.length)return this.bottomPins[e-1];if(e-=this.bottomPins.length,e<=this.rightPins.length)return this.rightPins[e-1];if(e-=this.rightPins.length,e<=this.topPins.length)return this.topPins[e-1];throw new Error(`Pin number ${r} not found`)}pin(r){this.pinPositionsAreSet||this.setPinPositions();const e=this._getPin(r);return e.fromJunctionId=null,e}getPinLocation(r){const{side:e,indexFromTop:t,indexFromLeft:n}=zb(r,this);if(this.isPassive){const l=(this.leftPinCount>0?this.getWidth()/2:0)*(r===1?1:-1),c=(this.bottomPinCount>0?this.getHeight()/2:0)*(r===2?1:-1);return{x:this.x+l,y:this.y+c}}let i,a;const o=this.circuit.defaultPinSpacing,s=.2;if(e==="left"||e==="right"){i=this.x+(e==="left"?0:this.getWidth());let l=t*o;for(let c=0;c<=t;c++){const u=this.getPinNumberFromSideIndex(e,c),A=this.pinMargins[u];A!=null&&A.marginTop&&A.marginTop>s&&(l+=A.marginTop-s)}a=this.y+this.getHeight()-l-this.circuit.defaultPinSpacing*2}else{let l=n*o;for(let c=0;c<=n;c++){const u=this.getPinNumberFromSideIndex(e,c),A=this.pinMargins[u];A!=null&&A.marginLeft&&A.marginLeft>s&&(l+=A.marginLeft-s)}i=this.x+l,a=this.y+(e==="bottom"?0:this.getHeight())}return{x:i,y:a}}addMark(r,e){this.marks[r]={pinBuilder:e,state:e.getMarkableState()}}fromMark(r){if(!this.marks[r])throw new Error(`Mark "${r}" not found`);const{pinBuilder:e,state:t}=this.marks[r],n=this.circuit.addJunction({x:t.x,y:t.y,pinRef:this.marks[r].pinBuilder.ref});return e.applyMarkableState(t),e.fromJunctionId=n.junctionId,e}getPinNumberFromSideIndex(r,e){let t=1;return(r==="bottom"||r==="right"||r==="top")&&(t+=this.leftPinCount),(r==="right"||r==="top")&&(t+=this.bottomPinCount),r==="top"&&(t+=this.rightPinCount),t+=e,t}},NAt=r=>{const e=[];for(const a of r.chips)e.push(a.x),e.push(a.x+4);for(const a of r.lines)e.push(a.start.x,a.end.x);for(const a of r.netLabels)e.push(a.x);for(const a of r.connectionPoints)e.push(a.x);if(e.length===0)return r;const t=Math.min(...e),n=Math.max(...e),i=t+n;for(const a of r.chips){a.x=i-(a.x+4);const o=a.leftPins,s=a.rightPins;a.leftPins=s.slice(),a.rightPins=o.slice().reverse();const l=a.leftPinCount;a.leftPinCount=a.rightPinCount,a.rightPinCount=l}for(const a of r.lines)a.start.x=i-a.start.x,a.end.x=i-a.end.x;for(const a of r.netLabels)a.x=i-a.x;for(const a of r.connectionPoints)a.x=i-a.x;return r},cm={left:1,right:2,up:4,down:8};function TAt(r){switch(r){case 0:return" ";case cm.left:case cm.right:return"─";case cm.up:case cm.down:return"│";case cm.left|cm.right:return"─";case cm.up|cm.down:return"│";case cm.left|cm.up:return"┘";case cm.left|cm.down:return"┐";case cm.right|cm.up:return"└";case cm.right|cm.down:return"┌";case cm.left|cm.right|cm.up:return"┴";case cm.left|cm.right|cm.down:return"┬";case cm.left|cm.up|cm.down:return"┤";case cm.right|cm.up|cm.down:return"├";case cm.left|cm.right|cm.up|cm.down:return"┼";default:return" "}}var PAt=class{constructor(e={}){Ke(this,"traces",new Map);Ke(this,"overlay",new Map);Ke(this,"gridScaleX");Ke(this,"gridScaleY");Ke(this,"showAxisLabels");this.gridScaleX=e.gridScaleX??e.gridScale??1,this.gridScaleY=e.gridScaleY??e.gridScale??1,this.showAxisLabels=e.showAxisLabels??!1}addEdge(e,t,n){const i=Math.round(e*this.gridScaleX),a=Math.round(t*this.gridScaleY),o=`${i},${a}`,s=cm[n];this.traces.set(o,(this.traces.get(o)??0)|s)}putOverlay(e,t,n){if(n.length>1)throw new Error("putOverlay only supports single characters");const i=Math.round(e*this.gridScaleX),a=Math.round(t*this.gridScaleY);this.overlay.set(`${i},${a}`,n)}*coords(){const e=new Set;for(const t of this.traces.keys())e.add(t);for(const t of this.overlay.keys())e.add(t);for(const t of e){const[n,i]=t.split(",");yield[Number(n),Number(i)]}}toString(){if(this.traces.size===0&&this.overlay.size===0)return"";let e=1/0,t=-1/0,n=1/0,i=-1/0;for(const[o,s]of this.coords())o<e&&(e=o),o>t&&(t=o),s<n&&(n=s),s>i&&(i=s);const a=[];if(this.showAxisLabels){const o=Math.max(1,Math.round(5*this.gridScaleX));let s=" ";for(let l=e;l<=t;l++)if(l%o===0){const u=(this.gridScaleX!==1?(l/this.gridScaleX).toFixed(1).slice(-4):l).toString();s+=u;for(let A=1;A<o&&l+A<=t;A++)s+=" ";l+=o-1}else s+=" ";a.push(s)}for(let o=i;o>=n;o--){let s="";this.showAxisLabels&&(s=`${(o/this.gridScaleY).toFixed(1).slice(-4).toString().padStart(4," ")} `);for(let l=e;l<=t;l++){const c=`${l},${o}`,u=this.overlay.get(c),A=this.traces.get(c)??0;s+=u??TAt(A)}a.push(s.replace(/ +$/g,""))}return a.join(`
851
851
  `)}},Cye=(r,e={})=>{e.chipLabels??(e.chipLabels=!0),e.showAxisLabels??(e.showAxisLabels=!1),e.gridScaleX??(e.gridScaleX=1),e.gridScaleY??(e.gridScaleY=1);const t=e.gridScaleX,n=e.gridScaleY,i=1/t,a=new PAt({showAxisLabels:e.showAxisLabels,gridScaleX:t,gridScaleY:n}),o=[];for(const s of r.chips){if(s.isPassive){o.push(s);continue}const l=s.getWidth(),c=s.getHeight(),u=Math.round(c*e.gridScaleY);if(e.chipLabels&&s.topPinCount===0){const f=s.y+s.getHeight(),g=s.chipId;for(let _=s.x,I=0;I<g.length;I++,_+=i)a.putOverlay(_,f,g[I])}const A=Math.round(s.x*e.gridScaleX),d=Math.round(s.y*e.gridScaleY);for(let f=0;f<u;++f){let g=" ",_=" ",I=" ";const E=f===0,x=f===u-1,B=l*e.gridScaleX;if(E)g="└",_="─".repeat(B),I="┘";else if(x)g="┌",_="─".repeat(B),I="┐";else{const L=d+f;let U,H;for(const z of s.leftPins){const ae=s.getPinLocation(z.pinNumber);if(Math.round(ae.y*e.gridScaleY)===L){U=z;break}}for(const z of s.rightPins){const ae=s.getPinLocation(z.pinNumber);if(Math.round(ae.y*e.gridScaleY)===L){H=z;break}}g=U?"┤":"│",I=H?"├":"│";const G=U?String(U.pinNumber):null,W=H?String(H.pinNumber):null;if(G&&W){const z=B-G.length-W.length;_=G+" ".repeat(Math.max(1,z))+W}else G?_=G+" ".repeat(Math.max(0,B-G.length)):W?_=" ".repeat(Math.max(0,B-W.length))+W:_=" ".repeat(Math.max(0,B))}const P=g+(_.length===l-2?_:_.padEnd(l-2," "))+I;for(let L=0;L<P.length;++L){const U=(A+L)/e.gridScaleX,H=(d+f)/e.gridScaleY;a.putOverlay(U,H,P[L])}}}for(const s of r.netLabels)if(s.netId.length>0){const l=s.netId[0];a.putOverlay(s.x,s.y,l)}for(const s of r.lines)if(s.start.x===s.end.x){const l=s.start.x,c=s.start.y,u=s.end.y,A=Math.min(c,u),d=Math.max(c,u);if(A===d)continue;a.addEdge(l,c,c<u?"up":"down"),a.addEdge(l,u,c<u?"down":"up");const f=Math.round(A*e.gridScaleY),g=Math.round(d*e.gridScaleY);for(let _=f+1;_<g;_++){const I=_/e.gridScaleY;a.addEdge(l,I,"up"),a.addEdge(l,I,"down")}}else if(s.start.y===s.end.y){const l=s.start.y,c=s.start.x,u=s.end.x,A=Math.min(c,u),d=Math.max(c,u);if(A===d)continue;a.addEdge(c,l,c<u?"right":"left"),a.addEdge(u,l,c<u?"left":"right");const f=Math.round(A*e.gridScaleX),g=Math.round(d*e.gridScaleX);for(let _=f+1;_<g;_++){const I=_/e.gridScaleX;a.addEdge(I,l,"left"),a.addEdge(I,l,"right")}}for(const s of r.connectionPoints)s.showAsIntersection&&a.putOverlay(s.x,s.y,"●");for(const s of o)if(s.leftPinCount>0||s.rightPinCount>0){const c=s.x-s.getWidth()/2,u=s.getWidth()/(1/e.gridScaleX);for(let A=0,d=0;A<s.getWidth();A+=1/e.gridScaleX,d++)u<=3?s.chipId[d]&&a.putOverlay(c+A,s.y,s.chipId[d]):A===0?a.putOverlay(c+A,s.y,"["):A>=s.getWidth()-1/e.gridScaleX?a.putOverlay(c+A,s.y,"]"):s.chipId[d-1]&&a.putOverlay(c+A,s.y,s.chipId[d-1])}else a.putOverlay(s.x,s.y-s.getHeight()/2,"┬"),a.putOverlay(s.x,s.y,s.chipId[0]),s.chipId[1]&&a.putOverlay(s.x+1/e.gridScaleX,s.y,s.chipId[1]),a.putOverlay(s.x,s.y+s.getHeight()/2,"┴");return a},WV=(r,e)=>"boxId"in r&&"boxId"in e?r.boxId===e.boxId&&r.pinNumber===e.pinNumber:"netId"in r&&"netId"in e?r.netId===e.netId:"lineId"in r&&"lineId"in e?r.lineId===e.lineId:!1,Hb=r=>"boxId"in r?`box[${r.boxId}].${r.pinNumber}`:"junctionId"in r?`junction[${r.junctionId}]`:`netlabel[${r.netId},${r.netLabelId}]`,qV=r=>{let e=r.match(/^box\[([^\]]+)\]\.(\d+)$/);if(e)return{boxId:e[1],pinNumber:parseInt(e[2])};if(e=r.match(/^junction\[([^\]]+)\]$/),e)return{junctionId:e[1]};if(e=r.match(/^netlabel\[([^\]]+),([^\]]+)\]$/),e)return{netId:e[1],netLabelId:e[2]};throw new Error(`Invalid ref key: ${r}`)},kAt=r=>{const e=[],t=[],n=[],i=[];for(const a of r.chips){a.pinPositionsAreSet||a.setPinPositions();const o=[],s=[...a.leftPins,...a.bottomPins,...a.rightPins,...a.topPins];for(const c of s){const u=a.getPinLocation(c.pinNumber);o.push({pinNumber:c.pinNumber,x:u.x,y:u.y})}const l=a.getCenter();e.push({boxId:a.chipId,leftPinCount:a.leftPinCount,rightPinCount:a.rightPinCount,topPinCount:a.topPinCount,bottomPinCount:a.bottomPinCount,centerX:l.x,centerY:l.y,pins:o})}for(const a of r.netLabels)t.push({netLabelId:a.netLabelId,netId:a.netId,x:a.x,y:a.y,anchorPosition:a.anchorSide});for(const a of r.paths){const o=r.lines.filter(A=>A.pathId===a.pathId),s=new Set(o.flatMap(A=>[Hb(A.start.fromJunctionId?{junctionId:A.start.fromJunctionId}:A.start.ref),Hb(A.end.fromJunctionId?{junctionId:A.end.fromJunctionId}:A.end.ref)]));let l=Array.from(s);if(l.length===3&&l.some(A=>A.startsWith("junction["))&&(l=l.filter(A=>!A.startsWith("junction["))),l.length>2)throw new Error(`Path composed of "${Array.from(s).join(",")}" has more than 2 references (use a junction instead of connecting multiple points to the same pin)`);if(l.length===1)continue;let[c,u]=l;Hb(o[0].start.ref)===u&&([c,u]=[u,c]),n.push({points:o.flatMap(A=>[{x:A.start.x,y:A.start.y},{x:A.end.x,y:A.end.y}]),from:qV(c),to:qV(u)})}for(const a of r.connectionPoints)i.push({junctionId:a.junctionId,x:a.x,y:a.y});return{boxes:e,netLabels:t,paths:n,junctions:i}},Eye="ABCDEFGHIJKLMNOPQRSTUVWXYZ",UAt=class tVe{constructor(e={}){Ke(this,"chips",[]);Ke(this,"netLabels",[]);Ke(this,"lines",[]);Ke(this,"paths",[]);Ke(this,"connectionPoints",[]);Ke(this,"defaultChipWidth",2);Ke(this,"defaultSingleSidedChipWidth",2);Ke(this,"defaultPinSpacing",.2);Ke(this,"defaultPassiveWidth",1);Ke(this,"defaultPassiveHeight",.2);Ke(this,"autoLabelCounter",1);Ke(this,"name");Ke(this,"_pathCounter",1);Ke(this,"_netLabelCounter",1);Ke(this,"_junctionCounter",1);this.name=e.name??"Circuit"}clone(){const e=new tVe({name:this.name});e.autoLabelCounter=this.autoLabelCounter,e.defaultChipWidth=this.defaultChipWidth,e.defaultSingleSidedChipWidth=this.defaultSingleSidedChipWidth,e.defaultPinSpacing=this.defaultPinSpacing,e.defaultPassiveWidth=this.defaultPassiveWidth,e.defaultPassiveHeight=this.defaultPassiveHeight;for(const t of this.chips){const n=new JV(e,t.chipId,t.isPassive);n.x=t.x,n.y=t.y,n.leftPinCount=t.leftPinCount,n.rightPinCount=t.rightPinCount,n.topPinCount=t.topPinCount,n.bottomPinCount=t.bottomPinCount,n.pinPositionsAreSet=t.pinPositionsAreSet;const i=(a,o,s)=>Array.from({length:a},(l,c)=>{const u=new jV(n,o+c),A=s[c];return A&&typeof A.x=="number"&&(u.x=A.x),A&&typeof A.y=="number"&&(u.y=A.y),u});n.leftPins=i(n.leftPinCount,1,t.leftPins),n.bottomPins=i(n.bottomPinCount,n.leftPinCount+1,t.bottomPins),n.rightPins=i(n.rightPinCount,n.leftPinCount+n.bottomPinCount+1,t.rightPins),n.topPins=i(n.topPinCount,n.leftPinCount+n.bottomPinCount+n.rightPinCount+1,t.topPins),e.chips.push(n)}return e.lines=structuredClone(this.lines),e.paths=structuredClone(this.paths),e.netLabels=structuredClone(this.netLabels),e.connectionPoints=structuredClone(this.connectionPoints),e}chip(e){e??(e=`U${this.chips.length+1}`);const t=new JV(this,e);return this.chips.push(t),t}passive(e){const t=e??`R${this.chips.length+1}`,n=new JV(this,t,!0);return this.chips.push(n),n}addPath(){const e={pathId:`PATH${this._pathCounter++}`};return this.paths.push(e),e}addNetLabel(e){const t={netLabelId:`NL${this._netLabelCounter++}`,...e};return this.netLabels.push(t),t}addJunction({x:e,y:t,pinRef:n,showAsIntersection:i=!1}){for(const o of this.connectionPoints)if(o.x===e&&o.y===t)return o;const a={junctionId:`XX${this._junctionCounter++}`,x:e,y:t,pinRef:n,showAsIntersection:i};return this.connectionPoints.push(a),a}toString(){return Cye(this,{chipLabels:!0,showAxisLabels:!0,gridScaleX:2,gridScaleY:5}).toString()}getNetlist(){const e=new xAt;for(const o of this.chips)e.addBox({boxId:o.chipId,leftPinCount:o.leftPinCount||0,rightPinCount:o.rightPinCount||0,topPinCount:o.topPinCount||0,bottomPinCount:o.bottomPinCount||0});for(const o of this.netLabels)e.addNet({netId:o.netId}),e.connect(o.fromRef,{netId:o.netId,netLabelId:o.netLabelId});for(const o of this.lines)WV(o.start.ref,o.end.ref)||e.connect(o.start.ref,o.end.ref);const t=(o,s,l)=>{const c=o.get(s)??[];c.push(l),o.set(s,c)},n=new Map;for(const o of this.connectionPoints)t(n,`${o.x},${o.y}`,o.pinRef);const i=new Set;for(const o of this.connectionPoints)i.add(`${o.x},${o.y}`);for(const o of this.lines)t(n,`${o.start.x},${o.start.y}`,o.start.ref),t(n,`${o.end.x},${o.end.y}`,o.end.ref);for(const[o,s]of n.entries())if(i.has(o))for(let l=0;l<s.length;++l)for(let c=l+1;c<s.length;++c)e.connect(s[l],s[c]);const a=(o,s,l)=>{if(l.start.x===l.end.x){if(o!==l.start.x)return!1;const c=Math.min(l.start.y,l.end.y),u=Math.max(l.start.y,l.end.y);return s>=c&&s<=u}else if(l.start.y===l.end.y){if(s!==l.start.y)return!1;const c=Math.min(l.start.x,l.end.x),u=Math.max(l.start.x,l.end.x);return o>=c&&o<=u}return!1};for(const o of this.connectionPoints)for(const s of this.lines)a(o.x,o.y,s)&&e.connect(o.pinRef,s.start.ref);return e.getNetlist()}getReadableNetlist(){return AD(this.getNetlist())}flipX(){return NAt(this)}generateAutoLabel(){return Eye[this.autoLabelCounter++-1]??`L${this.autoLabelCounter-Eye.length}`}getGrid(){return Cye(this)}getMark(e){var t;for(const n of this.chips){const i=(t=n.marks)==null?void 0:t[e];if(i)return i}throw new Error(`Mark "${e}" not found in circuit`)}getLayoutJson(){return kAt(this)}};function LS(r={}){return new UAt({name:r.name})}function FAt(r){const e=r.candidateNetlist.boxes[r.candidateBoxIndex],t=r.targetNetlist.boxes[r.targetBoxIndex],n=[];for(const i of KV){const a=e[`${i}PinCount`]??0,o=t[`${i}PinCount`]??0;a!==o&&n.push({type:"matched_box_side_has_wrong_pin_count",candidateBoxIndex:r.candidateBoxIndex,targetBoxIndex:r.targetBoxIndex})}return n}var ak=r=>{const e=r.boxes.map(i=>({boxId:`box${i.boxIndex}`,leftPinCount:i.leftPinCount,rightPinCount:i.rightPinCount,topPinCount:i.topPinCount,bottomPinCount:i.bottomPinCount})),t=r.nets.map(i=>({netId:`net${i.netIndex}`})),n=r.connections.map(i=>({connectedPorts:i.connectedPorts.map(a=>"boxIndex"in a?{boxId:`box${a.boxIndex}`,pinNumber:a.pinNumber}:{netId:`net${a.netIndex}`})}));return{boxes:e,nets:t,connections:n}};function ZV(r){const{netlist:e,chipId:t,pinNumber:n}=r,i=`${t}.pin${n}`,a=[{boxId:i,leftPinCount:0,rightPinCount:1,topPinCount:0,bottomPinCount:0}],o=[],s=[],l=new Set([i]),c=new Set;for(const u of e.connections)if(u.connectedPorts.some(d=>"boxId"in d&&d.boxId===t&&d.pinNumber===n)){const d=[{boxId:i,pinNumber:1}];for(const f of u.connectedPorts)if("boxId"in f){if(f.boxId===t&&f.pinNumber===n)continue;if(d.push({boxId:f.boxId,pinNumber:f.pinNumber}),!l.has(f.boxId)){const g=e.boxes.find(_=>_.boxId===f.boxId);g&&a.push(g),l.add(f.boxId)}}else"netId"in f&&(d.push({netId:f.netId}),c.has(f.netId)||(o.push({netId:f.netId}),c.add(f.netId)));d.length>1&&s.push({connectedPorts:d})}return{boxes:a,nets:o,connections:s}}var XV=r=>[r.leftPinCount>0?`L${r.leftPinCount}`:"",r.bottomPinCount>0?`B${r.bottomPinCount}`:"",r.rightPinCount>0?`R${r.rightPinCount}`:"",r.topPinCount>0?`T${r.topPinCount}`:""].join(""),$V=r=>{const{netlist:e,chipId:t,pinNumber:n}=r,i=new Set;for(const a of e.connections)if(a.connectedPorts.some(s=>"boxId"in s&&s.boxId===t&&s.pinNumber===n))for(const s of a.connectedPorts)"boxId"in s&&s.boxId!==t&&i.add(s.boxId);return`box_count_${i.size}`},eK=r=>{let e;if("pinShapeNetlist"in r)e=r.pinShapeNetlist;else{const{netlist:n,chipId:i,pinNumber:a}=r;e=ZV({chipId:i,pinNumber:a,netlist:n})}return`${J2(e).normalizedNetlist.boxes.map(n=>XV(n)).join(",")}`};function LAt(r){const e=ak(r.candidateNetlist),t=ak(r.targetNetlist),n=[],i=e.boxes[r.candidateBoxIndex],a=t.boxes[r.targetBoxIndex],o=i.leftPinCount+i.rightPinCount+i.topPinCount+i.bottomPinCount,s=o===2&&Math.max(i.leftPinCount,i.rightPinCount,i.topPinCount,i.bottomPinCount)===1;for(let d=0;d<o;d++){const f=d+1,g=ZV({netlist:e,chipId:i.boxId,pinNumber:f});n.push({side:zb(f,i).side,signature:eK({pinShapeNetlist:g})})}const l=[...n],c=[],u=a.leftPinCount+a.rightPinCount+a.topPinCount+a.bottomPinCount,A=u===2&&Math.max(a.leftPinCount,a.rightPinCount,a.topPinCount,a.bottomPinCount)===1;for(let d=0;d<u;d++){const f=d+1,g=ZV({netlist:t,chipId:a.boxId,pinNumber:f});if(g.connections.length===0)continue;const _={signature:eK({pinShapeNetlist:g}),side:zb(f,a).side},I=A&&s,E=l.findIndex(x=>x.signature===_.signature&&(x.side===_.side||I));if(E!==-1){l.splice(E,1);continue}c.push({type:"matched_box_missing_pin_shape_on_side",candidateBoxIndex:r.candidateBoxIndex,targetBoxIndex:r.targetBoxIndex,targetPinNumber:f,targetPinShapeSignature:_.signature,candidateShapeSignatures:l.map(x=>x.signature),side:_.side})}return c}function GAt(r){const{candidateNetlist:e,targetNetlist:t,candidateBoxIndex:n,targetBoxIndex:i}=r,a=[],o=ak(e),s=ak(t),l=o.boxes[n],c=s.boxes[i];if(!l||!c)return a;const u=[],A=l.leftPinCount+l.rightPinCount+l.topPinCount+l.bottomPinCount;for(let _=0;_<A;_++){const I=_+1,E=$V({netlist:o,chipId:l.boxId,pinNumber:I});u.push({side:zb(I,l).side,signature:E})}const d=[...u],f=c.leftPinCount+c.rightPinCount+c.topPinCount+c.bottomPinCount;if(A===2&&f===2&&Math.max(l.leftPinCount,l.rightPinCount,l.topPinCount,l.bottomPinCount)===1&&Math.max(c.leftPinCount,c.rightPinCount,c.topPinCount,c.bottomPinCount)===1){const _=u.map(E=>E.signature).filter(E=>E!=="box_count_0").sort(),I=[];for(let E=0;E<f;E++){const x=E+1,B=$V({netlist:s,chipId:c.boxId,pinNumber:x});B!=="box_count_0"&&I.push(B)}I.sort(),_.length>0&&I.length>0&&_.join(",")!==I.join(",")&&a.push({type:"matched_box_missing_pin_shape_box_count_on_side",candidateBoxIndex:n,targetBoxIndex:i,side:"left",targetPinNumber:-1,targetBoxCountSignature:I.join(","),candidateBoxCountSignatures:_})}else for(let _=0;_<f;_++){const I=_+1,E=$V({netlist:s,chipId:c.boxId,pinNumber:I});if(E==="box_count_0")continue;const x={signature:E,side:zb(I,c).side},B=d.findIndex(P=>P.signature===x.signature&&P.side===x.side);if(B===-1){const P=u.filter(L=>L.side===x.side).map(L=>L.signature);a.push({type:"matched_box_missing_pin_shape_box_count_on_side",candidateBoxIndex:n,targetBoxIndex:i,side:x.side,targetPinNumber:I,targetBoxCountSignature:E,candidateBoxCountSignatures:P})}else d.splice(B,1)}return a}var OAt=[FAt,LAt,GAt];function zAt(r){const e=[];for(const t of OAt)e.push(...t(r));return e}function _ye(r){if(r.leftPinCount+r.rightPinCount+r.topPinCount+r.bottomPinCount!==2)return!1;const t=r.leftPinCount>0&&r.rightPinCount>0,n=r.topPinCount>0&&r.bottomPinCount>0;return t||n}function HAt(r){return{...r,leftPinCount:r.topPinCount,rightPinCount:r.bottomPinCount,topPinCount:r.leftPinCount,bottomPinCount:r.rightPinCount}}function YAt(r){return{...r,leftPinCount:r.rightPinCount,rightPinCount:r.leftPinCount,topPinCount:r.bottomPinCount,bottomPinCount:r.topPinCount}}function VAt(r){const{targetNetlist:e,candidateNetlist:t,targetBoxIndex:n,candidateBoxIndex:i}=r,a=e.boxes[n],o=t.boxes[i];if(!a||!o)return[{netlist:e,rotation:0}];if(!_ye(a)||!_ye(o))return[{netlist:e,rotation:0}];const s=[];let l={...a},c=0;for(let g=0;g<4&&!(l.leftPinCount===o.leftPinCount&&l.rightPinCount===o.rightPinCount&&l.topPinCount===o.topPinCount&&l.bottomPinCount===o.bottomPinCount);g++)l=HAt(l),c=(c+90)%360;const u={...e,boxes:e.boxes.map((g,_)=>_===n?l:g)};s.push({netlist:u,rotation:c});const A=YAt(l),d={...e,boxes:e.boxes.map((g,_)=>_===n?A:g)},f=(c+180)%360;return s.push({netlist:d,rotation:f}),s}function ok(r){const{candidateNetlist:e,targetNetlist:t}=r,n=[],i=new Set;for(let a=0;a<t.boxes.length;a++){const o=new Map;for(let c=0;c<e.boxes.length;c++){if(i.has(c))continue;const u=VAt({targetNetlist:t,candidateNetlist:e,targetBoxIndex:a,candidateBoxIndex:c});let A=[],d=1/0,f=0;for(const{netlist:g,rotation:_}of u){const I=zAt({candidateNetlist:e,targetNetlist:g,candidateBoxIndex:c,targetBoxIndex:a,alreadyMatchedBoxes:n}),E=VV(I);E<d&&(d=E,A=I,f=_)}o.set({targetBoxIndex:a,candidateBoxIndex:c},{issues:A,similarityDistance:d,rotation:f})}let s=null,l=1/0;for(const[c,{similarityDistance:u}]of o.entries())u<l&&(l=u,s=c);if(s){const{candidateBoxIndex:c}=s,{issues:u,similarityDistance:A,rotation:d}=o.get(s);i.add(c),n.push({targetBoxIndex:a,candidateBoxIndex:c,issues:u,score:A,targetBoxRotationCcw:d})}}return n}function tK(r){return r==="left"?{dx:-1,dy:0}:r==="right"?{dx:1,dy:0}:r==="top"?{dx:0,dy:1}:{dx:0,dy:-1}}function KAt(r,e){const{chipId:t,pinNumber:n,netName:i}=e,a=r.chips.find(A=>A.chipId===t);if(!a||n<1||n>a.totalPinCount)return;const o=a.pin(n);if(!o||typeof o.line!="function")return;const{side:s}=zb(n,a),{dx:l,dy:c}=tK(s);o.line(l*2,c*2);const u=i||r.generateAutoLabel();o.label(u)}function jAt(r,e){const{chipId:t,pinNumber:n}=e,i=a=>"boxId"in a&&a.boxId===t&&a.pinNumber===n;r.lines=r.lines.filter(a=>!i(a.start.ref)&&!i(a.end.ref)),r.connectionPoints=r.connectionPoints.filter(a=>!i(a.pinRef)),r.netLabels=r.netLabels.filter(a=>!i(a.fromRef))}function JAt(r,e){const{chipId:t,pinNumber:n}=e,i=r.chips.find(o=>o.chipId===t);if(!i)return;const a=i.pin(n);if(a.lastDx===0&&a.lastDy===0&&!a.lastCreatedLine){const o=tK(a.side);a.line(o.dx*2,o.dy*2)}a.passive()}function WAt(r,e){const{chipId:t,pinNumber:n,labelNetId:i}=e,a=r.chips.find(l=>l.chipId===t);if(!a)return;const o=a.pin(n);if(o.lastDx===0&&o.lastDy===0&&!o.lastCreatedLine){const l=tK(o.side);o.line(l.dx*2,l.dy*2)}o.passive().label(i)}function qAt(r,e){const{chipId:t}=e;r.chips=r.chips.filter(a=>a.chipId!==t);const n=a=>"boxId"in a&&a.boxId===t,i=r.lines.filter(a=>n(a.start.ref)||n(a.end.ref));r.lines=r.lines.filter(a=>!(n(a.start.ref)&&n(a.end.ref)));for(const a of i){if(n(a.start.ref)&&n(a.end.ref))continue;const o=n(a.start.ref)?a.start:a.end,s=n(a.start.ref)?a.end:a.start;xye(r,s.x,s.y,a)?r.lines=r.lines.filter(c=>c!==a):(r.lines=r.lines.filter(c=>c!==a),Bye(r,s.x,s.y,s.ref,o.ref))}r.connectionPoints=r.connectionPoints.filter(a=>!n(a.pinRef)),r.netLabels=r.netLabels.filter(a=>!n(a.fromRef))}function xye(r,e,t,n){let i=0;for(const a of r.lines)a!==n&&(a.start.x===e&&a.start.y===t||a.end.x===e&&a.end.y===t)&&i++;for(const a of r.connectionPoints)if(a.x===e&&a.y===t){i++;break}return i>=2}function Bye(r,e,t,n,i){const a=r.lines.filter(o=>{const s=o.start.x===e&&o.start.y===t&&!WV(o.start.ref,i),l=o.end.x===e&&o.end.y===t&&!WV(o.end.ref,i);return s||l});for(const o of a){const s=o.start.x===e&&o.start.y===t?o.end:o.start;if(xye(r,s.x,s.y,o))return;r.lines=r.lines.filter(c=>c!==o),Bye(r,s.x,s.y,s.ref,i)}}var ZAt=(r,e,t)=>{const n=i=>"boxId"in i&&i.boxId===e&&t.has(i.pinNumber)?{...i,pinNumber:t.get(i.pinNumber)}:i;for(const i of r.lines)i.start.ref=n(i.start.ref),i.end.ref=n(i.end.ref);for(const i of r.connectionPoints)i.pinRef=n(i.pinRef);for(const i of r.netLabels)i.fromRef=n(i.fromRef)};function XAt(r,e){const{chipId:t,side:n,pinNumber:i}=e,a=r.chips.find(B=>B.chipId===t);if(!a)return;const o=a.totalPinCount;if(i<1||i>o)throw new Error(`Invalid pin number: ${i} for chip ${a.chipId} with dimensions ${a.leftPinCount}x${a.bottomPinCount}x${a.rightPinCount}x${a.topPinCount}`);a.pinPositionsAreSet||a.setPinPositions();const s=new Map;for(let B=1;B<=o;++B)s.set(B,a.getPinLocation(B));const l=B=>"boxId"in B&&B.boxId===t&&B.pinNumber===i;r.lines=r.lines.filter(B=>!l(B.start.ref)&&!l(B.end.ref)),r.connectionPoints=r.connectionPoints.filter(B=>!l(B.pinRef)),r.netLabels=r.netLabels.filter(B=>!l(B.fromRef));let c,u;switch(n){case"left":c=a.leftPins,u="leftPinCount";break;case"right":c=a.rightPins,u="rightPinCount";break;case"top":c=a.topPins,u="topPinCount";break;case"bottom":c=a.bottomPins,u="bottomPinCount";break;default:return}const A=c.findIndex(B=>B.pinNumber===i);if(A===-1)throw new Error(`Pin number ${i} not found on side ${n} of chip ${a.chipId}`);c.splice(A,1),a[u]--;const d=new Map;for(let B=1;B<=o;++B)B!==i&&(B<i?d.set(B,B):d.set(B,B-1));const f=[...a.leftPins,...a.bottomPins,...a.rightPins,...a.topPins];for(const B of f){const P=B.pinNumber,L=d.get(P);L!==void 0&&(B.pinNumber=L)}const{side:g,indexOnSide:_}=zb(i,{leftPinCount:a.leftPinCount+(n==="left"?1:0),rightPinCount:a.rightPinCount+(n==="right"?1:0),topPinCount:a.topPinCount+(n==="top"?1:0),bottomPinCount:a.bottomPinCount+(n==="bottom"?1:0)}),I={};for(const[B,P]of d.entries())a.pinMargins[B]&&(I[P]={...a.pinMargins[B]});for(const[B,P]of d.entries()){const L=zb(B,{leftPinCount:a.leftPinCount+(n==="left"?1:0),rightPinCount:a.rightPinCount+(n==="right"?1:0),topPinCount:a.topPinCount+(n==="top"?1:0),bottomPinCount:a.bottomPinCount+(n==="bottom"?1:0)});if(L.side===g&&L.indexOnSide>_){const U=I[P]||{marginTop:.2,marginLeft:.2};n==="left"||n==="right"?I[P]={...U,marginTop:U.marginTop+.2}:I[P]={...U,marginLeft:U.marginLeft+.2}}}a.pinMargins=I;const E=new Map;for(const[B,P]of d.entries())B!==P&&E.set(B,P);E.size>0&&ZAt(r,a.chipId,E),a.pinPositionsAreSet=!1,a.setPinPositions();const x=new Map;for(let B=1;B<=o;++B){if(B===i)continue;const P=d.get(B),L=s.get(B),U=a.getPinLocation(P),H=U.x-L.x,G=U.y-L.y;(H!==0||G!==0)&&x.set(P,{dx:H,dy:G})}if(x.size>0){const B=P=>"boxId"in P&&P.boxId===t&&x.has(P.pinNumber)?x.get(P.pinNumber):null;for(const P of r.lines){const L=B(P.start.ref),U=B(P.end.ref);(L??U)&&(L&&(P.start.x+=L.dx,P.start.y+=L.dy),U&&(P.end.x+=U.dx,P.end.y+=U.dy))}for(const P of r.connectionPoints){const L=B(P.pinRef);L&&(P.x+=L.dx,P.y+=L.dy)}for(const P of r.netLabels){const L=B(P.fromRef);L&&(P.x+=L.dx,P.y+=L.dy)}}}var $At=(r,e,t)=>{const n=i=>"boxId"in i&&i.boxId===e&&t.has(i.pinNumber)?{...i,pinNumber:t.get(i.pinNumber)}:i;for(const i of r.lines)i.start.ref=n(i.start.ref),i.end.ref=n(i.end.ref);for(const i of r.connectionPoints)i.pinRef=n(i.pinRef);for(const i of r.netLabels)i.fromRef=n(i.fromRef)};function edt(r,e){const{chipId:t,side:n,betweenPinNumbers:i}=e,a=r.chips.find(B=>B.chipId===t);if(!a)return;const o=a.totalPinCount,s=new Map;for(let B=1;B<=o;++B)s.set(B,a.getPinLocation(B));const l=Math.min(...i),c=n==="left"?a.leftPins:n==="right"?a.rightPins:n==="top"?a.topPins:a.bottomPins,u=c.findIndex(B=>B.pinNumber===l)+1;if(l!==0&&u===0)return;a[`${n}PinCount`]+=1;const A=l+1,d=new jV(a,A);c.splice(u,0,d);const f=new Map,g=a.totalPinCount-1;for(let B=1;B<=g;++B)B>l&&f.set(B,B+1);const _=new Set([d]),I=B=>B.forEach(P=>{_.has(P)||f.has(P.pinNumber)&&(P.pinNumber=f.get(P.pinNumber))});I(a.leftPins),I(a.rightPins),I(a.topPins),I(a.bottomPins),$At(r,t,f),a.pinPositionsAreSet=!1,a.setPinPositions();const E=new Map;for(let B=1;B<=o;++B){const P=s.get(B),L=f.get(B)??B,U=a.getPinLocation(L),H=U.x-P.x,G=U.y-P.y;(H||G)&&E.set(L,{dx:H,dy:G})}const x=B=>"boxId"in B&&B.boxId===t&&E.has(B.pinNumber)?E.get(B.pinNumber):null;for(const B of r.lines){const P=x(B.start.ref)??x(B.end.ref);P&&(B.start.x+=P.dx,B.start.y+=P.dy,B.end.x+=P.dx,B.end.y+=P.dy)}for(const B of r.connectionPoints){const P=x(B.pinRef);P&&(B.x+=P.dx,B.y+=P.dy)}for(const B of r.netLabels){const P=x(B.fromRef);P&&(B.x+=P.dx,B.y+=P.dy)}}function tdt(r,e){const t=r.chips.find(i=>i.chipId===e.chipId);if(!t)throw new Error(`Chip ${e.chipId} not found`);if(!t.isPassive)throw new Error(`Chip ${e.chipId} is not a passive component`);if(t.totalPinCount!==2)throw new Error(`Passive orientation change only supports 2-pin passives, got ${t.totalPinCount} pins`);(t.leftPinCount>0||t.rightPinCount>0?"horizontal":"vertical")!==e.toOrientation&&(e.toOrientation==="horizontal"?(t.leftPinCount=1,t.rightPinCount=1,t.bottomPinCount=0,t.topPinCount=0,t.leftPins=[t.bottomPins[0]||t.topPins[0]],t.rightPins=[t.topPins[0]||t.bottomPins[0]],t.bottomPins=[],t.topPins=[]):(t.bottomPinCount=1,t.topPinCount=1,t.leftPinCount=0,t.rightPinCount=0,t.bottomPins=[t.leftPins[0]||t.rightPins[0]],t.topPins=[t.rightPins[0]||t.leftPins[0]],t.leftPins=[],t.rightPins=[]))}function ndt(r,e){const{fromChipId:t,fromPinNumber:n,toChipId:i,toPinNumber:a,netName:o}=e,s=r.chips.find(f=>f.chipId===t),l=r.chips.find(f=>f.chipId===i);if(!s)throw new Error(`Could not find from chip with id: ${t}`);if(!l)throw new Error(`Could not find to chip with id: ${i}`);const c=s.pin(n),u=l.pin(a);if(!c)throw new Error(`Could not find pin ${n} on chip ${t}`);if(!u)throw new Error(`Could not find pin ${a} on chip ${i}`);const A=l.getPinLocation(a),d=o||`connection_${t}_${n}_to_${i}_${a}`;c.pathTo(A.x,A.y).mark(d),u.connectToMark(d)}function mM(r,e){switch(e.type){case"add_label_to_pin":KAt(r,e);break;case"add_passive_to_pin":JAt(r,e);break;case"add_passive_with_label_to_pin":WAt(r,e);break;case"clear_pin":jAt(r,e);break;case"add_pin_to_side":edt(r,e);break;case"remove_pin_from_side":XAt(r,e);break;case"remove_chip":qAt(r,e);break;case"change_passive_orientation":tdt(r,e);break;case"draw_line_between_pins":ndt(r,e);break}}function dD(r){const e=[],{template:t,target:n}=r,i=t.getNetlist(),a=J2(i),o=J2(n),s=a.normalizedNetlist,l=o.normalizedNetlist,c=ok({candidateNetlist:s,targetNetlist:l}).map(u=>{var A,d;return{...u,candidateChipId:(A=Object.entries(a.transform.boxIdToBoxIndex).find(([f,g])=>g===u.candidateBoxIndex))==null?void 0:A[0],targetChipId:(d=Object.entries(o.transform.boxIdToBoxIndex).find(([f,g])=>g===u.targetBoxIndex))==null?void 0:d[0]}});for(const u of t.chips){if(c.some(f=>f.candidateChipId===u.chipId))continue;const d={type:"remove_chip",chipId:u.chipId};mM(t,d),e.push(d);break}return{appliedOperations:e,matchedBoxes:c}}function rdt(r){const{template:e,target:t,matchedBoxes:n}=r,i=[],a=t.boxes;for(const{candidateChipId:o,targetChipId:s}of n){const l=e.chips.find(u=>u.chipId===o),c=a.find(u=>u.boxId===s);if(!(!c||!l)&&!l.isPassive)for(const u of KV){const A=c[`${u}PinCount`];if(l[`${u}PinCount`]<A){let d;u==="left"?d=0:u==="bottom"?d=l.leftPinCount+l.bottomPinCount:u==="right"?d=l.leftPinCount+l.bottomPinCount+l.rightPinCount:d=l.totalPinCount;const f={type:"add_pin_to_side",chipId:l.chipId,side:u,betweenPinNumbers:[d,d+1]};return mM(e,f),i.push(f),{appliedOperations:i}}if(l[`${u}PinCount`]>A){const d=idt({template:e,target:t,chipId:l.chipId,side:u}),f={type:"remove_pin_from_side",chipId:l.chipId,side:u,pinNumber:d};return mM(e,f),i.push(f),{appliedOperations:i}}}}return{appliedOperations:i}}function idt(r){const{template:e,target:t,chipId:n,side:i}=r,a=e.chips.find(u=>u.chipId===n);if(!a)throw new Error(`Chip ${n} not found`);const s={left:a.leftPins,right:a.rightPins,top:a.topPins,bottom:a.bottomPins}[i];if(s.length===0)throw new Error(`No pins found on side ${i} of chip ${n}`);let l=s[s.length-1].pinNumber,c=Number.POSITIVE_INFINITY;for(const u of s)try{const A=e.clone(),d={type:"remove_pin_from_side",chipId:n,side:i,pinNumber:u.pinNumber};mM(A,d);const f=adt(A,t);f<c&&(c=f,l=u.pinNumber)}catch{continue}return l}function adt(r,e){try{const t=J2(r.getNetlist()),n=J2(e),a=ok({candidateNetlist:t.normalizedNetlist,targetNetlist:n.normalizedNetlist}).flatMap(o=>o.issues||[]);return VV(a)}catch{return Number.POSITIVE_INFINITY}}function odt(r){const{template:e,target:t,matchedBoxes:n}=r,i=[];for(const{candidateChipId:a,targetChipId:o}of n){const s=e.chips.find(u=>u.chipId===a),l=t.boxes.find(u=>u.boxId===o);if(!l||!s)continue;const c=["left","right","top","bottom"];for(const u of c){const A=s[`${u}PinCount`],d=l[`${u}PinCount`]||0;if(A>d){const f=A-d,g=sdt({template:e,chipId:a,side:u,pinsToRemove:f});if(g.length>0){const _=g[0];return mM(e,_),i.push(_),{appliedOperations:i}}}}}return{appliedOperations:i}}function sdt(r){const{template:e,chipId:t,side:n,pinsToRemove:i}=r,a=e.chips.find(c=>c.chipId===t);if(!a)return[];const s={left:a.leftPins,right:a.rightPins,top:a.topPins,bottom:a.bottomPins}[n];if(s.length<=i)return s.map(c=>({type:"remove_pin_from_side",chipId:t,side:n,pinNumber:c.pinNumber}));const l=s[s.length-1];return[{type:"remove_pin_from_side",chipId:t,side:n,pinNumber:l.pinNumber}]}function ldt(r){const e=[],{template:t,target:n,matchedBoxes:i}=r,a=n.connections||[];for(const o of a){const s=o.connectedPorts.filter(E=>"boxId"in E);if(s.length!==2)continue;const[l,c]=s;if(!l||!c)continue;const u=i.find(E=>{var x,B;return((B=(x=n.boxes)==null?void 0:x[E.targetBoxIndex])==null?void 0:B.boxId)===l.boxId}),A=i.find(E=>{var x,B;return((B=(x=n.boxes)==null?void 0:x[E.targetBoxIndex])==null?void 0:B.boxId)===c.boxId});if(!(u!=null&&u.candidateChipId)||!(A!=null&&A.candidateChipId))continue;const d=u.candidateChipId,f=A.candidateChipId;if(!(t.getNetlist().connections||[]).some(E=>{const x=E.connectedPorts.filter(L=>"boxId"in L),B=x.some(L=>L.boxId===d&&L.pinNumber===l.pinNumber),P=x.some(L=>L.boxId===f&&L.pinNumber===c.pinNumber);return B&&P})){const E={type:"draw_line_between_pins",fromChipId:d,fromPinNumber:l.pinNumber,toChipId:f,toPinNumber:c.pinNumber};try{mM(t,E),e.push(E);break}catch(x){console.warn("Failed to apply draw line operation:",x)}}}return{appliedOperations:e}}var cdt=class extends hM{constructor(e){super();Ke(this,"inputTemplate");Ke(this,"targetNetlist");Ke(this,"transformedTarget",null);Ke(this,"outputAdaptedTemplate",null);Ke(this,"outputAppliedOperations",[]);Ke(this,"phase","transform-target");Ke(this,"matchedBoxes",[]);Ke(this,"stepCount",0);Ke(this,"maxSteps",100);this.inputTemplate=e.inputTemplate,this.targetNetlist=e.targetNetlist}getConstructorParams(){return{inputTemplate:this.inputTemplate,targetNetlist:this.targetNetlist}}getStatsSummary(){return`Phase: ${this.phase}, ${this.outputAppliedOperations.length} operations applied`}_step(){var e,t;if(this.stepCount++,this.stepCount>this.maxSteps){console.warn(`AdaptTemplateToNetlistSolver exceeded max steps (${this.maxSteps}), stopping`),this.solved=!0;return}switch(this.outputAdaptedTemplate||(this.outputAdaptedTemplate=this.inputTemplate.clone()),this.phase){case"transform-target":this.transformedTarget=SAt(this.outputAdaptedTemplate,this.targetNetlist),this.phase="remove-unmatched-chips-1";break;case"remove-unmatched-chips-1":{const n=dD({template:this.outputAdaptedTemplate,target:this.transformedTarget});if(this.matchedBoxes=n.matchedBoxes,n.appliedOperations.length>0){const i=n.appliedOperations[0];this.outputAppliedOperations.push(i)}else this.phase="fix-matched-box-pin-counts";break}case"fix-matched-box-pin-counts":{const n=dD({template:this.outputAdaptedTemplate,target:this.transformedTarget}),i=rdt({template:this.outputAdaptedTemplate,target:this.transformedTarget,matchedBoxes:n.matchedBoxes});if(i.appliedOperations.length>0){const a=i.appliedOperations[0];this.outputAppliedOperations.push(a)}else this.phase="fix-matched-box-pin-shapes";break}case"fix-matched-box-pin-shapes":{const n=dD({template:this.outputAdaptedTemplate,target:this.transformedTarget}),i=odt({template:this.outputAdaptedTemplate,target:this.transformedTarget,matchedBoxes:n.matchedBoxes});if(i.appliedOperations.length>0){const a=i.appliedOperations[0];this.outputAppliedOperations.push(a)}else this.phase="remove-unmatched-chips-2";break}case"remove-unmatched-chips-2":{const n=dD({template:this.outputAdaptedTemplate,target:this.transformedTarget});if(n.appliedOperations.length>0){const i=n.appliedOperations[0];this.outputAppliedOperations.push(i)}else this.phase="draw-missing-connections";break}case"draw-missing-connections":{const n=dD({template:this.outputAdaptedTemplate,target:this.transformedTarget}),i=ldt({template:this.outputAdaptedTemplate,target:this.transformedTarget,matchedBoxes:n.matchedBoxes});if(i.appliedOperations.length>0){const a=i.appliedOperations[0];this.outputAppliedOperations.push(a)}else this.phase="complete";break}case"complete":this.stats={operationCount:this.outputAppliedOperations.length,templateBoxCount:((e=this.outputAdaptedTemplate.getNetlist().boxes)==null?void 0:e.length)||0,targetBoxCount:((t=this.targetNetlist.boxes)==null?void 0:t.length)||0},this.solved=!0;break}}visualize(){var e,t;return[{title:"inputTemplate",ascii:this.inputTemplate.toString()},{title:"targetNetlist",ascii:AD(this.targetNetlist)},{title:"adaptedTemplate",ascii:((e=this.outputAdaptedTemplate)==null?void 0:e.toString())||"No adapted template"},{title:"appliedOperations",table:this.outputAppliedOperations.map((n,i)=>({operation_index:i,type:n.type,details:n}))},{title:"inputTemplateReadableNetlist",ascii:this.inputTemplate.getReadableNetlist()},{title:"adaptedTemplateReadableNetlist",ascii:((t=this.outputAdaptedTemplate)==null?void 0:t.getReadableNetlist())||"No adapted template"}]}},udt=class extends hM{constructor(e){super();Ke(this,"matchedTemplates");Ke(this,"adaptationSolvers",[]);Ke(this,"currentAdaptationIndex",0);Ke(this,"outputAdaptedTemplates",[]);this.matchedTemplates=e.matchedTemplates,this.adaptationSolvers=this.matchedTemplates.map(t=>new cdt({inputTemplate:t.template,targetNetlist:t.netlist})),this.setActiveSubSolver(this.adaptationSolvers[this.currentAdaptationIndex])}getConstructorParams(){return{matchedTemplates:this.matchedTemplates}}computeProgress(){return this.adaptationSolvers.length===0?1:this.currentAdaptationIndex/this.adaptationSolvers.length}_step(){if(this.currentAdaptationIndex<this.adaptationSolvers.length){const e=this.adaptationSolvers[this.currentAdaptationIndex];if(!e.solved&&!e.failed){e.step();return}this.clearActiveSubSolver(),e.solved&&e.outputAdaptedTemplate&&this.outputAdaptedTemplates.push({template:e.outputAdaptedTemplate,netlist:this.matchedTemplates[this.currentAdaptationIndex].netlist,appliedOperations:e.outputAppliedOperations}),this.currentAdaptationIndex++,this.setActiveSubSolver(this.adaptationSolvers[this.currentAdaptationIndex]);return}this.solved=!0}},Adt=()=>{const r=LS({name:"Template 1"}),e=r.chip().leftpins(2).rightpins(2);return e.pin(1).line(-8,0).line(0,-2).passive().line(0,-2).label(),e.pin(2).line(-3,0).line(0,-2).label(),e.pin(3).line(4,0).label(),e.pin(4).line(4,0).label(),r},ddt=()=>{const r=LS({name:"Template 2"}),e=r.chip("J1").rightpins(7);return e.pin(7).line(2,0).line(0,1).label("VUSB"),e.pin(6).line(3,0).line(0,.4).line(2,0).passive("R9").line(1,0).label("P"),e.pin(5).line(5,0).passive("R0").line(1,0).label("M"),e.pin(4).line(5,0).line(0,-.6).passive("R2").line(0,-1).label("GND"),e.pin(3).line(3,0).line(0,-.4).passive("R1").line(0,-1).label("GND"),e.pin(2).line(1,0).line(0,-2.2).label("GND"),e.pin(1).line(1,0).intersect(),r},fdt=()=>{const r=LS({name:"Template 3"}),e=r.chip().rightpins(3);return e.pin(3).line(4,0).mark("m0").line(3,0).mark("m1").line(0,1).label(),e.fromMark("m1").line(0,-2).passive().line(0,-3).label(),e.pin(2).line(2,0).line(0,-4).line(2,0).line(0,1.2).passive().line(0,2).intersectAtMark("m0"),e.pin(1).line(1,0).line(0,-3).label(),r},hdt=()=>{const r=LS({name:"Template 4"}),e=r.chip().rightpins(3);return e.pin(3).line(4,0).mark("m1").line(0,2).label(),e.fromMark("m1").line(0,-2).passive().line(0,-2).label(),e.pin(2).line(2,0).label(),e.pin(1).line(1,0).line(0,-2).label(),r},pdt=()=>{const r=LS({name:"Template 5"}),e=r.chip().leftpins(2).rightpins(2).at(0,0),t=r.chip().leftpins(1).rightpins(1).at(10,.2);return e.pin(4).line(3,0).mark("bus"),t.pin(1).connectToMark("bus"),r},gdt=()=>{const r=LS({name:"Template 6"}),e=r.chip("U2").leftpins(3).rightpins(3).at(0,0);return e.pin(1).line(-1.9,0).mark("vin1").line(-1,0).mark("vin2").line(0,.8).label(),e.fromMark("vin2").line(0,-.4).passive("C1").line(0,-1).label("GND"),e.fromMark("vin1").line(0,-.4).passive("R3").line(0,-.4).mark("en1").line(-.2,0).label(),e.pin(2).line(-1,0).intersectAtMark("en1"),e.pin(3).line(-.5,0).line(0,-2).label("GND"),e.pin(6).line(1,0).mark("VOUT").line(0,-.4).passive("C2").line(0,-1).label("GND"),e.fromMark("VOUT").line(0,.8).label(),r},mdt=()=>{const r=LS({name:"Template 7"}),e=r.chip("U1").leftpins(3).rightpins(3).at(0,0),t=r.chip("J2").leftpins(2).at(9,.2);return e.pin(1).line(-2,0).mark("VUSB1").line(-1,0).mark("VUSB2").line(0,.2).label("VUSB"),e.fromMark("VUSB2").line(0,-.4).passive("C3").line(0,-.2).label("GND"),e.fromMark("VUSB1").line(0,-.2).passive("D4").line(0,-.2).mark("belowD4"),e.pin(3).line(-1,0).line(0,-.2).passive("R5").line(0,-.2).connectToMark("belowD4"),e.pin(4).line(1,0).line(0,-1.2).line(1,0).mark("GND1").line(1,0).mark("GND2").line(2,0).mark("aboveGND").line(0,-.2).label("GND"),e.pin(5).line(2,0).line(0,-.2).passive("R6").connectToMark("GND1"),e.pin(6).line(2,0).mark("belowVBat").line(1,0).mark("aboveC4"),e.fromMark("belowVBat").line(0,.2).label("VBAT"),t.pin(1).connectToMark("aboveC4"),e.fromMark("aboveGND").line(0,.8).mark("aboveGND2"),e.fromMark("aboveC4").line(0,-.4).passive("C4").connectToMark("GND2"),t.pin(2).connectToMark("aboveGND2"),r},ydt=()=>{const r=LS({name:"Template 8"}),e=r.chip("U1").leftpins(4).at(0,0);return e.pin(1).line(-2,0).label("SCL"),e.pin(2).line(-2,0).label("SDA"),e.pin(3).line(-1,0).line(0,.8).label("V3_3"),e.pin(4).line(-1,0).line(0,-.4).label("GND"),r},vdt=()=>{const r=LS({name:"Template 9"}),e=r.chip("U3").leftpins(6).rightpins(6);return e.pin(1).line(-1,0).mark("aboveC2").line(0,-.001).passive("C20").line(0,-.001).mark("GND1").line(0,-.2).label("GND"),e.fromMark("aboveC2").line(0,.2).label("V3_3"),e.pin(6).intersectAtMark("GND1"),e.pin(7).line(2,0).line(0,.2).mark("rightOf7").line(0,2).label("V3_3"),e.pin(8).intersectAtMark("rightOf7"),e.pin(9).line(3,0).label(),e.pin(10).line(3,0).label(),e.pin(11).line(3,0).label(),e.pin(12).line(1,0).mark("rightOfNCS").line(2,0).label(),e.fromMark("rightOfNCS").line(0,.2).passive("R11").line(0,.2).label("V3_3"),r},Idt={template1:Adt,template2:ddt,template3:fdt,template4:hdt,template5:pdt,template6:gdt,template7:mdt,template8:ydt,template9:vdt},Cdt=Object.values(Idt);function bye(r,e){switch(e){case 0:return r;case 90:return{...r,leftPinCount:r.bottomPinCount,rightPinCount:r.topPinCount,topPinCount:r.leftPinCount,bottomPinCount:r.rightPinCount};case 180:return{...r,leftPinCount:r.rightPinCount,rightPinCount:r.leftPinCount,topPinCount:r.bottomPinCount,bottomPinCount:r.topPinCount};case 270:return{...r,leftPinCount:r.topPinCount,rightPinCount:r.bottomPinCount,topPinCount:r.rightPinCount,bottomPinCount:r.leftPinCount};default:return r}}function Edt(r,e,t){if(t===0)return r;const{side:n,indexOnSide:i}=zb(r,e),a=bye(e,t);let o;switch(t){case 90:switch(n){case"left":o="top";break;case"bottom":o="left";break;case"right":o="bottom";break;case"top":o="right";break;default:o=n}break;case 180:switch(n){case"left":o="right";break;case"right":o="left";break;case"top":o="bottom";break;case"bottom":o="top";break;default:o=n}break;case 270:switch(n){case"left":o="bottom";break;case"bottom":o="right";break;case"right":o="top";break;case"top":o="left";break;default:o=n}break;default:o=n}let s=i;const l=e[`${n}PinCount`];t===180?s=l-1-i:t===90?(n==="left"||n==="right")&&(s=l-1-i):t===270&&(n==="left"||n==="right")&&(s=l-1-i);let c=1;const u=["left","bottom","right","top"];for(const A of u){const d=a[`${A}PinCount`];if(d){if(A===o)return c+s;c+=d}}throw new Error(`Could not map pin ${r} after ${t}° rotation`)}function _dt(r){const{inputNetlist:e,matchedBoxes:t}=r,n=new Map;for(const o of t)n.set(o.targetBoxIndex,o.targetBoxRotationCcw);const i=e.boxes.map((o,s)=>{const l=n.get(s);return l?bye(o,l):o}),a=e.connections.map(o=>{const s=o.connectedPorts.map(l=>{if("boxId"in l){const c=e.boxes.findIndex(u=>u.boxId===l.boxId);if(c!==-1){const u=n.get(c);if(u){const A=e.boxes[c],d=Edt(l.pinNumber,A,u);return{...l,pinNumber:d}}}}return l});return{...o,connectedPorts:s}});return{...e,boxes:i,connections:a}}function xdt(r,e,t,n=45){if(!t)return[`Box ${r} (no transform)`];const i=Object.keys(t.boxIdToBoxIndex).find(_=>t.boxIdToBoxIndex[_]===r);if(!i)return[`Box ${r} (not found)`];const a=e.boxes.find(_=>_.boxId===i);if(!a)return[`Box ${i} (not found)`];const o=[],{leftPinCount:s,rightPinCount:l,topPinCount:c,bottomPinCount:u}=a,A=Math.min(n-4,16),d=2,f=Math.max(s,l,1);let g=i;if(i.length>A-2&&(g=`${i.substring(0,A-3)}…`),c>0){let _="";for(let B=0;B<c;B++){const P=s+u+l+B+1;_+=P.toString().padStart(2)}const I=_.substring(0,A),E=Math.floor((A-I.length)/2),x=" ".repeat(E)+I;o.push(`${" ".repeat(d+1)}${x}`)}o.push(`${" ".repeat(d)}┌${"─".repeat(A)}┐`);for(let _=0;_<f;_++){const I=_<s?(_+1).toString():"",E=_<l?(s+u+(l-1-_)+1).toString():"";let x="";if(_===Math.floor((f-1)/2)){const B=Math.floor((A-g.length)/2),P=A-g.length-B;x=" ".repeat(B)+g+" ".repeat(P)}else x=" ".repeat(A);o.push(`${I.padStart(d)}│${x}│${E.padEnd(d)}`)}if(o.push(`${" ".repeat(d)}└${"─".repeat(A)}┘`),u>0){let _="";for(let B=0;B<u;B++){const P=s+B+1;_+=P.toString().padStart(2)}const I=_.substring(0,A),E=Math.floor((A-I.length)/2),x=" ".repeat(E)+I;o.push(`${" ".repeat(d+1)}${x}`)}return o}function Bdt(r){const{candidateNetlist:e,targetNetlist:t}=r,n=[],i=new Map;for(let a=0;a<e.boxes.length;a++){const o=e.boxes[a],s=XV({leftPinCount:o.leftPinCount,bottomPinCount:o.bottomPinCount,rightPinCount:o.rightPinCount,topPinCount:o.topPinCount});i.has(s)||i.set(s,[]),i.get(s).push(a)}for(let a=0;a<t.boxes.length;a++){const o=t.boxes[a],s=XV({leftPinCount:o.leftPinCount,bottomPinCount:o.bottomPinCount,rightPinCount:o.rightPinCount,topPinCount:o.topPinCount});(i.get(s)||[]).length===0&&n.push({type:"no_box_matching_pin_counts",candidateBoxIndex:-1,targetBoxIndex:a})}return n}function bdt(r){const{candidateNetlist:e,targetNetlist:t}=r,n=Bdt({candidateNetlist:e,targetNetlist:t}),i=ok({candidateNetlist:e,targetNetlist:t});return[...n,...i.flatMap(a=>a.issues)]}var Sye=r=>{const e=[];for(const t of r.boxes){const n=t.leftPinCount+t.rightPinCount+t.topPinCount+t.bottomPinCount;for(let i=1;i<=n;i++){const a=eK({netlist:r,chipId:t.boxId,pinNumber:i});e.push({boxId:t.boxId,pinNumber:i,pinShapeSignature:a})}}return e},Sdt=({targetNetlist:r,candidateNetlist:e,matchedBoxes:t,targetTransform:n,candidateTransform:i})=>{const a=Sye(r),o=Sye(e),s=[];for(const l of t){const c=Object.keys(n.boxIdToBoxIndex).find(g=>n.boxIdToBoxIndex[g]===l.targetBoxIndex),u=Object.keys(i.boxIdToBoxIndex).find(g=>i.boxIdToBoxIndex[g]===l.candidateBoxIndex);if(!c||!u)continue;const A=a.filter(g=>g.boxId===c),d=o.filter(g=>g.boxId===u),f=new Set([...A.map(g=>g.pinNumber),...d.map(g=>g.pinNumber)]);for(const g of f){const _=A.find(E=>E.pinNumber===g),I=d.find(E=>E.pinNumber===g);s.push({targetBoxIdPinNumber:_?`${c}.${g}`:"",candidateBoxIdPinNumber:I?`${u}.${g}`:"",targetPinShapeSignature:(_==null?void 0:_.pinShapeSignature)||"",candidatePinShapeSignature:(I==null?void 0:I.pinShapeSignature)||""})}}return s},wdt=class extends hM{constructor(e){super();Ke(this,"inputNetlist");Ke(this,"template");Ke(this,"inputNetlistWithRotations",null);Ke(this,"outputIssues",[]);Ke(this,"outputSimilarityDistance",1/0);Ke(this,"candidateTransform",null);Ke(this,"targetTransform",null);Ke(this,"matchedBoxes",[]);this.inputNetlist=e.inputNetlist,this.template=e.template}getConstructorParams(){return{inputNetlist:this.inputNetlist,template:this.template}}getStatsSummary(){return`${this.stats.similarityDistance.toFixed(1)} SD ・ ${this.stats.issueCount} issues ・ ${this.template.name}`}_step(){var c,u;const e=this.template.getNetlist(),t=J2(e),n=J2(structuredClone(this.inputNetlist)),i=t.normalizedNetlist,a=n.normalizedNetlist;this.matchedBoxes=ok({candidateNetlist:i,targetNetlist:a});for(const A of this.matchedBoxes)A._targetBoxId=n.transform.boxIndexToBoxId[A.targetBoxIndex],A._candidateBoxId=t.transform.boxIndexToBoxId[A.candidateBoxIndex];const o=_dt({inputNetlist:structuredClone(this.inputNetlist),matchedBoxes:this.matchedBoxes});this.inputNetlistWithRotations=o;const s=J2(o),l=s.normalizedNetlist;this.candidateTransform=t.transform,this.targetTransform=s.transform,this.outputIssues=bdt({candidateNetlist:i,targetNetlist:l}),this.outputSimilarityDistance=VV(this.outputIssues),this.stats={similarityDistance:this.outputSimilarityDistance,issueCount:this.outputIssues.length,templateBoxCount:((c=i.boxes)==null?void 0:c.length)||0,templateConnectionCount:((u=i.connections)==null?void 0:u.length)||0,matchedBoxCount:this.matchedBoxes.length},this.solved=!0}getBoxNameFromIndex(e,t){const n=t?this.candidateTransform:this.targetTransform;if(!n)return e.toString();const i=Object.keys(n.boxIdToBoxIndex).find(a=>n.boxIdToBoxIndex[a]===e);return i?`${e} (${i})`:e.toString()}getAsciiForNetlistBoxHelper(e,t,n=45){const i=t?this.template.getNetlist():this.inputNetlistWithRotations,a=t?this.candidateTransform:this.targetTransform;return a?xdt(e,i,a,n):[`Box ${e} (no transform)`]}generateMatchedBoxesVisualization(){if(this.matchedBoxes.length===0)return"No matched boxes found";const e=[];for(const t of this.matchedBoxes){const n=this.getAsciiForNetlistBoxHelper(t.targetBoxIndex,!1,48),i=this.getAsciiForNetlistBoxHelper(t.candidateBoxIndex,!0,48),a=Math.max(n.length,i.length);for(;n.length<a;)n.push(" ".repeat(48));for(;i.length<a;)i.push(" ".repeat(48));const o=`Target ${this.getBoxNameFromIndex(t.targetBoxIndex,!1)}`.padEnd(48),s=`Template ${this.getBoxNameFromIndex(t.candidateBoxIndex,!0)}`.padEnd(48);e.push(`${o} → ${s}`),e.push(`${"─".repeat(48)} → ${"─".repeat(48)}`);for(let l=0;l<a;l++){const c=n[l]||"",u=i[l]||"",A=l===Math.floor(a/2)?" → ":" ";e.push(`${c.padEnd(48)}${A}${u.padEnd(48)}`)}e.push("")}return e.join(`
852
- `)}visualize(){return[{title:"inputTemplate",ascii:this.template.toString(),table:this.outputIssues.map((e,t)=>({issue_index:t,type:e.type,target_box:"targetBoxIndex"in e?this.getBoxNameFromIndex(e.targetBoxIndex,!1):"N/A",candidate_box:"candidateBoxIndex"in e?this.getBoxNameFromIndex(e.candidateBoxIndex,!0):"N/A",details:e}))},{title:"pairwisePinShapeSignatures",table:Sdt({targetNetlist:this.inputNetlistWithRotations,candidateNetlist:this.template.getNetlist(),matchedBoxes:this.matchedBoxes,targetTransform:this.targetTransform,candidateTransform:this.candidateTransform})},{title:"matchedBoxes",ascii:this.generateMatchedBoxesVisualization(),table:this.matchedBoxes.map(e=>({target_box:this.getBoxNameFromIndex(e.targetBoxIndex,!1),candidate_box:this.getBoxNameFromIndex(e.candidateBoxIndex,!0),rotation:e.targetBoxRotationCcw,issueCount:e.issues.length,details:e}))},{title:"inputTemplateReadableNetlist",ascii:this.template.getReadableNetlist()},{title:"inputTargetReadableNetlist",ascii:AD(this.inputNetlist)},this.inputNetlistWithRotations&&{title:"targetReadableNetlistWithRotations",ascii:AD(this.inputNetlistWithRotations)}].filter(Boolean)}},Qdt=class extends hM{constructor(e){var t;super();Ke(this,"inputNetlist");Ke(this,"templates");Ke(this,"scoringSolvers",[]);Ke(this,"currentScoringIndex",0);Ke(this,"outputBestMatchTemplate",null);Ke(this,"templateMatchResults",[]);this.inputNetlist=e.inputNetlist,this.templates=((t=e.templateFns)==null?void 0:t.map(n=>n()))||Cdt.map(n=>n()),this.scoringSolvers=this.templates.map(n=>new wdt({inputNetlist:this.inputNetlist,template:n}))}getConstructorParams(){return{inputNetlist:this.inputNetlist}}computeProgress(){return this.scoringSolvers.length===0?1:this.currentScoringIndex/this.scoringSolvers.length}_step(){if(this.currentScoringIndex<this.scoringSolvers.length){const t=this.scoringSolvers[this.currentScoringIndex];if(!t.solved&&!t.failed){this.setActiveSubSolver(t),t.step();return}this.clearActiveSubSolver(),this.currentScoringIndex++;return}if(this.templateMatchResults=this.scoringSolvers.map(t=>({template:t.template,issues:t.outputIssues,similarityDistance:t.outputSimilarityDistance})),this.templateMatchResults.length===0){this.outputBestMatchTemplate=null,this.solved=!0;return}let e=this.templateMatchResults[0];for(let t=1;t<this.templateMatchResults.length;t++)this.templateMatchResults[t].similarityDistance<e.similarityDistance&&(e=this.templateMatchResults[t]);e.similarityDistance===1/0?this.outputBestMatchTemplate=null:this.outputBestMatchTemplate=e.template,this.solved=!0}visualize(){var e;return[{title:"inputNetlist",ascii:AD(this.inputNetlist)},{title:"bestMatchTemplate",ascii:((e=this.outputBestMatchTemplate)==null?void 0:e.toString())||"No suitable match found"},{title:"templateScores",table:this.templateMatchResults.map((t,n)=>({template_index:n,template_name:t.template.name||`Template ${n}`,similarity_distance:t.similarityDistance,issue_count:t.issues.length,is_best_match:t.template===this.outputBestMatchTemplate}))}]}},Mdt=class extends hM{constructor(e){super();Ke(this,"inputNetlists");Ke(this,"currentInputNetlistIndex",0);Ke(this,"templateFns");Ke(this,"outputMatchedTemplates",[]);this.inputNetlists=e.inputNetlists,this.templateFns=e.templateFns}get activeSubSolver(){return this._activeSubSolver}_step(){if(this.activeSubSolver)if(this.activeSubSolver.step(),this.activeSubSolver.solved){this.outputMatchedTemplates.push({template:this.activeSubSolver.outputBestMatchTemplate,netlist:this.inputNetlists[this.currentInputNetlistIndex]}),this.currentInputNetlistIndex++,this.clearActiveSubSolver();return}else return;if(this.currentInputNetlistIndex>=this.inputNetlists.length){this.solved=!0;return}this.setActiveSubSolver(new Qdt({inputNetlist:this.inputNetlists[this.currentInputNetlistIndex],templateFns:this.templateFns}))}};function wye(r,e,t,n={}){return{solverName:r,solverClass:e,getConstructorParams:t,onSolved:n.onSolved}}var Ddt=class extends hM{constructor(e){super();Ke(this,"inputNetlist");Ke(this,"templateFnsOverride");Ke(this,"matchPhaseSolver");Ke(this,"adaptPhaseSolver");Ke(this,"startTimeOfPhase",{});Ke(this,"endTimeOfPhase",{});Ke(this,"timeSpentOnPhase",{});Ke(this,"pipelineDef",[wye("matchPhaseSolver",Mdt,()=>[{inputNetlists:[this.inputNetlist],templateFns:this.templateFnsOverride}]),wye("adaptPhaseSolver",udt,()=>{var e;return[{matchedTemplates:(e=this.matchPhaseSolver)==null?void 0:e.outputMatchedTemplates}]})]);Ke(this,"currentPipelineStepIndex",0);this.inputNetlist=e.inputNetlist,this.templateFnsOverride=e.templateFns}_step(){var n,i;const e=this.pipelineDef[this.currentPipelineStepIndex];if(!e){this.solved=!0;return}if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){this.endTimeOfPhase[e.solverName]=performance.now(),this.timeSpentOnPhase[e.solverName]=this.endTimeOfPhase[e.solverName]-this.startTimeOfPhase[e.solverName],(n=e.onSolved)==null||n.call(e,this),this.clearActiveSubSolver(),this.currentPipelineStepIndex++;return}if(this.activeSubSolver.failed){this.error=(i=this.activeSubSolver)==null?void 0:i.error,this.failed=!0,this.clearActiveSubSolver();return}return}const t=e.getConstructorParams(this);this.setActiveSubSolver(new e.solverClass(...t)),this[e.solverName]=this.activeSubSolver,this.timeSpentOnPhase[e.solverName]=0,this.startTimeOfPhase[e.solverName]=performance.now()}getLayout(){var e,t;if(!((t=(e=this.adaptPhaseSolver)==null?void 0:e.outputAdaptedTemplates)!=null&&t[0]))throw new Error("No adapted template available. Make sure the pipeline has completed successfully.");return this.adaptPhaseSolver.outputAdaptedTemplates[0].template.getLayoutJson()}},Rdt=r=>{switch(r){case"left":return"left";case"right":return"right";case"up":return"top";case"down":return"bottom"}},Ndt=r=>{const e=FS(r),t=PB(r).source_component.list().map(o=>({source_component:o,schematic_component:PB(r).schematic_component.getWhere({source_component_id:o.source_component_id}),source_ports:PB(r).source_port.list().filter(s=>s.source_component_id===o.source_component_id).map(s=>{const l=e.getNetConnectedToId(s.source_port_id),c=PB(r).schematic_port.getWhere({source_port_id:s.source_port_id}),u=(c==null?void 0:c.true_ccw_index)!=null?c.true_ccw_index+1:s.pin_number;return{source_port:s,schematic_port:PB(r).schematic_port.getWhere({source_port_id:s.source_port_id}),pin_number:u,connectivity_net_id:l}}).filter(({schematic_port:s})=>!!s)})),n=[],i=[];for(const{source_component:o,schematic_component:s,source_ports:l}of t){const c={boxId:o.name,leftPinCount:0,rightPinCount:0,topPinCount:0,bottomPinCount:0};for(const{source_port:u,schematic_port:A,pin_number:d}of l){const f=Rdt(A.facing_direction);c[`${f}PinCount`]++;const g=e.getNetConnectedToId(u.source_port_id);let _=i.find(I=>I._connectivityNetId===g);_||(_={_connectivityNetId:g,connectedPorts:[]},i.push(_)),_.connectedPorts.push({boxId:o.name,pinNumber:(A==null?void 0:A.true_ccw_index)!=null?A.true_ccw_index+1:d})}n.push(c)}const a=[];for(const o of i){if(o.connectedPorts.length<2)continue;let s=o._connectivityNetId;const l=e.getIdsConnectedToNet(s).map(c=>gye(r,c));for(const c of l)if((c==null?void 0:c.type)==="source_net"){s=c.name;break}o.connectedPorts.push({netId:s}),a.push({netId:s})}return{boxes:n,connections:i,nets:a}},Tdt=r=>{const e=JSON.parse(JSON.stringify(r)),t=e.filter(n=>n.type==="schematic_component"&&n.port_arrangement);for(const n of t){const i=e.filter(o=>o.type==="schematic_port"&&o.schematic_component_id===n.schematic_component_id&&o.true_ccw_index!==void 0);if(i.length===0)continue;i.sort((o,s)=>o.true_ccw_index-s.true_ccw_index);const a={};i.forEach((o,s)=>{a[o.pin_number]=s+1});for(const o of i){const s=a[o.pin_number];o.pin_number=s}for(const o of i){const s=e.find(l=>l.type==="source_port"&&l.source_port_id===o.source_port_id);s&&(s.pin_number=o.pin_number)}if(n.port_arrangement){const o=s=>{var l;(l=n.port_arrangement[s])!=null&&l.pins&&(n.port_arrangement[s].pins=n.port_arrangement[s].pins.map(c=>a[c]||c))};o("left_side"),o("right_side"),o("top_side"),o("bottom_side")}if(n.port_labels){const o={};for(const[s,l]of Object.entries(n.port_labels)){const c=parseInt(s.replace("pin","")),u=a[c];u!==void 0?o[`pin${u}`]=l:o[s]=l}n.port_labels=o}if(n.pin_styles){const o={};for(const[s,l]of Object.entries(n.pin_styles)){const c=parseInt(s.replace("pin","")),u=a[c];u!==void 0?o[`pin${u}`]=l:o[s]=l}n.pin_styles=o}}return e},nK=[{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:"µ"},{value:1e-9,symbol:"n"},{value:1e-12,symbol:"p"}];function kB(r){if(r==null)return"";if(r===0)return"0";const e=Math.abs(r),t=nK.find(a=>{const o=e/a.value;return o>=1&&o<1e3})||nK[nK.length-1];let i=(r/t.value).toPrecision(3);return i.includes(".")&&!/\.0+$/.test(i)&&(i=i.replace(/0+$/,"")),i=i.replace(/\.0+$/,""),`${i}${t.symbol}`}var Pdt=Object.defineProperty,kdt=(r,e)=>{for(var t in e)Pdt(r,t,{get:e[t],enumerable:!0})},Qye={};kdt(Qye,{Battery:()=>Xft,Board:()=>Rft,Capacitor:()=>Tft,Chip:()=>$ye,Constraint:()=>zft,Crystal:()=>oht,Cutout:()=>Zft,Diode:()=>Pft,FabricationNotePath:()=>Hft,FabricationNoteText:()=>Yft,Footprint:()=>ift,Fuse:()=>kft,Group:()=>hK,Hole:()=>Oye,Inductor:()=>nht,Jumper:()=>Uft,Keepout:()=>lK,Led:()=>Fft,Mosfet:()=>lht,Net:()=>Uye,NetAlias:()=>Kft,NormalComponent:()=>T1,PcbTrace:()=>Gye,PinHeader:()=>$ft,PlatedHole:()=>sK,Port:()=>GS,Potentiometer:()=>iht,PowerSource:()=>Lft,PrimitiveComponent:()=>$v,PushButton:()=>aht,Renderable:()=>Mye,Resistor:()=>Gft,Resonator:()=>tht,SchematicBox:()=>Aht,SchematicText:()=>uht,SilkscreenCircle:()=>jft,SilkscreenLine:()=>Wft,SilkscreenPath:()=>Lye,SilkscreenRect:()=>Jft,SilkscreenText:()=>cK,SmtPad:()=>oK,Subcircuit:()=>Vft,Switch:()=>cht,Trace:()=>OS,TraceHint:()=>qye,Transistor:()=>sht,Via:()=>qft});var Udt=nv("tscircuit:renderable"),Hx=["ReactSubtreesRender","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","CreateTracesFromProps","CreateTraceHintsFromProps","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicLayout","SchematicTraceRender","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbLayout","PcbComponentSizeCalculation","PcbBoardAutoSize","PcbTraceHintRender","PcbTraceRender","PcbRouteNetIslands","PcbDesignRuleChecks","CadModelRender","PartsEngineRender"],Fdt=0,Mye=class{constructor(e){Ke(this,"renderPhaseStates");Ke(this,"shouldBeRemoved",!1);Ke(this,"children");Ke(this,"isPcbPrimitive",!1);Ke(this,"isSchematicPrimitive",!1);Ke(this,"_renderId");Ke(this,"_currentRenderPhase",null);Ke(this,"_asyncEffects",[]);Ke(this,"parent",null);this._renderId=`${Fdt++}`,this.children=[],this.renderPhaseStates={};for(const t of Hx)this.renderPhaseStates[t]={initialized:!1,dirty:!1}}_markDirty(e){var n;this.renderPhaseStates[e].dirty=!0;const t=Hx.indexOf(e);for(let i=t+1;i<Hx.length;i++)this.renderPhaseStates[Hx[i]].dirty=!0;(n=this.parent)!=null&&n._markDirty&&this.parent._markDirty(e)}_queueAsyncEffect(e,t){const 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}":
853
- ${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){Udt(`${e}:${t} ${this.getString()}`);const 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)}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(const e of Hx)this.runRenderPhaseForChildren(e),this.runRenderPhase(e)}runRenderPhase(e){var o,s,l;this._currentRenderPhase=e;const t=this.renderPhaseStates[e],n=t.initialized,i=t.dirty;if(!n&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&n){this._emitRenderLifecycleEvent(e,"start"),(o=this==null?void 0:this[`remove${e}`])==null||o.call(this),t.initialized=!1,t.dirty=!1,this._emitRenderLifecycleEvent(e,"end");return}const a=Hx.indexOf(e)-1;if(a>=0){const c=Hx[a];if(this._asyncEffects.filter(A=>A.phase===c).some(A=>!A.complete))return}if(this._emitRenderLifecycleEvent(e,"start"),n){i&&((s=this==null?void 0:this[`update${e}`])==null||s.call(this),t.dirty=!1),this._emitRenderLifecycleEvent(e,"end");return}t.dirty=!1,(l=this==null?void 0:this[`doInitial${e}`])==null||l.call(this),t.initialized=!0,this._emitRenderLifecycleEvent(e,"end")}runRenderPhaseForChildren(e){for(const 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))}},sk={},Dye=r=>{const e=Object.fromEntries(Object.entries(r).map(([t,n])=>[t.toLowerCase(),n]));Object.assign(sk,r),Object.assign(sk,e)},Ldt=class extends Error{constructor(e,t,n){let i;const o=Object.keys(n).filter(s=>s!=="_errors").map(s=>n[s]._errors[0]?`${s} (${n[s]._errors[0]})`:`${s} (${JSON.stringify(n[s])})`).join(", ");"name"in t?i=`Invalid props for ${e} "${t.name}": ${o}`:"footprint"in t&&typeof t.footprint=="string"?i=`Invalid props for ${e} (unnamed ${t.footprint} component): ${o}`:i=`Invalid props for ${e} (unnamed): ${o}`,super(i),this.componentName=e,this.originalProps=t,this.formattedError=n}};function rK(r,e){const t=e.match(/^#(\w+)/);if(t)return r.props.id===t[1];const n=e.match(/^\.(\w+)/);if(n)return r.isMatchingNameOrAlias(n[1]);let[i,...a]=e.split(/(?=[#.[])/);return i==="pin"&&(i="port"),i&&i!=="*"&&r.lowercaseComponentName!==i.toLowerCase()?!1:a.every(o=>{if(o.startsWith("#"))return r.props.id===o.slice(1);if(o.startsWith("."))return r.isMatchingNameOrAlias(o.slice(1));const s=o.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!s)return!0;const[,l,c]=s;return r.props[l].toString()===c})}var iK={isTag:r=>!0,getParent:r=>r.parent,getChildren:r=>r.children,getName:r=>r.lowercaseComponentName,getAttributeValue:(r,e)=>{var t;if(e==="class"&&"getNameAndAliases"in r)return r.getNameAndAliases().join(" ");if(e==="name"&&((t=r._parsedProps)!=null&&t.name))return r._parsedProps.name;if(r._parsedProps&&e in r._parsedProps){const n=r._parsedProps[e];return typeof n=="string"?n:n!=null?String(n):null}return null},hasAttrib:(r,e)=>{var t;return e==="class"?!!((t=r._parsedProps)!=null&&t.name):r._parsedProps&&e in r._parsedProps},getSiblings:r=>r.parent?r.parent.children:[],prevElementSibling:r=>{if(!r.parent)return null;const e=r.parent.children,t=e.indexOf(r);return t>0?e[t-1]:null},getText:()=>"",removeSubsets:r=>r.filter((e,t)=>!r.some((n,i)=>t!==i&&n!==e&&n.getDescendants().includes(e))),existsOne:(r,e)=>e.some(r),findAll:(r,e)=>{const t=[],n=i=>{r(i)&&t.push(i);for(const a of i.children)n(a)};for(const i of e)n(i);return t},findOne:(r,e)=>{for(const t of e){if(r(t))return t;const n=t.children;if(n.length>0){const i=iK.findOne(r,n);if(i)return i}}return null},equals:(r,e)=>r._renderId===e._renderId,isHovered:r=>!1,isVisited:r=>!1,isActive:r=>!1},Gdt={...iK,getChildren:r=>r.children.filter(e=>!e.isSubcircuit)},Rye={...iK,getChildren:r=>r.children.filter(e=>e.isSubcircuit)},Nye=r=>{if(/net\.[^\s>]*\./.test(r))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\.[0-9]/.test(r))throw new Error('Net names cannot start with a number, try using a prefix like "VBUS1"');return r.replace(/ pin/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,(e,t,n,i)=>{const a=/^\d+$/.test(i)?`pin${i}`:i;return`${t}.${n} > .${a}`}).trim()},aK={adapter:Gdt,cacheResults:!0},$v=class extends Mye{constructor(t){super(t);Ke(this,"parent",null);Ke(this,"children");Ke(this,"childrenPendingRemoval");Ke(this,"props");Ke(this,"_parsedProps");Ke(this,"externallyAddedAliases");Ke(this,"isPrimitiveContainer",!1);Ke(this,"source_group_id",null);Ke(this,"source_component_id",null);Ke(this,"schematic_component_id",null);Ke(this,"pcb_component_id",null);Ke(this,"cad_component_id",null);Ke(this,"_cachedSelectAllQueries",new Map);Ke(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=t??{},this.externallyAddedAliases=[];const n=this.config.zodProps.safeParse(t??{});if(n.success)this._parsedProps=n.data;else throw new Ldt(this.lowercaseComponentName,this.props,n.error.format())}get config(){return{componentName:"",zodProps:tn({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(t){var i;let n=this;for(;n;){if(n._parsedProps&&t in n._parsedProps)return n._parsedProps[t];n=n.parent}if((i=this.root)!=null&&i.platform&&t in this.root.platform)return this.root.platform[t]}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){var t;return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&((t=this==null?void 0:this.parent)==null?void 0:t.isRoot)}get isGroup(){return this.lowercaseComponentName==="group"}setProps(t){var a,o;const 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)}),(o=(a=this.parent)==null?void 0:a.onChildChanged)==null||o.call(a,this)}computePcbPropsTransform(){const{_parsedProps:t}=this;return Fu(Od(t.pcbX??0,t.pcbY??0),px((t.pcbRotation??0)*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){var i,a,o;const{_parsedProps:t}=this,n=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(n&&this.props.pcbX===void 0&&this.props.pcbY===void 0)return Fu(((i=this.parent)==null?void 0:i._computePcbGlobalTransformBeforeLayout())??wy(),Fu(Od(n.x,n.y),px((t.pcbRotation??0)*Math.PI/180)));if(this.isPcbPrimitive){const s=this.getPrimitiveContainer();if(s){const l=s._parsedProps.layer==="bottom",c=s._getGlobalPcbPositionBeforeLayout();if(l)return Fu(Od(c.x,c.y),Y5(),Od(-c.x,-c.y)),Fu(((a=this.parent)==null?void 0:a._computePcbGlobalTransformBeforeLayout())??wy(),Y5(),this.computePcbPropsTransform())}}return Fu(((o=this.parent)==null?void 0:o._computePcbGlobalTransformBeforeLayout())??wy(),this.computePcbPropsTransform())}getPrimitiveContainer(){var t,n;return this.isPrimitiveContainer?this:((n=(t=this.parent)==null?void 0:t.getPrimitiveContainer)==null?void 0:n.call(t))??null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){const t=this.getPrimitiveContainer(),n=t?t._parsedProps.layer==="bottom":!1;return{isFlipped:n,maybeFlipLayer:a=>n?a==="top"?"bottom":"top":a}}_setPositionFromLayout(t){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){const{_parsedProps:t}=this;return Fu(Od(t.schX??0,t.schY??0))}computeSchematicGlobalTransform(){var n,i;const t=this._getSchematicGlobalManualPlacementTransform(this);return t||Fu(((i=(n=this.parent)==null?void 0:n.computeSchematicGlobalTransform)==null?void 0:i.call(n))??wy(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){const{_parsedProps:t}=this,n=this.config.schematicSymbolName;let i=t.schRotation;if(i===void 0&&(i=0),i=i%360,i<0&&(i+=360),t.schRotation!==void 0&&i%90!==0)throw new Error(`Schematic rotation ${t.schRotation} is not supported for ${this.componentName}`);const a=`${n}_horz`,o=`${n}_vert`,s=`${n}_up`,l=`${n}_down`,c=`${n}_left`,u=`${n}_right`;if(u in yI&&i===0)return u;if(s in yI&&i===90)return s;if(c in yI&&i===180)return c;if(l in yI&&i===270)return l;if(a in yI&&(i===0||i===180))return a;if(o in yI&&(i===90||i===270))return o;if(n in yI)return n}_getSchematicSymbolNameOrThrow(){const t=this._getSchematicSymbolName();if(!t)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return t}getSchematicSymbol(){const t=this._getSchematicSymbolName();return t?yI[t]??null:null}_getPcbManualPlacementForComponent(t){var o;if(!this.isSubcircuit)return null;const n=this.props.layout,i=this.props.manualEdits;if(!n&&!i)return null;const a=((o=n==null?void 0:n.manual_pcb_placement_config)==null?void 0:o.positions)||(i==null?void 0:i.pcb_placements);if(!a)return null;for(const s of a)if(n&&rK(t,s.selector)||t.props.name===s.selector)return ti(this._computePcbGlobalTransformBeforeLayout(),s.center);return null}_getSchematicManualPlacementForComponent(t){if(!this.isSubcircuit)return null;const n=this.props.manualEdits;if(!n)return null;const i=n.schematic_placements;if(!i)return null;for(const a of i)if(rK(t,a.selector)||t.props.name===a.selector)return ti(this.computeSchematicGlobalTransform(),a.center);return null}_getSchematicGlobalManualPlacementTransform(t){var i,a;const n=(i=this.getSubcircuit())==null?void 0:i._parsedProps.manualEdits;if(!n)return null;for(const o of n.schematic_placements??[])if((rK(t,o.selector)||t.props.name===o.selector)&&o.relative_to==="group_center")return Fu(((a=this.parent)==null?void 0:a._computePcbGlobalTransformBeforeLayout())??wy(),Od(o.center.x,o.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return ti(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return ti(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){var t;return((t=this.parent)==null?void 0:t.root)??null}onAddToParent(t){this.parent=t}onPropsChange(t){}onChildChanged(t){var n,i;(i=(n=this.parent)==null?void 0:n.onChildChanged)==null||i.call(n,t)}add(t){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(const n of t)this.add(n)}remove(t){this.children=this.children.filter(n=>n!==t),this.childrenPendingRemoval.push(t),t.shouldBeRemoved=!0}getSubcircuitSelector(){const t=this._parsedProps.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?n:`${this.parent.getSubcircuitSelector()} > ${n}`}getFullPathSelector(){var a,o;const t=this._parsedProps.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName,i=(o=(a=this.parent)==null?void 0:a.getFullPathSelector)==null?void 0:o.call(a);return i?`${i} > ${n}`:n}getNameAndAliases(){return[this._parsedProps.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){const n=[this.componentName,this.lowercaseComponentName],i=[this._parsedProps.name].filter(Boolean),a=t.trim().split(/\> /)[0],o=a[0];return a.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(){var n,i;if(this.isSubcircuit)return this;const t=(i=(n=this.parent)==null?void 0:n.getSubcircuit)==null?void 0:i.call(n);if(!t)throw new Error("Component is not inside an opaque group (no board?)");return t}getGroup(){var t,n;return this.isGroup?this:((n=(t=this.parent)==null?void 0:t.getGroup)==null?void 0:n.call(t))??null}doInitialOptimizeSelectorCache(){var n;if(!this.isSubcircuit)return;const t=this.selectAll("port");for(const i of t){const a=(n=i.parent)==null?void 0:n.getNameAndAliases(),o=i.getNameAndAliases();if(a)for(const s of a)for(const l of o){const c=[`.${s} > .${l}`,`.${s} .${l}`];for(const u of c){const A=this._cachedSelectAllQueries.get(u);A?A.push(i):this._cachedSelectAllQueries.set(u,[i])}}}for(const[i,a]of this._cachedSelectAllQueries.entries())a.length===1&&this._cachedSelectOneQueries.set(i,a[0])}selectAll(t){if(this._cachedSelectAllQueries.has(t))return this._cachedSelectAllQueries.get(t);const n=Nye(t),i=IP(n,this,aK);if(i.length>0)return this._cachedSelectAllQueries.set(t,i),i;const[a,...o]=n.split(" "),s=rM(a,this,{adapter:Rye});if(!s)return[];const l=s.selectAll(o.join(" "));return this._cachedSelectAllQueries.set(t,l),l}selectOne(t,n){if(this._cachedSelectOneQueries.has(t))return this._cachedSelectOneQueries.get(t);const i=Nye(t);n!=null&&n.port&&(n.type="port");let a=null;if(n!=null&&n.type&&(a=IP(i,this,aK).find(u=>u.lowercaseComponentName===n.type)),a??(a=rM(i,this,aK)),a)return this._cachedSelectOneQueries.set(t,a),a;const[o,...s]=i.split(" "),l=rM(o,this,{adapter:Rye});return l?(a=l.selectOne(s.join(" "),n),this._cachedSelectOneQueries.set(t,a),a):null}getAvailablePcbLayers(){var t,n;if(this.isPcbPrimitive){const{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[i(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?((n=(t=this.root)==null?void 0:t._getBoard())==null?void 0:n.allLayers)??["top","bottom"]:[]}return[]}getDescendants(){const t=[];for(const n of this.children)t.push(n),t.push(...n.getDescendants());return t}getSelectableDescendants(){const t=[];for(const 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;const{_parsedProps:t}=this;return{schWidth:t.schWidth,schHeight:t.schHeight}}renderError(t){var n;if(typeof t=="string")return super.renderError(t);(n=this.root)==null||n.db.pcb_placement_error.insert(t)}getString(){var a,o;const{lowercaseComponentName:t,_parsedProps:n,parent:i}=this;return(n==null?void 0:n.pinNumber)!==void 0&&((a=i==null?void 0:i.props)!=null&&a.name)&&(n!=null&&n.name)?`<${t}#${this._renderId}(pin:${n.pinNumber} .${i==null?void 0:i.props.name}>.${n.name}) />`:(o=i==null?void 0:i.props)!=null&&o.name&&(n!=null&&n.name)?`<${t}#${this._renderId}(.${i==null?void 0:i.props.name}>.${n==null?void 0:n.name}) />`:n!=null&&n.from&&(n!=null&&n.to)?`<${t}#${this._renderId}(from:${n.from} to:${n==null?void 0:n.to}) />`:n!=null&&n.name?`<${t}#${this._renderId} name=".${n==null?void 0:n.name}" />`:n!=null&&n.portHints?`<${t}#${this._renderId}(${n.portHints.map(s=>`.${s}`).join(", ")}) />`:`<${t}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},Odt=class extends $v{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:tn({}).passthrough()}}doInitialSourceRender(){var e,t,n,i;if((e=this.root)!=null&&e.db){const a=this._getGlobalPcbPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,message:((i=(n=(t=this._parsedProps.error)==null?void 0:t.formattedError)==null?void 0:n._errors)==null?void 0:i.join("; "))||this._parsedProps.message,pcb_center:a,schematic_center:o})}}};function zdt(r,e){return new Odt(r,e)}function Hdt(r,e){const t=r;return t.__tsci={...e},r}var Tye={supportsMutation:!0,createInstance(r,e){const t=sk[r];if(!t)throw Object.keys(sk).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 (not registered in @tscircuit/core catalogue): "${r}" See CREATING_NEW_COMPONENTS.md`);try{return Hdt(new t(e),{})}catch(n){return zdt(e,n)}},createTextInstance(){return{}},appendInitialChild(r,e){r.add(e)},appendChild(r,e){r.add(e)},appendChildToContainer(r,e){r.add(e)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(r){return r},preparePortalMount(r){throw new Error("Function not implemented.")},scheduleTimeout(r,e){throw new Error("Function not implemented.")},cancelTimeout(r){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(r){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(r,e)=>{throw new Error("Function not implemented.")},getInstanceFromScope:r=>{throw new Error("Function not implemented.")},detachDeletedInstance:r=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>X9.DefaultEventPriority,getCurrentUpdatePriority:()=>X9.DefaultEventPriority,resolveUpdatePriority:()=>X9.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},aQ;Uu.version.startsWith("19.")?aQ=tfe(Tye):aQ=afe(Tye);var Pye=r=>{const e={children:[],props:{name:"$root"},add(a){a.parent=this,this.children.push(a)},computePcbGlobalTransform(){return wy()}},t=[],n=aQ.createContainer(e,0,null,!1,null,"tsci",a=>{console.log("Error in createContainer"),console.error(a),t.push(a)},null);if(Uu.version.startsWith("19.")?(aQ.updateContainerSync(r,n,null,()=>{}),aQ.flushSyncWork()):aQ.updateContainer(r,n,null,()=>{}),t.length>0)throw t[0];const i=aQ.getPublicRootInstance(n);return i||e.children[0]},fD=(r,e)=>{if(typeof r=="number")return r;if(r.startsWith("pin"))return Number(r.slice(3));if(!e)throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`);for(const t in e)if((Array.isArray(e[t])?e[t]:[e[t]]).includes(r))return Number(t.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`)},Ydt=(r,e)=>{if(!r)return;const t={},n={};for(const[i,a]of Object.entries(r)){const o=fD(i,e);n[o]={...n[o],...a}}for(const[i,a]of Object.entries(n)){const o=`pin${i}`;t[o]={bottom_margin:a.bottomMargin,left_margin:a.leftMargin,right_margin:a.rightMargin,top_margin:a.topMargin}}return t},Vdt=r=>{if(r){if("leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r)return{left_side:r.leftSide,right_side:r.rightSide,top_side:r.topSide,bottom_side:r.bottomSide};if("leftPinCount"in r||"rightPinCount"in r||"topPinCount"in r||"bottomPinCount"in r)return{left_size:r.leftPinCount,right_size:r.rightPinCount,top_size:r.topPinCount,bottom_size:r.bottomPinCount};if("leftSize"in r||"rightSize"in r||"topSize"in r||"bottomSize"in r)return{left_size:r.leftSize,right_size:r.rightSize,top_size:r.topSize,bottom_size:r.bottomSize}}};function kye(r){const e=[];for(let t=0;t<r.length-1;t++)e.push([r[t],r[t+1]]);return e}var Kdt=tn({name:Be()}),Uye=class extends $v{constructor(){super(...arguments);Ke(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:Kdt}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_net.insert({name:n.name,member_source_group_ids:[]});this.source_net_id=i.source_net_id}doInitialSourceParentAttachment(){const t=this.getSubcircuit();if(!t)return;const{db:n}=this.root;n.source_net.update(this.source_net_id,{subcircuit_id:t.subcircuit_id})}getAllConnectedPorts(){const t=this.getSubcircuit().selectAll("port"),n=[];for(const i of t){const a=i._getDirectlyConnectedTraces();for(const o of a)if(o._isExplicitlyConnectedToNet(this)){n.push(i);break}}return n}_getAllDirectlyConnectedTraces(){const t=this.getSubcircuit().selectAll("trace"),n=[];for(const i of t)i._isExplicitlyConnectedToNet(this)&&n.push(i);return n}doInitialPcbRouteNetIslands(){var s;if((s=this.root)!=null&&s.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;const{db:t}=this.root,{_parsedProps:n}=this,i=this._getAllDirectlyConnectedTraces().filter(l=>{var c;return(((c=l._portsRoutedOnPcb)==null?void 0:c.length)??0)>0}),a=[];for(const l of i){const c=l._portsRoutedOnPcb,u=a.find(A=>c.some(d=>A.ports.includes(d)));if(!u){a.push({ports:[...c],traces:[l]});continue}u.traces.push(l),u.ports.push(...c)}if(a.length===0)return;const o=kye(a);for(const[l,c]of o){const u=l.ports.map(B=>B._getGlobalPcbPositionBeforeLayout()),A=c.ports.map(B=>B._getGlobalPcbPositionBeforeLayout());let d=1/0,f=[-1,-1];for(let B=0;B<u.length;B++){const P=u[B];for(let L=0;L<A.length;L++){const U=A[L],H=Math.sqrt((P.x-U.x)**2+(P.y-U.y)**2);H<d&&(d=H,f=[B,L])}}const g=l.ports[f[0]],_=c.ports[f[1]],I=t.toArray().filter(B=>B.type==="pcb_smtpad"||B.type==="pcb_trace"||B.type==="pcb_plated_hole"||B.type==="pcb_hole"||B.type==="source_port"||B.type==="pcb_port"),{solution:E}=x0e(I.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[g.source_port_id,_.source_port_id]}])),x=E[0];if(!x){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[g.pcb_component_id,_.pcb_component_id].filter(Boolean),pcb_port_ids:[g.pcb_port_id,_.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}t.pcb_trace.insert(x)}}renderError(t){var n;if(typeof t=="string")return super.renderError(t);(n=this.root)==null||n.db.pcb_trace_error.insert(t)}},Fye=(r,e)=>{for(const t of e)if(typeof t=="string"&&t.startsWith("net.")){if(/net\.[^\s>]*\./.test(t))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[0-9]/.test(t))throw new Error('Net names cannot start with a number, try using a prefix like "VBUS1"');const n=r.getSubcircuit();if(!n.selectOne(t)){const i=new Uye({name:t.split("net.")[1]});n.add(i)}}},oK=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_smtpad_id",null);Ke(this,"matchedPort",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:O0e}}getPcbSize(){const{_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};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){var n;const t=(n=this.getPrimitiveContainer())==null?void 0:n.selectAll("port");if(this.props.portHints){for(const i of t)if(i.isMatchingAnyOf(this.props.portHints)){this.matchedPort=i,i.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){var f,g,_,I,E,x,B,P,L,U;if((f=this.root)!=null&&f.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this;if(!n.portHints)return;const i=this.getPrimitiveContainer(),a=this.getSubcircuit(),o=this._getGlobalPcbPositionBeforeLayout();i==null||i._getGlobalPcbPositionBeforeLayout();const s=Zw(this._computePcbGlobalTransformBeforeLayout()),l=Math.abs(s.rotation.angle*(180/Math.PI)-90)%180<.01,{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),u=(i==null?void 0:i._parsedProps.pcbRotation)??0;let A=null;const d=((g=this.parent)==null?void 0:g.pcb_component_id)??((_=this.getPrimitiveContainer())==null?void 0:_.pcb_component_id);n.shape==="circle"?(A=t.pcb_smtpad.insert({pcb_component_id:d,pcb_port_id:(I=this.matchedPort)==null?void 0:I.pcb_port_id,layer:c(n.layer??"top"),shape:"circle",radius:n.radius,port_hints:n.portHints.map(H=>H.toString()),x:o.x,y:o.y,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0}),t.pcb_solder_paste.insert({layer:A.layer,shape:"circle",radius:A.radius*.7,x:A.x,y:A.y,pcb_component_id:A.pcb_component_id,pcb_smtpad_id:A.pcb_smtpad_id,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((E=this.getGroup())==null?void 0:E.pcb_group_id)??void 0})):n.shape==="rect"&&(A=u===0||l?t.pcb_smtpad.insert({pcb_component_id:d,pcb_port_id:(x=this.matchedPort)==null?void 0:x.pcb_port_id,layer:c(n.layer??"top"),shape:"rect",width:l?n.height:n.width,height:l?n.width:n.height,port_hints:n.portHints.map(H=>H.toString()),x:o.x,y:o.y,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((B=this.getGroup())==null?void 0:B.pcb_group_id)??void 0}):t.pcb_smtpad.insert({pcb_component_id:d,layer:c(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(H=>H.toString()),subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((P=this.getGroup())==null?void 0:P.pcb_group_id)??void 0}),A.shape==="rect"&&t.pcb_solder_paste.insert({layer:c(n.layer??"top"),shape:"rect",width:A.width*.7,height:A.height*.7,x:A.x,y:A.y,pcb_component_id:A.pcb_component_id,pcb_smtpad_id:A.pcb_smtpad_id,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((L=this.getGroup())==null?void 0:L.pcb_group_id)??void 0}),A.shape==="rotated_rect"&&t.pcb_solder_paste.insert({layer:c(n.layer??"top"),shape:"rotated_rect",width:A.width*.7,height:A.height*.7,x:A.x,y:A.y,ccw_rotation:u,pcb_component_id:A.pcb_component_id,pcb_smtpad_id:A.pcb_smtpad_id,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((U=this.getGroup())==null?void 0:U.pcb_group_id)??void 0})),A&&(this.pcb_smtpad_id=A.pcb_smtpad_id)}doInitialPcbPortAttachment(){var n,i;if((n=this.root)!=null&&n.pcbDisabled)return;const{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:(i=this.matchedPort)==null?void 0:i.pcb_port_id})}_getPcbCircuitJsonBounds(){const{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"){const i=n.ccw_rotation*Math.PI/180,a=Math.cos(i),o=Math.sin(i),s=n.width/2,l=n.height/2,c=Math.abs(s*a)+Math.abs(l*o),u=Math.abs(s*o)+Math.abs(l*a);return{center:{x:n.x,y:n.y},bounds:{left:n.x-c,right:n.x+c,top:n.y-u,bottom:n.y+u},width:c*2,height:u*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};throw new Error(`circuitJson bounds calculation not implemented for shape "${n.shape}"`)}_setPositionFromLayout(t){var a;const{db:n}=this.root;n.pcb_smtpad.update(this.pcb_smtpad_id,{x:t.x,y:t.y});const i=n.pcb_solder_paste.list().find(o=>o.pcb_smtpad_id===this.pcb_smtpad_id);n.pcb_solder_paste.update(i==null?void 0:i.pcb_solder_paste_id,{x:t.x,y:t.y}),(a=this.matchedPort)==null||a._setPositionFromLayout(t)}},Lye=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_silkscreen_path_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:ume}}doInitialPcbPrimitiveRender(){var c,u,A;if((c=this.root)!=null&&c.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),a=i(n.layer??"top");if(a!=="top"&&a!=="bottom")throw new Error(`Invalid layer "${a}" for SilkscreenPath. Must be "top" or "bottom".`);const o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),l=t.pcb_silkscreen_path.insert({pcb_component_id:(u=this.parent)==null?void 0:u.pcb_component_id,layer:a,route:n.route.map(d=>{const f=ti(o,{x:d.x,y:d.y});return{...d,x:f.x,y:f.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:(s==null?void 0:s.subcircuit_id)??void 0,pcb_group_id:((A=this.getGroup())==null?void 0:A.pcb_group_id)??void 0});this.pcb_silkscreen_path_id=l.pcb_silkscreen_path_id}getPcbSize(){const{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,a=1/0,o=-1/0;for(const s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),a=Math.min(a,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-a}}},jdt=tn({route:hi(ST),source_trace_id:Be().optional()}),Gye=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_trace_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:jdt}}doInitialPcbPrimitiveRender(){var u,A;if((u=this.root)!=null&&u.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),a=this.getSubcircuit(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),s=this._computePcbGlobalTransformBeforeLayout(),l=n.route.map(d=>{const{x:f,y:g,..._}=d,I=ti(s,{x:f,y:g});return d.route_type==="wire"&&d.layer?{...I,..._,layer:o(d.layer)}:{...I,..._}}),c=t.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:n.source_trace_id,route:l,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((A=this.getGroup())==null?void 0:A.pcb_group_id)??void 0});this.pcb_trace_id=c.pcb_trace_id}getPcbSize(){const{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,a=1/0,o=-1/0;for(const s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),a=Math.min(a,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),a=Math.min(a,s.y-s.width/2),o=Math.max(o,s.y+s.width/2));return n===1/0||i===-1/0||a===1/0||o===-1/0?{width:0,height:0}:{width:i-n,height:o-a}}},sK=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_plated_hole_id",null);Ke(this,"matchedPort",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:R0e}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){const{_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(){const{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){var i;const{db:n}=this.root;n.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:t.x,y:t.y}),(i=this.matchedPort)==null||i._setPositionFromLayout(t)}doInitialPortMatching(){var n;const t=(n=this.getPrimitiveContainer())==null?void 0:n.selectAll("port");if(this.props.portHints){for(const i of t)if(i.isMatchingAnyOf(this.props.portHints)){this.matchedPort=i,i.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){var s,l,c,u,A,d,f,g,_,I,E,x,B,P,L;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),a=((l=this.parent)==null?void 0:l.pcb_component_id)??((c=this.getPrimitiveContainer())==null?void 0:c.pcb_component_id),o=this.getSubcircuit();if(n.shape==="circle"){const U=t.pcb_plated_hole.insert({pcb_component_id:a,pcb_port_id:(u=this.matchedPort)==null?void 0:u.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==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((A=this.getGroup())==null?void 0:A.pcb_group_id)??void 0});this.pcb_plated_hole_id=U.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==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((d=this.getGroup())==null?void 0:d.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==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((f=this.getGroup())==null?void 0:f.pcb_group_id)??void 0})}else if(n.shape==="pill"||n.shape==="oval"){const U=t.pcb_plated_hole.insert({pcb_component_id:a,pcb_port_id:(g=this.matchedPort)==null?void 0:g.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==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((_=this.getGroup())==null?void 0:_.pcb_group_id)??void 0});this.pcb_plated_hole_id=U.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==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((I=this.getGroup())==null?void 0:I.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==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((E=this.getGroup())==null?void 0:E.pcb_group_id)??void 0})}else if(n.shape==="circular_hole_with_rect_pad"){const U=t.pcb_plated_hole.insert({pcb_component_id:a,pcb_port_id:(x=this.matchedPort)==null?void 0:x.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==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((B=this.getGroup())==null?void 0:B.pcb_group_id)??void 0});this.pcb_plated_hole_id=U.pcb_plated_hole_id}else if(n.shape==="pill_hole_with_rect_pad"){const U=t.pcb_plated_hole.insert({pcb_component_id:a,pcb_port_id:(P=this.matchedPort)==null?void 0:P.pcb_port_id,hole_width:n.holeWidth,hole_height:n.holeHeight,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((L=this.getGroup())==null?void 0:L.pcb_group_id)??void 0});this.pcb_plated_hole_id=U.pcb_plated_hole_id}}doInitialPcbPortAttachment(){var n,i;if((n=this.root)!=null&&n.pcbDisabled)return;const{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:(i=this.matchedPort)==null?void 0:i.pcb_port_id})}},lK=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_keepout_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:ame}}doInitialPcbPrimitiveRender(){var c,u,A;if((c=this.root)!=null&&c.pcbDisabled)return;const t=this.getSubcircuit(),{db:n}=this.root,{_parsedProps:i}=this,a=this._getGlobalPcbPositionBeforeLayout(),o=Zw(this._computePcbGlobalTransformBeforeLayout()),s=Math.abs(o.rotation.angle*(180/Math.PI)-90)%180<.01;let l=null;i.shape==="circle"?l=n.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:a.x,y:a.y},subcircuit_id:(t==null?void 0:t.subcircuit_id)??void 0,pcb_group_id:((u=t==null?void 0:t.getGroup())==null?void 0:u.pcb_group_id)??void 0}):i.shape==="rect"&&(l=n.pcb_keepout.insert({layers:["top"],shape:"rect",...s?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:a.x,y:a.y},subcircuit_id:(t==null?void 0:t.subcircuit_id)??void 0,pcb_group_id:((A=t==null?void 0:t.getGroup())==null?void 0:A.pcb_group_id)??void 0})),l&&(this.pcb_keepout_id=l.pcb_keepout_id)}},Oye=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_hole_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:z0e}}getPcbSize(){const{_parsedProps:t}=this;return{width:t.diameter,height:t.diameter}}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),a=this._getGlobalPcbPositionBeforeLayout(),o=t.pcb_hole.insert({hole_shape:"circle",hole_diameter:n.diameter,x:a.x,y:a.y,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((l=i==null?void 0:i.getGroup())==null?void 0:l.pcb_group_id)??void 0});this.pcb_hole_id=o.pcb_hole_id}_getPcbCircuitJsonBounds(){const{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){const{db:n}=this.root;n.pcb_hole.update(this.pcb_hole_id,{x:t.x,y:t.y})}},cK=class extends $v{constructor(){super(...arguments);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:cme}}doInitialPcbPrimitiveRender(){var l,c;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),a=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),s=this.getSubcircuit();t.pcb_silkscreen_text.insert({anchor_alignment:n.anchorAlignment,anchor_position:{x:a.x,y:a.y},font:n.font??"tscircuit2024",font_size:n.fontSize??1,layer:o(n.layer??"top"),text:n.text??"",ccw_rotation:n.pcbRotation,pcb_component_id:i.pcb_component_id,subcircuit_id:(s==null?void 0:s.subcircuit_id)??void 0,pcb_group_id:((c=this.getGroup())==null?void 0:c.pcb_group_id)??void 0})}getPcbSize(){const{_parsedProps:t}=this,n=t.fontSize??1,a=(t.text??"").length*n,o=n;return{width:a*n,height:o*n}}},Jdt=({elm:r,pinLabels:e,readableRotation:t,anchorAlignment:n})=>{var o;const i=r.text.replace(/[{}]/g,"").toLowerCase();let a=i;if(Array.isArray(e)){const s=parseInt(i.replace(/[^\d]/g,""),10)-1;a=e[s]??i}else typeof e=="object"&&(a=((o=e[i])==null?void 0:o[0])??i);return new cK({anchorAlignment:n||"center",text:a??i,fontSize:r.font_size+.2,pcbX:isNaN(r.anchor_position.x)?0:r.anchor_position.x,pcbY:r.anchor_position.y,pcbRotation:t??0})},Wdt=(r,e)=>((-parseInt(r||"0",10)+(e??0))%360+360)%360,zye=({componentName:r,componentRotation:e,footprint:t,pinLabels:n},i)=>{const a=[];for(const o of i)if(o.type==="pcb_smtpad"&&o.shape==="rect")a.push(new oK({pcbX:o.x,pcbY:o.y,layer:o.layer,shape:"rect",height:o.height,width:o.width,portHints:o.port_hints}));else if(o.type==="pcb_smtpad"&&o.shape==="circle")a.push(new oK({pcbX:o.x,pcbY:o.y,layer:o.layer,shape:"circle",radius:o.radius,portHints:o.port_hints}));else if(o.type==="pcb_silkscreen_path")a.push(new Lye({layer:o.layer,route:o.route,strokeWidth:o.stroke_width}));else if(o.type==="pcb_plated_hole")o.shape==="circle"?a.push(new sK({pcbX:o.x,pcbY:o.y,shape:"circle",holeDiameter:o.hole_diameter,outerDiameter:o.outer_diameter,portHints:o.port_hints})):o.shape==="circular_hole_with_rect_pad"&&a.push(new sK({pcbX:o.x,pcbY:o.y,shape:"circular_hole_with_rect_pad",holeDiameter:o.hole_diameter,rectPadHeight:o.rect_pad_height,rectPadWidth:o.rect_pad_width,portHints:o.port_hints}));else if(o.type==="pcb_keepout"&&o.shape==="circle")a.push(new lK({pcbX:o.center.x,pcbY:o.center.y,shape:"circle",radius:o.radius}));else if(o.type==="pcb_keepout"&&o.shape==="rect")a.push(new lK({pcbX:o.center.x,pcbY:o.center.y,shape:"rect",width:o.width,height:o.height}));else if(o.type==="pcb_hole"&&o.hole_shape==="circle")a.push(new Oye({pcbX:o.x,pcbY:o.y,diameter:o.hole_diameter}));else if(o.type==="pcb_silkscreen_text"){const s=Wdt(e,o.ccw_rotation);t.includes("pinrow")&&o.text.includes("PIN")?a.push(Jdt({elm:o,pinLabels:n,readableRotation:s,anchorAlignment:o.anchor_alignment})):a.push(new cK({anchorAlignment:o.anchor_alignment||"center",text:r,fontSize:o.font_size+.2,pcbX:isNaN(o.anchor_position.x)?0:o.anchor_position.x,pcbY:o.anchor_position.y,pcbRotation:s??0}))}else o.type==="pcb_trace"&&a.push(new Gye({route:o.route}));return a};function uK(r){let e=1/0,t=1/0,n=-1/0,i=-1/0,a=!1;for(const l of r)if(l.isPcbPrimitive&&!l.componentName.startsWith("Silkscreen")){const{x:c,y:u}=l._getGlobalPcbPositionBeforeLayout(),{width:A,height:d}=l.getPcbSize();e=Math.min(e,c-A/2),t=Math.min(t,u-d/2),n=Math.max(n,c+A/2),i=Math.max(i,u+d/2),a=!0}else if(l.children.length>0){const c=uK(l.children);(c.width>0||c.height>0)&&(e=Math.min(e,c.minX),t=Math.min(t,c.minY),n=Math.max(n,c.maxX),i=Math.max(i,c.maxY),a=!0)}if(!a)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let o=n-e,s=i-t;return o<0&&(o=0),s<0&&(s=0),{minX:e,minY:t,maxX:n,maxY:i,width:o,height:s}}function qdt(r,e){const t=e.x-r.x,n=e.y-r.y;return Math.abs(t)>Math.abs(n)?t>=0?"right":"left":n>=0?"up":"down"}var Zdt=r=>{if(r.length<=1)return!0;const e=r.map(a=>{const o=a._getPcbCircuitJsonBounds();return{left:o.bounds.left,right:o.bounds.right,top:o.bounds.top,bottom:o.bounds.bottom}}),t=Array(e.length).fill(!1).map(()=>Array(e.length).fill(!1));for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++){const s=e[a],l=e[o];t[a][o]=t[o][a]=!(s.right<l.left||s.left>l.right||s.bottom>l.top||s.top<l.bottom)}const n=new Set,i=a=>{n.add(a);for(let o=0;o<e.length;o++)t[a][o]&&!n.has(o)&&i(o)};return i(0),n.size===e.length},Xdt=r=>{if(r.length===0)throw new Error("Cannot get center of empty PCB primitives array");const e=r.map(i=>i._getPcbCircuitJsonBounds().center).filter(Boolean),t=e.reduce((i,a)=>i+a.x,0),n=e.reduce((i,a)=>i+a.y,0);return{x:t/e.length,y:n/e.length}},$dt=tn({name:Be().optional(),pinNumber:yn().optional(),aliases:hi(Be()).optional()}),GS=class extends $v{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);Ke(this,"source_port_id",null);Ke(this,"pcb_port_id",null);Ke(this,"schematic_port_id",null);Ke(this,"schematicSymbolPortDef",null);Ke(this,"matchedComponents");Ke(this,"facingDirection",null);Ke(this,"originDescription",null);n.originDescription&&(this.originDescription=n.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:$dt}}_getGlobalPcbPositionBeforeLayout(){const 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==null?void 0:t._getGlobalPcbPositionBeforeLayout())??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();const{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(){const t=this.parent;if(!t||!t._getInternallyConnectedPins)return[];const n=t._getInternallyConnectedPins();for(const i of n)if(i.some(a=>a===this))return i;return[]}_hasSchematicPort(){var i,a;if((i=this.parent)==null?void 0:i.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(s=>s.schematicSymbolPortDef));const n=(a=this==null?void 0:this.parent)==null?void 0:a._getSchematicBoxDimensions();return!!(n&&this.props.pinNumber!==void 0&&n.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){var i,a,o;const t=(i=this.parent)==null?void 0:i.getSchematicSymbol();if(t){let s=this.schematicSymbolPortDef;if(!s&&(s=((a=this._getPortsInternallyConnectedToThisPort().find(c=>c.schematicSymbolPortDef))==null?void 0:a.schematicSymbolPortDef)??null,!s))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?`);const l=Fu(this.parent.computeSchematicGlobalTransform(),Od(-t.center.x,-t.center.y));return ti(l,s)}const n=(o=this==null?void 0:this.parent)==null?void 0:o._getSchematicBoxDimensions();if(n&&this.props.pinNumber!==void 0){const s=n.getPortPositionByPinNumber(this.props.pinNumber);if(!s)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return ti(this.parent.computeSchematicGlobalTransform(),s)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){const{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`);const 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(){const{_parsedProps:t}=this;return Array.from(new Set([...t.aliases??[],...t.name?[t.name]:[],...typeof t.pinNumber=="number"?[`pin${t.pinNumber}`,t.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}isMatchingPort(t){return this.isMatchingAnyOf(t.getNameAndAliases())}getPortSelector(){var t;return`.${(t=this.parent)==null?void 0:t.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){return Array.from(new Set(this.matchedComponents.flatMap(t=>t.getAvailablePcbLayers())))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(i=>i._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){var o,s;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getNameAndAliases(),a=t.source_port.insert({name:n.name,pin_number:n.pinNumber,port_hints:i,source_component_id:(o=this.parent)==null?void 0:o.source_component_id,subcircuit_id:(s=this.getSubcircuit())==null?void 0:s.subcircuit_id});this.source_port_id=a.source_port_id}doInitialSourceParentAttachment(){var n,i,a,o,s;const{db:t}=this.root;if(!((n=this.parent)!=null&&n.source_component_id))throw new Error(`${this.getString()} has no parent source component (parent: ${(i=this.parent)==null?void 0:i.getString()})`);t.source_port.update(this.source_port_id,{source_component_id:(a=this.parent)==null?void 0:a.source_component_id,subcircuit_id:(o=this.getSubcircuit())==null?void 0:o.subcircuit_id}),this.source_component_id=(s=this.parent)==null?void 0:s.source_component_id}doInitialPcbPortRender(){var o,s,l,c,u;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:t}=this.root,{matchedComponents:n}=this;if(!((s=this.parent)!=null&&s.pcb_component_id))throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${(l=this.parent)==null?void 0:l.getString()})`);const i=n.filter(A=>A.isPcbPrimitive);if(i.length===0)return;let a=null;if(i.length===1&&(a=i[0]._getPcbCircuitJsonBounds().center),i.length>1){if(!Zdt(i))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${i.map(A=>A.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);a=Xdt(i)}if(a){const A=this.getSubcircuit(),d=t.pcb_port.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:(A==null?void 0:A.subcircuit_id)??void 0,pcb_group_id:((u=this.getGroup())==null?void 0:u.pcb_group_id)??void 0,...a,source_port_id:this.source_port_id});this.pcb_port_id=d.pcb_port_id}else{const A=i[0];throw new Error(`${A.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}doInitialSchematicPortRender(){var d;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer();if(!i||!this._hasSchematicPort())return;const a=i._getGlobalSchematicPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout();let s=null;const l=i._getSchematicBoxDimensions();l&&n.pinNumber!==void 0&&(s=l.getPortPositionByPinNumber(n.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&t.schematic_debug_object.insert({shape:"rect",center:o,size:{width:.1,height:.1},label:"obstacle"}),s!=null&&s.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[s.side]:this.facingDirection=qdt(a,o);const c=t.source_port.get(this.source_port_id);let u;for(const f of(c==null?void 0:c.port_hints)??[])f.match(/^(pin)?\d+$/)||f.match(/^(left|right)/)&&!(c!=null&&c.name.match(/^(left|right)/))||(u=f);const A=t.schematic_port.insert({schematic_component_id:(d=this.parent)==null?void 0:d.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==null?void 0:s.side,pin_number:n.pinNumber,true_ccw_index:s==null?void 0:s.trueIndex,display_pin_label:u});this.schematic_port_id=A.schematic_port_id}_setPositionFromLayout(t){const{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)}},Hye=r=>{const e=r.find(t=>/^(pin)?\d+$/.test(t));return e?Number.parseInt(e.replace(/^pin/,"")):null};function hD(r,e){var a;const t=Hye(r);if(!t)return null;const i=[...r.filter(o=>o.toString()!==t.toString()&&o!==`pin${t}`),...((a=e==null?void 0:e.additionalAliases)==null?void 0:a[`pin${t}`])??[]];return new GS({pinNumber:t,aliases:i})}var eft=r=>{for(const e of["leftSide","rightSide","topSide","bottomSide"])if(e in r&&typeof r[e]=="number")throw new Error(`A number was specified for "${e}", you probably meant to use "size" not "side"`);return"leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r},tft=r=>{var a,o,s,l;if(eft(r))return{leftSize:((a=r.leftSide)==null?void 0:a.pins.length)??0,rightSize:((o=r.rightSide)==null?void 0:o.pins.length)??0,topSize:((s=r.topSide)==null?void 0:s.pins.length)??0,bottomSize:((l=r.bottomSide)==null?void 0:l.pins.length)??0};const{leftSize:e=0,rightSize:t=0,topSize:n=0,bottomSize:i=0}=r;return{leftSize:e,rightSize:t,topSize:n,bottomSize:i}};function Yye(r){return r.leftSide!==void 0}var nft=r=>{var I,E,x,B,P,L,U,H;const e=r.portDistanceFromEdge??.4;let t=r.schPortArrangement?tft(r.schPortArrangement):null;const n={left:0,right:0,top:0,bottom:0};let i=r.pinCount??null;if(i===null)if(t)i=t.leftSize+t.rightSize+t.topSize;else throw new Error("Could not determine pin count for the schematic box");if(i&&!t){const G=Math.floor(i/2);t={leftSize:i-G,rightSize:G,topSize:0,bottomSize:0}}t||(t={leftSize:0,rightSize:0,topSize:0,bottomSize:0});const a=({side:G,sideIndex:W,truePinIndex:z})=>{var Ae,he,Ie,ge;if(!r.schPortArrangement||!Yye(r.schPortArrangement))return z+1;const ae={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[G],te=((he=(Ae=r.schPortArrangement)==null?void 0:Ae[`${G}Side`])==null?void 0:he.direction)??ae,oe=(ge=(Ie=r.schPortArrangement)==null?void 0:Ie[`${G}Side`])==null?void 0:ge.pins;let pe=W;return te!==ae&&(pe=oe.length-W-1),fD(oe[pe],r.pinLabels)},o=[];let s=0,l=0;for(let G=0;G<t.leftSize;G++){const W=a({side:"left",sideIndex:G,truePinIndex:l}),z=((I=r.numericSchPinStyle)==null?void 0:I[`pin${W}`])??((E=r.numericSchPinStyle)==null?void 0:E[W]);z!=null&&z.topMargin&&(s+=z.topMargin),o.push({trueIndex:l,pinNumber:W,side:"left",distanceFromOrthogonalEdge:s}),z!=null&&z.bottomMargin&&(s+=z.bottomMargin),G===t.leftSize-1?n.left=s:s+=r.schPinSpacing,l++}s=0;for(let G=0;G<t.bottomSize;G++){const W=a({side:"bottom",sideIndex:G,truePinIndex:l}),z=((x=r.numericSchPinStyle)==null?void 0:x[`pin${W}`])??((B=r.numericSchPinStyle)==null?void 0:B[W]);z!=null&&z.leftMargin&&(s+=z.leftMargin),o.push({trueIndex:l,pinNumber:W,side:"bottom",distanceFromOrthogonalEdge:s}),z!=null&&z.rightMargin&&(s+=z.rightMargin),G===t.bottomSize-1?n.bottom=s:s+=r.schPinSpacing,l++}s=0;for(let G=0;G<t.rightSize;G++){const W=a({side:"right",sideIndex:G,truePinIndex:l}),z=((P=r.numericSchPinStyle)==null?void 0:P[`pin${W}`])??((L=r.numericSchPinStyle)==null?void 0:L[W]);z!=null&&z.bottomMargin&&(s+=z.bottomMargin),o.push({trueIndex:l,pinNumber:W,side:"right",distanceFromOrthogonalEdge:s}),z!=null&&z.topMargin&&(s+=z.topMargin),G===t.rightSize-1?n.right=s:s+=r.schPinSpacing,l++}s=0;for(let G=0;G<t.topSize;G++){const W=a({side:"top",sideIndex:G,truePinIndex:l}),z=((U=r.numericSchPinStyle)==null?void 0:U[`pin${W}`])??((H=r.numericSchPinStyle)==null?void 0:H[W]);z!=null&&z.rightMargin&&(s+=z.rightMargin),o.push({trueIndex:l,pinNumber:W,side:"top",distanceFromOrthogonalEdge:s}),z!=null&&z.leftMargin&&(s+=z.leftMargin),G===t.topSize-1?n.top=s:s+=r.schPinSpacing,l++}let c=r.schWidth;c||(c=Math.max(n.top+r.schPinSpacing*2,n.bottom+r.schPinSpacing*2));const u=r.pinLabels?Math.max(...Object.values(r.pinLabels).map(G=>G.length*.1)):0,A=u>0?1.1:0;c=Math.max(c,u+A);let d=r.schHeight;d||(d=Math.max(n.left+r.schPinSpacing*2,n.right+r.schPinSpacing*2));const f={left:{x:-c/2-e,y:n.left/2},bottom:{x:-n.bottom/2,y:-d/2-e},right:{x:c/2+e,y:-n.right/2},top:{x:n.top/2,y:d/2+e}},g={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},_=o.map(G=>{const{distanceFromOrthogonalEdge:W,side:z}=G,ae=f[z],te=g[z];return{x:ae.x+W*te.x,y:ae.y+W*te.y,...G}});return{getPortPositionByPinNumber(G){const W=_.find(z=>z.pinNumber.toString()===G.toString());return W||null},getSize(){return{width:c,height:d}},getSizeIncludingPins(){return{width:c+(t.leftSize||t.rightSize?.4:0),height:d+(t.topSize||t.bottomSize?.4:0)}},pinCount:i}},rft=nv("tscircuit:core:footprint"),ift=class extends $v{get config(){return{componentName:"Footprint",zodProps:V0e}}doInitialPcbFootprintLayout(){var d,f,g,_,I;if((d=this.root)!=null&&d.pcbDisabled)return;const e=this.children.filter(E=>E.componentName==="Constraint");if(e.length===0)return;const{isFlipped:t}=this._getPcbPrimitiveFlippedHelpers(),n=E=>t&&"left"in E&&"right"in E?{...E,left:E.right,right:E.left}:E,i=e.flatMap(E=>E._getAllReferencedComponents().componentsWithSelectors).map(({component:E,selector:x,componentSelector:B,edge:P})=>({component:E,selector:x,componentSelector:B,edge:P,bounds:E._getPcbCircuitJsonBounds()}));if(i.some(E=>E.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function a(E){return i.find(({selector:x})=>x===E)}const o=new gme,s={};function l(E){return E in s||(s[E]=new DP(E),o.addEditVariable(s[E],iC.weak)),s[E]}for(const{selector:E,bounds:x}of i){const B=l(`${E}_x`),P=l(`${E}_y`);o.suggestValue(B,x.center.x),o.suggestValue(P,x.center.y)}for(const E of e){const x=E._parsedProps;if("xDist"in x){const{xDist:B,left:P,right:L,edgeToEdge:U,centerToCenter:H}=n(x),G=l(`${P}_x`),W=l(`${L}_x`),z=(f=a(P))==null?void 0:f.bounds,ae=(g=a(L))==null?void 0:g.bounds;if(H){const te=new II(W,[-1,G]);o.addConstraint(new Gx(te,aE.Eq,x.xDist,iC.required))}else if(U){const te=new II(W,-ae.width/2,[-1,G],-z.width/2);o.addConstraint(new Gx(te,aE.Eq,x.xDist,iC.required))}}else if("yDist"in x){const{yDist:B,top:P,bottom:L,edgeToEdge:U,centerToCenter:H}=x,G=l(`${P}_y`),W=l(`${L}_y`),z=(_=a(P))==null?void 0:_.bounds,ae=(I=a(L))==null?void 0:I.bounds;if(H){const te=new II(G,[-1,W]);o.addConstraint(new Gx(te,aE.Eq,x.yDist,iC.required))}else if(U){const te=new II(G,z.height/2,[-1,W],-ae.height/2);o.addConstraint(new Gx(te,aE.Eq,x.yDist,iC.required))}}else if("sameY"in x){const{for:B}=x;if(B.length<2)continue;const P=B.map(U=>l(`${U}_y`)),L=new II(...P.slice(1));o.addConstraint(new Gx(L,aE.Eq,P[0],iC.required))}else if("sameX"in x){const{for:B}=x;if(B.length<2)continue;const P=B.map(U=>l(`${U}_x`)),L=new II(...P.slice(1));o.addConstraint(new Gx(L,aE.Eq,P[0],iC.required))}}o.updateVariables(),rft.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(s).map(([E,x])=>({var:E,val:x.value()}))));const c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(const{selector:E,bounds:{width:x,height:B}}of i){const P=l(`${E}_x`),L=l(`${E}_y`),U=P.value()-x/2,H=P.value()+x/2,G=L.value()+B/2,W=L.value()-B/2;c.left=Math.min(c.left,U),c.right=Math.max(c.right,H),c.top=Math.max(c.top,G),c.bottom=Math.min(c.bottom,W)}const u={x:-(c.right+c.left)/2,y:-(c.top+c.bottom)/2},A=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();u.x+=A.x,u.y+=A.y;for(const{component:E,selector:x}of i){const B=l(`${x}_x`),P=l(`${x}_y`);E._setPositionFromLayout({x:B.value()+u.x,y:P.value()+u.y})}}},aft=(r,e)=>{if(!r)return;const t={};for(const[n,i]of Object.entries(r)){const a=fD(n,e),o={leftMargin:i.marginLeft??i.leftMargin,rightMargin:i.marginRight??i.rightMargin,topMargin:i.marginTop??i.topMargin,bottomMargin:i.marginBottom??i.bottomMargin};t[`pin${a}`]={...t[`pin${a}`],...o}}return t},Vye=class{constructor({input:e}){Ke(this,"input");this.input=e}solveAndMapToTraces(){const e=[];for(const t of this.input.connections){if(t.pointsToConnect.length!==2)continue;const[n,i]=t.pointsToConnect,a={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(a)}return e}},oft=r=>{const e=Math.min(...r.map(a=>a.center.x)),t=Math.max(...r.map(a=>a.center.x)),n=Math.min(...r.map(a=>a.center.y)),i=Math.max(...r.map(a=>a.center.y));return{minX:e,maxX:t,minY:n,maxY:i}},Kye=["top","bottom","inner1","inner2"],lk=(r,e=[])=>{var s;const t=[];if(e.length===0){const l=r[0].layers;for(const c of l)t.push(...lk(r.slice(1),[c]));return t}if(r.length===0)return[];const n=r[0],i=n.via||n.optional_via,a=e[e.length-1];if(r.length===1){const l=n;return l.layers&&i?l.layers.map(c=>({layer_path:[...e,c]})):(s=l.layers)!=null&&s.includes(a)?[{layer_path:[...e,a]}]:[]}if(!i)return n.layers&&!n.layers.includes(a)?[]:lk(r.slice(1),e.concat([a]));const o=(n.optional_via?Kye:Kye.filter(l=>l!==a)).filter(l=>{var c;return!n.layers||((c=n.layers)==null?void 0:c.includes(l))});for(const l of o)t.push(...lk(r.slice(1),e.concat(l)));return t};function jye(r){const e={x:r.to.x-r.from.x,y:r.to.y-r.from.y},t=Math.abs(e.x),n=Math.abs(e.y);return t>n?e.x>0?"right":"left":e.y>0?"down":"up"}function yM(r,e){return Math.hypot(r.x-e.x,r.y-e.y)}var sft=r=>{if(r.length===1)return r[0];if(r.some(l=>l.length===0))throw new Error("Cannot merge routes with zero length");const e=[],t=r[0][0],n=r[0][r[0].length-1],i=r[1][0],a=r[1][r[1].length-1],o=Math.min(yM(t,i),yM(t,a)),s=Math.min(yM(n,i),yM(n,a));o<s?e.push(...r[0].reverse()):e.push(...r[0]);for(let l=1;l<r.length;l++){const c=e[e.length-1],u=r[l],A=u[0],d=u[u.length-1],f=yM(c,A),g=yM(c,d);f<g?e.push(...u):e.push(...u.reverse())}for(let l=1;l<e.length-1;l++){const c=e[l-1],u=e[l];c.route_type==="wire"&&u.route_type==="wire"&&c.layer!==u.layer&&e.splice(l,0,{x:c.x,y:c.y,from_layer:c.layer,to_layer:u.layer,route_type:"via"})}return e},lft=(r,e)=>{const t="_getGlobalPcbPositionBeforeLayout"in r?r._getGlobalPcbPositionBeforeLayout():r,n="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((t.x-n.x)**2+(t.y-n.y)**2)};function cft(r,e){if(e.length===0)throw new Error("No candidates given to getClosest method");let t=e[0],n=1/0;for(const i of e){const a=lft(r,i);a<n&&(t=i,n=a)}return t}var uft=(r,e)=>{let t=0;t+=r.length??0,t+=e.filter(n=>n.is_crossing).length;for(let n=1;n<e.length;n++){const i=e[n-1],a=e[n],o=Math.abs(i.from.x-i.to.x)<.01,s=Math.abs(a.from.x-a.to.x)<.01;o!==s&&t++}return t},AK=r=>({up:"bottom",down:"top",left:"right",right:"left"})[r]??null,dK=({firstEdge:r,firstEdgePort:e,firstDominantDirection:t,lastEdge:n,lastEdgePort:i,lastDominantDirection:a})=>{if(r&&e)return dK({lastEdge:{from:r.to,to:r.from},lastEdgePort:e,lastDominantDirection:t}).reverse().map(s=>({from:s.to,to:s.from}));let o=[];if(n&&i){const s={x:n.to.x,y:n.to.y};a==="left"||a==="right"?(s.x=i.position.x,o.push({from:n.to,to:{...s}}),o.push({from:s,to:{...i.position}})):(s.y=i.position.y,o.push({from:n.to,to:{...s}}),o.push({from:s,to:{...i.position}}))}return o=o.filter(s=>NB(s.from,s.to)>.01),o};function Aft(r){try{return[r(),null]}catch(e){return[null,e]}}function dft(r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];if(n.route_type==="wire"){const i=r[t+1];if(i){const a=i.x-n.x,o=i.y-n.y;e+=Math.sqrt(a*a+o*o)}}else n.route_type==="via"&&(e+=1.6)}return e}var ck=({db:r,source_trace_id:e,sameNetOnly:t,differentNetOnly:n})=>{!t&&!n&&(n=!0);const i=r.source_trace.get(e),a=[];for(const o of r.schematic_trace.list()){if(o.source_trace_id===e)continue;const s=r.source_trace.get(o.source_trace_id),l=(s==null?void 0:s.subcircuit_connectivity_map_key)===i.subcircuit_connectivity_map_key;n&&l||t&&!l||a.push(o)}return a},Jye=({edges:r,otherEdges:e})=>{const t=[...r];for(let n=0;n<t.length;n++){if(n>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");const i=t[n],a=Math.abs(i.from.x-i.to.x)<.01?"vertical":i.from.y===i.to.y?"horizontal":"not-orthogonal";if(a==="not-orthogonal")continue;const o=[];for(const _ of e){const I=_.from.x===_.to.x?"vertical":_.from.y===_.to.y?"horizontal":"not-orthogonal";if(I==="not-orthogonal"||a===I)continue;if(TP([i.from,i.to],[_.from,_.to],{lineThickness:.01})){const x=a==="vertical"?i.from.x:_.from.x,B=a==="vertical"?_.from.y:i.from.y,P={x,y:B};o.push({otherEdge:_,crossingPoint:P,distanceFromEdgeFrom:NB(i.from,P)})}}if(o.length===0)continue;let s=o[0];for(const _ of o)_.distanceFromEdgeFrom<s.distanceFromEdgeFrom&&(s=_);const l=s.crossingPoint,c=.075;if(l.x===i.from.x&&l.y===i.from.y)continue;const u=yme(i.from,l),A={x:l.x-u.x*c/2,y:l.y-u.y*c/2},d={x:l.x+u.x*c/2,y:l.y+u.y*c/2},f=NB(d,i.to)<c,g=[{from:i.from,to:A},{from:A,to:d,is_crossing:!0},{from:d,to:i.to}];t.splice(n,1,...g),n+=g.length-2,f&&n++}return t},fft=(r,e)=>{if(r.from.x===r.to.x&&e.from.x===e.to.x)return null;if(r.from.x===r.to.x){const u=r.from.x,A=(e.to.y-e.from.y)/(e.to.x-e.from.x),d=e.from.y-A*e.from.x,f=A*u+d;return u>=Math.min(e.from.x,e.to.x)&&u<=Math.max(e.from.x,e.to.x)&&f>=Math.min(e.from.y,e.to.y)&&f<=Math.max(e.from.y,e.to.y)?{x:u,y:f}:null}if(e.from.x===e.to.x){const u=e.from.x,A=(r.to.y-r.from.y)/(r.to.x-r.from.x),d=r.from.y-A*r.from.x,f=A*u+d;return u>=Math.min(r.from.x,r.to.x)&&u<=Math.max(r.from.x,r.to.x)&&f>=Math.min(r.from.y,r.to.y)&&f<=Math.max(r.from.y,r.to.y)?{x:u,y:f}:null}const t=(r.to.y-r.from.y)/(r.to.x-r.from.x),n=r.from.y-t*r.from.x,i=(e.to.y-e.from.y)/(e.to.x-e.from.x),a=e.from.y-i*e.from.x;if(t===i)return null;const o=(a-n)/(t-i),s=t*o+n,l=o>=Math.min(r.from.x,r.to.x)&&o<=Math.max(r.from.x,r.to.x)&&s>=Math.min(r.from.y,r.to.y)&&s<=Math.max(r.from.y,r.to.y),c=o>=Math.min(e.from.x,e.to.x)&&o<=Math.max(e.from.x,e.to.x)&&s>=Math.min(e.from.y,e.to.y)&&s<=Math.max(e.from.y,e.to.y);return l&&c?{x:o,y:s}:null},Wye=({edges:r,db:e,source_trace_id:t})=>{const n=ck({db:e,source_trace_id:t,sameNetOnly:!0}).flatMap(i=>i.edges);for(const i of r)for(const a of n){const o=fft(i,a);if(o)return`${o.x}${o.y}`,[{x:o.x,y:o.y}]}return[]},hft=(r,{db:e})=>{const t=r.map(n=>{const i=e.source_port.get(n.source_port_id);if(!(i!=null&&i.source_component_id))return null;const a=e.source_component.get(i.source_component_id);return(a==null?void 0:a.ftype)==="simple_capacitor"?a.max_decoupling_trace_length:null}).filter(n=>n!==null);if(t.length!==0)return Math.min(...t)};function pft(r){var a,o,s,l,c,u,A,d,f;let e=1/0,t=1/0,n=-1/0,i=-1/0;for(const g of r){let _,I,E,x;g.type==="schematic_component"?(_=(a=g.center)==null?void 0:a.x,I=(o=g.center)==null?void 0:o.y,E=(s=g.size)==null?void 0:s.width,x=(l=g.size)==null?void 0:l.height):g.type==="schematic_box"?(_=g.x,I=g.y,E=g.width,x=g.height):g.type==="schematic_port"?(_=(c=g.center)==null?void 0:c.x,I=(u=g.center)==null?void 0:u.y,E=.2,x=.2):g.type==="schematic_text"&&(_=(A=g.position)==null?void 0:A.x,I=(d=g.position)==null?void 0:d.y,E=(((f=g.text)==null?void 0:f.length)??0)*.1,x=.2),typeof _=="number"&&typeof I=="number"&&typeof E=="number"&&typeof x=="number"&&(e=Math.min(e,_-E/2),n=Math.max(n,_+E/2),t=Math.min(t,I-x/2),i=Math.max(i,I+x/2))}return{minX:e,maxX:n,minY:t,maxY:i}}function gft(r,e={}){const{minX:t,maxX:n,minY:i,maxY:a}=r,o=e.padding??1;if(!isFinite(t)||!isFinite(n)||!isFinite(i)||!isFinite(a))return[];const s=t-o,l=n+o,c=a+o,u=i-o,A=.01;return[{type:"rect",layers:["top"],center:{x:(s+l)/2,y:c},width:l-s,height:A,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(s+l)/2,y:u},width:l-s,height:A,connectedTo:[]},{type:"rect",layers:["top"],center:{x:s,y:(c+u)/2},width:A,height:c-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:l,y:(c+u)/2},width:A,height:c-u,connectedTo:[]}]}var mft=r=>{var o;const e=r.root.db,t=r._findConnectedPorts().ports??[],n=new Set(t.map(s=>s.schematic_port_id)),i=[];for(const s of e.toArray()){if(s.type==="schematic_component"){const l=!!s.symbol_name,c=s.size.width>s.size.height?"horz":"vert";i.push({type:"rect",layers:["top"],center:s.center,width:s.size.width+(l&&c==="horz"?-.5:0),height:s.size.height+(l&&c==="vert"?-.5:0),connectedTo:[]})}if(s.type==="schematic_port"){if(n.has(s.schematic_port_id))continue;const l=s.facing_direction?vme(s.facing_direction):{x:0,y:0};i.push({type:"rect",layers:["top"],center:{x:s.center.x-l.x*.1,y:s.center.y-l.y*.1},width:.1+Math.abs(l.x)*.3,height:.1+Math.abs(l.y)*.3,connectedTo:[]})}s.type==="schematic_text"&&i.push({type:"rect",layers:["top"],center:s.position,width:(((o=s.text)==null?void 0:o.length)??0)*.1,height:.2,connectedTo:[]}),s.type==="schematic_box"&&i.push({type:"rect",layers:["top"],center:{x:s.x,y:s.y},width:s.width,height:s.height,connectedTo:[]})}const a=pft(e.toArray());return i.push(...gft(a,{padding:1})),i};function yft({ports:r,nets:e}){var t,n,i;if(r.length>=2)return`${(t=r[0])==null?void 0:t.selector} to ${(n=r[1])==null?void 0:n.selector}`;if(r.length===1&&e.length===1)return`${(i=r[0])==null?void 0:i.selector} to net.${e[0]._parsedProps.name}`}var vft=({edges:r,db:e,source_trace_id:t})=>{e.source_trace.get(t);const n=ck({db:e,source_trace_id:t,differentNetOnly:!0}).flatMap(a=>a.edges),i=a=>{const{from:o,to:s}=a;return o.x===s.x?"vertical":"horizontal"};for(const a of r){const o=i(a),s=()=>n.find(c=>i(c)===o&&TP([a.from,a.to],[c.from,c.to],{lineThickness:.05}));let l=s();for(;l;)o==="horizontal"?(a.from.y+=.1,a.to.y+=.1):(a.from.x+=.1,a.to.x+=.1),l=s()}},Ift=(r,{db:e})=>{const t=e.pcb_board.list()[0];if(t.outline){const l=t.outline,c=(u,A)=>{let d=!1;for(let f=0,g=A.length-1;f<A.length;g=f++){const _=A[f].x,I=A[f].y,E=A[g].x,x=A[g].y;I>u.y!=x>u.y&&u.x<(E-_)*(u.y-I)/(x-I)+_&&(d=!d)}return d};return r.some(u=>!c(u,l))}const n=t.width,i=t.height,a=t.center.x,o=t.center.y;return r.some(l=>l.x<a-n/2||l.y<o-i/2||l.x>a+n/2||l.y>o+i/2)},uk=r=>({...r._getGlobalPcbPositionAfterLayout(),layers:r.getAvailablePcbLayers()}),OS=class extends $v{constructor(t){super(t);Ke(this,"source_trace_id",null);Ke(this,"pcb_trace_id",null);Ke(this,"schematic_trace_id",null);Ke(this,"_portsRoutedOnPcb");Ke(this,"subcircuit_connectivity_map_key",null);Ke(this,"_traceConnectionHash",null);this._portsRoutedOnPcb=[]}get config(){return{zodProps:Y0e,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(){const{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)throw new Error("Trace has no parent");const o=this.getTracePortPathSelectors().map(s=>({selector:s,port:this.getSubcircuit().selectOne(s,{type:"port"})??null}));for(const{selector:s,port:l}of o)if(!l){const c=s.replace(/(\> )?[^ ]+$/,""),u=this.getSubcircuit().selectOne(c);u?this.renderError(`Could not find port for selector "${s}" (did you forget to include the pin name?)
854
- searched component ${u.getString()}, which has ports: ${u.children.filter(A=>A.componentName==="Port").map(A=>`${A.getString()}(${A.getNameAndAliases().join(",")})`).join(" & ")}`):this.renderError(`Could not find port for selector "${s}"`)}return o.some(s=>!s.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:o,ports:o.map(({port:s})=>s)}}_findConnectedNets(){const t=this.getTracePathNetSelectors().map(i=>({selector:i,net:this.getSubcircuit().selectOne(i,{type:"net"})})),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(){const t=this.getSubcircuit().selectAll("trace"),n=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return t.filter(a=>{if(a===this)return!1;const o=a._findConnectedNets().nets,s=a._findConnectedPorts().ports??[];return o.some(l=>n.includes(l))||s.some(l=>i.includes(l))})}_isExplicitlyConnectedToPort(t){const{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(){Fye(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){const{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(){var d;const{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}const{allPortsFound:a,portsWithSelectors:o}=this._findConnectedPorts();if(!a)return;this._traceConnectionHash=this._computeTraceConnectionHash();const l=t.source_trace.list().find(f=>f.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&f.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(l){this.source_trace_id=l.source_trace_id;return}const c=this._findConnectedNets().nets,u=yft({ports:o,nets:c}),A=t.source_trace.insert({connected_source_port_ids:o.map(f=>f.port.source_port_id),connected_source_net_ids:c.map(f=>f.source_net_id),subcircuit_id:(d=this.getSubcircuit())==null?void 0:d.subcircuit_id,max_length:hft(o.map(f=>f.port),{db:t})??n.maxLength,display_name:u,min_trace_thickness:n.thickness});this.source_trace_id=A.source_trace_id}_insertErrorIfTraceIsOutsideBoard(t,n){const{db:i}=this.root;Ift(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)})}doInitialPcbTraceRender(){var W,z,ae,te;if((W=this.root)!=null&&W.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n,parent:i}=this,a=this.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(a._parsedProps.routingDisabled)return;const o=(z=a._parsedProps.pcbRouteCache)==null?void 0:z.pcbTraces;if(o){const oe=t.pcb_trace.insert({route:o.flatMap(pe=>pe.route),source_trace_id:this.source_trace_id,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((ae=this.getGroup())==null?void 0:ae.pcb_group_id)??void 0});this.pcb_trace_id=oe.pcb_trace_id;return}if(!a._shouldUseTraceByTraceRouting())return;const{allPortsFound:s,ports:l}=this._findConnectedPorts();if(!s)return;const c=[];for(const oe of l)oe._hasMatchedPcbPrimitive()||c.push(oe);if(c.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.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, ${this} wasn't routed. Missing ports: ${c.map(oe=>oe.getString()).join(", ")}`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:c.map(oe=>oe.pcb_port_id).filter(Boolean)});return}const u=this._findConnectedNets().netsWithSelectors;if(l.length===0&&u.length===2){this.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(l.length===1&&u.length===1){const oe=l[0],Ae=u[0].net.getAllConnectedPorts().filter(Ie=>Ie!==oe);if(Ae.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}const he=cft(oe,Ae);l.push(he)}else if(l.length>1&&u.length>=1){this.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}const A=l.flatMap(oe=>oe.matchedComponents.filter(pe=>pe.componentName==="TraceHint")),d=(this._parsedProps.pcbRouteHints??[]).concat(A.flatMap(oe=>oe.getPcbRouteHints()));if(l.length>2){this.renderError(`Trace has more than two ports (${l.map(oe=>oe.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(this.getSubcircuit().selectAll("trace").filter(oe=>oe.renderPhaseStates.PcbTraceRender.initialized).some(oe=>oe._portsRoutedOnPcb.length===l.length&&oe._portsRoutedOnPcb.every(pe=>l.includes(pe))))return;let _=[];d.length===0?_=[uk(l[0]),uk(l[1])]:_=[uk(l[0]),...d,uk(l[1])];const I=lk(_),E=FS(this.root.db.toArray()),[x,B]=Aft(()=>BP(this.root.db.toArray()));if(B){this.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:this.pcb_trace_id,message:`Error getting obstacles for autorouting: ${B.message}`,source_trace_id:this.source_trace_id,center:{x:0,y:0},pcb_port_ids:l.map(oe=>oe.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[]});return}for(const oe of x)if(oe.connectedTo.length>0){const Ae=E.getNetConnectedToId(oe.connectedTo[0]);Ae&&oe.connectedTo.push(Ae)}let P=[];if(I.length===0)P=_;else{const oe=I[0].layer_path;P=_.map((pe,Ae)=>pe.via?{...pe,via_to_layer:oe[Ae]}:{...pe,layers:[oe[Ae]]})}P[0].pcb_port_id=l[0].pcb_port_id,P[P.length-1].pcb_port_id=l[1].pcb_port_id;const L=[];for(const[oe,pe]of kye(P)){const Ae="via_to_layer"in oe?oe.via_to_layer:null,he=2,Ie="layers"in oe&&oe.layers.length===1?oe.layers[0]:Ae??"top",ge="layers"in pe&&pe.layers.length===1?pe.layers[0]:Ae??"top",Me="pcb_port_id"in oe?oe.pcb_port_id:null,Se="pcb_port_id"in pe?pe.pcb_port_id:null,Re=this.getSubcircuit()._parsedProps.minTraceWidth??.16,we=new xP({OBSTACLE_MARGIN:Re*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(Me&&Se),connMap:E,input:{obstacles:x,minTraceWidth:Re,connections:[{name:this.source_trace_id,pointsToConnect:[{...oe,layer:Ie,pcb_port_id:Me},{...pe,layer:ge,pcb_port_id:Se}]}],layerCount:2,bounds:{minX:Math.min(oe.x,pe.x)-he,maxX:Math.max(oe.x,pe.x)+he,minY:Math.min(oe.y,pe.y)-he,maxY:Math.max(oe.y,pe.y)+he}}});let Ge=null;try{Ge=we.solveAndMapToTraces()}catch(ht){this.renderError({type:"pcb_trace_error",pcb_trace_error_id:this.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${ht.message}`,source_trace_id:this.pcb_trace_id,center:{x:(oe.x+pe.x)/2,y:(oe.y+pe.y)/2},pcb_port_ids:l.map(kt=>kt.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:l.map(kt=>kt.pcb_component_id)})}if(!Ge)return;if(Ge.length===0){this.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:this.pcb_trace_id,message:`Could not find a route for ${this}`,source_trace_id:this.source_trace_id,center:{x:(oe.x+pe.x)/2,y:(oe.y+pe.y)/2},pcb_port_ids:l.map(ht=>ht.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:l.map(ht=>ht.pcb_component_id)});return}const[$e]=Ge;Ae&&($e.route=$e.route.map(ht=>(ht.route_type==="wire"&&!ht.layer&&(ht.layer=Ae),ht))),Me&&$e.route[0].route_type==="wire"&&($e.route[0].start_pcb_port_id=Me);const lt=$e.route[$e.route.length-1];Se&&lt.route_type==="wire"&&(lt.end_pcb_port_id=Se),L.push($e.route)}const U=sft(L),H=dft(U),G=t.pcb_trace.insert({route:U,source_trace_id:this.source_trace_id,subcircuit_id:(te=this.getSubcircuit())==null?void 0:te.subcircuit_id,trace_length:H});this._portsRoutedOnPcb=l,this.pcb_trace_id=G.pcb_trace_id;for(const oe of U)oe.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:G.pcb_trace_id,x:oe.x,y:oe.y,hole_diameter:.3,outer_diameter:.6,layers:[oe.from_layer,oe.to_layer],from_layer:oe.from_layer,to_layer:oe.to_layer});this._insertErrorIfTraceIsOutsideBoard(U,l)}_doInitialSchematicTraceRenderWithDisplayLabel(){var L,U,H,G;if((L=this.root)!=null&&L.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)throw new Error("Trace has no parent");const{allPortsFound:a,portsWithSelectors:o}=this._findConnectedPorts();if(!a)return;const s=o.map(({port:W})=>({port:W,position:W._getGlobalSchematicPositionAfterLayout(),schematic_port_id:W.schematic_port_id,facingDirection:W.facingDirection}));if(s.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let l,c;const u=s[0].position,A=s[0].port;if("path"in this.props){if(this.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[l,c]=this.props.path}else{if(!("from"in this.props&&"to"in this.props))throw new Error("Missing 'from' or 'to' properties in props.");l=this.props.from,c=this.props.to}if(!A.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${l}).`);const d=s[1].position,f=s[1].port;if(!f.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);const g=t.schematic_net_label.list().find(W=>W.source_net_id===A.source_port_id),_=t.schematic_net_label.list().find(W=>W.source_net_id===f.source_port_id),[I,E]=o.map(({port:W})=>W),B=((U=I.parent)==null?void 0:U.config.shouldRenderAsSchematicBox)?`${(H=I==null?void 0:I.parent)==null?void 0:H.props.name}_${I==null?void 0:I.props.name}`:`${(G=E==null?void 0:E.parent)==null?void 0:G.props.name}_${E==null?void 0:E.props.name}`,P=this.props.schDisplayLabel??B;g&&g.text!==P&&(g.text=`${P} / ${g.text}`),_&&(_==null?void 0:_.text)!==P&&(_.text=`${P} / ${_.text}`),_||t.schematic_net_label.insert({text:this.props.schDisplayLabel??B,source_net_id:f.source_port_id,anchor_position:d,center:d,anchor_side:AK(f.facingDirection)??"bottom"}),g||t.schematic_net_label.insert({text:this.props.schDisplayLabel??B,source_net_id:A.source_port_id,anchor_position:u,center:u,anchor_side:AK(A.facingDirection)??"bottom"})}_isSymbolToChipConnection(){const{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;const[i,a]=n;if(!(i!=null&&i.parent)||!(a!=null&&a.parent))return!1;const o=i.parent.config.shouldRenderAsSchematicBox,s=a.parent.config.shouldRenderAsSchematicBox;return o&&!s||!o&&s}_isSymbolToSymbolConnection(){const{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;const[i,a]=n;if(!(i!=null&&i.parent)||!(a!=null&&a.parent))return!1;const o=!i.parent.config.shouldRenderAsSchematicBox,s=!a.parent.config.shouldRenderAsSchematicBox;return o&&s}_isChipToChipConnection(){const{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;const[i,a]=n;if(!(i!=null&&i.parent)||!(a!=null&&a.parent))return!1;const o=i.parent.config.shouldRenderAsSchematicBox,s=a.parent.config.shouldRenderAsSchematicBox;return o&&s}doInitialSchematicTraceRender(){var Ie,ge,Me;if((Ie=this.root)!=null&&Ie.schematicDisabled||((ge=this.getGroup())==null?void 0:ge._getSchematicLayoutMode())==="match-adapt")return;const{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)throw new Error("Trace has no parent");const{allPortsFound:a,portsWithSelectors:o}=this._findConnectedPorts(),{netsWithSelectors:s}=this._findConnectedNets();if(!a)return;const c=o.map(Se=>Se.port.schematic_port_id).sort().join(","),u=(Me=this.root)==null?void 0:Me._getBoard();if(u!=null&&u._connectedSchematicPortPairs&&u._connectedSchematicPortPairs.has(c))return;if(this.props.schDisplayLabel&&("from"in this.props&&"to"in this.props||"path"in this.props)){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const A={name:this.source_trace_id,pointsToConnect:[]},d=mft(this),f=o.map(({port:Se})=>({port:Se,position:Se._getGlobalSchematicPositionAfterLayout(),schematic_port_id:Se.schematic_port_id??void 0,facingDirection:Se.facingDirection}));if(f.length===1&&s.length===1){const Se=s[0].net,{port:Re,position:we}=f[0];t.schematic_net_label.insert({text:Se._parsedProps.name,source_net_id:Se.source_net_id,anchor_position:we,center:we,anchor_side:AK(Re.facingDirection)??"bottom"});return}if(f.length<2)return;A.pointsToConnect=f.map(({position:Se})=>({...Se,layer:"top"}));const _=oft(d),I=2,E={minTraceWidth:.1,obstacles:d,connections:[A],bounds:{minX:_.minX-I,maxX:_.maxX+I,minY:_.minY-I,maxY:_.maxY+I},layerCount:1};let x=xP,B=!1;this.getSubcircuit().props._schDirectLineRoutingEnabled&&(x=Vye,B=!0);let L=new x({input:E,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(L.length===0){if(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection()){this._doInitialSchematicTraceRenderWithDisplayLabel();return}L=new Vye({input:E}).solveAndMapToTraces(),B=!0}const[{route:U}]=L;let H=[];for(let Se=0;Se<U.length-1;Se++)H.push({from:U[Se],to:U[Se+1]});const G=this.source_trace_id;let W=[];if(!B){vft({edges:H,db:t,source_trace_id:G});const Se=ck({db:t,source_trace_id:G,differentNetOnly:!0}).flatMap(Re=>Re.edges);H=Jye({edges:H,otherEdges:Se}),W=Wye({edges:H,db:t,source_trace_id:this.source_trace_id})}const z=H[H.length-1],ae=f[f.length-1],te=jye(z);H.push(...dK({lastEdge:z,lastEdgePort:ae,lastDominantDirection:te}));const oe=H[0],pe=f[0],Ae=jye(oe);if(H.unshift(...dK({firstEdge:oe,firstEdgePort:pe,firstDominantDirection:Ae})),!this.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(this.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&uft(W,H)>=5&&(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection())){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const he=t.schematic_trace.insert({source_trace_id:this.source_trace_id,edges:H,junctions:W});this.schematic_trace_id=he.schematic_trace_id,u!=null&&u._connectedSchematicPortPairs&&u._connectedSchematicPortPairs.add(c)}},Cft=nv("tscircuit:core"),Eft=tn({x:Fx,y:Fx,z:Fx}),T1=class extends $v{constructor(t){super(t);Ke(this,"reactSubtrees",[]);Ke(this,"_impliedFootprint");Ke(this,"isPrimitiveContainer",!0);Ke(this,"_asyncSupplierPartNumbers");Ke(this,"pcb_missing_footprint_error_id");Ke(this,"_hasStartedFootprintUrlLoad",!1);this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames}initPorts(t={}){var s,l,c,u,A,d,f,g,_,I;if((s=this.root)!=null&&s.schematicDisabled)return;const{config:n}=this,i=[],a=this._getSchematicPortArrangement();if(a&&!this._parsedProps.pinLabels){for(const B in a){const P=a[B].pins;if(Array.isArray(P))for(const L of P){const U=fD(L,this._parsedProps.pinLabels);i.push(new GS({pinNumber:U,aliases:((l=t.additionalAliases)==null?void 0:l[`pin${U}`])??[]},{originDescription:`schPortArrangement:${B}`}))}}const E=["left","right","top","bottom"];let x=1;for(const B of E){const P=a[`${B}Size`];for(let L=0;L<P;L++)i.push(new GS({pinNumber:x++,aliases:((c=t.additionalAliases)==null?void 0:c[`pin${x}`])??[]},{originDescription:`schPortArrangement:${B}`}))}}const o=this._parsedProps.pinLabels;if(o)for(let[E,x]of Object.entries(o)){E=E.replace("pin","");let B=i.find(U=>U._parsedProps.pinNumber===Number(E));const P=Array.isArray(x)?x[0]:x,L=Array.isArray(x)?x.slice(1):[];B?(B.externallyAddedAliases.push(P,...L),B.props.name=P):(B=new GS({pinNumber:parseInt(E),name:P,aliases:[...L,...((u=t.additionalAliases)==null?void 0:u[`pin${parseInt(E)}`])??[]]},{originDescription:`pinLabels:pin${E}`}),i.push(B))}if(n.schematicSymbolName){const E=yI[this._getSchematicSymbolNameOrThrow()];if(!E)return;for(const x of E.ports){const B=Hye(x.labels);if(!B)continue;const P=i.find(L=>L._parsedProps.pinNumber===Number(B));if(P)P.schematicSymbolPortDef=x;else{const L=hD(x.labels.concat(((A=t.additionalAliases)==null?void 0:A[`pin${B}`])??[]));L&&(L.originDescription=`schematicSymbol:labels[0]:${x.labels[0]}`,L.schematicSymbolPortDef=x,i.push(L))}}this.addAll(i)}if(!this._getSchematicPortArrangement()){const E=this.getPortsFromFootprint(t);for(const x of E)i.some(B=>B.isMatchingAnyOf(x.getNameAndAliases()))||i.push(x)}for(let E=1;E<=(t.pinCount??this._getPinCount());E++){if(!a||i.find(B=>B._parsedProps.pinNumber===E))continue;let x=[...((d=a.leftSide)==null?void 0:d.pins)??[],...((f=a.rightSide)==null?void 0:f.pins)??[],...((g=a.topSide)==null?void 0:g.pins)??[],...((_=a.bottomSide)==null?void 0:_.pins)??[]].map(B=>fD(B,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(B=>B in a)&&(x=Array.from({length:this._getPinCount()},(B,P)=>P+1)),x.includes(E)&&i.push(new GS({pinNumber:E,aliases:((I=t.additionalAliases)==null?void 0:I[`pin${E}`])??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${E}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_isFootprintUrl(t){return t.startsWith("http://")||t.startsWith("https://")}_addChildrenFromStringFootprint(){var o;const{name:t,pcbRotation:n,pinLabels:i}=this.props;let{footprint:a}=this.props;if(a??(a=(o=this._getImpliedFootprintString)==null?void 0:o.call(this)),!!a&&typeof a=="string"){if(this._isFootprintUrl(a))return;const s=kT.string(a).soup(),l=zye({componentName:t,componentRotation:n,footprint:a,pinLabels:i},s);this.addAll(l)}}get portMap(){return new Proxy({},{get:(t,n)=>{const i=this.children.find(a=>a.componentName==="Port"&&a.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(const n of this.reactSubtrees)if(n.element===t)return n.component;return null}doInitialSourceRender(){const t=this.config.sourceFtype;if(!t)return;const{db:n}=this.root,{_parsedProps:i}=this,a=n.source_component.insert({ftype:t,name:i.name,manufacturer_part_number:i.manufacturerPartNumber??i.mfn,supplier_part_numbers:i.supplierPartNumbers});this.source_component_id=a.source_component_id}doInitialSchematicComponentRender(){var a,o,s;if((a=this.root)!=null&&a.schematicDisabled)return;const{db:t}=this.root,{schematicSymbolName:n}=this.config;n?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();const i=(o=this.getSubcircuit())==null?void 0:o._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&i){if(!this.schematic_component_id)return;const l=bT.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:(s=this.getSubcircuit())==null?void 0:s.subcircuit_id});t.schematic_manual_edit_conflict_warning.insert(l)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];const t=[];for(const n of this.internallyConnectedPinNames){const i=[];for(const a of n)i.push(this.portMap[a]);t.push(i)}return t}_doInitialSchematicComponentRenderWithSymbol(){var s;if((s=this.root)!=null&&s.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicSymbolNameOrThrow(),a=yI[i],o=this._getGlobalSchematicPositionBeforeLayout();if(a){const l=t.schematic_component.insert({center:o,size:a.size,source_component_id:this.source_component_id,symbol_name:i,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=l.schematic_component_id}}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){var d;if((d=this.root)!=null&&d.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicBoxDimensions(),a={};if(Array.isArray(n.pinLabels))n.pinLabels.forEach((f,g)=>{a[String(g+1)]=f});else for(const[f,g]of Object.entries(n.pinLabels??{}))a[f]=Array.isArray(g)?g[0]:g;const o=this._getGlobalSchematicPositionBeforeLayout(),s=this._getSchematicPortArrangement(),l=t.schematic_component.insert({center:o,rotation:n.schRotation??0,size:i.getSize(),port_arrangement:Vdt(s),pin_spacing:n.schPinSpacing??.2,pin_styles:Ydt(n.schPinStyle,n.pinLabels),port_labels:a,source_component_id:this.source_component_id}),c=(s==null?void 0:s.topSide)!==void 0||(s==null?void 0:s.bottomSide)!==void 0,u=i==null?void 0:i.getSize().width,A=i==null?void 0:i.getSize().height;t.schematic_text.insert({text:n.manufacturerPartNumber??"",schematic_component_id:l.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(u??0)/2+.1:o.x-(u??0)/2,y:c?o.y+(A??0)/2+.35:o.y-(A??0)/2-.13},color:"#006464",font_size:.18}),t.schematic_text.insert({text:n.name??"",schematic_component_id:l.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(u??0)/2+.1:o.x-(u??0)/2,y:c?o.y+(A??0)/2+.55:o.y+(A??0)/2+.13},color:"#006464",font_size:.18}),this.schematic_component_id=l.schematic_component_id}doInitialPcbComponentRender(){var s;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),a=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.isGroup){const l=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=l.pcb_missing_footprint_error_id}this.pcb_component_id=a.pcb_component_id;const o=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&o){const l=wT.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(l)}}doInitialPcbComponentSizeCalculation(){var o;if((o=this.root)!=null&&o.pcbDisabled||!this.pcb_component_id)return;const{db:t}=this.root,{_parsedProps:n}=this,i=uK(this.children);if(i.width===0||i.height===0)return;const a={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};t.pcb_component.update(this.pcb_component_id,{center:a,width:i.width,height:i.height})}_renderReactSubtree(t){return{element:t,component:Pye(t)}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){}doInitialPcbFootprintStringRender(){var o;let{footprint:t}=this.props;if(t??(t=(o=this._getImpliedFootprintString)==null?void 0:o.call(this)),!t)return;const{name:n,pcbRotation:i,pinLabels:a}=this.props;if(typeof t=="string"&&this._isFootprintUrl(t)){if(this._hasStartedFootprintUrlLoad)return;this._hasStartedFootprintUrlLoad=!0;const s=t;this._queueAsyncEffect("load-footprint-url",async()=>{const c=await(await fetch(s)).json(),u=zye({componentName:n,componentRotation:i,footprint:s,pinLabels:a},c);this.addAll(u),this._markDirty("InitializePortsFromChildren")});return}if(nt.isValidElement(t)){if(this.reactSubtrees.some(l=>l.element===t))return;const s=this._renderReactSubtree(t);this.reactSubtrees.push(s),this.add(s.component);return}!nt.isValidElement(t)&&t.componentName==="Footprint"&&this.add(t)}_hasExistingPortExactly(t){return this.children.filter(i=>i.componentName==="Port").some(i=>{const a=t.getNameAndAliases(),o=i.getNameAndAliases();return a.length===o.length&&a.every(s=>o.includes(s))})}add(t){let n;if(nt.isValidElement(t)){const i=this._renderReactSubtree(t);this.reactSubtrees.push(i),n=i.component}else n=t;if(n.componentName==="Port"){if(this._hasExistingPortExactly(n))return;const a=this.children.filter(o=>o.componentName==="Port").find(o=>o.isMatchingAnyOf(n.getNameAndAliases()));a&&Cft(`Similar ports added. Port 1: ${a}, Port 2: ${n}`)}super.add(n)}getPortsFromFootprint(t){let{footprint:n}=this.props;if((!n||nt.isValidElement(n))&&(n=this.children.find(a=>a.componentName==="Footprint")),typeof n=="string"){if(this._isFootprintUrl(n))return[];const a=kT.string(n).soup(),o=[];for(const s of a)if("port_hints"in s&&s.port_hints){const l=hD(s.port_hints,t);if(!l)continue;l.originDescription=`footprint:string:${n}:port_hints[0]:${s.port_hints[0]}`,o.push(l)}return o}if(!nt.isValidElement(n)&&n&&n.componentName==="Footprint"){const a=n;let o=1;const s=[];for(const l of a.children){if(!l.props.portHints)continue;let c=l.props.portHints;c.some(d=>d.startsWith("pin"))||(c=[...c,`pin${o}`]),o++;const A=hD(c);A&&(A.originDescription=`footprint:${n}`,s.push(A))}return s}const i=[];if(!n){for(const a of this.children)if(a.props.portHints&&a.isPcbPrimitive){const o=hD(a.props.portHints);o&&i.push(o)}}return i}getPortsFromSchematicSymbol(){var a;if((a=this.root)!=null&&a.schematicDisabled)return[];const{config:t}=this;if(!t.schematicSymbolName)return[];const n=yI[t.schematicSymbolName];if(!n)return[];const i=[];for(const o of n.ports){const s=hD(o.labels);s&&(s.schematicSymbolPortDef=o,i.push(s))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){const{_parsedProps:t}=this,n=[];if(t.connections)for(const[i,a]of Object.entries(t.connections)){const o=Array.isArray(a)?a:[a];for(const s of o)n.push(s)}return n}_createNetsFromProps(t){Fye(this,t)}_getPcbCircuitJsonBounds(){const{db:t}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();const 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(){const t=this._getSchematicPortArrangement();if(!t)return 0;if(!Yye(t))return(t.leftSize??t.leftPinCount??0)+(t.rightSize??t.rightPinCount??0)+(t.topSize??t.topPinCount??0)+(t.bottomSize??t.bottomPinCount??0);const{leftSide:i,rightSide:a,topSide:o,bottomSide:s}=t;return Math.max(...(i==null?void 0:i.pins)??[],...(a==null?void 0:a.pins)??[],...(o==null?void 0:o.pins)??[],...(s==null?void 0:s.pins)??[])}_getPinCount(){return this._getSchematicPortArrangement()?this._getPinCountFromSchematicPortArrangement():this.getPortsFromFootprint().length}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;const{_parsedProps:t}=this,n=this._getPinCount(),i=t.schPinSpacing??.2;return nft({schWidth:t.schWidth,schHeight:t.schHeight,schPinSpacing:i,numericSchPinStyle:aft(t.schPinStyle,t.pinLabels),pinCount:n,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:t.pinLabels})}doInitialCadModelRender(){var u;const{db:t}=this.root,{boardThickness:n=0}=((u=this.root)==null?void 0:u._getBoard())??{},i=this._parsedProps.cadModel;if(!this.pcb_component_id||!i&&!this.props.footprint||i===null)return;const a=this._getPcbCircuitJsonBounds(),o=t.pcb_component.get(this.pcb_component_id);if(typeof i=="string")throw new Error("String cadModel not yet implemented");const s=Eft.parse({x:0,y:0,z:typeof(i==null?void 0:i.rotationOffset)=="number"?i.rotationOffset:0,...typeof(i==null?void 0:i.rotationOffset)=="object"?i.rotationOffset??{}:{}}),l=qw.parse({x:0,y:0,z:0,...typeof(i==null?void 0:i.positionOffset)=="object"?i.positionOffset:{}}),c=this.props.layer==="bottom"?"bottom":"top";t.cad_component.insert({position:{x:a.center.x+l.x,y:a.center.y+l.y,z:(c==="bottom"?-n/2:n/2)+l.z},rotation:{x:s.x,y:(c==="top"?0:180)+s.y,z:c==="bottom"?-(((o==null?void 0:o.rotation)??0)+s.z)+180:((o==null?void 0:o.rotation)??0)+s.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(i??{})?this._addCachebustToModelUrl(i.stlUrl):void 0,model_obj_url:"objUrl"in(i??{})?this._addCachebustToModelUrl(i.objUrl):void 0,model_jscad:"jscad"in(i??{})?i.jscad:void 0,footprinter_string:typeof this.props.footprint=="string"&&!i?this.props.footprint:void 0})}_addCachebustToModelUrl(t){var i;if(!t||!t.includes("modelcdn.tscircuit.com"))return t;const n=((i=this.root)==null?void 0:i.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){var c,u;if(this.props.doNotPlace)return{};const a=(u=(c=this.root)==null?void 0:c.platform)==null?void 0:u.localCacheEngine,o=this._getPartsEngineCacheKey(n,i);if(a){const A=await a.getItem(o);if(A)try{return JSON.parse(A)}catch{}}const s=await Promise.resolve(t.findPart({sourceComponent:n,footprinterString:i})),l=s==="Not found"?{}:s;if(a)try{await a.setItem(o,JSON.stringify(l))}catch{}return l}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;const t=this.getInheritedProperty("partsEngine");if(!t)return;const{db:n}=this.root,i=n.source_component.get(this.source_component_id);if(!i||i.supplier_part_numbers)return;let a;this.props.footprint&&typeof this.props.footprint=="string"&&(a=this.props.footprint);const o=this._getSupplierPartNumbers(t,i,a);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;const{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}}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){const{_parsedProps:t}=this;if(t.connections)for(const[n,i]of Object.entries(t.connections)){const a=Array.isArray(i)?i:[i];for(const o of a)this.add(new OS({from:`${this.getSubcircuitSelector()} > port.${n}`,to:o}))}}},_ft=class{constructor(e,t={}){Ke(this,"input");Ke(this,"isRouting",!1);Ke(this,"solver");Ke(this,"eventHandlers",{complete:[],error:[],progress:[]});Ke(this,"cycleCount",0);Ke(this,"stepDelay");Ke(this,"timeoutId");this.input=e;const{capacityDepth:n,targetMinCapacity:i,stepDelay:a=0}=t;this.solver=new dye(e,{capacityDepth:n,targetMinCapacity:i,cacheProvider:null}),this.stepDelay=a}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){var e;if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new Error(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}const t=Date.now(),n=this.solver.iterations;for(;Date.now()-t<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();const i=(this.solver.iterations-n)/(Date.now()-t)*1e3;this.cycleCount++;const a=((e=this.solver)==null?void 0:e.preview())||void 0,o=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:i,progress:o,phase:this.solver.getCurrentPhase(),debugGraphics:a}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(t){this.emitEvent({type:"error",error:t instanceof Error?t:new Error(String(t))}),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(const t of this.eventHandlers.complete)t(e);else if(e.type==="error")for(const t of this.eventHandlers.error)t(e);else if(e.type==="progress")for(const t of this.eventHandlers.progress)t(e)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new Error(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},qye=class extends $v{constructor(){super(...arguments);Ke(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:pme}}doInitialPortMatching(){const{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}const a=i.selectOne(n.for,{type:"port"});a||this.renderError(`${this} could not find port for selector "${n.for}"`),this.matchedPort=a,a.registerMatch(this)}getPcbRouteHints(){const{_parsedProps:t}=this,n=t.offset?[t.offset]:t.offsets;if(!n)return[];const i=this._computePcbGlobalTransformBeforeLayout();return n.map(a=>({...ti(i,a),via:a.via,to_layer:a.to_layer,trace_width:a.trace_width}))}doInitialPcbTraceHintRender(){var i,a,o;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this;t.pcb_trace_hint.insert({pcb_component_id:(a=this.matchedPort)==null?void 0:a.pcb_component_id,pcb_port_id:(o=this.matchedPort)==null?void 0:o.pcb_port_id,route:this.getPcbRouteHints()})}},xft=({circuitJson:r,editEvents:e,manualEditsFile:t})=>{var i;const n={...t,pcb_placements:[...t.pcb_placements??[]]};for(const a of e)if(a.edit_event_type==="edit_pcb_component_location"){const{pcb_component_id:o,new_center:s}=a,l=o1(r).pcb_component.get(o);if(!l)continue;const c=o1(r).source_component.get(l.source_component_id);if(!c)continue;const u=(i=n.pcb_placements)==null?void 0:i.findIndex(d=>d.selector===c.name),A={selector:c.name,center:s,relative_to:"group_center"};u>=0?n.pcb_placements[u]=A:n.pcb_placements.push(A)}return n},Bft=({circuitJson:r,editEvents:e,manualEditsFile:t})=>{var i;const n={...t,schematic_placements:[...t.schematic_placements??[]]};for(const a of e)if(a.edit_event_type==="edit_schematic_component_location"){const{schematic_component_id:o,new_center:s}=a,l=o1(r).schematic_component.get(o);if(!l)continue;const c=o1(r).source_component.get(l.source_component_id);if(!c)continue;const u=(i=n.schematic_placements)==null?void 0:i.findIndex(d=>d.selector===c.name),A={selector:c.name,center:s,relative_to:"group_center"};u>=0?n.schematic_placements[u]=A:n.schematic_placements.push(A)}return n},Zye=({circuitJson:r,editEvents:e,manualEditsFile:t})=>{const n=e.filter(o=>o.edit_event_type==="edit_schematic_component_location"),i=e.filter(o=>o.edit_event_type==="edit_pcb_component_location");let a=t;return n.length>0&&(a=Bft({circuitJson:r,editEvents:n,manualEditsFile:a})),i.length>0&&(a=xft({circuitJson:r,editEvents:i,manualEditsFile:a})),a},bft=(r,e)=>{const t=r.source_group.list(),n=[],i=a=>{const o=t.filter(s=>s.parent_subcircuit_id===a);for(const s of o)s.subcircuit_id&&(n.push(s.subcircuit_id),i(s.subcircuit_id))};return i(e),n},Xye=({db:r,circuitJson:e,subcircuit_id:t,minTraceWidth:n=.1})=>{if(!r&&e&&(r=o1(e)),!r)throw new Error("db or circuitJson is required");const i=r.pcb_trace_hint.list(),a=t?new Set([t]):null;if(t){const _=bft(r,t);for(const I of _)a.add(I)}const o=(e??r.toArray()).filter(_=>!t||"subcircuit_id"in _&&a.has(_.subcircuit_id)),s=r.pcb_board.list()[0];r=o1(o);const l=FS(o),c=BP([...r.pcb_component.list(),...r.pcb_smtpad.list(),...r.pcb_plated_hole.list(),...r.pcb_hole.list(),...r.pcb_via.list()].filter(_=>!t||(a==null?void 0:a.has(_.subcircuit_id))),l);for(const _ of c){const I=_.connectedTo.flatMap(E=>l.getIdsConnectedToNet(E));_.connectedTo.push(...I)}const u=c.flatMap(_=>[{x:_.center.x-_.width/2,y:_.center.y-_.height/2},{x:_.center.x+_.width/2,y:_.center.y+_.height/2}]);let A;s?A={minX:s.center.x-s.width/2,maxX:s.center.x+s.width/2,minY:s.center.y-s.height/2,maxY:s.center.y+s.height/2}:A={minX:Math.min(...u.map(_=>_.x))-1,maxX:Math.max(...u.map(_=>_.x))+1,minY:Math.min(...u.map(_=>_.y))-1,maxY:Math.max(...u.map(_=>_.y))+1};const d=r.source_trace.list().map(_=>{var H,G,W;const I=_.connected_source_port_ids.map(z=>{const ae=r.source_port.get(z),te=r.pcb_port.getWhere({source_port_id:z});return{...ae,...te}});if(I.length<2)return null;const[E,x]=I,B=((H=E.layers)==null?void 0:H[0])??"top",P=((G=x.layers)==null?void 0:G[0])??"top",L=i.filter(z=>z.pcb_port_id===E.pcb_port_id||z.pcb_port_id===x.pcb_port_id),U=[];for(const z of L){const ae=r.pcb_port.get(z.pcb_port_id),te=((W=ae==null?void 0:ae.layers)==null?void 0:W[0])??"top";for(const oe of z.route)U.push({x:oe.x,y:oe.y,layer:te})}return{name:_.source_trace_id??l.getNetConnectedToId(_.source_trace_id)??"",source_trace_id:_.source_trace_id,pointsToConnect:[{x:E.x,y:E.y,layer:B},...U,{x:x.x,y:x.y,layer:P}]}}).filter(_=>_!==null),f=r.source_net.list().filter(_=>!t||(a==null?void 0:a.has(_.subcircuit_id))),g=[];for(const _ of f){const I=r.source_trace.list().filter(E=>{var x;return(x=E.connected_source_net_ids)==null?void 0:x.includes(_.source_net_id)});g.push({name:_.source_net_id??l.getNetConnectedToId(_.source_net_id),pointsToConnect:I.flatMap(E=>r.pcb_port.list().filter(B=>E.connected_source_port_ids.includes(B.source_port_id)).map(B=>{var P;return{x:B.x,y:B.y,layer:((P=B.layers)==null?void 0:P[0])??"top",pcb_port_id:B.pcb_port_id}}))})}return{simpleRouteJson:{bounds:A,obstacles:c,connections:[...d,...g],layerCount:2,minTraceWidth:n},connMap:l}};function fK(r,e){if("boxId"in r){const{boxId:t,pinNumber:n}=r,i=e.source_component.getWhere({name:t});if(!i)throw new Error(`Source component "${t}" not found, but returned from match-adapt ${JSON.stringify(r)}`);const a=e.source_port.getWhere({source_component_id:i.source_component_id,pin_number:n});return{subcircuit_connectivity_map_key:(a==null?void 0:a.subcircuit_connectivity_map_key)??null,source_port_id:a.source_port_id}}if("netId"in r){const{netId:t}=r;return e.source_net.getWhere({name:t}),null}if("junctionId"in r){const{junctionId:t}=r;return null}return null}function Sft({path:r,db:e,layoutConnMap:t}){let n=fK(r.to,e)??fK(r.from,e);if(!n){const a=t.getNetConnectedToId(Hb(r.to));n=t.getIdsConnectedToNet(a).map(s=>qV(s)).map(s=>fK(s,e)).find(Boolean)}if(!(n!=null&&n.subcircuit_connectivity_map_key))throw new Error(`No connectivity net id found for match-adapt path ${JSON.stringify(r)}`);const i=e.source_trace.list({subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key});for(const a of i)if(a.connected_source_port_ids.includes(n.source_port_id))return a.source_trace_id;if(i.length>0)return i[0].source_trace_id;throw new Error(`No source trace found for match-adapt path "${JSON.stringify(r)}"`)}function wft(r){const{db:e}=r.root;let t=structuredClone(e.toArray());t=Tdt(t);const n=Ndt(t),i=new Ddt({inputNetlist:n});let a=null;try{i.solve(),a=i.getLayout()}catch(A){e.schematic_layout_error.insert({message:`Match-adapt layout failed: ${A.toString()}`,source_group_id:r.source_group_id,schematic_group_id:r.schematic_group_id});return}const{boxes:o,junctions:s,netLabels:l,paths:c}=a,u=new aM({});for(const A of c)u.addConnections([[Hb(A.from),Hb(A.to)]]);for(const A of s)for(const d of c)for(const f of d.points)Math.abs(f.x-A.x)<.001&&Math.abs(f.y-A.y)<.001&&u.addConnections([[Hb(d.from),Hb(A)],[Hb(d.to),Hb(A)]]);for(const A of o){const d=e.source_component.list().find(E=>E.name===A.boxId);if(!d)continue;const f=e.schematic_component.getWhere({source_component_id:d.source_component_id});if(!f)continue;const g={x:A.centerX-f.center.x+.1,y:A.centerY-f.center.y-.1};e.schematic_component.update(f.schematic_component_id,{center:{x:f.center.x+g.x,y:f.center.y+g.y}});const _=e.schematic_port.list({schematic_component_id:f.schematic_component_id});for(const E of _)e.schematic_port.update(E.schematic_port_id,{center:{x:E.center.x+g.x,y:E.center.y+g.y}});const I=e.schematic_text.list({schematic_component_id:f.schematic_component_id});for(const E of I)e.schematic_text.update(E.schematic_text_id,{position:{x:E.position.x+g.x,y:E.position.y+g.y}})}for(const A of l){const d=e.source_net.list().find(f=>f.name===A.netId);e.schematic_net_label.insert({text:A.netId,source_net_id:d==null?void 0:d.source_net_id,anchor_position:{x:A.x,y:A.y},center:{x:A.x,y:A.y},anchor_side:A.anchorPosition})}for(const A of c){if(!A.points||A.points.length<2)continue;const d=Sft({path:A,db:PB(t),layoutConnMap:u});let f=[];for(let I=0;I<A.points.length-1;I++)f.push({from:{x:A.points[I].x,y:A.points[I].y},to:{x:A.points[I+1].x,y:A.points[I+1].y}});const g=ck({db:e,source_trace_id:d,differentNetOnly:!0}).flatMap(I=>I.edges);g.length>0&&(f=Jye({edges:f,otherEdges:g}));const _=Wye({edges:f,db:e,source_trace_id:d});e.schematic_trace.insert({source_trace_id:d,edges:f,junctions:_})}}function Qft(r){if(!r.isSubcircuit)return;const{db:e}=r.root,t=r.selectAll("trace"),n=new aM({});n.addConnections(t.map(s=>{const l=e.source_trace.get(s.source_trace_id);return l?[l.source_trace_id,...l.connected_source_port_ids,...l.connected_source_net_ids]:null}).filter(s=>s!==null));const{name:i}=r._parsedProps;for(const s of t){if(!s.source_trace_id)continue;const l=n.getNetConnectedToId(s.source_trace_id);l&&(s.subcircuit_connectivity_map_key=`${i??`unnamedsubcircuit${r._renderId}`}_${l}`,e.source_trace.update(s.source_trace_id,{subcircuit_connectivity_map_key:s.subcircuit_connectivity_map_key}))}const a=new Set;for(const s of t){if(!s.source_trace_id)continue;const l=e.source_trace.get(s.source_trace_id);if(l)for(const c of l.connected_source_port_ids)a.add(c)}for(const s of a){const l=n.getNetConnectedToId(s);if(!l)continue;const c=`${i??`unnamedsubcircuit${r._renderId}`}_${l}`;e.source_port.update(s,{subcircuit_connectivity_map_key:c})}const o=new Set;for(const s of t){if(!s.source_trace_id)continue;const l=e.source_trace.get(s.source_trace_id);if(l)for(const c of l.connected_source_net_ids)o.add(c)}for(const s of o){const l=n.getNetConnectedToId(s);if(!l)continue;const c=`${i??`unnamedsubcircuit${r._renderId}`}_${l}`;e.source_net.update(s,{subcircuit_connectivity_map_key:c})}}function Mft(r){var x;const{db:e}=r.root,t=r._parsedProps,n=r.children.filter(B=>B.schematic_component_id);if(n.length===0)return;let i=0,a=0;for(const B of n){const P=e.schematic_component.get(B.schematic_component_id);P!=null&&P.size&&(i=Math.max(i,P.size.width),a=Math.max(a,P.size.height))}i===0&&n.length>0&&(i=1),a===0&&n.length>0&&(a=1);let o=t.gridCols,s,l=t.gridGap;(x=t.schLayout)!=null&&x.grid&&(o=t.schLayout.grid.cols??o,s=t.schLayout.grid.rows,l=t.schLayout.grid.gap??l);let c,u;o!==void 0&&s!==void 0?(c=o,u=s):o!==void 0?(c=o,u=Math.ceil(n.length/c)):s!==void 0?(u=s,c=Math.ceil(n.length/u)):(c=Math.ceil(Math.sqrt(n.length)),u=Math.ceil(n.length/c)),c===0&&n.length>0&&(c=1),u===0&&n.length>0&&(u=n.length);let A,d;typeof l=="number"?(A=l,d=l):typeof l=="object"&&l!==null?(A=l.x,d=l.y):(A=1,d=1);const f=c*i+Math.max(0,c-1)*A,g=u*a+Math.max(0,u-1)*d,_=r._getGlobalSchematicPositionBeforeLayout(),I=_.x-f/2+i/2,E=_.y+g/2-a/2;for(let B=0;B<n.length;B++){const P=n[B];if(!P.schematic_component_id)continue;const L=Math.floor(B/c),U=B%c;if(L>=u||U>=c){console.warn(`Schematic grid layout: Child ${P.getString()} at index ${B} (row ${L}, col ${U}) exceeds specified grid dimensions (${u}x${c}). Skipping placement.`);continue}const H=I+U*(i+A),G=E-L*(a+d),W=e.schematic_component.get(P.schematic_component_id);if(W){const z=W.center,ae={x:H,y:G};e.schematic_component.update(P.schematic_component_id,{center:ae});const te=ae.x-z.x,oe=ae.y-z.y,pe=e.schematic_port.list({schematic_component_id:P.schematic_component_id});for(const he of pe)e.schematic_port.update(he.schematic_port_id,{center:{x:he.center.x+te,y:he.center.y+oe}});const Ae=e.schematic_text.list({schematic_component_id:P.schematic_component_id});for(const he of Ae)e.schematic_text.update(he.schematic_text_id,{position:{x:he.position.x+te,y:he.position.y+oe}})}}r.schematic_group_id&&e.schematic_group.update(r.schematic_group_id,{width:f,height:g,center:_})}function Dft(r){var x;const{db:e}=r.root,t=r._parsedProps,n=r.children.filter(B=>B.pcb_component_id);if(n.length===0)return;let i=0,a=0;for(const B of n){const P=e.pcb_component.get(B.pcb_component_id);P&&(i=Math.max(i,P.width),a=Math.max(a,P.height))}i===0&&n.length>0&&(i=1),a===0&&n.length>0&&(a=1);let o=t.gridCols,s,l=t.gridGap;(x=t.pcbLayout)!=null&&x.grid&&(o=t.pcbLayout.grid.cols??o,s=t.pcbLayout.grid.rows,l=t.pcbLayout.grid.gap??l);let c,u;o!==void 0&&s!==void 0?(c=o,u=s):o!==void 0?(c=o,u=Math.ceil(n.length/c)):s!==void 0?(u=s,c=Math.ceil(n.length/u)):(c=Math.ceil(Math.sqrt(n.length)),u=Math.ceil(n.length/c)),c===0&&n.length>0&&(c=1),u===0&&n.length>0&&(u=n.length);let A,d;typeof l=="number"?(A=l,d=l):typeof l=="object"&&l!==null?(A=l.x,d=l.y):(A=1,d=1);const f=c*i+Math.max(0,c-1)*A,g=u*a+Math.max(0,u-1)*d,_=r._getGlobalPcbPositionBeforeLayout(),I=_.x-f/2+i/2,E=_.y+g/2-a/2;for(let B=0;B<n.length;B++){const P=n[B];if(!P.pcb_component_id)continue;const L=Math.floor(B/c),U=B%c;if(L>=u||U>=c){console.warn(`PCB grid layout: Child ${P.getString()} at index ${B} (row ${L}, col ${U}) exceeds grid dimensions (${u}x${c}). Skipping placement.`);continue}const H=I+U*(i+A),G=E-L*(a+d),W=e.pcb_component.get(P.pcb_component_id);if(W){const z=W.center,ae={x:H,y:G},te=ae.x-z.x,oe=ae.y-z.y,pe=Od(te,oe),Ae=e.toArray().filter(Ie=>Ie.pcb_component_id===P.pcb_component_id),he=fAt(Ae,pe);for(const Ie of he){const ge=rk(Ie);e[Ie.type].update(Ie[ge],Ie)}e.pcb_component.update(P.pcb_component_id,{center:ae}),P.setProps({...P.props,pcbX:(P.props.pcbX??0)+te,pcbY:(P.props.pcbY??0)+oe})}}r.pcb_group_id&&e.pcb_group.update(r.pcb_group_id,{width:f,height:g,center:_})}var hK=class extends T1{constructor(){super(...arguments);Ke(this,"pcb_group_id",null);Ke(this,"schematic_group_id",null);Ke(this,"subcircuit_id",null);Ke(this,"_hasStartedAsyncAutorouting",!1);Ke(this,"_asyncAutoroutingResult",null)}get config(){return{zodProps:M0e,componentName:"Group"}}doInitialSourceRender(){const{db:t}=this.root,n=t.source_group.insert({name:this._parsedProps.name,is_subcircuit:this.isSubcircuit});this.subcircuit_id=`subcircuit_${n.source_group_id}`,this.source_group_id=n.source_group_id,t.source_group.update(n.source_group_id,{subcircuit_id:this.subcircuit_id});for(const i of this.children)t.source_component.update(i.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){var i,a,o;const{db:t}=this.root;if(!this.isSubcircuit)return;const n=(o=(a=(i=this.parent)==null?void 0:i.getSubcircuit)==null?void 0:a.call(i))==null?void 0:o.subcircuit_id;n&&t.source_group.update(this.source_group_id,{parent_subcircuit_id:n})}doInitialPcbComponentRender(){var a;if((a=this.root)!=null&&a.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this._parsedProps.name,center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,pcb_component_ids:[],source_group_id:this.source_group_id});this.pcb_group_id=i.pcb_group_id;for(const o of this.children)t.pcb_component.update(o.pcb_component_id,{pcb_group_id:i.pcb_group_id})}doInitialPcbPrimitiveRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:t}=this.root,n=uK(this.children);this.pcb_group_id&&t.pcb_group.update(this.pcb_group_id,{width:n.width,height:n.height,center:{x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2}})}doInitialCreateTraceHintsFromProps(){var o;const{_parsedProps:t}=this,{db:n}=this.root,i=t;if(!this.isSubcircuit)return;const a=(o=i.layout)==null?void 0:o.manual_trace_hints;if(a)for(const s of a)this.add(new qye({for:s.pcb_port_selector,offsets:s.offsets}))}doInitialSourceAddConnectivityMapKey(){Qft(this)}_areChildSubcircuitsRouted(){const t=this.selectAll("group").filter(n=>n.isSubcircuit);for(const n of t)if(n._shouldRouteAsync()&&!n._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){const t=this._getAutorouterConfig();return t.groupMode==="sequential-trace"?!1:!!(t.local&&t.groupMode==="subcircuit"||!t.local)}_hasTracesToRoute(){const t=nv("tscircuit:core:_hasTracesToRoute"),n=this.selectAll("trace");return t(`[${this.getString()}] has ${n.length} traces to route`),n.length>0}async _runEffectMakeHttpAutoroutingRequest(){var u,A,d,f;const{db:t}=this.root,n=nv("tscircuit:core:_runEffectMakeHttpAutoroutingRequest");this._parsedProps;const i=this._getAutorouterConfig(),a=i.serverUrl,o=i.serverMode,s=(g,_)=>{var I;return n("fetching",g),_.headers&&(_.headers["Tscircuit-Core-Version"]=(I=this.root)==null?void 0:I.getCoreVersion()),fetch(g,_)},l=this.root.db.toArray().filter(g=>g.type.startsWith("source_")||g.type.startsWith("pcb_"));if(o==="solve-endpoint"){if(((u=this.props.autorouter)==null?void 0:u.inputFormat)==="simplified"){const{autorouting_result:_}=await s(`${a}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:Xye({db:t,minTraceWidth:((A=this.props.autorouter)==null?void 0:A.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(I=>I.json());this._asyncAutoroutingResult=_,this._markDirty("PcbTraceRender");return}const{autorouting_result:g}=await s(`${a}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:l,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(_=>_.json());this._asyncAutoroutingResult=g,this._markDirty("PcbTraceRender");return}const{autorouting_job:c}=await s(`${a}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:l,provider:"freerouting",autostart:!0,display_name:(d=this.root)==null?void 0:d.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:i.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(g=>g.json());for(;;){const{autorouting_job:g}=await s(`${a}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:c.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(_=>_.json());if(g.is_finished){const{autorouting_job_output:_}=await s(`${a}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:c.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(I=>I.json());this._asyncAutoroutingResult={output_pcb_traces:_.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(g.has_error)throw t.pcb_autorouting_error.insert({pcb_error_id:c.autorouting_job_id,message:((f=g.error)==null?void 0:f.message)??JSON.stringify(g.error)}),new Error(`Autorouting job failed: ${JSON.stringify(g.error)}`);await new Promise(_=>setTimeout(_,100))}}async _runLocalAutorouting(){var l,c,u,A,d;const{db:t}=this.root;this._parsedProps;const n=nv("tscircuit:core:_runLocalAutorouting");n(`[${this.getString()}] starting local autorouting`);const i=this._getAutorouterConfig(),{simpleRouteJson:a}=Xye({db:t,minTraceWidth:((l=this.props.autorouter)==null?void 0:l.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id});(c=this.root)==null||c.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:a});let o;i.algorithmFn?o=await i.algorithmFn(a):o=new _ft(a,{capacityDepth:(u=this.props.autorouter)==null?void 0:u.capacityDepth,targetMinCapacity:(A=this.props.autorouter)==null?void 0:A.targetMinCapacity});const s=new Promise((f,g)=>{o.on("complete",_=>{n(`[${this.getString()}] local autorouting complete`),f(_.traces)}),o.on("error",_=>{n(`[${this.getString()}] local autorouting error: ${_.error.message}`),g(_.error)})});o.on("progress",f=>{var g;(g=this.root)==null||g.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...f})}),o.start();try{const f=await s;this._asyncAutoroutingResult={output_pcb_traces:f},this._markDirty("PcbTraceRender")}catch(f){const{db:g}=this.root;throw g.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,message:f instanceof Error?f.message:String(f)}),(d=this.root)==null||d.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:f instanceof Error?f.message:String(f)},simpleRouteJson:a}),f}finally{o.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(){var n;const t=nv("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!((n=this.root)!=null&&n.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()}}updatePcbTraceRender(){var i;const t=nv("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;const{db:n}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){t(`[${this.getString()}] updating PCB traces from simple route json (${(i=this._asyncAutoroutingResult.output_simple_route_json.traces)==null?void 0:i.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(){const{db:t}=this.root,{traces:n}=this._asyncAutoroutingResult.output_simple_route_json;if(n)for(const i of n)t.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}_updatePcbTraceRenderFromPcbTraces(){const{output_pcb_traces:t}=this._asyncAutoroutingResult;if(!t)return;const{db:n}=this.root;for(const i of t)if(i.type==="pcb_trace"){if(i.subcircuit_id=this.subcircuit_id,i.connection_name){const a=i.connection_name;i.source_trace_id=a}n.pcb_trace.insert(i)}for(const i of t)if(i.type!=="pcb_via"&&i.type==="pcb_trace")for(const a of i.route)a.route_type==="via"&&n.pcb_via.insert({pcb_trace_id:i.pcb_trace_id,x:a.x,y:a.y,hole_diameter:.3,outer_diameter:.6,layers:[a.from_layer,a.to_layer],from_layer:a.from_layer,to_layer:a.to_layer})}doInitialSchematicComponentRender(){var a;if((a=this.root)!=null&&a.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=t.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this._parsedProps.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(const o of this.children)o.schematic_component_id&&t.schematic_component.update(o.schematic_component_id,{schematic_group_id:i.schematic_group_id})}_getSchematicLayoutMode(){var n,i,a;const t=this._parsedProps;return(n=t.schLayout)!=null&&n.matchAdapt?"match-adapt":(i=t.schLayout)!=null&&i.flex?"flex":(a=t.schLayout)!=null&&a.grid?"grid":t.matchAdapt?"match-adapt":t.flex?"flex":t.grid?"grid":"none"}doInitialSchematicLayout(){this._parsedProps;const t=this._getSchematicLayoutMode();t==="match-adapt"&&this._doInitialSchematicLayoutMatchAdapt(),t==="grid"&&this._doInitialSchematicLayoutGrid()}_doInitialSchematicLayoutMatchAdapt(){wft(this)}_doInitialSchematicLayoutGrid(){Mft(this)}_getPcbLayoutMode(){var n,i,a;const t=this._parsedProps;return(n=t.pcbLayout)!=null&&n.matchAdapt?"match-adapt":(i=t.pcbLayout)!=null&&i.flex?"flex":(a=t.pcbLayout)!=null&&a.grid?"grid":t.matchAdapt?"match-adapt":t.flex?"flex":t.grid?"grid":"none"}doInitialPcbLayout(){this._getPcbLayoutMode()==="grid"&&this._doInitialPcbLayoutGrid()}_doInitialPcbLayoutGrid(){Dft(this)}_determineSideFromPosition(t,n){if(!t.center||!n.center)return"left";const i=t.center.x-n.center.x,a=t.center.y-n.center.y;return Math.abs(i)>Math.abs(a)?i>0?"right":"left":a>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,a=1/0,o=-1/0;for(const l of t)n=Math.min(n,l.centerX),i=Math.max(i,l.centerX),a=Math.min(a,l.centerY),o=Math.max(o,l.centerY);const s=2;return{minX:n-s,maxX:i+s,minY:a-s,maxY:o+s}}_getAutorouterConfig(){const t={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0},n=this._parsedProps.autorouter??this.getInheritedProperty("autorouter");return typeof n=="object"?{local:!(n.serverUrl||n.serverMode||n.serverCacheEnabled),...t,...n}:n==="auto-local"?{local:!0,groupMode:"subcircuit"}:n==="sequential-trace"?{local:!0,groupMode:"sequential-trace"}:n==="subcircuit"?{local:!0,groupMode:"subcircuit"}:n==="auto-cloud"?{local:!1,groupMode:"subcircuit",serverUrl:t.serverUrl,serverMode:t.serverMode,serverCacheEnabled:!0}:{local:!0,groupMode:"subcircuit"}}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){var n;if((n=this.root)!=null&&n.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:t}=this.root;if(this.isSubcircuit){const i=new Map;for(const a of this.children)if(!a.isSubcircuit&&a._parsedProps.name){const o=i.get(a._parsedProps.name)||[];o.push(a),i.set(a._parsedProps.name,o)}for(const[a,o]of i.entries())o.length>1&&t.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${a}" in subcircuit "${this._parsedProps.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:o.map(s=>s.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}},Rft=class extends hK{constructor(){super(...arguments);Ke(this,"pcb_board_id",null);Ke(this,"_drcChecksComplete",!1);Ke(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:cV}}get boardThickness(){const{_parsedProps:t}=this;return 1.4}get allLayers(){return["top","bottom","inner1","inner2"]}doInitialPcbBoardAutoSize(){var g;if((g=this.root)!=null&&g.pcbDisabled||!this.pcb_board_id)return;const{db:t}=this.root,{_parsedProps:n}=this;if(n.width&&n.height)return;let i=1/0,a=1/0,o=-1/0,s=-1/0;const l=t.pcb_component.list();let c=!1;for(const _ of l){const{width:I,height:E,center:x}=_;I===0||E===0||(c=!0,i=Math.min(i,x.x-I/2),a=Math.min(a,x.y-E/2),o=Math.max(o,x.x+I/2),s=Math.max(s,x.y+E/2))}const u=2,A=c?o-i+u*2:0,d=c?s-a+u*2:0,f={x:c?(i+o)/2+(n.outlineOffsetX??0):n.outlineOffsetX??0,y:c?(a+s)/2+(n.outlineOffsetY??0):n.outlineOffsetY??0};t.pcb_board.update(this.pcb_board_id,{width:A,height:d,center:f})}doInitialPcbComponentRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this;let i=n.width??0,a=n.height??0;if(n.outline){const c=n.outline.map(_=>_.x),u=n.outline.map(_=>_.y),A=Math.min(...c),d=Math.max(...c),f=Math.min(...u),g=Math.max(...u);i=d-A,a=g-f}const o=t.pcb_board.insert({center:{x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)},thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:a,outline:(l=n.outline)==null?void 0:l.map(c=>({x:c.x+(n.outlineOffsetX??0),y:c.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=o.pcb_board_id}removePcbComponentRender(){const{db:t}=this.root;this.pcb_board_id&&(t.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return wy()}doInitialPcbDesignRuleChecks(){var t;(t=this.root)!=null&&t.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){var i;if((i=this.root)!=null&&i.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;const n=Iye(t.toArray());for(const a of n)t.pcb_trace_error.insert(a)}_emitRenderLifecycleEvent(t,n){var i;super._emitRenderLifecycleEvent(t,n),n==="start"&&((i=this.root)==null||i.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t}))}},Nft=new Proxy({},{get:(r,e)=>e}),oQ=Nft,Tft=class extends T1{get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:F0e,sourceFtype:oQ.simple_capacitor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){const e=`${kB(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${e}/${kB(this._parsedProps.maxVoltageRating)}V`:e}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new OS({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new OS({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_capacitor",name:t.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,capacitance:t.capacitance,max_voltage_rating:t.maxVoltageRating,max_decoupling_trace_length:t.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!t.polarized});this.source_component_id=n.source_component_id}},$ye=class extends T1{constructor(){super(...arguments);Ke(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:uV,shouldRenderAsSchematicBox:!0}}doInitialSchematicComponentRender(){const{_parsedProps:t}=this;(t==null?void 0:t.noSchematicRepresentation)!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:n.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){var a;if((a=this.root)!=null&&a.pcbDisabled)return;const{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(){const{_parsedProps:t}=this;if(t.externallyConnectedPins)for(const[n,i]of t.externallyConnectedPins)this.add(new OS({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}},Pft=class extends T1{constructor(){super(...arguments);Ke(this,"pos",this.portMap.pin1);Ke(this,"anode",this.portMap.pin1);Ke(this,"neg",this.portMap.pin2);Ke(this,"cathode",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"diode",componentName:"Diode",zodProps:$0e,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:n.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}},kft=class extends T1{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:xst,sourceFtype:oQ.simple_fuse}}_getSchematicSymbolDisplayValue(){const r=this._parsedProps.currentRating,e=this._parsedProps.voltageRating,t=typeof r=="string"?parseFloat(r):r,n=typeof e=="string"?parseFloat(e):e;return`${kB(t)}A / ${kB(n)}V`}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=typeof e.currentRating=="string"?parseFloat(e.currentRating):e.currentRating,n=typeof e.voltageRating=="string"?parseFloat(e.voltageRating):e.voltageRating,i=r.source_component.insert({name:e.name,ftype:oQ.simple_fuse,current_rating_amps:t,voltage_rating_volts:n,display_current_rating:`${kB(t)}A`,display_voltage_rating:`${kB(n)}V`});this.source_component_id=i.source_component_id}},Uft=class extends T1{constructor(){super(...arguments);Ke(this,"schematicDimensions",null)}get config(){let t="";if(this.props.pinCount&&(t+=`solderjumper${this.props.pinCount||2}`),Array.isArray(this.props.internallyConnectedPins)&&this.props.internallyConnectedPins.length>0){const n=Array.from(new Set(this.props.internallyConnectedPins.flat())).sort().join("");t+=`_bridged${n}`}return{schematicSymbolName:t,componentName:"Jumper",zodProps:D0e,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){const t=super._getSchematicPortArrangement();if(t)return t;const 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(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:n.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){var a;if((a=this.root)!=null&&a.pcbDisabled)return;const{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(){const{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++){const l=n[s],c=t.source_port.get(l.source_port_id);let u="";if(typeof(c==null?void 0:c.pin_number)=="number")u=c.pin_number.toString();else if(Array.isArray(c==null?void 0:c.port_hints)){let A=c.port_hints.find(d=>/^(pin)?\d+$/.test(d));A&&(/^pin\d+$/.test(A)?u=A.replace(/^pin/,""):u=A)}i[u]=l.pcb_port_id}const a=t.pcb_trace.list(),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){const l=s.replace("{PIN","").replace("}","");return i[l]||s}return s};for(const s of a)if(s.route)for(const l of s.route)l.route_type==="wire"&&(l.start_pcb_port_id=o(l.start_pcb_port_id),l.end_pcb_port_id=o(l.end_pcb_port_id))}},Fft=class extends T1{constructor(){super(...arguments);Ke(this,"pos",this.portMap.pin1);Ke(this,"anode",this.portMap.pin1);Ke(this,"neg",this.portMap.pin2);Ke(this,"cathode",this.portMap.pin2)}get config(){return{componentName:"Led",schematicSymbolName:this.props.symbolName??"led",zodProps:eme,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(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_led",name:n.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}},Lft=class extends T1{constructor(){super(...arguments);Ke(this,"pos",this.portMap.pin1);Ke(this,"positive",this.portMap.pin1);Ke(this,"neg",this.portMap.pin2);Ke(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:ome,sourceFtype:"simple_power_source"}}initPorts(){this.add(new GS({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new GS({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:n.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},Gft=class extends T1{get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:T0e,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${kB(this._parsedProps.resistance)}Ω`}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 OS({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new OS({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new OS({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new OS({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_resistor",name:t.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,resistance:t.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},Oft=["leftedge","rightedge","topedge","bottomedge","center"],zft=class extends $v{get config(){return{componentName:"Constraint",zodProps:L0e}}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(){const e=[],t=this.getPrimitiveContainer();function n(i){const a=i.split(" ").pop(),o=Oft.includes(a)?a:void 0,s=o?i.replace(` ${o}`,""):i,l=t.selectOne(s,{pcbPrimitive:!0});l&&e.push({selector:i,component:l,componentSelector:s,edge:o})}for(const i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(const i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},Hft=class extends $v{constructor(){super(...arguments);Ke(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:rme}}doInitialPcbPrimitiveRender(){var l,c;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,n=this.getSubcircuit(),{_parsedProps:i}=this,a=i.layer??"top";if(a!=="top"&&a!=="bottom")throw new Error(`Invalid layer "${a}" for SilkscreenPath. Must be "top" or "bottom".`);const o=this._computePcbGlobalTransformBeforeLayout(),s=t.pcb_fabrication_note_path.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layer:a,color:i.color,route:i.route.map(u=>{const A=ti(o,{x:u.x,y:u.y});return{...u,x:A.x,y:A.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0});this.fabrication_note_path_id=s.pcb_fabrication_note_path_id}},Yft=class extends $v{get config(){return{componentName:"FabricationNoteText",zodProps:nme}}doInitialPcbPrimitiveRender(){var a,o;if((a=this.root)!=null&&a.pcbDisabled)return;const{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==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((o=this.getGroup())==null?void 0:o.pcb_group_id)??void 0})}},Vft=class extends hK{constructor(e){super({...e,subcircuit:!0})}},Kft=class extends $v{constructor(){super(...arguments);Ke(this,"source_net_alias_id")}get config(){return{componentName:"NetAlias",zodProps:J0e}}doInitialSchematicComponentRender(){var o;if((o=this.root)!=null&&o.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i={x:n.schX??0,y:n.schY??0},a=t.schematic_net_label.insert({text:n.net,source_net_id:n.net,anchor_position:i,center:i,anchor_side:"bottom"});this.source_net_alias_id=a.source_net_id}},jft=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_silkscreen_circle_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:fme}}doInitialPcbPrimitiveRender(){var l,c,u;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),a=i(n.layer??"top");if(a!=="top"&&a!=="bottom")throw new Error(`Invalid layer "${a}" for SilkscreenCircle. Must be "top" or "bottom".`);this._computePcbGlobalTransformBeforeLayout();const o=this.getSubcircuit(),s=t.pcb_silkscreen_circle.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layer:a,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((u=this.getGroup())==null?void 0:u.pcb_group_id)??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=s.pcb_silkscreen_circle_id}getPcbSize(){const{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},Jft=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_silkscreen_rect_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:dme}}doInitialPcbPrimitiveRender(){var l,c,u;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),a=i(n.layer??"top");if(a!=="top"&&a!=="bottom")throw new Error(`Invalid layer "${a}" for SilkscreenRect. Must be "top" or "bottom".`);const o=this.getSubcircuit(),s=t.pcb_silkscreen_rect.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layer:a,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((u=this==null?void 0:this.getGroup())==null?void 0:u.pcb_group_id)??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_rect_id=s.pcb_silkscreen_rect_id}getPcbSize(){const{_parsedProps:t}=this;return{width:t.width,height:t.height}}},Wft=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_silkscreen_line_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:Ame}}doInitialPcbPrimitiveRender(){var l,c,u;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),a=i(n.layer??"top");if(a!=="top"&&a!=="bottom")throw new Error(`Invalid layer "${a}" for SilkscreenLine. Must be "top" or "bottom".`);const o=this.getSubcircuit(),s=t.pcb_silkscreen_line.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layer:a,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((u=o==null?void 0:o.getGroup())==null?void 0:u.pcb_group_id)??void 0});this.pcb_silkscreen_line_id=s.pcb_silkscreen_line_id}getPcbSize(){const{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},qft=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_via_id",null);Ke(this,"matchedPort",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Via",zodProps:ime}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){const{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){const{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){const{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),a=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:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((l=this.getGroup())==null?void 0:l.pcb_group_id)??void 0});this.pcb_via_id=o.pcb_via_id}},Zft=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_cutout_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:G0e}}doInitialPcbPrimitiveRender(){var l,c;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),a=((c=this.getGroup())==null?void 0:c.pcb_group_id)??void 0,o=this._getGlobalPcbPositionBeforeLayout();let s;if(n.shape==="rect"){const u={shape:"rect",center:o,width:n.width,height:n.height,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:a};s=t.pcb_cutout.insert(u)}else if(n.shape==="circle"){const u={shape:"circle",center:o,radius:n.radius,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:a};s=t.pcb_cutout.insert(u)}else if(n.shape==="polygon"){const u=this._computePcbGlobalTransformBeforeLayout(),d={shape:"polygon",points:n.points.map(f=>ti(u,f)),subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:a};s=t.pcb_cutout.insert(d)}s&&(this.pcb_cutout_id=s.pcb_cutout_id)}getPcbSize(){const{_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,a=1/0,o=-1/0;for(const s of t.points)n=Math.min(n,s.x),i=Math.max(i,s.x),a=Math.min(a,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-a}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();const{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,a=-1/0,o=1/0,s=-1/0;for(const l of n.points)i=Math.min(i,l.x),a=Math.max(a,l.x),o=Math.min(o,l.y),s=Math.max(s,l.y);return{center:{x:(i+a)/2,y:(o+s)/2},bounds:{left:i,top:s,right:a,bottom:o},width:a-i,height:s-o}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(t){if(!this.pcb_cutout_id)return;const{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"){const a=this._getPcbCircuitJsonBounds().center,o=t.x-a.x,s=t.y-a.y,l=i.points.map(c=>({x:c.x+o,y:c.y+s}));n.pcb_cutout.update(this.pcb_cutout_id,{...i,points:l})}}}},Xft=class extends T1{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:K0e,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:t.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}},$ft=class extends T1{get config(){return{componentName:"PinHeader",zodProps:j0e,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){var a;const e=this._parsedProps.pinCount??((a=this._parsedProps.pinLabels)==null?void 0:a.length)??0,t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch;return e>0&&i?!t&&!n?`pinrow${e}_p${i}`:`pinrow${e}_p${i}_id${t}_od${n}`:null}initPorts(){var t,n;const e=this._parsedProps.pinCount??((t=this._parsedProps.pinLabels)==null?void 0:t.length)??1;for(let i=1;i<=e;i++)this.add(new GS({name:`pin${i}`,pinNumber:i,aliases:[(n=this._parsedProps.pinLabels)==null?void 0:n[i-1]].filter(Boolean)}))}_getSchematicPortArrangement(){var i,a,o,s;const e=this._parsedProps.pinCount??1,t=this._parsedProps.facingDirection??"right",n=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:((i=n==null?void 0:n.leftSide)==null?void 0:i.direction)??"top-to-bottom",pins:((a=n==null?void 0:n.leftSide)==null?void 0:a.pins)??Array.from({length:e},(l,c)=>`pin${c+1}`)}}:{rightSide:{direction:((o=n==null?void 0:n.rightSide)==null?void 0:o.direction)??"top-to-bottom",pins:((s=n==null?void 0:n.rightSide)==null?void 0:s.pins)??Array.from({length:e},(l,c)=>`pin${c+1}`)}}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:t.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 eht(r){switch(r){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var tht=class extends T1{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??eht(this.props.pinVariant),zodProps:U0e,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:t.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}},nht=class extends T1{get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:X0e,sourceFtype:oQ.simple_inductor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:t.name,ftype:oQ.simple_inductor,inductance:t.inductance,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function rht(r){switch(r){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var iht=class extends T1{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??rht(this.props.pinVariant),zodProps:P0e,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:t.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},aht=class extends T1{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:W0e,sourceFtype:oQ.simple_push_button}}get defaultInternallyConnectedPinNames(){return[["pin1","pin4"],["pin2","pin3"]]}initPorts(){super.initPorts({pinCount:4,additionalAliases:{pin1:["side1"],pin3:["side2"]}})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:t.name,ftype:oQ.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},oht=class extends T1{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:k0e,sourceFtype:"simple_crystal"}}initPorts(){const 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(){return`${kB(this._parsedProps.frequency)}Hz`}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:t.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}},sht=class extends T1{constructor(){super(...arguments);Ke(this,"emitter",this.portMap.pin1);Ke(this,"collector",this.portMap.pin2);Ke(this,"base",this.portMap.pin3)}get config(){return{componentName:"Transistor",schematicSymbolName:this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor",zodProps:q0e,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){const t=this.props.type==="npn"?{pin1:["emitter","e"],pin2:["collector","c"],pin3:["base","b"]}:{pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:n.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},lht=class extends T1{get config(){const e=this.props.mosfetMode==="depletion"?"d":"e";return{componentName:"Mosfet",schematicSymbolName:`${this.props.channelType}_channel_${e}_mosfet_transistor`,zodProps:Z0e,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:t.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}},cht=class extends T1{_getSwitchType(){const{spst:e,spdt:t,dpst:n,dpdt:i,type:a}=this._parsedProps??{};return i?"dpdt":e?"spst":t?"spdt":n?"dpst":a??"spst"}get config(){const e=this._getSwitchType(),{isNormallyClosed:t}=this._parsedProps??{};return{componentName:"Switch",schematicSymbolName:{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",zodProps:tme,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_switch",name:t.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}},uht=class extends $v{constructor(){super(...arguments);Ke(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:lme}}doInitialSchematicPrimitiveRender(){var i;if((i=this.root)!=null&&i.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this;t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:n.schX,y:n.schY},rotation:n.schRotation??0})}},Aht=class extends $v{constructor(){super(...arguments);Ke(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:sme,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){var I;if((I=this.root)!=null&&I.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=sme.safeParse(t);if(!n.success)throw console.error("Validation failed:",n.error.format()),n.error;const i=.6,a=typeof t.padding=="number"?t.padding:0,o=typeof t.paddingTop=="number"?t.paddingTop:a,s=typeof t.paddingBottom=="number"?t.paddingBottom:a,l=typeof t.paddingLeft=="number"?t.paddingLeft:a,c=typeof t.paddingRight=="number"?t.paddingRight:a,u=t.overlay&&t.overlay.length>0,A=typeof t.width=="number"&&typeof t.height=="number";let d,f,g,_;if(u){const x=t.overlay.map(Re=>({selector:Re,port:this.getSubcircuit().selectOne(Re,{type:"port"})})).filter(({port:Re})=>Re!=null).map(({port:Re})=>({position:Re._getGlobalSchematicPositionAfterLayout()}));if(x.length===0)return;const B=x.map(Re=>Re.position.x),P=x.map(Re=>Re.position.y),L=Math.min(...B),U=Math.max(...B),H=Math.min(...P),G=Math.max(...P),W=U-L,z=G-H,ae=W===0?i:0,te=z===0?i:0,oe=l+ae/2,pe=c+ae/2,Ae=o+te/2,he=s+te/2,Ie=L-oe,ge=U+pe,Me=H-he,Se=G+Ae;d=ge-Ie,f=Se-Me,g=Ie+(t.schX??0),_=Me+(t.schY??0)}else if(A){d=t.width,f=t.height;const E=typeof t.schX=="number"?t.schX:0,x=typeof t.schY=="number"?t.schY:0;g=E-d/2,_=x-f/2}else return;e.schematic_box.insert({height:f,width:d,x:g,y:_,is_dashed:t.strokeStyle==="dashed",schematic_component_id:""})}},dht={version:"0.0.445"},fht=class{constructor({platform:r}={}){Ke(this,"firstChild",null);Ke(this,"children");Ke(this,"db");Ke(this,"root",null);Ke(this,"isRoot",!0);Ke(this,"schematicDisabled",!1);Ke(this,"pcbDisabled",!1);Ke(this,"pcbRoutingDisabled",!1);Ke(this,"name");Ke(this,"platform");Ke(this,"_hasRenderedAtleastOnce",!1);Ke(this,"_eventListeners",{});this.children=[],this.db=o1([]),this.root=this,this.platform=r}add(r){let e;nt.isValidElement(r)?e=Pye(r):e=r,this.children.push(e)}_getBoard(){return this.children.find(r=>r.componentName==="Board")}_guessRootComponent(){if(!this.firstChild){if(this.children.length===1){this.firstChild=this.children[0];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>0){const r=this.children.find(e=>e.componentName==="Board")??null;if(r){this.firstChild=r;return}}throw new Error("Not able to guess root component: RootCircuit has multiple children and no board")}}render(){this.firstChild||this._guessRootComponent();const{firstChild:r,db:e}=this;if(!r)throw new Error("RootCircuit has no root component");r.parent=this,r.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){var r;for((r=this.db.source_project_metadata.list())!=null&&r[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(e=>setTimeout(e,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(r=>r._hasIncompleteAsyncEffects()?!0:r.children.some(e=>e._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(r){const e=await Promise.resolve().then(()=>mHt).catch(t=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
852
+ `)}visualize(){return[{title:"inputTemplate",ascii:this.template.toString(),table:this.outputIssues.map((e,t)=>({issue_index:t,type:e.type,target_box:"targetBoxIndex"in e?this.getBoxNameFromIndex(e.targetBoxIndex,!1):"N/A",candidate_box:"candidateBoxIndex"in e?this.getBoxNameFromIndex(e.candidateBoxIndex,!0):"N/A",details:e}))},{title:"pairwisePinShapeSignatures",table:Sdt({targetNetlist:this.inputNetlistWithRotations,candidateNetlist:this.template.getNetlist(),matchedBoxes:this.matchedBoxes,targetTransform:this.targetTransform,candidateTransform:this.candidateTransform})},{title:"matchedBoxes",ascii:this.generateMatchedBoxesVisualization(),table:this.matchedBoxes.map(e=>({target_box:this.getBoxNameFromIndex(e.targetBoxIndex,!1),candidate_box:this.getBoxNameFromIndex(e.candidateBoxIndex,!0),rotation:e.targetBoxRotationCcw,issueCount:e.issues.length,details:e}))},{title:"inputTemplateReadableNetlist",ascii:this.template.getReadableNetlist()},{title:"inputTargetReadableNetlist",ascii:AD(this.inputNetlist)},this.inputNetlistWithRotations&&{title:"targetReadableNetlistWithRotations",ascii:AD(this.inputNetlistWithRotations)}].filter(Boolean)}},Qdt=class extends hM{constructor(e){var t;super();Ke(this,"inputNetlist");Ke(this,"templates");Ke(this,"scoringSolvers",[]);Ke(this,"currentScoringIndex",0);Ke(this,"outputBestMatchTemplate",null);Ke(this,"templateMatchResults",[]);this.inputNetlist=e.inputNetlist,this.templates=((t=e.templateFns)==null?void 0:t.map(n=>n()))||Cdt.map(n=>n()),this.scoringSolvers=this.templates.map(n=>new wdt({inputNetlist:this.inputNetlist,template:n}))}getConstructorParams(){return{inputNetlist:this.inputNetlist}}computeProgress(){return this.scoringSolvers.length===0?1:this.currentScoringIndex/this.scoringSolvers.length}_step(){if(this.currentScoringIndex<this.scoringSolvers.length){const t=this.scoringSolvers[this.currentScoringIndex];if(!t.solved&&!t.failed){this.setActiveSubSolver(t),t.step();return}this.clearActiveSubSolver(),this.currentScoringIndex++;return}if(this.templateMatchResults=this.scoringSolvers.map(t=>({template:t.template,issues:t.outputIssues,similarityDistance:t.outputSimilarityDistance})),this.templateMatchResults.length===0){this.outputBestMatchTemplate=null,this.solved=!0;return}let e=this.templateMatchResults[0];for(let t=1;t<this.templateMatchResults.length;t++)this.templateMatchResults[t].similarityDistance<e.similarityDistance&&(e=this.templateMatchResults[t]);e.similarityDistance===1/0?this.outputBestMatchTemplate=null:this.outputBestMatchTemplate=e.template,this.solved=!0}visualize(){var e;return[{title:"inputNetlist",ascii:AD(this.inputNetlist)},{title:"bestMatchTemplate",ascii:((e=this.outputBestMatchTemplate)==null?void 0:e.toString())||"No suitable match found"},{title:"templateScores",table:this.templateMatchResults.map((t,n)=>({template_index:n,template_name:t.template.name||`Template ${n}`,similarity_distance:t.similarityDistance,issue_count:t.issues.length,is_best_match:t.template===this.outputBestMatchTemplate}))}]}},Mdt=class extends hM{constructor(e){super();Ke(this,"inputNetlists");Ke(this,"currentInputNetlistIndex",0);Ke(this,"templateFns");Ke(this,"outputMatchedTemplates",[]);this.inputNetlists=e.inputNetlists,this.templateFns=e.templateFns}get activeSubSolver(){return this._activeSubSolver}_step(){if(this.activeSubSolver)if(this.activeSubSolver.step(),this.activeSubSolver.solved){this.outputMatchedTemplates.push({template:this.activeSubSolver.outputBestMatchTemplate,netlist:this.inputNetlists[this.currentInputNetlistIndex]}),this.currentInputNetlistIndex++,this.clearActiveSubSolver();return}else return;if(this.currentInputNetlistIndex>=this.inputNetlists.length){this.solved=!0;return}this.setActiveSubSolver(new Qdt({inputNetlist:this.inputNetlists[this.currentInputNetlistIndex],templateFns:this.templateFns}))}};function wye(r,e,t,n={}){return{solverName:r,solverClass:e,getConstructorParams:t,onSolved:n.onSolved}}var Ddt=class extends hM{constructor(e){super();Ke(this,"inputNetlist");Ke(this,"templateFnsOverride");Ke(this,"matchPhaseSolver");Ke(this,"adaptPhaseSolver");Ke(this,"startTimeOfPhase",{});Ke(this,"endTimeOfPhase",{});Ke(this,"timeSpentOnPhase",{});Ke(this,"pipelineDef",[wye("matchPhaseSolver",Mdt,()=>[{inputNetlists:[this.inputNetlist],templateFns:this.templateFnsOverride}]),wye("adaptPhaseSolver",udt,()=>{var e;return[{matchedTemplates:(e=this.matchPhaseSolver)==null?void 0:e.outputMatchedTemplates}]})]);Ke(this,"currentPipelineStepIndex",0);this.inputNetlist=e.inputNetlist,this.templateFnsOverride=e.templateFns}_step(){var n,i;const e=this.pipelineDef[this.currentPipelineStepIndex];if(!e){this.solved=!0;return}if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){this.endTimeOfPhase[e.solverName]=performance.now(),this.timeSpentOnPhase[e.solverName]=this.endTimeOfPhase[e.solverName]-this.startTimeOfPhase[e.solverName],(n=e.onSolved)==null||n.call(e,this),this.clearActiveSubSolver(),this.currentPipelineStepIndex++;return}if(this.activeSubSolver.failed){this.error=(i=this.activeSubSolver)==null?void 0:i.error,this.failed=!0,this.clearActiveSubSolver();return}return}const t=e.getConstructorParams(this);this.setActiveSubSolver(new e.solverClass(...t)),this[e.solverName]=this.activeSubSolver,this.timeSpentOnPhase[e.solverName]=0,this.startTimeOfPhase[e.solverName]=performance.now()}getLayout(){var e,t;if(!((t=(e=this.adaptPhaseSolver)==null?void 0:e.outputAdaptedTemplates)!=null&&t[0]))throw new Error("No adapted template available. Make sure the pipeline has completed successfully.");return this.adaptPhaseSolver.outputAdaptedTemplates[0].template.getLayoutJson()}},Rdt=r=>{switch(r){case"left":return"left";case"right":return"right";case"up":return"top";case"down":return"bottom"}},Ndt=r=>{const e=FS(r),t=PB(r).source_component.list().map(o=>({source_component:o,schematic_component:PB(r).schematic_component.getWhere({source_component_id:o.source_component_id}),source_ports:PB(r).source_port.list().filter(s=>s.source_component_id===o.source_component_id).map(s=>{const l=e.getNetConnectedToId(s.source_port_id),c=PB(r).schematic_port.getWhere({source_port_id:s.source_port_id}),u=(c==null?void 0:c.true_ccw_index)!=null?c.true_ccw_index+1:s.pin_number;return{source_port:s,schematic_port:PB(r).schematic_port.getWhere({source_port_id:s.source_port_id}),pin_number:u,connectivity_net_id:l}}).filter(({schematic_port:s})=>!!s)})),n=[],i=[];for(const{source_component:o,schematic_component:s,source_ports:l}of t){const c={boxId:o.name,leftPinCount:0,rightPinCount:0,topPinCount:0,bottomPinCount:0};for(const{source_port:u,schematic_port:A,pin_number:d}of l){const f=Rdt(A.facing_direction);c[`${f}PinCount`]++;const g=e.getNetConnectedToId(u.source_port_id);let _=i.find(I=>I._connectivityNetId===g);_||(_={_connectivityNetId:g,connectedPorts:[]},i.push(_)),_.connectedPorts.push({boxId:o.name,pinNumber:(A==null?void 0:A.true_ccw_index)!=null?A.true_ccw_index+1:d})}n.push(c)}const a=[];for(const o of i){if(o.connectedPorts.length<2)continue;let s=o._connectivityNetId;const l=e.getIdsConnectedToNet(s).map(c=>gye(r,c));for(const c of l)if((c==null?void 0:c.type)==="source_net"){s=c.name;break}o.connectedPorts.push({netId:s}),a.push({netId:s})}return{boxes:n,connections:i,nets:a}},Tdt=r=>{const e=JSON.parse(JSON.stringify(r)),t=e.filter(n=>n.type==="schematic_component"&&n.port_arrangement);for(const n of t){const i=e.filter(o=>o.type==="schematic_port"&&o.schematic_component_id===n.schematic_component_id&&o.true_ccw_index!==void 0);if(i.length===0)continue;i.sort((o,s)=>o.true_ccw_index-s.true_ccw_index);const a={};i.forEach((o,s)=>{a[o.pin_number]=s+1});for(const o of i){const s=a[o.pin_number];o.pin_number=s}for(const o of i){const s=e.find(l=>l.type==="source_port"&&l.source_port_id===o.source_port_id);s&&(s.pin_number=o.pin_number)}if(n.port_arrangement){const o=s=>{var l;(l=n.port_arrangement[s])!=null&&l.pins&&(n.port_arrangement[s].pins=n.port_arrangement[s].pins.map(c=>a[c]||c))};o("left_side"),o("right_side"),o("top_side"),o("bottom_side")}if(n.port_labels){const o={};for(const[s,l]of Object.entries(n.port_labels)){const c=parseInt(s.replace("pin","")),u=a[c];u!==void 0?o[`pin${u}`]=l:o[s]=l}n.port_labels=o}if(n.pin_styles){const o={};for(const[s,l]of Object.entries(n.pin_styles)){const c=parseInt(s.replace("pin","")),u=a[c];u!==void 0?o[`pin${u}`]=l:o[s]=l}n.pin_styles=o}}return e},nK=[{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:"µ"},{value:1e-9,symbol:"n"},{value:1e-12,symbol:"p"}];function kB(r){if(r==null)return"";if(r===0)return"0";const e=Math.abs(r),t=nK.find(a=>{const o=e/a.value;return o>=1&&o<1e3})||nK[nK.length-1];let i=(r/t.value).toPrecision(3);return i.includes(".")&&!/\.0+$/.test(i)&&(i=i.replace(/0+$/,"")),i=i.replace(/\.0+$/,""),`${i}${t.symbol}`}var Pdt=Object.defineProperty,kdt=(r,e)=>{for(var t in e)Pdt(r,t,{get:e[t],enumerable:!0})},Qye={};kdt(Qye,{Battery:()=>Xft,Board:()=>Rft,Capacitor:()=>Tft,Chip:()=>$ye,Constraint:()=>zft,Crystal:()=>oht,Cutout:()=>Zft,Diode:()=>Pft,FabricationNotePath:()=>Hft,FabricationNoteText:()=>Yft,Footprint:()=>ift,Fuse:()=>kft,Group:()=>hK,Hole:()=>Oye,Inductor:()=>nht,Jumper:()=>Uft,Keepout:()=>lK,Led:()=>Fft,Mosfet:()=>lht,Net:()=>Uye,NetAlias:()=>Kft,NormalComponent:()=>T1,PcbTrace:()=>Gye,PinHeader:()=>$ft,PlatedHole:()=>sK,Port:()=>GS,Potentiometer:()=>iht,PowerSource:()=>Lft,PrimitiveComponent:()=>$v,PushButton:()=>aht,Renderable:()=>Mye,Resistor:()=>Gft,Resonator:()=>tht,SchematicBox:()=>Aht,SchematicText:()=>uht,SilkscreenCircle:()=>jft,SilkscreenLine:()=>Wft,SilkscreenPath:()=>Lye,SilkscreenRect:()=>Jft,SilkscreenText:()=>cK,SmtPad:()=>oK,Subcircuit:()=>Vft,Switch:()=>cht,Trace:()=>OS,TraceHint:()=>qye,Transistor:()=>sht,Via:()=>qft});var Udt=nv("tscircuit:renderable"),Hx=["ReactSubtreesRender","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","CreateTracesFromProps","CreateTraceHintsFromProps","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicLayout","SchematicTraceRender","SchematicReplaceNetLabelsWithSymbols","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbLayout","PcbComponentSizeCalculation","PcbBoardAutoSize","PcbTraceHintRender","PcbTraceRender","PcbRouteNetIslands","PcbDesignRuleChecks","CadModelRender","PartsEngineRender"],Fdt=0,Mye=class{constructor(e){Ke(this,"renderPhaseStates");Ke(this,"shouldBeRemoved",!1);Ke(this,"children");Ke(this,"isPcbPrimitive",!1);Ke(this,"isSchematicPrimitive",!1);Ke(this,"_renderId");Ke(this,"_currentRenderPhase",null);Ke(this,"_asyncEffects",[]);Ke(this,"parent",null);this._renderId=`${Fdt++}`,this.children=[],this.renderPhaseStates={};for(const t of Hx)this.renderPhaseStates[t]={initialized:!1,dirty:!1}}_markDirty(e){var n;this.renderPhaseStates[e].dirty=!0;const t=Hx.indexOf(e);for(let i=t+1;i<Hx.length;i++)this.renderPhaseStates[Hx[i]].dirty=!0;(n=this.parent)!=null&&n._markDirty&&this.parent._markDirty(e)}_queueAsyncEffect(e,t){const 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}":
853
+ ${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){Udt(`${e}:${t} ${this.getString()}`);const 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)}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(const e of Hx)this.runRenderPhaseForChildren(e),this.runRenderPhase(e)}runRenderPhase(e){var o,s,l;this._currentRenderPhase=e;const t=this.renderPhaseStates[e],n=t.initialized,i=t.dirty;if(!n&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&n){this._emitRenderLifecycleEvent(e,"start"),(o=this==null?void 0:this[`remove${e}`])==null||o.call(this),t.initialized=!1,t.dirty=!1,this._emitRenderLifecycleEvent(e,"end");return}const a=Hx.indexOf(e)-1;if(a>=0){const c=Hx[a];if(this._asyncEffects.filter(A=>A.phase===c).some(A=>!A.complete))return}if(this._emitRenderLifecycleEvent(e,"start"),n){i&&((s=this==null?void 0:this[`update${e}`])==null||s.call(this),t.dirty=!1),this._emitRenderLifecycleEvent(e,"end");return}t.dirty=!1,(l=this==null?void 0:this[`doInitial${e}`])==null||l.call(this),t.initialized=!0,this._emitRenderLifecycleEvent(e,"end")}runRenderPhaseForChildren(e){for(const 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))}},sk={},Dye=r=>{const e=Object.fromEntries(Object.entries(r).map(([t,n])=>[t.toLowerCase(),n]));Object.assign(sk,r),Object.assign(sk,e)},Ldt=class extends Error{constructor(e,t,n){let i;const o=Object.keys(n).filter(s=>s!=="_errors").map(s=>n[s]._errors[0]?`${s} (${n[s]._errors[0]})`:`${s} (${JSON.stringify(n[s])})`).join(", ");"name"in t?i=`Invalid props for ${e} "${t.name}": ${o}`:"footprint"in t&&typeof t.footprint=="string"?i=`Invalid props for ${e} (unnamed ${t.footprint} component): ${o}`:i=`Invalid props for ${e} (unnamed): ${o}`,super(i),this.componentName=e,this.originalProps=t,this.formattedError=n}};function rK(r,e){const t=e.match(/^#(\w+)/);if(t)return r.props.id===t[1];const n=e.match(/^\.(\w+)/);if(n)return r.isMatchingNameOrAlias(n[1]);let[i,...a]=e.split(/(?=[#.[])/);return i==="pin"&&(i="port"),i&&i!=="*"&&r.lowercaseComponentName!==i.toLowerCase()?!1:a.every(o=>{if(o.startsWith("#"))return r.props.id===o.slice(1);if(o.startsWith("."))return r.isMatchingNameOrAlias(o.slice(1));const s=o.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!s)return!0;const[,l,c]=s;return r.props[l].toString()===c})}var iK={isTag:r=>!0,getParent:r=>r.parent,getChildren:r=>r.children,getName:r=>r.lowercaseComponentName,getAttributeValue:(r,e)=>{var t;if(e==="class"&&"getNameAndAliases"in r)return r.getNameAndAliases().join(" ");if(e==="name"&&((t=r._parsedProps)!=null&&t.name))return r._parsedProps.name;if(r._parsedProps&&e in r._parsedProps){const n=r._parsedProps[e];return typeof n=="string"?n:n!=null?String(n):null}return null},hasAttrib:(r,e)=>{var t;return e==="class"?!!((t=r._parsedProps)!=null&&t.name):r._parsedProps&&e in r._parsedProps},getSiblings:r=>r.parent?r.parent.children:[],prevElementSibling:r=>{if(!r.parent)return null;const e=r.parent.children,t=e.indexOf(r);return t>0?e[t-1]:null},getText:()=>"",removeSubsets:r=>r.filter((e,t)=>!r.some((n,i)=>t!==i&&n!==e&&n.getDescendants().includes(e))),existsOne:(r,e)=>e.some(r),findAll:(r,e)=>{const t=[],n=i=>{r(i)&&t.push(i);for(const a of i.children)n(a)};for(const i of e)n(i);return t},findOne:(r,e)=>{for(const t of e){if(r(t))return t;const n=t.children;if(n.length>0){const i=iK.findOne(r,n);if(i)return i}}return null},equals:(r,e)=>r._renderId===e._renderId,isHovered:r=>!1,isVisited:r=>!1,isActive:r=>!1},Gdt={...iK,getChildren:r=>r.children.filter(e=>!e.isSubcircuit)},Rye={...iK,getChildren:r=>r.children.filter(e=>e.isSubcircuit)},Nye=r=>{if(/net\.[^\s>]*\./.test(r))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\.[0-9]/.test(r))throw new Error('Net names cannot start with a number, try using a prefix like "VBUS1"');return r.replace(/ pin/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,(e,t,n,i)=>{const a=/^\d+$/.test(i)?`pin${i}`:i;return`${t}.${n} > .${a}`}).trim()},aK={adapter:Gdt,cacheResults:!0},$v=class extends Mye{constructor(t){super(t);Ke(this,"parent",null);Ke(this,"children");Ke(this,"childrenPendingRemoval");Ke(this,"props");Ke(this,"_parsedProps");Ke(this,"externallyAddedAliases");Ke(this,"isPrimitiveContainer",!1);Ke(this,"source_group_id",null);Ke(this,"source_component_id",null);Ke(this,"schematic_component_id",null);Ke(this,"pcb_component_id",null);Ke(this,"cad_component_id",null);Ke(this,"_cachedSelectAllQueries",new Map);Ke(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=t??{},this.externallyAddedAliases=[];const n=this.config.zodProps.safeParse(t??{});if(n.success)this._parsedProps=n.data;else throw new Ldt(this.lowercaseComponentName,this.props,n.error.format())}get config(){return{componentName:"",zodProps:tn({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(t){var i;let n=this;for(;n;){if(n._parsedProps&&t in n._parsedProps)return n._parsedProps[t];n=n.parent}if((i=this.root)!=null&&i.platform&&t in this.root.platform)return this.root.platform[t]}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){var t;return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&((t=this==null?void 0:this.parent)==null?void 0:t.isRoot)}get isGroup(){return this.lowercaseComponentName==="group"}setProps(t){var a,o;const 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)}),(o=(a=this.parent)==null?void 0:a.onChildChanged)==null||o.call(a,this)}computePcbPropsTransform(){const{_parsedProps:t}=this;return Fu(Od(t.pcbX??0,t.pcbY??0),px((t.pcbRotation??0)*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){var i,a,o;const{_parsedProps:t}=this,n=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(n&&this.props.pcbX===void 0&&this.props.pcbY===void 0)return Fu(((i=this.parent)==null?void 0:i._computePcbGlobalTransformBeforeLayout())??wy(),Fu(Od(n.x,n.y),px((t.pcbRotation??0)*Math.PI/180)));if(this.isPcbPrimitive){const s=this.getPrimitiveContainer();if(s){const l=s._parsedProps.layer==="bottom",c=s._getGlobalPcbPositionBeforeLayout();if(l)return Fu(Od(c.x,c.y),Y5(),Od(-c.x,-c.y)),Fu(((a=this.parent)==null?void 0:a._computePcbGlobalTransformBeforeLayout())??wy(),Y5(),this.computePcbPropsTransform())}}return Fu(((o=this.parent)==null?void 0:o._computePcbGlobalTransformBeforeLayout())??wy(),this.computePcbPropsTransform())}getPrimitiveContainer(){var t,n;return this.isPrimitiveContainer?this:((n=(t=this.parent)==null?void 0:t.getPrimitiveContainer)==null?void 0:n.call(t))??null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){const t=this.getPrimitiveContainer(),n=t?t._parsedProps.layer==="bottom":!1;return{isFlipped:n,maybeFlipLayer:a=>n?a==="top"?"bottom":"top":a}}_setPositionFromLayout(t){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){const{_parsedProps:t}=this;return Fu(Od(t.schX??0,t.schY??0))}computeSchematicGlobalTransform(){var n,i;const t=this._getSchematicGlobalManualPlacementTransform(this);return t||Fu(((i=(n=this.parent)==null?void 0:n.computeSchematicGlobalTransform)==null?void 0:i.call(n))??wy(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){const{_parsedProps:t}=this,n=this.config.schematicSymbolName;let i=t.schRotation;if(i===void 0&&(i=0),i=i%360,i<0&&(i+=360),t.schRotation!==void 0&&i%90!==0)throw new Error(`Schematic rotation ${t.schRotation} is not supported for ${this.componentName}`);const a=`${n}_horz`,o=`${n}_vert`,s=`${n}_up`,l=`${n}_down`,c=`${n}_left`,u=`${n}_right`;if(u in yI&&i===0)return u;if(s in yI&&i===90)return s;if(c in yI&&i===180)return c;if(l in yI&&i===270)return l;if(a in yI&&(i===0||i===180))return a;if(o in yI&&(i===90||i===270))return o;if(n in yI)return n}_getSchematicSymbolNameOrThrow(){const t=this._getSchematicSymbolName();if(!t)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return t}getSchematicSymbol(){const t=this._getSchematicSymbolName();return t?yI[t]??null:null}_getPcbManualPlacementForComponent(t){var o;if(!this.isSubcircuit)return null;const n=this.props.layout,i=this.props.manualEdits;if(!n&&!i)return null;const a=((o=n==null?void 0:n.manual_pcb_placement_config)==null?void 0:o.positions)||(i==null?void 0:i.pcb_placements);if(!a)return null;for(const s of a)if(n&&rK(t,s.selector)||t.props.name===s.selector)return ti(this._computePcbGlobalTransformBeforeLayout(),s.center);return null}_getSchematicManualPlacementForComponent(t){if(!this.isSubcircuit)return null;const n=this.props.manualEdits;if(!n)return null;const i=n.schematic_placements;if(!i)return null;for(const a of i)if(rK(t,a.selector)||t.props.name===a.selector)return ti(this.computeSchematicGlobalTransform(),a.center);return null}_getSchematicGlobalManualPlacementTransform(t){var i,a;const n=(i=this.getSubcircuit())==null?void 0:i._parsedProps.manualEdits;if(!n)return null;for(const o of n.schematic_placements??[])if((rK(t,o.selector)||t.props.name===o.selector)&&o.relative_to==="group_center")return Fu(((a=this.parent)==null?void 0:a._computePcbGlobalTransformBeforeLayout())??wy(),Od(o.center.x,o.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return ti(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return ti(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){var t;return((t=this.parent)==null?void 0:t.root)??null}onAddToParent(t){this.parent=t}onPropsChange(t){}onChildChanged(t){var n,i;(i=(n=this.parent)==null?void 0:n.onChildChanged)==null||i.call(n,t)}add(t){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(const n of t)this.add(n)}remove(t){this.children=this.children.filter(n=>n!==t),this.childrenPendingRemoval.push(t),t.shouldBeRemoved=!0}getSubcircuitSelector(){const t=this._parsedProps.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?n:`${this.parent.getSubcircuitSelector()} > ${n}`}getFullPathSelector(){var a,o;const t=this._parsedProps.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName,i=(o=(a=this.parent)==null?void 0:a.getFullPathSelector)==null?void 0:o.call(a);return i?`${i} > ${n}`:n}getNameAndAliases(){return[this._parsedProps.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){const n=[this.componentName,this.lowercaseComponentName],i=[this._parsedProps.name].filter(Boolean),a=t.trim().split(/\> /)[0],o=a[0];return a.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(){var n,i;if(this.isSubcircuit)return this;const t=(i=(n=this.parent)==null?void 0:n.getSubcircuit)==null?void 0:i.call(n);if(!t)throw new Error("Component is not inside an opaque group (no board?)");return t}getGroup(){var t,n;return this.isGroup?this:((n=(t=this.parent)==null?void 0:t.getGroup)==null?void 0:n.call(t))??null}doInitialOptimizeSelectorCache(){var n;if(!this.isSubcircuit)return;const t=this.selectAll("port");for(const i of t){const a=(n=i.parent)==null?void 0:n.getNameAndAliases(),o=i.getNameAndAliases();if(a)for(const s of a)for(const l of o){const c=[`.${s} > .${l}`,`.${s} .${l}`];for(const u of c){const A=this._cachedSelectAllQueries.get(u);A?A.push(i):this._cachedSelectAllQueries.set(u,[i])}}}for(const[i,a]of this._cachedSelectAllQueries.entries())a.length===1&&this._cachedSelectOneQueries.set(i,a[0])}selectAll(t){if(this._cachedSelectAllQueries.has(t))return this._cachedSelectAllQueries.get(t);const n=Nye(t),i=IP(n,this,aK);if(i.length>0)return this._cachedSelectAllQueries.set(t,i),i;const[a,...o]=n.split(" "),s=rM(a,this,{adapter:Rye});if(!s)return[];const l=s.selectAll(o.join(" "));return this._cachedSelectAllQueries.set(t,l),l}selectOne(t,n){if(this._cachedSelectOneQueries.has(t))return this._cachedSelectOneQueries.get(t);const i=Nye(t);n!=null&&n.port&&(n.type="port");let a=null;if(n!=null&&n.type&&(a=IP(i,this,aK).find(u=>u.lowercaseComponentName===n.type)),a??(a=rM(i,this,aK)),a)return this._cachedSelectOneQueries.set(t,a),a;const[o,...s]=i.split(" "),l=rM(o,this,{adapter:Rye});return l?(a=l.selectOne(s.join(" "),n),this._cachedSelectOneQueries.set(t,a),a):null}getAvailablePcbLayers(){var t,n;if(this.isPcbPrimitive){const{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[i(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?((n=(t=this.root)==null?void 0:t._getBoard())==null?void 0:n.allLayers)??["top","bottom"]:[]}return[]}getDescendants(){const t=[];for(const n of this.children)t.push(n),t.push(...n.getDescendants());return t}getSelectableDescendants(){const t=[];for(const 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;const{_parsedProps:t}=this;return{schWidth:t.schWidth,schHeight:t.schHeight}}renderError(t){var n;if(typeof t=="string")return super.renderError(t);(n=this.root)==null||n.db.pcb_placement_error.insert(t)}getString(){var a,o;const{lowercaseComponentName:t,_parsedProps:n,parent:i}=this;return(n==null?void 0:n.pinNumber)!==void 0&&((a=i==null?void 0:i.props)!=null&&a.name)&&(n!=null&&n.name)?`<${t}#${this._renderId}(pin:${n.pinNumber} .${i==null?void 0:i.props.name}>.${n.name}) />`:(o=i==null?void 0:i.props)!=null&&o.name&&(n!=null&&n.name)?`<${t}#${this._renderId}(.${i==null?void 0:i.props.name}>.${n==null?void 0:n.name}) />`:n!=null&&n.from&&(n!=null&&n.to)?`<${t}#${this._renderId}(from:${n.from} to:${n==null?void 0:n.to}) />`:n!=null&&n.name?`<${t}#${this._renderId} name=".${n==null?void 0:n.name}" />`:n!=null&&n.portHints?`<${t}#${this._renderId}(${n.portHints.map(s=>`.${s}`).join(", ")}) />`:`<${t}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},Odt=class extends $v{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:tn({}).passthrough()}}doInitialSourceRender(){var e,t,n,i;if((e=this.root)!=null&&e.db){const a=this._getGlobalPcbPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,message:((i=(n=(t=this._parsedProps.error)==null?void 0:t.formattedError)==null?void 0:n._errors)==null?void 0:i.join("; "))||this._parsedProps.message,pcb_center:a,schematic_center:o})}}};function zdt(r,e){return new Odt(r,e)}function Hdt(r,e){const t=r;return t.__tsci={...e},r}var Tye={supportsMutation:!0,createInstance(r,e){const t=sk[r];if(!t)throw Object.keys(sk).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 (not registered in @tscircuit/core catalogue): "${r}" See CREATING_NEW_COMPONENTS.md`);try{return Hdt(new t(e),{})}catch(n){return zdt(e,n)}},createTextInstance(){return{}},appendInitialChild(r,e){r.add(e)},appendChild(r,e){r.add(e)},appendChildToContainer(r,e){r.add(e)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(r){return r},preparePortalMount(r){throw new Error("Function not implemented.")},scheduleTimeout(r,e){throw new Error("Function not implemented.")},cancelTimeout(r){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(r){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(r,e)=>{throw new Error("Function not implemented.")},getInstanceFromScope:r=>{throw new Error("Function not implemented.")},detachDeletedInstance:r=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>X9.DefaultEventPriority,getCurrentUpdatePriority:()=>X9.DefaultEventPriority,resolveUpdatePriority:()=>X9.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},aQ;Uu.version.startsWith("19.")?aQ=tfe(Tye):aQ=afe(Tye);var Pye=r=>{const e={children:[],props:{name:"$root"},add(a){a.parent=this,this.children.push(a)},computePcbGlobalTransform(){return wy()}},t=[],n=aQ.createContainer(e,0,null,!1,null,"tsci",a=>{console.log("Error in createContainer"),console.error(a),t.push(a)},null);if(Uu.version.startsWith("19.")?(aQ.updateContainerSync(r,n,null,()=>{}),aQ.flushSyncWork()):aQ.updateContainer(r,n,null,()=>{}),t.length>0)throw t[0];const i=aQ.getPublicRootInstance(n);return i||e.children[0]},fD=(r,e)=>{if(typeof r=="number")return r;if(r.startsWith("pin"))return Number(r.slice(3));if(!e)throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`);for(const t in e)if((Array.isArray(e[t])?e[t]:[e[t]]).includes(r))return Number(t.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`)},Ydt=(r,e)=>{if(!r)return;const t={},n={};for(const[i,a]of Object.entries(r)){const o=fD(i,e);n[o]={...n[o],...a}}for(const[i,a]of Object.entries(n)){const o=`pin${i}`;t[o]={bottom_margin:a.bottomMargin,left_margin:a.leftMargin,right_margin:a.rightMargin,top_margin:a.topMargin}}return t},Vdt=r=>{if(r){if("leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r)return{left_side:r.leftSide,right_side:r.rightSide,top_side:r.topSide,bottom_side:r.bottomSide};if("leftPinCount"in r||"rightPinCount"in r||"topPinCount"in r||"bottomPinCount"in r)return{left_size:r.leftPinCount,right_size:r.rightPinCount,top_size:r.topPinCount,bottom_size:r.bottomPinCount};if("leftSize"in r||"rightSize"in r||"topSize"in r||"bottomSize"in r)return{left_size:r.leftSize,right_size:r.rightSize,top_size:r.topSize,bottom_size:r.bottomSize}}};function kye(r){const e=[];for(let t=0;t<r.length-1;t++)e.push([r[t],r[t+1]]);return e}var Kdt=tn({name:Be()}),Uye=class extends $v{constructor(){super(...arguments);Ke(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:Kdt}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_net.insert({name:n.name,member_source_group_ids:[]});this.source_net_id=i.source_net_id}doInitialSourceParentAttachment(){const t=this.getSubcircuit();if(!t)return;const{db:n}=this.root;n.source_net.update(this.source_net_id,{subcircuit_id:t.subcircuit_id})}getAllConnectedPorts(){const t=this.getSubcircuit().selectAll("port"),n=[];for(const i of t){const a=i._getDirectlyConnectedTraces();for(const o of a)if(o._isExplicitlyConnectedToNet(this)){n.push(i);break}}return n}_getAllDirectlyConnectedTraces(){const t=this.getSubcircuit().selectAll("trace"),n=[];for(const i of t)i._isExplicitlyConnectedToNet(this)&&n.push(i);return n}doInitialPcbRouteNetIslands(){var s;if((s=this.root)!=null&&s.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;const{db:t}=this.root,{_parsedProps:n}=this,i=this._getAllDirectlyConnectedTraces().filter(l=>{var c;return(((c=l._portsRoutedOnPcb)==null?void 0:c.length)??0)>0}),a=[];for(const l of i){const c=l._portsRoutedOnPcb,u=a.find(A=>c.some(d=>A.ports.includes(d)));if(!u){a.push({ports:[...c],traces:[l]});continue}u.traces.push(l),u.ports.push(...c)}if(a.length===0)return;const o=kye(a);for(const[l,c]of o){const u=l.ports.map(B=>B._getGlobalPcbPositionBeforeLayout()),A=c.ports.map(B=>B._getGlobalPcbPositionBeforeLayout());let d=1/0,f=[-1,-1];for(let B=0;B<u.length;B++){const P=u[B];for(let L=0;L<A.length;L++){const U=A[L],H=Math.sqrt((P.x-U.x)**2+(P.y-U.y)**2);H<d&&(d=H,f=[B,L])}}const g=l.ports[f[0]],_=c.ports[f[1]],I=t.toArray().filter(B=>B.type==="pcb_smtpad"||B.type==="pcb_trace"||B.type==="pcb_plated_hole"||B.type==="pcb_hole"||B.type==="source_port"||B.type==="pcb_port"),{solution:E}=x0e(I.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[g.source_port_id,_.source_port_id]}])),x=E[0];if(!x){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[g.pcb_component_id,_.pcb_component_id].filter(Boolean),pcb_port_ids:[g.pcb_port_id,_.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}t.pcb_trace.insert(x)}}renderError(t){var n;if(typeof t=="string")return super.renderError(t);(n=this.root)==null||n.db.pcb_trace_error.insert(t)}},Fye=(r,e)=>{for(const t of e)if(typeof t=="string"&&t.startsWith("net.")){if(/net\.[^\s>]*\./.test(t))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[0-9]/.test(t))throw new Error('Net names cannot start with a number, try using a prefix like "VBUS1"');const n=r.getSubcircuit();if(!n.selectOne(t)){const i=new Uye({name:t.split("net.")[1]});n.add(i)}}},oK=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_smtpad_id",null);Ke(this,"matchedPort",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:O0e}}getPcbSize(){const{_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};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){var n;const t=(n=this.getPrimitiveContainer())==null?void 0:n.selectAll("port");if(this.props.portHints){for(const i of t)if(i.isMatchingAnyOf(this.props.portHints)){this.matchedPort=i,i.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){var f,g,_,I,E,x,B,P,L,U;if((f=this.root)!=null&&f.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this;if(!n.portHints)return;const i=this.getPrimitiveContainer(),a=this.getSubcircuit(),o=this._getGlobalPcbPositionBeforeLayout();i==null||i._getGlobalPcbPositionBeforeLayout();const s=Zw(this._computePcbGlobalTransformBeforeLayout()),l=Math.abs(s.rotation.angle*(180/Math.PI)-90)%180<.01,{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),u=(i==null?void 0:i._parsedProps.pcbRotation)??0;let A=null;const d=((g=this.parent)==null?void 0:g.pcb_component_id)??((_=this.getPrimitiveContainer())==null?void 0:_.pcb_component_id);n.shape==="circle"?(A=t.pcb_smtpad.insert({pcb_component_id:d,pcb_port_id:(I=this.matchedPort)==null?void 0:I.pcb_port_id,layer:c(n.layer??"top"),shape:"circle",radius:n.radius,port_hints:n.portHints.map(H=>H.toString()),x:o.x,y:o.y,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0}),t.pcb_solder_paste.insert({layer:A.layer,shape:"circle",radius:A.radius*.7,x:A.x,y:A.y,pcb_component_id:A.pcb_component_id,pcb_smtpad_id:A.pcb_smtpad_id,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((E=this.getGroup())==null?void 0:E.pcb_group_id)??void 0})):n.shape==="rect"&&(A=u===0||l?t.pcb_smtpad.insert({pcb_component_id:d,pcb_port_id:(x=this.matchedPort)==null?void 0:x.pcb_port_id,layer:c(n.layer??"top"),shape:"rect",width:l?n.height:n.width,height:l?n.width:n.height,port_hints:n.portHints.map(H=>H.toString()),x:o.x,y:o.y,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((B=this.getGroup())==null?void 0:B.pcb_group_id)??void 0}):t.pcb_smtpad.insert({pcb_component_id:d,layer:c(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(H=>H.toString()),subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((P=this.getGroup())==null?void 0:P.pcb_group_id)??void 0}),A.shape==="rect"&&t.pcb_solder_paste.insert({layer:c(n.layer??"top"),shape:"rect",width:A.width*.7,height:A.height*.7,x:A.x,y:A.y,pcb_component_id:A.pcb_component_id,pcb_smtpad_id:A.pcb_smtpad_id,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((L=this.getGroup())==null?void 0:L.pcb_group_id)??void 0}),A.shape==="rotated_rect"&&t.pcb_solder_paste.insert({layer:c(n.layer??"top"),shape:"rotated_rect",width:A.width*.7,height:A.height*.7,x:A.x,y:A.y,ccw_rotation:u,pcb_component_id:A.pcb_component_id,pcb_smtpad_id:A.pcb_smtpad_id,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((U=this.getGroup())==null?void 0:U.pcb_group_id)??void 0})),A&&(this.pcb_smtpad_id=A.pcb_smtpad_id)}doInitialPcbPortAttachment(){var n,i;if((n=this.root)!=null&&n.pcbDisabled)return;const{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:(i=this.matchedPort)==null?void 0:i.pcb_port_id})}_getPcbCircuitJsonBounds(){const{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"){const i=n.ccw_rotation*Math.PI/180,a=Math.cos(i),o=Math.sin(i),s=n.width/2,l=n.height/2,c=Math.abs(s*a)+Math.abs(l*o),u=Math.abs(s*o)+Math.abs(l*a);return{center:{x:n.x,y:n.y},bounds:{left:n.x-c,right:n.x+c,top:n.y-u,bottom:n.y+u},width:c*2,height:u*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};throw new Error(`circuitJson bounds calculation not implemented for shape "${n.shape}"`)}_setPositionFromLayout(t){var a;const{db:n}=this.root;n.pcb_smtpad.update(this.pcb_smtpad_id,{x:t.x,y:t.y});const i=n.pcb_solder_paste.list().find(o=>o.pcb_smtpad_id===this.pcb_smtpad_id);n.pcb_solder_paste.update(i==null?void 0:i.pcb_solder_paste_id,{x:t.x,y:t.y}),(a=this.matchedPort)==null||a._setPositionFromLayout(t)}},Lye=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_silkscreen_path_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:ume}}doInitialPcbPrimitiveRender(){var c,u,A;if((c=this.root)!=null&&c.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),a=i(n.layer??"top");if(a!=="top"&&a!=="bottom")throw new Error(`Invalid layer "${a}" for SilkscreenPath. Must be "top" or "bottom".`);const o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),l=t.pcb_silkscreen_path.insert({pcb_component_id:(u=this.parent)==null?void 0:u.pcb_component_id,layer:a,route:n.route.map(d=>{const f=ti(o,{x:d.x,y:d.y});return{...d,x:f.x,y:f.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:(s==null?void 0:s.subcircuit_id)??void 0,pcb_group_id:((A=this.getGroup())==null?void 0:A.pcb_group_id)??void 0});this.pcb_silkscreen_path_id=l.pcb_silkscreen_path_id}getPcbSize(){const{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,a=1/0,o=-1/0;for(const s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),a=Math.min(a,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-a}}},jdt=tn({route:hi(ST),source_trace_id:Be().optional()}),Gye=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_trace_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:jdt}}doInitialPcbPrimitiveRender(){var u,A;if((u=this.root)!=null&&u.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),a=this.getSubcircuit(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),s=this._computePcbGlobalTransformBeforeLayout(),l=n.route.map(d=>{const{x:f,y:g,..._}=d,I=ti(s,{x:f,y:g});return d.route_type==="wire"&&d.layer?{...I,..._,layer:o(d.layer)}:{...I,..._}}),c=t.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:n.source_trace_id,route:l,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((A=this.getGroup())==null?void 0:A.pcb_group_id)??void 0});this.pcb_trace_id=c.pcb_trace_id}getPcbSize(){const{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,a=1/0,o=-1/0;for(const s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),a=Math.min(a,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),a=Math.min(a,s.y-s.width/2),o=Math.max(o,s.y+s.width/2));return n===1/0||i===-1/0||a===1/0||o===-1/0?{width:0,height:0}:{width:i-n,height:o-a}}},sK=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_plated_hole_id",null);Ke(this,"matchedPort",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:R0e}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){const{_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(){const{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){var i;const{db:n}=this.root;n.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:t.x,y:t.y}),(i=this.matchedPort)==null||i._setPositionFromLayout(t)}doInitialPortMatching(){var n;const t=(n=this.getPrimitiveContainer())==null?void 0:n.selectAll("port");if(this.props.portHints){for(const i of t)if(i.isMatchingAnyOf(this.props.portHints)){this.matchedPort=i,i.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){var s,l,c,u,A,d,f,g,_,I,E,x,B,P,L;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),a=((l=this.parent)==null?void 0:l.pcb_component_id)??((c=this.getPrimitiveContainer())==null?void 0:c.pcb_component_id),o=this.getSubcircuit();if(n.shape==="circle"){const U=t.pcb_plated_hole.insert({pcb_component_id:a,pcb_port_id:(u=this.matchedPort)==null?void 0:u.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==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((A=this.getGroup())==null?void 0:A.pcb_group_id)??void 0});this.pcb_plated_hole_id=U.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==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((d=this.getGroup())==null?void 0:d.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==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((f=this.getGroup())==null?void 0:f.pcb_group_id)??void 0})}else if(n.shape==="pill"||n.shape==="oval"){const U=t.pcb_plated_hole.insert({pcb_component_id:a,pcb_port_id:(g=this.matchedPort)==null?void 0:g.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==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((_=this.getGroup())==null?void 0:_.pcb_group_id)??void 0});this.pcb_plated_hole_id=U.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==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((I=this.getGroup())==null?void 0:I.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==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((E=this.getGroup())==null?void 0:E.pcb_group_id)??void 0})}else if(n.shape==="circular_hole_with_rect_pad"){const U=t.pcb_plated_hole.insert({pcb_component_id:a,pcb_port_id:(x=this.matchedPort)==null?void 0:x.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==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((B=this.getGroup())==null?void 0:B.pcb_group_id)??void 0});this.pcb_plated_hole_id=U.pcb_plated_hole_id}else if(n.shape==="pill_hole_with_rect_pad"){const U=t.pcb_plated_hole.insert({pcb_component_id:a,pcb_port_id:(P=this.matchedPort)==null?void 0:P.pcb_port_id,hole_width:n.holeWidth,hole_height:n.holeHeight,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((L=this.getGroup())==null?void 0:L.pcb_group_id)??void 0});this.pcb_plated_hole_id=U.pcb_plated_hole_id}}doInitialPcbPortAttachment(){var n,i;if((n=this.root)!=null&&n.pcbDisabled)return;const{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:(i=this.matchedPort)==null?void 0:i.pcb_port_id})}},lK=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_keepout_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:ame}}doInitialPcbPrimitiveRender(){var c,u,A;if((c=this.root)!=null&&c.pcbDisabled)return;const t=this.getSubcircuit(),{db:n}=this.root,{_parsedProps:i}=this,a=this._getGlobalPcbPositionBeforeLayout(),o=Zw(this._computePcbGlobalTransformBeforeLayout()),s=Math.abs(o.rotation.angle*(180/Math.PI)-90)%180<.01;let l=null;i.shape==="circle"?l=n.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:a.x,y:a.y},subcircuit_id:(t==null?void 0:t.subcircuit_id)??void 0,pcb_group_id:((u=t==null?void 0:t.getGroup())==null?void 0:u.pcb_group_id)??void 0}):i.shape==="rect"&&(l=n.pcb_keepout.insert({layers:["top"],shape:"rect",...s?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:a.x,y:a.y},subcircuit_id:(t==null?void 0:t.subcircuit_id)??void 0,pcb_group_id:((A=t==null?void 0:t.getGroup())==null?void 0:A.pcb_group_id)??void 0})),l&&(this.pcb_keepout_id=l.pcb_keepout_id)}},Oye=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_hole_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:z0e}}getPcbSize(){const{_parsedProps:t}=this;return{width:t.diameter,height:t.diameter}}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),a=this._getGlobalPcbPositionBeforeLayout(),o=t.pcb_hole.insert({hole_shape:"circle",hole_diameter:n.diameter,x:a.x,y:a.y,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((l=i==null?void 0:i.getGroup())==null?void 0:l.pcb_group_id)??void 0});this.pcb_hole_id=o.pcb_hole_id}_getPcbCircuitJsonBounds(){const{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){const{db:n}=this.root;n.pcb_hole.update(this.pcb_hole_id,{x:t.x,y:t.y})}},cK=class extends $v{constructor(){super(...arguments);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:cme}}doInitialPcbPrimitiveRender(){var l,c;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),a=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),s=this.getSubcircuit();t.pcb_silkscreen_text.insert({anchor_alignment:n.anchorAlignment,anchor_position:{x:a.x,y:a.y},font:n.font??"tscircuit2024",font_size:n.fontSize??1,layer:o(n.layer??"top"),text:n.text??"",ccw_rotation:n.pcbRotation,pcb_component_id:i.pcb_component_id,subcircuit_id:(s==null?void 0:s.subcircuit_id)??void 0,pcb_group_id:((c=this.getGroup())==null?void 0:c.pcb_group_id)??void 0})}getPcbSize(){const{_parsedProps:t}=this,n=t.fontSize??1,a=(t.text??"").length*n,o=n;return{width:a*n,height:o*n}}},Jdt=({elm:r,pinLabels:e,layer:t,readableRotation:n,anchorAlignment:i})=>{const a=r.text.replace(/[{}]/g,"").toLowerCase();let o=a;if(Array.isArray(e)){const s=parseInt(a.replace(/[^\d]/g,""),10)-1;o=String(e[s]??a)}else typeof e=="object"&&(o=String(e[a]??a));return new cK({anchorAlignment:i||"center",text:o??a,layer:t||"top",fontSize:r.font_size+.2,pcbX:isNaN(r.anchor_position.x)?0:r.anchor_position.x,pcbY:r.anchor_position.y,pcbRotation:n??0})},Wdt=(r,e)=>((-parseInt(r||"0",10)+(e??0))%360+360)%360,zye=({componentName:r,componentRotation:e,footprint:t,pinLabels:n},i)=>{const a=[];for(const o of i)if(o.type==="pcb_smtpad"&&o.shape==="rect")a.push(new oK({pcbX:o.x,pcbY:o.y,layer:o.layer,shape:"rect",height:o.height,width:o.width,portHints:o.port_hints}));else if(o.type==="pcb_smtpad"&&o.shape==="circle")a.push(new oK({pcbX:o.x,pcbY:o.y,layer:o.layer,shape:"circle",radius:o.radius,portHints:o.port_hints}));else if(o.type==="pcb_silkscreen_path")a.push(new Lye({layer:o.layer,route:o.route,strokeWidth:o.stroke_width}));else if(o.type==="pcb_plated_hole")o.shape==="circle"?a.push(new sK({pcbX:o.x,pcbY:o.y,shape:"circle",holeDiameter:o.hole_diameter,outerDiameter:o.outer_diameter,portHints:o.port_hints})):o.shape==="circular_hole_with_rect_pad"&&a.push(new sK({pcbX:o.x,pcbY:o.y,shape:"circular_hole_with_rect_pad",holeDiameter:o.hole_diameter,rectPadHeight:o.rect_pad_height,rectPadWidth:o.rect_pad_width,portHints:o.port_hints}));else if(o.type==="pcb_keepout"&&o.shape==="circle")a.push(new lK({pcbX:o.center.x,pcbY:o.center.y,shape:"circle",radius:o.radius}));else if(o.type==="pcb_keepout"&&o.shape==="rect")a.push(new lK({pcbX:o.center.x,pcbY:o.center.y,shape:"rect",width:o.width,height:o.height}));else if(o.type==="pcb_hole"&&o.hole_shape==="circle")a.push(new Oye({pcbX:o.x,pcbY:o.y,diameter:o.hole_diameter}));else if(o.type==="pcb_silkscreen_text"){const s=Wdt(e,o.ccw_rotation);t.includes("pinrow")&&o.text.includes("PIN")?a.push(Jdt({elm:o,pinLabels:n,layer:o.layer,readableRotation:s,anchorAlignment:o.anchor_alignment})):a.push(new cK({anchorAlignment:o.anchor_alignment||"center",text:r,fontSize:o.font_size+.2,pcbX:isNaN(o.anchor_position.x)?0:o.anchor_position.x,pcbY:o.anchor_position.y,pcbRotation:s??0}))}else o.type==="pcb_trace"&&a.push(new Gye({route:o.route}));return a};function uK(r){let e=1/0,t=1/0,n=-1/0,i=-1/0,a=!1;for(const l of r)if(l.isPcbPrimitive&&!l.componentName.startsWith("Silkscreen")){const{x:c,y:u}=l._getGlobalPcbPositionBeforeLayout(),{width:A,height:d}=l.getPcbSize();e=Math.min(e,c-A/2),t=Math.min(t,u-d/2),n=Math.max(n,c+A/2),i=Math.max(i,u+d/2),a=!0}else if(l.children.length>0){const c=uK(l.children);(c.width>0||c.height>0)&&(e=Math.min(e,c.minX),t=Math.min(t,c.minY),n=Math.max(n,c.maxX),i=Math.max(i,c.maxY),a=!0)}if(!a)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let o=n-e,s=i-t;return o<0&&(o=0),s<0&&(s=0),{minX:e,minY:t,maxX:n,maxY:i,width:o,height:s}}function qdt(r,e){const t=e.x-r.x,n=e.y-r.y;return Math.abs(t)>Math.abs(n)?t>=0?"right":"left":n>=0?"up":"down"}var Zdt=r=>{if(r.length<=1)return!0;const e=r.map(a=>{const o=a._getPcbCircuitJsonBounds();return{left:o.bounds.left,right:o.bounds.right,top:o.bounds.top,bottom:o.bounds.bottom}}),t=Array(e.length).fill(!1).map(()=>Array(e.length).fill(!1));for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++){const s=e[a],l=e[o];t[a][o]=t[o][a]=!(s.right<l.left||s.left>l.right||s.bottom>l.top||s.top<l.bottom)}const n=new Set,i=a=>{n.add(a);for(let o=0;o<e.length;o++)t[a][o]&&!n.has(o)&&i(o)};return i(0),n.size===e.length},Xdt=r=>{if(r.length===0)throw new Error("Cannot get center of empty PCB primitives array");const e=r.map(i=>i._getPcbCircuitJsonBounds().center).filter(Boolean),t=e.reduce((i,a)=>i+a.x,0),n=e.reduce((i,a)=>i+a.y,0);return{x:t/e.length,y:n/e.length}},$dt=tn({name:Be().optional(),pinNumber:yn().optional(),aliases:hi(Be()).optional()}),GS=class extends $v{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);Ke(this,"source_port_id",null);Ke(this,"pcb_port_id",null);Ke(this,"schematic_port_id",null);Ke(this,"schematicSymbolPortDef",null);Ke(this,"matchedComponents");Ke(this,"facingDirection",null);Ke(this,"originDescription",null);n.originDescription&&(this.originDescription=n.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:$dt}}_getGlobalPcbPositionBeforeLayout(){const 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==null?void 0:t._getGlobalPcbPositionBeforeLayout())??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();const{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(){const t=this.parent;if(!t||!t._getInternallyConnectedPins)return[];const n=t._getInternallyConnectedPins();for(const i of n)if(i.some(a=>a===this))return i;return[]}_hasSchematicPort(){var i,a;if((i=this.parent)==null?void 0:i.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(s=>s.schematicSymbolPortDef));const n=(a=this==null?void 0:this.parent)==null?void 0:a._getSchematicBoxDimensions();return!!(n&&this.props.pinNumber!==void 0&&n.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){var i,a,o;const t=(i=this.parent)==null?void 0:i.getSchematicSymbol();if(t){let s=this.schematicSymbolPortDef;if(!s&&(s=((a=this._getPortsInternallyConnectedToThisPort().find(c=>c.schematicSymbolPortDef))==null?void 0:a.schematicSymbolPortDef)??null,!s))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?`);const l=Fu(this.parent.computeSchematicGlobalTransform(),Od(-t.center.x,-t.center.y));return ti(l,s)}const n=(o=this==null?void 0:this.parent)==null?void 0:o._getSchematicBoxDimensions();if(n&&this.props.pinNumber!==void 0){const s=n.getPortPositionByPinNumber(this.props.pinNumber);if(!s)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return ti(this.parent.computeSchematicGlobalTransform(),s)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){const{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`);const 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(){const{_parsedProps:t}=this;return Array.from(new Set([...t.aliases??[],...t.name?[t.name]:[],...typeof t.pinNumber=="number"?[`pin${t.pinNumber}`,t.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}isMatchingPort(t){return this.isMatchingAnyOf(t.getNameAndAliases())}getPortSelector(){var t;return`.${(t=this.parent)==null?void 0:t.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){return Array.from(new Set(this.matchedComponents.flatMap(t=>t.getAvailablePcbLayers())))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(i=>i._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){var o,s;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getNameAndAliases(),a=t.source_port.insert({name:n.name,pin_number:n.pinNumber,port_hints:i,source_component_id:(o=this.parent)==null?void 0:o.source_component_id,subcircuit_id:(s=this.getSubcircuit())==null?void 0:s.subcircuit_id});this.source_port_id=a.source_port_id}doInitialSourceParentAttachment(){var n,i,a,o,s;const{db:t}=this.root;if(!((n=this.parent)!=null&&n.source_component_id))throw new Error(`${this.getString()} has no parent source component (parent: ${(i=this.parent)==null?void 0:i.getString()})`);t.source_port.update(this.source_port_id,{source_component_id:(a=this.parent)==null?void 0:a.source_component_id,subcircuit_id:(o=this.getSubcircuit())==null?void 0:o.subcircuit_id}),this.source_component_id=(s=this.parent)==null?void 0:s.source_component_id}doInitialPcbPortRender(){var o,s,l,c,u;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:t}=this.root,{matchedComponents:n}=this;if(!((s=this.parent)!=null&&s.pcb_component_id))throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${(l=this.parent)==null?void 0:l.getString()})`);const i=n.filter(A=>A.isPcbPrimitive);if(i.length===0)return;let a=null;if(i.length===1&&(a=i[0]._getPcbCircuitJsonBounds().center),i.length>1){if(!Zdt(i))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${i.map(A=>A.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);a=Xdt(i)}if(a){const A=this.getSubcircuit(),d=t.pcb_port.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:(A==null?void 0:A.subcircuit_id)??void 0,pcb_group_id:((u=this.getGroup())==null?void 0:u.pcb_group_id)??void 0,...a,source_port_id:this.source_port_id});this.pcb_port_id=d.pcb_port_id}else{const A=i[0];throw new Error(`${A.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}doInitialSchematicPortRender(){var d;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer();if(!i||!this._hasSchematicPort())return;const a=i._getGlobalSchematicPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout();let s=null;const l=i._getSchematicBoxDimensions();l&&n.pinNumber!==void 0&&(s=l.getPortPositionByPinNumber(n.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&t.schematic_debug_object.insert({shape:"rect",center:o,size:{width:.1,height:.1},label:"obstacle"}),s!=null&&s.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[s.side]:this.facingDirection=qdt(a,o);const c=t.source_port.get(this.source_port_id);let u;for(const f of(c==null?void 0:c.port_hints)??[])f.match(/^(pin)?\d+$/)||f.match(/^(left|right)/)&&!(c!=null&&c.name.match(/^(left|right)/))||(u=f);const A=t.schematic_port.insert({schematic_component_id:(d=this.parent)==null?void 0:d.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==null?void 0:s.side,pin_number:n.pinNumber,true_ccw_index:s==null?void 0:s.trueIndex,display_pin_label:u});this.schematic_port_id=A.schematic_port_id}_setPositionFromLayout(t){const{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)}},Hye=r=>{const e=r.find(t=>/^(pin)?\d+$/.test(t));return e?Number.parseInt(e.replace(/^pin/,"")):null};function hD(r,e){var a;const t=Hye(r);if(!t)return null;const i=[...r.filter(o=>o.toString()!==t.toString()&&o!==`pin${t}`),...((a=e==null?void 0:e.additionalAliases)==null?void 0:a[`pin${t}`])??[]];return new GS({pinNumber:t,aliases:i})}var eft=r=>{for(const e of["leftSide","rightSide","topSide","bottomSide"])if(e in r&&typeof r[e]=="number")throw new Error(`A number was specified for "${e}", you probably meant to use "size" not "side"`);return"leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r},tft=r=>{var a,o,s,l;if(eft(r))return{leftSize:((a=r.leftSide)==null?void 0:a.pins.length)??0,rightSize:((o=r.rightSide)==null?void 0:o.pins.length)??0,topSize:((s=r.topSide)==null?void 0:s.pins.length)??0,bottomSize:((l=r.bottomSide)==null?void 0:l.pins.length)??0};const{leftSize:e=0,rightSize:t=0,topSize:n=0,bottomSize:i=0}=r;return{leftSize:e,rightSize:t,topSize:n,bottomSize:i}};function Yye(r){return r.leftSide!==void 0}var nft=r=>{var I,E,x,B,P,L,U,H;const e=r.portDistanceFromEdge??.4;let t=r.schPortArrangement?tft(r.schPortArrangement):null;const n={left:0,right:0,top:0,bottom:0};let i=r.pinCount??null;if(i===null)if(t)i=t.leftSize+t.rightSize+t.topSize;else throw new Error("Could not determine pin count for the schematic box");if(i&&!t){const G=Math.floor(i/2);t={leftSize:i-G,rightSize:G,topSize:0,bottomSize:0}}t||(t={leftSize:0,rightSize:0,topSize:0,bottomSize:0});const a=({side:G,sideIndex:W,truePinIndex:z})=>{var Ae,he,Ie,ge;if(!r.schPortArrangement||!Yye(r.schPortArrangement))return z+1;const ae={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[G],te=((he=(Ae=r.schPortArrangement)==null?void 0:Ae[`${G}Side`])==null?void 0:he.direction)??ae,oe=(ge=(Ie=r.schPortArrangement)==null?void 0:Ie[`${G}Side`])==null?void 0:ge.pins;let pe=W;return te!==ae&&(pe=oe.length-W-1),fD(oe[pe],r.pinLabels)},o=[];let s=0,l=0;for(let G=0;G<t.leftSize;G++){const W=a({side:"left",sideIndex:G,truePinIndex:l}),z=((I=r.numericSchPinStyle)==null?void 0:I[`pin${W}`])??((E=r.numericSchPinStyle)==null?void 0:E[W]);z!=null&&z.topMargin&&(s+=z.topMargin),o.push({trueIndex:l,pinNumber:W,side:"left",distanceFromOrthogonalEdge:s}),z!=null&&z.bottomMargin&&(s+=z.bottomMargin),G===t.leftSize-1?n.left=s:s+=r.schPinSpacing,l++}s=0;for(let G=0;G<t.bottomSize;G++){const W=a({side:"bottom",sideIndex:G,truePinIndex:l}),z=((x=r.numericSchPinStyle)==null?void 0:x[`pin${W}`])??((B=r.numericSchPinStyle)==null?void 0:B[W]);z!=null&&z.leftMargin&&(s+=z.leftMargin),o.push({trueIndex:l,pinNumber:W,side:"bottom",distanceFromOrthogonalEdge:s}),z!=null&&z.rightMargin&&(s+=z.rightMargin),G===t.bottomSize-1?n.bottom=s:s+=r.schPinSpacing,l++}s=0;for(let G=0;G<t.rightSize;G++){const W=a({side:"right",sideIndex:G,truePinIndex:l}),z=((P=r.numericSchPinStyle)==null?void 0:P[`pin${W}`])??((L=r.numericSchPinStyle)==null?void 0:L[W]);z!=null&&z.bottomMargin&&(s+=z.bottomMargin),o.push({trueIndex:l,pinNumber:W,side:"right",distanceFromOrthogonalEdge:s}),z!=null&&z.topMargin&&(s+=z.topMargin),G===t.rightSize-1?n.right=s:s+=r.schPinSpacing,l++}s=0;for(let G=0;G<t.topSize;G++){const W=a({side:"top",sideIndex:G,truePinIndex:l}),z=((U=r.numericSchPinStyle)==null?void 0:U[`pin${W}`])??((H=r.numericSchPinStyle)==null?void 0:H[W]);z!=null&&z.rightMargin&&(s+=z.rightMargin),o.push({trueIndex:l,pinNumber:W,side:"top",distanceFromOrthogonalEdge:s}),z!=null&&z.leftMargin&&(s+=z.leftMargin),G===t.topSize-1?n.top=s:s+=r.schPinSpacing,l++}let c=r.schWidth;c||(c=Math.max(n.top+r.schPinSpacing*2,n.bottom+r.schPinSpacing*2));const u=r.pinLabels?Math.max(...Object.values(r.pinLabels).map(G=>G.length*.1)):0,A=u>0?1.1:0;c=Math.max(c,u+A);let d=r.schHeight;d||(d=Math.max(n.left+r.schPinSpacing*2,n.right+r.schPinSpacing*2));const f={left:{x:-c/2-e,y:n.left/2},bottom:{x:-n.bottom/2,y:-d/2-e},right:{x:c/2+e,y:-n.right/2},top:{x:n.top/2,y:d/2+e}},g={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},_=o.map(G=>{const{distanceFromOrthogonalEdge:W,side:z}=G,ae=f[z],te=g[z];return{x:ae.x+W*te.x,y:ae.y+W*te.y,...G}});return{getPortPositionByPinNumber(G){const W=_.find(z=>z.pinNumber.toString()===G.toString());return W||null},getSize(){return{width:c,height:d}},getSizeIncludingPins(){return{width:c+(t.leftSize||t.rightSize?.4:0),height:d+(t.topSize||t.bottomSize?.4:0)}},pinCount:i}},rft=nv("tscircuit:core:footprint"),ift=class extends $v{get config(){return{componentName:"Footprint",zodProps:V0e}}doInitialPcbFootprintLayout(){var d,f,g,_,I;if((d=this.root)!=null&&d.pcbDisabled)return;const e=this.children.filter(E=>E.componentName==="Constraint");if(e.length===0)return;const{isFlipped:t}=this._getPcbPrimitiveFlippedHelpers(),n=E=>t&&"left"in E&&"right"in E?{...E,left:E.right,right:E.left}:E,i=e.flatMap(E=>E._getAllReferencedComponents().componentsWithSelectors).map(({component:E,selector:x,componentSelector:B,edge:P})=>({component:E,selector:x,componentSelector:B,edge:P,bounds:E._getPcbCircuitJsonBounds()}));if(i.some(E=>E.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function a(E){return i.find(({selector:x})=>x===E)}const o=new gme,s={};function l(E){return E in s||(s[E]=new DP(E),o.addEditVariable(s[E],iC.weak)),s[E]}for(const{selector:E,bounds:x}of i){const B=l(`${E}_x`),P=l(`${E}_y`);o.suggestValue(B,x.center.x),o.suggestValue(P,x.center.y)}for(const E of e){const x=E._parsedProps;if("xDist"in x){const{xDist:B,left:P,right:L,edgeToEdge:U,centerToCenter:H}=n(x),G=l(`${P}_x`),W=l(`${L}_x`),z=(f=a(P))==null?void 0:f.bounds,ae=(g=a(L))==null?void 0:g.bounds;if(H){const te=new II(W,[-1,G]);o.addConstraint(new Gx(te,aE.Eq,x.xDist,iC.required))}else if(U){const te=new II(W,-ae.width/2,[-1,G],-z.width/2);o.addConstraint(new Gx(te,aE.Eq,x.xDist,iC.required))}}else if("yDist"in x){const{yDist:B,top:P,bottom:L,edgeToEdge:U,centerToCenter:H}=x,G=l(`${P}_y`),W=l(`${L}_y`),z=(_=a(P))==null?void 0:_.bounds,ae=(I=a(L))==null?void 0:I.bounds;if(H){const te=new II(G,[-1,W]);o.addConstraint(new Gx(te,aE.Eq,x.yDist,iC.required))}else if(U){const te=new II(G,z.height/2,[-1,W],-ae.height/2);o.addConstraint(new Gx(te,aE.Eq,x.yDist,iC.required))}}else if("sameY"in x){const{for:B}=x;if(B.length<2)continue;const P=B.map(U=>l(`${U}_y`)),L=new II(...P.slice(1));o.addConstraint(new Gx(L,aE.Eq,P[0],iC.required))}else if("sameX"in x){const{for:B}=x;if(B.length<2)continue;const P=B.map(U=>l(`${U}_x`)),L=new II(...P.slice(1));o.addConstraint(new Gx(L,aE.Eq,P[0],iC.required))}}o.updateVariables(),rft.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(s).map(([E,x])=>({var:E,val:x.value()}))));const c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(const{selector:E,bounds:{width:x,height:B}}of i){const P=l(`${E}_x`),L=l(`${E}_y`),U=P.value()-x/2,H=P.value()+x/2,G=L.value()+B/2,W=L.value()-B/2;c.left=Math.min(c.left,U),c.right=Math.max(c.right,H),c.top=Math.max(c.top,G),c.bottom=Math.min(c.bottom,W)}const u={x:-(c.right+c.left)/2,y:-(c.top+c.bottom)/2},A=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();u.x+=A.x,u.y+=A.y;for(const{component:E,selector:x}of i){const B=l(`${x}_x`),P=l(`${x}_y`);E._setPositionFromLayout({x:B.value()+u.x,y:P.value()+u.y})}}},aft=(r,e)=>{if(!r)return;const t={};for(const[n,i]of Object.entries(r)){const a=fD(n,e),o={leftMargin:i.marginLeft??i.leftMargin,rightMargin:i.marginRight??i.rightMargin,topMargin:i.marginTop??i.topMargin,bottomMargin:i.marginBottom??i.bottomMargin};t[`pin${a}`]={...t[`pin${a}`],...o}}return t},Vye=class{constructor({input:e}){Ke(this,"input");this.input=e}solveAndMapToTraces(){const e=[];for(const t of this.input.connections){if(t.pointsToConnect.length!==2)continue;const[n,i]=t.pointsToConnect,a={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(a)}return e}},oft=r=>{const e=Math.min(...r.map(a=>a.center.x)),t=Math.max(...r.map(a=>a.center.x)),n=Math.min(...r.map(a=>a.center.y)),i=Math.max(...r.map(a=>a.center.y));return{minX:e,maxX:t,minY:n,maxY:i}},Kye=["top","bottom","inner1","inner2"],lk=(r,e=[])=>{var s;const t=[];if(e.length===0){const l=r[0].layers;for(const c of l)t.push(...lk(r.slice(1),[c]));return t}if(r.length===0)return[];const n=r[0],i=n.via||n.optional_via,a=e[e.length-1];if(r.length===1){const l=n;return l.layers&&i?l.layers.map(c=>({layer_path:[...e,c]})):(s=l.layers)!=null&&s.includes(a)?[{layer_path:[...e,a]}]:[]}if(!i)return n.layers&&!n.layers.includes(a)?[]:lk(r.slice(1),e.concat([a]));const o=(n.optional_via?Kye:Kye.filter(l=>l!==a)).filter(l=>{var c;return!n.layers||((c=n.layers)==null?void 0:c.includes(l))});for(const l of o)t.push(...lk(r.slice(1),e.concat(l)));return t};function jye(r){const e={x:r.to.x-r.from.x,y:r.to.y-r.from.y},t=Math.abs(e.x),n=Math.abs(e.y);return t>n?e.x>0?"right":"left":e.y>0?"down":"up"}function yM(r,e){return Math.hypot(r.x-e.x,r.y-e.y)}var sft=r=>{if(r.length===1)return r[0];if(r.some(l=>l.length===0))throw new Error("Cannot merge routes with zero length");const e=[],t=r[0][0],n=r[0][r[0].length-1],i=r[1][0],a=r[1][r[1].length-1],o=Math.min(yM(t,i),yM(t,a)),s=Math.min(yM(n,i),yM(n,a));o<s?e.push(...r[0].reverse()):e.push(...r[0]);for(let l=1;l<r.length;l++){const c=e[e.length-1],u=r[l],A=u[0],d=u[u.length-1],f=yM(c,A),g=yM(c,d);f<g?e.push(...u):e.push(...u.reverse())}for(let l=1;l<e.length-1;l++){const c=e[l-1],u=e[l];c.route_type==="wire"&&u.route_type==="wire"&&c.layer!==u.layer&&e.splice(l,0,{x:c.x,y:c.y,from_layer:c.layer,to_layer:u.layer,route_type:"via"})}return e},lft=(r,e)=>{const t="_getGlobalPcbPositionBeforeLayout"in r?r._getGlobalPcbPositionBeforeLayout():r,n="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((t.x-n.x)**2+(t.y-n.y)**2)};function cft(r,e){if(e.length===0)throw new Error("No candidates given to getClosest method");let t=e[0],n=1/0;for(const i of e){const a=lft(r,i);a<n&&(t=i,n=a)}return t}var uft=(r,e)=>{let t=0;t+=r.length??0,t+=e.filter(n=>n.is_crossing).length;for(let n=1;n<e.length;n++){const i=e[n-1],a=e[n],o=Math.abs(i.from.x-i.to.x)<.01,s=Math.abs(a.from.x-a.to.x)<.01;o!==s&&t++}return t},AK=r=>({up:"bottom",down:"top",left:"right",right:"left"})[r]??null,dK=({firstEdge:r,firstEdgePort:e,firstDominantDirection:t,lastEdge:n,lastEdgePort:i,lastDominantDirection:a})=>{if(r&&e)return dK({lastEdge:{from:r.to,to:r.from},lastEdgePort:e,lastDominantDirection:t}).reverse().map(s=>({from:s.to,to:s.from}));let o=[];if(n&&i){const s={x:n.to.x,y:n.to.y};a==="left"||a==="right"?(s.x=i.position.x,o.push({from:n.to,to:{...s}}),o.push({from:s,to:{...i.position}})):(s.y=i.position.y,o.push({from:n.to,to:{...s}}),o.push({from:s,to:{...i.position}}))}return o=o.filter(s=>NB(s.from,s.to)>.01),o};function Aft(r){try{return[r(),null]}catch(e){return[null,e]}}function dft(r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];if(n.route_type==="wire"){const i=r[t+1];if(i){const a=i.x-n.x,o=i.y-n.y;e+=Math.sqrt(a*a+o*o)}}else n.route_type==="via"&&(e+=1.6)}return e}var ck=({db:r,source_trace_id:e,sameNetOnly:t,differentNetOnly:n})=>{!t&&!n&&(n=!0);const i=r.source_trace.get(e),a=[];for(const o of r.schematic_trace.list()){if(o.source_trace_id===e)continue;const s=r.source_trace.get(o.source_trace_id),l=(s==null?void 0:s.subcircuit_connectivity_map_key)===i.subcircuit_connectivity_map_key;n&&l||t&&!l||a.push(o)}return a},Jye=({edges:r,otherEdges:e})=>{const t=[...r];for(let n=0;n<t.length;n++){if(n>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");const i=t[n],a=Math.abs(i.from.x-i.to.x)<.01?"vertical":i.from.y===i.to.y?"horizontal":"not-orthogonal";if(a==="not-orthogonal")continue;const o=[];for(const _ of e){const I=_.from.x===_.to.x?"vertical":_.from.y===_.to.y?"horizontal":"not-orthogonal";if(I==="not-orthogonal"||a===I)continue;if(TP([i.from,i.to],[_.from,_.to],{lineThickness:.01})){const x=a==="vertical"?i.from.x:_.from.x,B=a==="vertical"?_.from.y:i.from.y,P={x,y:B};o.push({otherEdge:_,crossingPoint:P,distanceFromEdgeFrom:NB(i.from,P)})}}if(o.length===0)continue;let s=o[0];for(const _ of o)_.distanceFromEdgeFrom<s.distanceFromEdgeFrom&&(s=_);const l=s.crossingPoint,c=.075;if(l.x===i.from.x&&l.y===i.from.y)continue;const u=yme(i.from,l),A={x:l.x-u.x*c/2,y:l.y-u.y*c/2},d={x:l.x+u.x*c/2,y:l.y+u.y*c/2},f=NB(d,i.to)<c,g=[{from:i.from,to:A},{from:A,to:d,is_crossing:!0},{from:d,to:i.to}];t.splice(n,1,...g),n+=g.length-2,f&&n++}return t},fft=(r,e)=>{if(r.from.x===r.to.x&&e.from.x===e.to.x)return null;if(r.from.x===r.to.x){const u=r.from.x,A=(e.to.y-e.from.y)/(e.to.x-e.from.x),d=e.from.y-A*e.from.x,f=A*u+d;return u>=Math.min(e.from.x,e.to.x)&&u<=Math.max(e.from.x,e.to.x)&&f>=Math.min(e.from.y,e.to.y)&&f<=Math.max(e.from.y,e.to.y)?{x:u,y:f}:null}if(e.from.x===e.to.x){const u=e.from.x,A=(r.to.y-r.from.y)/(r.to.x-r.from.x),d=r.from.y-A*r.from.x,f=A*u+d;return u>=Math.min(r.from.x,r.to.x)&&u<=Math.max(r.from.x,r.to.x)&&f>=Math.min(r.from.y,r.to.y)&&f<=Math.max(r.from.y,r.to.y)?{x:u,y:f}:null}const t=(r.to.y-r.from.y)/(r.to.x-r.from.x),n=r.from.y-t*r.from.x,i=(e.to.y-e.from.y)/(e.to.x-e.from.x),a=e.from.y-i*e.from.x;if(t===i)return null;const o=(a-n)/(t-i),s=t*o+n,l=o>=Math.min(r.from.x,r.to.x)&&o<=Math.max(r.from.x,r.to.x)&&s>=Math.min(r.from.y,r.to.y)&&s<=Math.max(r.from.y,r.to.y),c=o>=Math.min(e.from.x,e.to.x)&&o<=Math.max(e.from.x,e.to.x)&&s>=Math.min(e.from.y,e.to.y)&&s<=Math.max(e.from.y,e.to.y);return l&&c?{x:o,y:s}:null},Wye=({edges:r,db:e,source_trace_id:t})=>{const n=ck({db:e,source_trace_id:t,sameNetOnly:!0}).flatMap(i=>i.edges);for(const i of r)for(const a of n){const o=fft(i,a);if(o)return`${o.x}${o.y}`,[{x:o.x,y:o.y}]}return[]},hft=(r,{db:e})=>{const t=r.map(n=>{const i=e.source_port.get(n.source_port_id);if(!(i!=null&&i.source_component_id))return null;const a=e.source_component.get(i.source_component_id);return(a==null?void 0:a.ftype)==="simple_capacitor"?a.max_decoupling_trace_length:null}).filter(n=>n!==null);if(t.length!==0)return Math.min(...t)};function pft(r){var a,o,s,l,c,u,A,d,f;let e=1/0,t=1/0,n=-1/0,i=-1/0;for(const g of r){let _,I,E,x;g.type==="schematic_component"?(_=(a=g.center)==null?void 0:a.x,I=(o=g.center)==null?void 0:o.y,E=(s=g.size)==null?void 0:s.width,x=(l=g.size)==null?void 0:l.height):g.type==="schematic_box"?(_=g.x,I=g.y,E=g.width,x=g.height):g.type==="schematic_port"?(_=(c=g.center)==null?void 0:c.x,I=(u=g.center)==null?void 0:u.y,E=.2,x=.2):g.type==="schematic_text"&&(_=(A=g.position)==null?void 0:A.x,I=(d=g.position)==null?void 0:d.y,E=(((f=g.text)==null?void 0:f.length)??0)*.1,x=.2),typeof _=="number"&&typeof I=="number"&&typeof E=="number"&&typeof x=="number"&&(e=Math.min(e,_-E/2),n=Math.max(n,_+E/2),t=Math.min(t,I-x/2),i=Math.max(i,I+x/2))}return{minX:e,maxX:n,minY:t,maxY:i}}function gft(r,e={}){const{minX:t,maxX:n,minY:i,maxY:a}=r,o=e.padding??1;if(!isFinite(t)||!isFinite(n)||!isFinite(i)||!isFinite(a))return[];const s=t-o,l=n+o,c=a+o,u=i-o,A=.01;return[{type:"rect",layers:["top"],center:{x:(s+l)/2,y:c},width:l-s,height:A,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(s+l)/2,y:u},width:l-s,height:A,connectedTo:[]},{type:"rect",layers:["top"],center:{x:s,y:(c+u)/2},width:A,height:c-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:l,y:(c+u)/2},width:A,height:c-u,connectedTo:[]}]}var mft=r=>{var o;const e=r.root.db,t=r._findConnectedPorts().ports??[],n=new Set(t.map(s=>s.schematic_port_id)),i=[];for(const s of e.toArray()){if(s.type==="schematic_component"){const l=!!s.symbol_name,c=s.size.width>s.size.height?"horz":"vert";i.push({type:"rect",layers:["top"],center:s.center,width:s.size.width+(l&&c==="horz"?-.5:0),height:s.size.height+(l&&c==="vert"?-.5:0),connectedTo:[]})}if(s.type==="schematic_port"){if(n.has(s.schematic_port_id))continue;const l=s.facing_direction?vme(s.facing_direction):{x:0,y:0};i.push({type:"rect",layers:["top"],center:{x:s.center.x-l.x*.1,y:s.center.y-l.y*.1},width:.1+Math.abs(l.x)*.3,height:.1+Math.abs(l.y)*.3,connectedTo:[]})}s.type==="schematic_text"&&i.push({type:"rect",layers:["top"],center:s.position,width:(((o=s.text)==null?void 0:o.length)??0)*.1,height:.2,connectedTo:[]}),s.type==="schematic_box"&&i.push({type:"rect",layers:["top"],center:{x:s.x,y:s.y},width:s.width,height:s.height,connectedTo:[]})}const a=pft(e.toArray());return i.push(...gft(a,{padding:1})),i};function yft({ports:r,nets:e}){var t,n,i;if(r.length>=2)return`${(t=r[0])==null?void 0:t.selector} to ${(n=r[1])==null?void 0:n.selector}`;if(r.length===1&&e.length===1)return`${(i=r[0])==null?void 0:i.selector} to net.${e[0]._parsedProps.name}`}var vft=({edges:r,db:e,source_trace_id:t})=>{e.source_trace.get(t);const n=ck({db:e,source_trace_id:t,differentNetOnly:!0}).flatMap(a=>a.edges),i=a=>{const{from:o,to:s}=a;return o.x===s.x?"vertical":"horizontal"};for(const a of r){const o=i(a),s=()=>n.find(c=>i(c)===o&&TP([a.from,a.to],[c.from,c.to],{lineThickness:.05}));let l=s();for(;l;)o==="horizontal"?(a.from.y+=.1,a.to.y+=.1):(a.from.x+=.1,a.to.x+=.1),l=s()}},Ift=(r,{db:e})=>{const t=e.pcb_board.list()[0];if(t.outline){const l=t.outline,c=(u,A)=>{let d=!1;for(let f=0,g=A.length-1;f<A.length;g=f++){const _=A[f].x,I=A[f].y,E=A[g].x,x=A[g].y;I>u.y!=x>u.y&&u.x<(E-_)*(u.y-I)/(x-I)+_&&(d=!d)}return d};return r.some(u=>!c(u,l))}const n=t.width,i=t.height,a=t.center.x,o=t.center.y;return r.some(l=>l.x<a-n/2||l.y<o-i/2||l.x>a+n/2||l.y>o+i/2)},uk=r=>({...r._getGlobalPcbPositionAfterLayout(),layers:r.getAvailablePcbLayers()}),OS=class extends $v{constructor(t){super(t);Ke(this,"source_trace_id",null);Ke(this,"pcb_trace_id",null);Ke(this,"schematic_trace_id",null);Ke(this,"_portsRoutedOnPcb");Ke(this,"subcircuit_connectivity_map_key",null);Ke(this,"_traceConnectionHash",null);this._portsRoutedOnPcb=[]}get config(){return{zodProps:Y0e,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(){const{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)throw new Error("Trace has no parent");const o=this.getTracePortPathSelectors().map(s=>({selector:s,port:this.getSubcircuit().selectOne(s,{type:"port"})??null}));for(const{selector:s,port:l}of o)if(!l){const c=s.replace(/(\> )?[^ ]+$/,""),u=this.getSubcircuit().selectOne(c);u?this.renderError(`Could not find port for selector "${s}" (did you forget to include the pin name?)
854
+ searched component ${u.getString()}, which has ports: ${u.children.filter(A=>A.componentName==="Port").map(A=>`${A.getString()}(${A.getNameAndAliases().join(",")})`).join(" & ")}`):this.renderError(`Could not find port for selector "${s}"`)}return o.some(s=>!s.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:o,ports:o.map(({port:s})=>s)}}_findConnectedNets(){const t=this.getTracePathNetSelectors().map(i=>({selector:i,net:this.getSubcircuit().selectOne(i,{type:"net"})})),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(){const t=this.getSubcircuit().selectAll("trace"),n=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return t.filter(a=>{if(a===this)return!1;const o=a._findConnectedNets().nets,s=a._findConnectedPorts().ports??[];return o.some(l=>n.includes(l))||s.some(l=>i.includes(l))})}_isExplicitlyConnectedToPort(t){const{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(){Fye(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){const{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(){var d;const{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}const{allPortsFound:a,portsWithSelectors:o}=this._findConnectedPorts();if(!a)return;this._traceConnectionHash=this._computeTraceConnectionHash();const l=t.source_trace.list().find(f=>f.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&f.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(l){this.source_trace_id=l.source_trace_id;return}const c=this._findConnectedNets().nets,u=yft({ports:o,nets:c}),A=t.source_trace.insert({connected_source_port_ids:o.map(f=>f.port.source_port_id),connected_source_net_ids:c.map(f=>f.source_net_id),subcircuit_id:(d=this.getSubcircuit())==null?void 0:d.subcircuit_id,max_length:hft(o.map(f=>f.port),{db:t})??n.maxLength,display_name:u,min_trace_thickness:n.thickness});this.source_trace_id=A.source_trace_id}_insertErrorIfTraceIsOutsideBoard(t,n){const{db:i}=this.root;Ift(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)})}doInitialPcbTraceRender(){var W,z,ae,te;if((W=this.root)!=null&&W.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n,parent:i}=this,a=this.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(a._parsedProps.routingDisabled)return;const o=(z=a._parsedProps.pcbRouteCache)==null?void 0:z.pcbTraces;if(o){const oe=t.pcb_trace.insert({route:o.flatMap(pe=>pe.route),source_trace_id:this.source_trace_id,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((ae=this.getGroup())==null?void 0:ae.pcb_group_id)??void 0});this.pcb_trace_id=oe.pcb_trace_id;return}if(!a._shouldUseTraceByTraceRouting())return;const{allPortsFound:s,ports:l}=this._findConnectedPorts();if(!s)return;const c=[];for(const oe of l)oe._hasMatchedPcbPrimitive()||c.push(oe);if(c.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.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, ${this} wasn't routed. Missing ports: ${c.map(oe=>oe.getString()).join(", ")}`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:c.map(oe=>oe.pcb_port_id).filter(Boolean)});return}const u=this._findConnectedNets().netsWithSelectors;if(l.length===0&&u.length===2){this.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(l.length===1&&u.length===1){const oe=l[0],Ae=u[0].net.getAllConnectedPorts().filter(Ie=>Ie!==oe);if(Ae.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}const he=cft(oe,Ae);l.push(he)}else if(l.length>1&&u.length>=1){this.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}const A=l.flatMap(oe=>oe.matchedComponents.filter(pe=>pe.componentName==="TraceHint")),d=(this._parsedProps.pcbRouteHints??[]).concat(A.flatMap(oe=>oe.getPcbRouteHints()));if(l.length>2){this.renderError(`Trace has more than two ports (${l.map(oe=>oe.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(this.getSubcircuit().selectAll("trace").filter(oe=>oe.renderPhaseStates.PcbTraceRender.initialized).some(oe=>oe._portsRoutedOnPcb.length===l.length&&oe._portsRoutedOnPcb.every(pe=>l.includes(pe))))return;let _=[];d.length===0?_=[uk(l[0]),uk(l[1])]:_=[uk(l[0]),...d,uk(l[1])];const I=lk(_),E=FS(this.root.db.toArray()),[x,B]=Aft(()=>BP(this.root.db.toArray()));if(B){this.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:this.pcb_trace_id,message:`Error getting obstacles for autorouting: ${B.message}`,source_trace_id:this.source_trace_id,center:{x:0,y:0},pcb_port_ids:l.map(oe=>oe.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[]});return}for(const oe of x)if(oe.connectedTo.length>0){const Ae=E.getNetConnectedToId(oe.connectedTo[0]);Ae&&oe.connectedTo.push(Ae)}let P=[];if(I.length===0)P=_;else{const oe=I[0].layer_path;P=_.map((pe,Ae)=>pe.via?{...pe,via_to_layer:oe[Ae]}:{...pe,layers:[oe[Ae]]})}P[0].pcb_port_id=l[0].pcb_port_id,P[P.length-1].pcb_port_id=l[1].pcb_port_id;const L=[];for(const[oe,pe]of kye(P)){const Ae="via_to_layer"in oe?oe.via_to_layer:null,he=2,Ie="layers"in oe&&oe.layers.length===1?oe.layers[0]:Ae??"top",ge="layers"in pe&&pe.layers.length===1?pe.layers[0]:Ae??"top",Me="pcb_port_id"in oe?oe.pcb_port_id:null,Se="pcb_port_id"in pe?pe.pcb_port_id:null,Re=this.getSubcircuit()._parsedProps.minTraceWidth??.16,we=new xP({OBSTACLE_MARGIN:Re*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(Me&&Se),connMap:E,input:{obstacles:x,minTraceWidth:Re,connections:[{name:this.source_trace_id,pointsToConnect:[{...oe,layer:Ie,pcb_port_id:Me},{...pe,layer:ge,pcb_port_id:Se}]}],layerCount:2,bounds:{minX:Math.min(oe.x,pe.x)-he,maxX:Math.max(oe.x,pe.x)+he,minY:Math.min(oe.y,pe.y)-he,maxY:Math.max(oe.y,pe.y)+he}}});let Ge=null;try{Ge=we.solveAndMapToTraces()}catch(ht){this.renderError({type:"pcb_trace_error",pcb_trace_error_id:this.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${ht.message}`,source_trace_id:this.pcb_trace_id,center:{x:(oe.x+pe.x)/2,y:(oe.y+pe.y)/2},pcb_port_ids:l.map(kt=>kt.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:l.map(kt=>kt.pcb_component_id)})}if(!Ge)return;if(Ge.length===0){this.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:this.pcb_trace_id,message:`Could not find a route for ${this}`,source_trace_id:this.source_trace_id,center:{x:(oe.x+pe.x)/2,y:(oe.y+pe.y)/2},pcb_port_ids:l.map(ht=>ht.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:l.map(ht=>ht.pcb_component_id)});return}const[$e]=Ge;Ae&&($e.route=$e.route.map(ht=>(ht.route_type==="wire"&&!ht.layer&&(ht.layer=Ae),ht))),Me&&$e.route[0].route_type==="wire"&&($e.route[0].start_pcb_port_id=Me);const lt=$e.route[$e.route.length-1];Se&&lt.route_type==="wire"&&(lt.end_pcb_port_id=Se),L.push($e.route)}const U=sft(L),H=dft(U),G=t.pcb_trace.insert({route:U,source_trace_id:this.source_trace_id,subcircuit_id:(te=this.getSubcircuit())==null?void 0:te.subcircuit_id,trace_length:H});this._portsRoutedOnPcb=l,this.pcb_trace_id=G.pcb_trace_id;for(const oe of U)oe.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:G.pcb_trace_id,x:oe.x,y:oe.y,hole_diameter:.3,outer_diameter:.6,layers:[oe.from_layer,oe.to_layer],from_layer:oe.from_layer,to_layer:oe.to_layer});this._insertErrorIfTraceIsOutsideBoard(U,l)}_doInitialSchematicTraceRenderWithDisplayLabel(){var L,U,H,G;if((L=this.root)!=null&&L.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)throw new Error("Trace has no parent");const{allPortsFound:a,portsWithSelectors:o}=this._findConnectedPorts();if(!a)return;const s=o.map(({port:W})=>({port:W,position:W._getGlobalSchematicPositionAfterLayout(),schematic_port_id:W.schematic_port_id,facingDirection:W.facingDirection}));if(s.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let l,c;const u=s[0].position,A=s[0].port;if("path"in this.props){if(this.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[l,c]=this.props.path}else{if(!("from"in this.props&&"to"in this.props))throw new Error("Missing 'from' or 'to' properties in props.");l=this.props.from,c=this.props.to}if(!A.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${l}).`);const d=s[1].position,f=s[1].port;if(!f.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);const g=t.schematic_net_label.list().find(W=>W.source_net_id===A.source_port_id),_=t.schematic_net_label.list().find(W=>W.source_net_id===f.source_port_id),[I,E]=o.map(({port:W})=>W),B=((U=I.parent)==null?void 0:U.config.shouldRenderAsSchematicBox)?`${(H=I==null?void 0:I.parent)==null?void 0:H.props.name}_${I==null?void 0:I.props.name}`:`${(G=E==null?void 0:E.parent)==null?void 0:G.props.name}_${E==null?void 0:E.props.name}`,P=this.props.schDisplayLabel??B;g&&g.text!==P&&(g.text=`${P} / ${g.text}`),_&&(_==null?void 0:_.text)!==P&&(_.text=`${P} / ${_.text}`),_||t.schematic_net_label.insert({text:this.props.schDisplayLabel??B,source_net_id:f.source_port_id,anchor_position:d,center:d,anchor_side:AK(f.facingDirection)??"bottom"}),g||t.schematic_net_label.insert({text:this.props.schDisplayLabel??B,source_net_id:A.source_port_id,anchor_position:u,center:u,anchor_side:AK(A.facingDirection)??"bottom"})}_isSymbolToChipConnection(){const{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;const[i,a]=n;if(!(i!=null&&i.parent)||!(a!=null&&a.parent))return!1;const o=i.parent.config.shouldRenderAsSchematicBox,s=a.parent.config.shouldRenderAsSchematicBox;return o&&!s||!o&&s}_isSymbolToSymbolConnection(){const{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;const[i,a]=n;if(!(i!=null&&i.parent)||!(a!=null&&a.parent))return!1;const o=!i.parent.config.shouldRenderAsSchematicBox,s=!a.parent.config.shouldRenderAsSchematicBox;return o&&s}_isChipToChipConnection(){const{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;const[i,a]=n;if(!(i!=null&&i.parent)||!(a!=null&&a.parent))return!1;const o=i.parent.config.shouldRenderAsSchematicBox,s=a.parent.config.shouldRenderAsSchematicBox;return o&&s}doInitialSchematicTraceRender(){var Ie,ge,Me;if((Ie=this.root)!=null&&Ie.schematicDisabled||((ge=this.getGroup())==null?void 0:ge._getSchematicLayoutMode())==="match-adapt")return;const{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)throw new Error("Trace has no parent");const{allPortsFound:a,portsWithSelectors:o}=this._findConnectedPorts(),{netsWithSelectors:s}=this._findConnectedNets();if(!a)return;const c=o.map(Se=>Se.port.schematic_port_id).sort().join(","),u=(Me=this.root)==null?void 0:Me._getBoard();if(u!=null&&u._connectedSchematicPortPairs&&u._connectedSchematicPortPairs.has(c))return;if(this.props.schDisplayLabel&&("from"in this.props&&"to"in this.props||"path"in this.props)){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const A={name:this.source_trace_id,pointsToConnect:[]},d=mft(this),f=o.map(({port:Se})=>({port:Se,position:Se._getGlobalSchematicPositionAfterLayout(),schematic_port_id:Se.schematic_port_id??void 0,facingDirection:Se.facingDirection}));if(f.length===1&&s.length===1){const Se=s[0].net,{port:Re,position:we}=f[0];t.schematic_net_label.insert({text:Se._parsedProps.name,source_net_id:Se.source_net_id,anchor_position:we,center:we,anchor_side:AK(Re.facingDirection)??"bottom"});return}if(f.length<2)return;A.pointsToConnect=f.map(({position:Se})=>({...Se,layer:"top"}));const _=oft(d),I=2,E={minTraceWidth:.1,obstacles:d,connections:[A],bounds:{minX:_.minX-I,maxX:_.maxX+I,minY:_.minY-I,maxY:_.maxY+I},layerCount:1};let x=xP,B=!1;this.getSubcircuit().props._schDirectLineRoutingEnabled&&(x=Vye,B=!0);let L=new x({input:E,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(L.length===0){if(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection()){this._doInitialSchematicTraceRenderWithDisplayLabel();return}L=new Vye({input:E}).solveAndMapToTraces(),B=!0}const[{route:U}]=L;let H=[];for(let Se=0;Se<U.length-1;Se++)H.push({from:U[Se],to:U[Se+1]});const G=this.source_trace_id;let W=[];if(!B){vft({edges:H,db:t,source_trace_id:G});const Se=ck({db:t,source_trace_id:G,differentNetOnly:!0}).flatMap(Re=>Re.edges);H=Jye({edges:H,otherEdges:Se}),W=Wye({edges:H,db:t,source_trace_id:this.source_trace_id})}const z=H[H.length-1],ae=f[f.length-1],te=jye(z);H.push(...dK({lastEdge:z,lastEdgePort:ae,lastDominantDirection:te}));const oe=H[0],pe=f[0],Ae=jye(oe);if(H.unshift(...dK({firstEdge:oe,firstEdgePort:pe,firstDominantDirection:Ae})),!this.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(this.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&uft(W,H)>=5&&(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection())){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const he=t.schematic_trace.insert({source_trace_id:this.source_trace_id,edges:H,junctions:W});this.schematic_trace_id=he.schematic_trace_id,u!=null&&u._connectedSchematicPortPairs&&u._connectedSchematicPortPairs.add(c)}},Cft=nv("tscircuit:core"),Eft=tn({x:Fx,y:Fx,z:Fx}),T1=class extends $v{constructor(t){super(t);Ke(this,"reactSubtrees",[]);Ke(this,"_impliedFootprint");Ke(this,"isPrimitiveContainer",!0);Ke(this,"_asyncSupplierPartNumbers");Ke(this,"pcb_missing_footprint_error_id");Ke(this,"_hasStartedFootprintUrlLoad",!1);this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames}initPorts(t={}){var s,l,c,u,A,d,f,g,_,I;if((s=this.root)!=null&&s.schematicDisabled)return;const{config:n}=this,i=[],a=this._getSchematicPortArrangement();if(a&&!this._parsedProps.pinLabels){for(const B in a){const P=a[B].pins;if(Array.isArray(P))for(const L of P){const U=fD(L,this._parsedProps.pinLabels);i.push(new GS({pinNumber:U,aliases:((l=t.additionalAliases)==null?void 0:l[`pin${U}`])??[]},{originDescription:`schPortArrangement:${B}`}))}}const E=["left","right","top","bottom"];let x=1;for(const B of E){const P=a[`${B}Size`];for(let L=0;L<P;L++)i.push(new GS({pinNumber:x++,aliases:((c=t.additionalAliases)==null?void 0:c[`pin${x}`])??[]},{originDescription:`schPortArrangement:${B}`}))}}const o=this._parsedProps.pinLabels;if(o)for(let[E,x]of Object.entries(o)){E=E.replace("pin","");let B=i.find(U=>U._parsedProps.pinNumber===Number(E));const P=Array.isArray(x)?x[0]:x,L=Array.isArray(x)?x.slice(1):[];B?(B.externallyAddedAliases.push(P,...L),B.props.name=P):(B=new GS({pinNumber:parseInt(E),name:P,aliases:[...L,...((u=t.additionalAliases)==null?void 0:u[`pin${parseInt(E)}`])??[]]},{originDescription:`pinLabels:pin${E}`}),i.push(B))}if(n.schematicSymbolName){const E=yI[this._getSchematicSymbolNameOrThrow()];if(!E)return;for(const x of E.ports){const B=Hye(x.labels);if(!B)continue;const P=i.find(L=>L._parsedProps.pinNumber===Number(B));if(P)P.schematicSymbolPortDef=x;else{const L=hD(x.labels.concat(((A=t.additionalAliases)==null?void 0:A[`pin${B}`])??[]));L&&(L.originDescription=`schematicSymbol:labels[0]:${x.labels[0]}`,L.schematicSymbolPortDef=x,i.push(L))}}this.addAll(i)}if(!this._getSchematicPortArrangement()){const E=this.getPortsFromFootprint(t);for(const x of E)i.some(B=>B.isMatchingAnyOf(x.getNameAndAliases()))||i.push(x)}for(let E=1;E<=(t.pinCount??this._getPinCount());E++){if(!a||i.find(B=>B._parsedProps.pinNumber===E))continue;let x=[...((d=a.leftSide)==null?void 0:d.pins)??[],...((f=a.rightSide)==null?void 0:f.pins)??[],...((g=a.topSide)==null?void 0:g.pins)??[],...((_=a.bottomSide)==null?void 0:_.pins)??[]].map(B=>fD(B,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(B=>B in a)&&(x=Array.from({length:this._getPinCount()},(B,P)=>P+1)),x.includes(E)&&i.push(new GS({pinNumber:E,aliases:((I=t.additionalAliases)==null?void 0:I[`pin${E}`])??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${E}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_isFootprintUrl(t){return t.startsWith("http://")||t.startsWith("https://")}_addChildrenFromStringFootprint(){var o;const{name:t,pcbRotation:n,pinLabels:i}=this.props;let{footprint:a}=this.props;if(a??(a=(o=this._getImpliedFootprintString)==null?void 0:o.call(this)),!!a&&typeof a=="string"){if(this._isFootprintUrl(a))return;const s=kT.string(a).soup(),l=zye({componentName:t,componentRotation:n,footprint:a,pinLabels:i},s);this.addAll(l)}}get portMap(){return new Proxy({},{get:(t,n)=>{const i=this.children.find(a=>a.componentName==="Port"&&a.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(const n of this.reactSubtrees)if(n.element===t)return n.component;return null}doInitialSourceRender(){const t=this.config.sourceFtype;if(!t)return;const{db:n}=this.root,{_parsedProps:i}=this,a=n.source_component.insert({ftype:t,name:i.name,manufacturer_part_number:i.manufacturerPartNumber??i.mfn,supplier_part_numbers:i.supplierPartNumbers});this.source_component_id=a.source_component_id}doInitialSchematicComponentRender(){var a,o,s;if((a=this.root)!=null&&a.schematicDisabled)return;const{db:t}=this.root,{schematicSymbolName:n}=this.config;n?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();const i=(o=this.getSubcircuit())==null?void 0:o._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&i){if(!this.schematic_component_id)return;const l=bT.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:(s=this.getSubcircuit())==null?void 0:s.subcircuit_id});t.schematic_manual_edit_conflict_warning.insert(l)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];const t=[];for(const n of this.internallyConnectedPinNames){const i=[];for(const a of n)i.push(this.portMap[a]);t.push(i)}return t}_doInitialSchematicComponentRenderWithSymbol(){var s;if((s=this.root)!=null&&s.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicSymbolNameOrThrow(),a=yI[i],o=this._getGlobalSchematicPositionBeforeLayout();if(a){const l=t.schematic_component.insert({center:o,size:a.size,source_component_id:this.source_component_id,symbol_name:i,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=l.schematic_component_id}}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){var d;if((d=this.root)!=null&&d.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicBoxDimensions(),a={};if(Array.isArray(n.pinLabels))n.pinLabels.forEach((f,g)=>{a[String(g+1)]=f});else for(const[f,g]of Object.entries(n.pinLabels??{}))a[f]=Array.isArray(g)?g[0]:g;const o=this._getGlobalSchematicPositionBeforeLayout(),s=this._getSchematicPortArrangement(),l=t.schematic_component.insert({center:o,rotation:n.schRotation??0,size:i.getSize(),port_arrangement:Vdt(s),pin_spacing:n.schPinSpacing??.2,pin_styles:Ydt(n.schPinStyle,n.pinLabels),port_labels:a,source_component_id:this.source_component_id}),c=(s==null?void 0:s.topSide)!==void 0||(s==null?void 0:s.bottomSide)!==void 0,u=i==null?void 0:i.getSize().width,A=i==null?void 0:i.getSize().height;t.schematic_text.insert({text:n.manufacturerPartNumber??"",schematic_component_id:l.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(u??0)/2+.1:o.x-(u??0)/2,y:c?o.y+(A??0)/2+.35:o.y-(A??0)/2-.13},color:"#006464",font_size:.18}),t.schematic_text.insert({text:n.name??"",schematic_component_id:l.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(u??0)/2+.1:o.x-(u??0)/2,y:c?o.y+(A??0)/2+.55:o.y+(A??0)/2+.13},color:"#006464",font_size:.18}),this.schematic_component_id=l.schematic_component_id}doInitialPcbComponentRender(){var s;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),a=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.isGroup){const l=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=l.pcb_missing_footprint_error_id}this.pcb_component_id=a.pcb_component_id;const o=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&o){const l=wT.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(l)}}doInitialPcbComponentSizeCalculation(){var o;if((o=this.root)!=null&&o.pcbDisabled||!this.pcb_component_id)return;const{db:t}=this.root,{_parsedProps:n}=this,i=uK(this.children);if(i.width===0||i.height===0)return;const a={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};t.pcb_component.update(this.pcb_component_id,{center:a,width:i.width,height:i.height})}_renderReactSubtree(t){return{element:t,component:Pye(t)}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){}doInitialPcbFootprintStringRender(){var o;let{footprint:t}=this.props;if(t??(t=(o=this._getImpliedFootprintString)==null?void 0:o.call(this)),!t)return;const{name:n,pcbRotation:i,pinLabels:a}=this.props;if(typeof t=="string"&&this._isFootprintUrl(t)){if(this._hasStartedFootprintUrlLoad)return;this._hasStartedFootprintUrlLoad=!0;const s=t;this._queueAsyncEffect("load-footprint-url",async()=>{const c=await(await fetch(s)).json(),u=zye({componentName:n,componentRotation:i,footprint:s,pinLabels:a},c);this.addAll(u),this._markDirty("InitializePortsFromChildren")});return}if(nt.isValidElement(t)){if(this.reactSubtrees.some(l=>l.element===t))return;const s=this._renderReactSubtree(t);this.reactSubtrees.push(s),this.add(s.component);return}!nt.isValidElement(t)&&t.componentName==="Footprint"&&this.add(t)}_hasExistingPortExactly(t){return this.children.filter(i=>i.componentName==="Port").some(i=>{const a=t.getNameAndAliases(),o=i.getNameAndAliases();return a.length===o.length&&a.every(s=>o.includes(s))})}add(t){let n;if(nt.isValidElement(t)){const i=this._renderReactSubtree(t);this.reactSubtrees.push(i),n=i.component}else n=t;if(n.componentName==="Port"){if(this._hasExistingPortExactly(n))return;const a=this.children.filter(o=>o.componentName==="Port").find(o=>o.isMatchingAnyOf(n.getNameAndAliases()));a&&Cft(`Similar ports added. Port 1: ${a}, Port 2: ${n}`)}super.add(n)}getPortsFromFootprint(t){let{footprint:n}=this.props;if((!n||nt.isValidElement(n))&&(n=this.children.find(a=>a.componentName==="Footprint")),typeof n=="string"){if(this._isFootprintUrl(n))return[];const a=kT.string(n).soup(),o=[];for(const s of a)if("port_hints"in s&&s.port_hints){const l=hD(s.port_hints,t);if(!l)continue;l.originDescription=`footprint:string:${n}:port_hints[0]:${s.port_hints[0]}`,o.push(l)}return o}if(!nt.isValidElement(n)&&n&&n.componentName==="Footprint"){const a=n;let o=1;const s=[];for(const l of a.children){if(!l.props.portHints)continue;let c=l.props.portHints;c.some(d=>d.startsWith("pin"))||(c=[...c,`pin${o}`]),o++;const A=hD(c);A&&(A.originDescription=`footprint:${n}`,s.push(A))}return s}const i=[];if(!n){for(const a of this.children)if(a.props.portHints&&a.isPcbPrimitive){const o=hD(a.props.portHints);o&&i.push(o)}}return i}getPortsFromSchematicSymbol(){var a;if((a=this.root)!=null&&a.schematicDisabled)return[];const{config:t}=this;if(!t.schematicSymbolName)return[];const n=yI[t.schematicSymbolName];if(!n)return[];const i=[];for(const o of n.ports){const s=hD(o.labels);s&&(s.schematicSymbolPortDef=o,i.push(s))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){const{_parsedProps:t}=this,n=[];if(t.connections)for(const[i,a]of Object.entries(t.connections)){const o=Array.isArray(a)?a:[a];for(const s of o)n.push(s)}return n}_createNetsFromProps(t){Fye(this,t)}_getPcbCircuitJsonBounds(){const{db:t}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();const 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(){const t=this._getSchematicPortArrangement();if(!t)return 0;if(!Yye(t))return(t.leftSize??t.leftPinCount??0)+(t.rightSize??t.rightPinCount??0)+(t.topSize??t.topPinCount??0)+(t.bottomSize??t.bottomPinCount??0);const{leftSide:i,rightSide:a,topSide:o,bottomSide:s}=t;return Math.max(...(i==null?void 0:i.pins)??[],...(a==null?void 0:a.pins)??[],...(o==null?void 0:o.pins)??[],...(s==null?void 0:s.pins)??[])}_getPinCount(){return this._getSchematicPortArrangement()?this._getPinCountFromSchematicPortArrangement():this.getPortsFromFootprint().length}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;const{_parsedProps:t}=this,n=this._getPinCount(),i=t.schPinSpacing??.2;return nft({schWidth:t.schWidth,schHeight:t.schHeight,schPinSpacing:i,numericSchPinStyle:aft(t.schPinStyle,t.pinLabels),pinCount:n,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:t.pinLabels})}doInitialCadModelRender(){var u;const{db:t}=this.root,{boardThickness:n=0}=((u=this.root)==null?void 0:u._getBoard())??{},i=this._parsedProps.cadModel;if(!this.pcb_component_id||!i&&!this.props.footprint||i===null)return;const a=this._getPcbCircuitJsonBounds(),o=t.pcb_component.get(this.pcb_component_id);if(typeof i=="string")throw new Error("String cadModel not yet implemented");const s=Eft.parse({x:0,y:0,z:typeof(i==null?void 0:i.rotationOffset)=="number"?i.rotationOffset:0,...typeof(i==null?void 0:i.rotationOffset)=="object"?i.rotationOffset??{}:{}}),l=qw.parse({x:0,y:0,z:0,...typeof(i==null?void 0:i.positionOffset)=="object"?i.positionOffset:{}}),c=this.props.layer==="bottom"?"bottom":"top";t.cad_component.insert({position:{x:a.center.x+l.x,y:a.center.y+l.y,z:(c==="bottom"?-n/2:n/2)+l.z},rotation:{x:s.x,y:(c==="top"?0:180)+s.y,z:c==="bottom"?-(((o==null?void 0:o.rotation)??0)+s.z)+180:((o==null?void 0:o.rotation)??0)+s.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(i??{})?this._addCachebustToModelUrl(i.stlUrl):void 0,model_obj_url:"objUrl"in(i??{})?this._addCachebustToModelUrl(i.objUrl):void 0,model_jscad:"jscad"in(i??{})?i.jscad:void 0,footprinter_string:typeof this.props.footprint=="string"&&!i?this.props.footprint:void 0})}_addCachebustToModelUrl(t){var i;if(!t||!t.includes("modelcdn.tscircuit.com"))return t;const n=((i=this.root)==null?void 0:i.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){var c,u;if(this.props.doNotPlace)return{};const a=(u=(c=this.root)==null?void 0:c.platform)==null?void 0:u.localCacheEngine,o=this._getPartsEngineCacheKey(n,i);if(a){const A=await a.getItem(o);if(A)try{return JSON.parse(A)}catch{}}const s=await Promise.resolve(t.findPart({sourceComponent:n,footprinterString:i})),l=s==="Not found"?{}:s;if(a)try{await a.setItem(o,JSON.stringify(l))}catch{}return l}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;const t=this.getInheritedProperty("partsEngine");if(!t)return;const{db:n}=this.root,i=n.source_component.get(this.source_component_id);if(!i||i.supplier_part_numbers)return;let a;this.props.footprint&&typeof this.props.footprint=="string"&&(a=this.props.footprint);const o=this._getSupplierPartNumbers(t,i,a);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;const{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}}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){const{_parsedProps:t}=this;if(t.connections)for(const[n,i]of Object.entries(t.connections)){const a=Array.isArray(i)?i:[i];for(const o of a)this.add(new OS({from:`${this.getSubcircuitSelector()} > port.${n}`,to:o}))}}},_ft=class{constructor(e,t={}){Ke(this,"input");Ke(this,"isRouting",!1);Ke(this,"solver");Ke(this,"eventHandlers",{complete:[],error:[],progress:[]});Ke(this,"cycleCount",0);Ke(this,"stepDelay");Ke(this,"timeoutId");this.input=e;const{capacityDepth:n,targetMinCapacity:i,stepDelay:a=0}=t;this.solver=new dye(e,{capacityDepth:n,targetMinCapacity:i,cacheProvider:null}),this.stepDelay=a}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){var e;if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new Error(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}const t=Date.now(),n=this.solver.iterations;for(;Date.now()-t<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();const i=(this.solver.iterations-n)/(Date.now()-t)*1e3;this.cycleCount++;const a=((e=this.solver)==null?void 0:e.preview())||void 0,o=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:i,progress:o,phase:this.solver.getCurrentPhase(),debugGraphics:a}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(t){this.emitEvent({type:"error",error:t instanceof Error?t:new Error(String(t))}),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(const t of this.eventHandlers.complete)t(e);else if(e.type==="error")for(const t of this.eventHandlers.error)t(e);else if(e.type==="progress")for(const t of this.eventHandlers.progress)t(e)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new Error(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},qye=class extends $v{constructor(){super(...arguments);Ke(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:pme}}doInitialPortMatching(){const{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}const a=i.selectOne(n.for,{type:"port"});a||this.renderError(`${this} could not find port for selector "${n.for}"`),this.matchedPort=a,a.registerMatch(this)}getPcbRouteHints(){const{_parsedProps:t}=this,n=t.offset?[t.offset]:t.offsets;if(!n)return[];const i=this._computePcbGlobalTransformBeforeLayout();return n.map(a=>({...ti(i,a),via:a.via,to_layer:a.to_layer,trace_width:a.trace_width}))}doInitialPcbTraceHintRender(){var i,a,o;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this;t.pcb_trace_hint.insert({pcb_component_id:(a=this.matchedPort)==null?void 0:a.pcb_component_id,pcb_port_id:(o=this.matchedPort)==null?void 0:o.pcb_port_id,route:this.getPcbRouteHints()})}},xft=({circuitJson:r,editEvents:e,manualEditsFile:t})=>{var i;const n={...t,pcb_placements:[...t.pcb_placements??[]]};for(const a of e)if(a.edit_event_type==="edit_pcb_component_location"){const{pcb_component_id:o,new_center:s}=a,l=o1(r).pcb_component.get(o);if(!l)continue;const c=o1(r).source_component.get(l.source_component_id);if(!c)continue;const u=(i=n.pcb_placements)==null?void 0:i.findIndex(d=>d.selector===c.name),A={selector:c.name,center:s,relative_to:"group_center"};u>=0?n.pcb_placements[u]=A:n.pcb_placements.push(A)}return n},Bft=({circuitJson:r,editEvents:e,manualEditsFile:t})=>{var i;const n={...t,schematic_placements:[...t.schematic_placements??[]]};for(const a of e)if(a.edit_event_type==="edit_schematic_component_location"){const{schematic_component_id:o,new_center:s}=a,l=o1(r).schematic_component.get(o);if(!l)continue;const c=o1(r).source_component.get(l.source_component_id);if(!c)continue;const u=(i=n.schematic_placements)==null?void 0:i.findIndex(d=>d.selector===c.name),A={selector:c.name,center:s,relative_to:"group_center"};u>=0?n.schematic_placements[u]=A:n.schematic_placements.push(A)}return n},Zye=({circuitJson:r,editEvents:e,manualEditsFile:t})=>{const n=e.filter(o=>o.edit_event_type==="edit_schematic_component_location"),i=e.filter(o=>o.edit_event_type==="edit_pcb_component_location");let a=t;return n.length>0&&(a=Bft({circuitJson:r,editEvents:n,manualEditsFile:a})),i.length>0&&(a=xft({circuitJson:r,editEvents:i,manualEditsFile:a})),a},bft=(r,e)=>{const t=r.source_group.list(),n=[],i=a=>{const o=t.filter(s=>s.parent_subcircuit_id===a);for(const s of o)s.subcircuit_id&&(n.push(s.subcircuit_id),i(s.subcircuit_id))};return i(e),n},Xye=({db:r,circuitJson:e,subcircuit_id:t,minTraceWidth:n=.1})=>{if(!r&&e&&(r=o1(e)),!r)throw new Error("db or circuitJson is required");const i=r.pcb_trace_hint.list(),a=t?new Set([t]):null;if(t){const _=bft(r,t);for(const I of _)a.add(I)}const o=(e??r.toArray()).filter(_=>!t||"subcircuit_id"in _&&a.has(_.subcircuit_id)),s=r.pcb_board.list()[0];r=o1(o);const l=FS(o),c=BP([...r.pcb_component.list(),...r.pcb_smtpad.list(),...r.pcb_plated_hole.list(),...r.pcb_hole.list(),...r.pcb_via.list()].filter(_=>!t||(a==null?void 0:a.has(_.subcircuit_id))),l);for(const _ of c){const I=_.connectedTo.flatMap(E=>l.getIdsConnectedToNet(E));_.connectedTo.push(...I)}const u=c.flatMap(_=>[{x:_.center.x-_.width/2,y:_.center.y-_.height/2},{x:_.center.x+_.width/2,y:_.center.y+_.height/2}]);let A;s?A={minX:s.center.x-s.width/2,maxX:s.center.x+s.width/2,minY:s.center.y-s.height/2,maxY:s.center.y+s.height/2}:A={minX:Math.min(...u.map(_=>_.x))-1,maxX:Math.max(...u.map(_=>_.x))+1,minY:Math.min(...u.map(_=>_.y))-1,maxY:Math.max(...u.map(_=>_.y))+1};const d=r.source_trace.list().map(_=>{var H,G,W;const I=_.connected_source_port_ids.map(z=>{const ae=r.source_port.get(z),te=r.pcb_port.getWhere({source_port_id:z});return{...ae,...te}});if(I.length<2)return null;const[E,x]=I,B=((H=E.layers)==null?void 0:H[0])??"top",P=((G=x.layers)==null?void 0:G[0])??"top",L=i.filter(z=>z.pcb_port_id===E.pcb_port_id||z.pcb_port_id===x.pcb_port_id),U=[];for(const z of L){const ae=r.pcb_port.get(z.pcb_port_id),te=((W=ae==null?void 0:ae.layers)==null?void 0:W[0])??"top";for(const oe of z.route)U.push({x:oe.x,y:oe.y,layer:te})}return{name:_.source_trace_id??l.getNetConnectedToId(_.source_trace_id)??"",source_trace_id:_.source_trace_id,pointsToConnect:[{x:E.x,y:E.y,layer:B},...U,{x:x.x,y:x.y,layer:P}]}}).filter(_=>_!==null),f=r.source_net.list().filter(_=>!t||(a==null?void 0:a.has(_.subcircuit_id))),g=[];for(const _ of f){const I=r.source_trace.list().filter(E=>{var x;return(x=E.connected_source_net_ids)==null?void 0:x.includes(_.source_net_id)});g.push({name:_.source_net_id??l.getNetConnectedToId(_.source_net_id),pointsToConnect:I.flatMap(E=>r.pcb_port.list().filter(B=>E.connected_source_port_ids.includes(B.source_port_id)).map(B=>{var P;return{x:B.x,y:B.y,layer:((P=B.layers)==null?void 0:P[0])??"top",pcb_port_id:B.pcb_port_id}}))})}return{simpleRouteJson:{bounds:A,obstacles:c,connections:[...d,...g],layerCount:2,minTraceWidth:n},connMap:l}};function fK(r,e){if("boxId"in r){const{boxId:t,pinNumber:n}=r,i=e.source_component.getWhere({name:t});if(!i)throw new Error(`Source component "${t}" not found, but returned from match-adapt ${JSON.stringify(r)}`);const a=e.source_port.getWhere({source_component_id:i.source_component_id,pin_number:n});return{subcircuit_connectivity_map_key:(a==null?void 0:a.subcircuit_connectivity_map_key)??null,source_port_id:a.source_port_id}}if("netId"in r){const{netId:t}=r;return e.source_net.getWhere({name:t}),null}if("junctionId"in r){const{junctionId:t}=r;return null}return null}function Sft({path:r,db:e,layoutConnMap:t}){let n=fK(r.to,e)??fK(r.from,e);if(!n){const a=t.getNetConnectedToId(Hb(r.to));n=t.getIdsConnectedToNet(a).map(s=>qV(s)).map(s=>fK(s,e)).find(Boolean)}if(!(n!=null&&n.subcircuit_connectivity_map_key))throw new Error(`No connectivity net id found for match-adapt path ${JSON.stringify(r)}`);const i=e.source_trace.list({subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key});for(const a of i)if(a.connected_source_port_ids.includes(n.source_port_id))return a.source_trace_id;if(i.length>0)return i[0].source_trace_id;throw new Error(`No source trace found for match-adapt path "${JSON.stringify(r)}"`)}function wft(r){const{db:e}=r.root;let t=structuredClone(e.toArray());t=Tdt(t);const n=Ndt(t),i=new Ddt({inputNetlist:n});let a=null;try{i.solve(),a=i.getLayout()}catch(A){e.schematic_layout_error.insert({message:`Match-adapt layout failed: ${A.toString()}`,source_group_id:r.source_group_id,schematic_group_id:r.schematic_group_id});return}const{boxes:o,junctions:s,netLabels:l,paths:c}=a,u=new aM({});for(const A of c)u.addConnections([[Hb(A.from),Hb(A.to)]]);for(const A of s)for(const d of c)for(const f of d.points)Math.abs(f.x-A.x)<.001&&Math.abs(f.y-A.y)<.001&&u.addConnections([[Hb(d.from),Hb(A)],[Hb(d.to),Hb(A)]]);for(const A of o){const d=e.source_component.list().find(E=>E.name===A.boxId);if(!d)continue;const f=e.schematic_component.getWhere({source_component_id:d.source_component_id});if(!f)continue;const g={x:A.centerX-f.center.x+.1,y:A.centerY-f.center.y-.1};e.schematic_component.update(f.schematic_component_id,{center:{x:f.center.x+g.x,y:f.center.y+g.y}});const _=e.schematic_port.list({schematic_component_id:f.schematic_component_id});for(const E of _)e.schematic_port.update(E.schematic_port_id,{center:{x:E.center.x+g.x,y:E.center.y+g.y}});const I=e.schematic_text.list({schematic_component_id:f.schematic_component_id});for(const E of I)e.schematic_text.update(E.schematic_text_id,{position:{x:E.position.x+g.x,y:E.position.y+g.y}})}for(const A of l){const d=e.source_net.list().find(f=>f.name===A.netId);e.schematic_net_label.insert({text:A.netId,source_net_id:d==null?void 0:d.source_net_id,anchor_position:{x:A.x,y:A.y},center:{x:A.x,y:A.y},anchor_side:A.anchorPosition})}for(const A of c){if(!A.points||A.points.length<2)continue;const d=Sft({path:A,db:PB(t),layoutConnMap:u});let f=[];for(let I=0;I<A.points.length-1;I++)f.push({from:{x:A.points[I].x,y:A.points[I].y},to:{x:A.points[I+1].x,y:A.points[I+1].y}});const g=ck({db:e,source_trace_id:d,differentNetOnly:!0}).flatMap(I=>I.edges);g.length>0&&(f=Jye({edges:f,otherEdges:g}));const _=Wye({edges:f,db:e,source_trace_id:d});e.schematic_trace.insert({source_trace_id:d,edges:f,junctions:_})}}function Qft(r){if(!r.isSubcircuit)return;const{db:e}=r.root,t=r.selectAll("trace"),n=new aM({});n.addConnections(t.map(s=>{const l=e.source_trace.get(s.source_trace_id);return l?[l.source_trace_id,...l.connected_source_port_ids,...l.connected_source_net_ids]:null}).filter(s=>s!==null));const{name:i}=r._parsedProps;for(const s of t){if(!s.source_trace_id)continue;const l=n.getNetConnectedToId(s.source_trace_id);l&&(s.subcircuit_connectivity_map_key=`${i??`unnamedsubcircuit${r._renderId}`}_${l}`,e.source_trace.update(s.source_trace_id,{subcircuit_connectivity_map_key:s.subcircuit_connectivity_map_key}))}const a=new Set;for(const s of t){if(!s.source_trace_id)continue;const l=e.source_trace.get(s.source_trace_id);if(l)for(const c of l.connected_source_port_ids)a.add(c)}for(const s of a){const l=n.getNetConnectedToId(s);if(!l)continue;const c=`${i??`unnamedsubcircuit${r._renderId}`}_${l}`;e.source_port.update(s,{subcircuit_connectivity_map_key:c})}const o=new Set;for(const s of t){if(!s.source_trace_id)continue;const l=e.source_trace.get(s.source_trace_id);if(l)for(const c of l.connected_source_net_ids)o.add(c)}for(const s of o){const l=n.getNetConnectedToId(s);if(!l)continue;const c=`${i??`unnamedsubcircuit${r._renderId}`}_${l}`;e.source_net.update(s,{subcircuit_connectivity_map_key:c})}}function Mft(r){var x;const{db:e}=r.root,t=r._parsedProps,n=r.children.filter(B=>B.schematic_component_id);if(n.length===0)return;let i=0,a=0;for(const B of n){const P=e.schematic_component.get(B.schematic_component_id);P!=null&&P.size&&(i=Math.max(i,P.size.width),a=Math.max(a,P.size.height))}i===0&&n.length>0&&(i=1),a===0&&n.length>0&&(a=1);let o=t.gridCols,s,l=t.gridGap;(x=t.schLayout)!=null&&x.grid&&(o=t.schLayout.grid.cols??o,s=t.schLayout.grid.rows,l=t.schLayout.grid.gap??l);let c,u;o!==void 0&&s!==void 0?(c=o,u=s):o!==void 0?(c=o,u=Math.ceil(n.length/c)):s!==void 0?(u=s,c=Math.ceil(n.length/u)):(c=Math.ceil(Math.sqrt(n.length)),u=Math.ceil(n.length/c)),c===0&&n.length>0&&(c=1),u===0&&n.length>0&&(u=n.length);let A,d;typeof l=="number"?(A=l,d=l):typeof l=="object"&&l!==null?(A=l.x,d=l.y):(A=1,d=1);const f=c*i+Math.max(0,c-1)*A,g=u*a+Math.max(0,u-1)*d,_=r._getGlobalSchematicPositionBeforeLayout(),I=_.x-f/2+i/2,E=_.y+g/2-a/2;for(let B=0;B<n.length;B++){const P=n[B];if(!P.schematic_component_id)continue;const L=Math.floor(B/c),U=B%c;if(L>=u||U>=c){console.warn(`Schematic grid layout: Child ${P.getString()} at index ${B} (row ${L}, col ${U}) exceeds specified grid dimensions (${u}x${c}). Skipping placement.`);continue}const H=I+U*(i+A),G=E-L*(a+d),W=e.schematic_component.get(P.schematic_component_id);if(W){const z=W.center,ae={x:H,y:G};e.schematic_component.update(P.schematic_component_id,{center:ae});const te=ae.x-z.x,oe=ae.y-z.y,pe=e.schematic_port.list({schematic_component_id:P.schematic_component_id});for(const he of pe)e.schematic_port.update(he.schematic_port_id,{center:{x:he.center.x+te,y:he.center.y+oe}});const Ae=e.schematic_text.list({schematic_component_id:P.schematic_component_id});for(const he of Ae)e.schematic_text.update(he.schematic_text_id,{position:{x:he.position.x+te,y:he.position.y+oe}})}}r.schematic_group_id&&e.schematic_group.update(r.schematic_group_id,{width:f,height:g,center:_})}function Dft(r){var x;const{db:e}=r.root,t=r._parsedProps,n=r.children.filter(B=>B.pcb_component_id);if(n.length===0)return;let i=0,a=0;for(const B of n){const P=e.pcb_component.get(B.pcb_component_id);P&&(i=Math.max(i,P.width),a=Math.max(a,P.height))}i===0&&n.length>0&&(i=1),a===0&&n.length>0&&(a=1);let o=t.gridCols,s,l=t.gridGap;(x=t.pcbLayout)!=null&&x.grid&&(o=t.pcbLayout.grid.cols??o,s=t.pcbLayout.grid.rows,l=t.pcbLayout.grid.gap??l);let c,u;o!==void 0&&s!==void 0?(c=o,u=s):o!==void 0?(c=o,u=Math.ceil(n.length/c)):s!==void 0?(u=s,c=Math.ceil(n.length/u)):(c=Math.ceil(Math.sqrt(n.length)),u=Math.ceil(n.length/c)),c===0&&n.length>0&&(c=1),u===0&&n.length>0&&(u=n.length);let A,d;typeof l=="number"?(A=l,d=l):typeof l=="object"&&l!==null?(A=l.x,d=l.y):(A=1,d=1);const f=c*i+Math.max(0,c-1)*A,g=u*a+Math.max(0,u-1)*d,_=r._getGlobalPcbPositionBeforeLayout(),I=_.x-f/2+i/2,E=_.y+g/2-a/2;for(let B=0;B<n.length;B++){const P=n[B];if(!P.pcb_component_id)continue;const L=Math.floor(B/c),U=B%c;if(L>=u||U>=c){console.warn(`PCB grid layout: Child ${P.getString()} at index ${B} (row ${L}, col ${U}) exceeds grid dimensions (${u}x${c}). Skipping placement.`);continue}const H=I+U*(i+A),G=E-L*(a+d),W=e.pcb_component.get(P.pcb_component_id);if(W){const z=W.center,ae={x:H,y:G},te=ae.x-z.x,oe=ae.y-z.y,pe=Od(te,oe),Ae=e.toArray().filter(Ie=>Ie.pcb_component_id===P.pcb_component_id),he=fAt(Ae,pe);for(const Ie of he){const ge=rk(Ie);e[Ie.type].update(Ie[ge],Ie)}e.pcb_component.update(P.pcb_component_id,{center:ae}),P.setProps({...P.props,pcbX:(P.props.pcbX??0)+te,pcbY:(P.props.pcbY??0)+oe})}}r.pcb_group_id&&e.pcb_group.update(r.pcb_group_id,{width:f,height:g,center:_})}var hK=class extends T1{constructor(){super(...arguments);Ke(this,"pcb_group_id",null);Ke(this,"schematic_group_id",null);Ke(this,"subcircuit_id",null);Ke(this,"_hasStartedAsyncAutorouting",!1);Ke(this,"_asyncAutoroutingResult",null)}get config(){return{zodProps:M0e,componentName:"Group"}}doInitialSourceRender(){const{db:t}=this.root,n=t.source_group.insert({name:this._parsedProps.name,is_subcircuit:this.isSubcircuit});this.subcircuit_id=`subcircuit_${n.source_group_id}`,this.source_group_id=n.source_group_id,t.source_group.update(n.source_group_id,{subcircuit_id:this.subcircuit_id});for(const i of this.children)t.source_component.update(i.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){var i,a,o;const{db:t}=this.root;if(!this.isSubcircuit)return;const n=(o=(a=(i=this.parent)==null?void 0:i.getSubcircuit)==null?void 0:a.call(i))==null?void 0:o.subcircuit_id;n&&t.source_group.update(this.source_group_id,{parent_subcircuit_id:n})}doInitialPcbComponentRender(){var a;if((a=this.root)!=null&&a.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this._parsedProps.name,center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,pcb_component_ids:[],source_group_id:this.source_group_id});this.pcb_group_id=i.pcb_group_id;for(const o of this.children)t.pcb_component.update(o.pcb_component_id,{pcb_group_id:i.pcb_group_id})}doInitialPcbPrimitiveRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:t}=this.root,n=uK(this.children);this.pcb_group_id&&t.pcb_group.update(this.pcb_group_id,{width:n.width,height:n.height,center:{x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2}})}doInitialCreateTraceHintsFromProps(){var o;const{_parsedProps:t}=this,{db:n}=this.root,i=t;if(!this.isSubcircuit)return;const a=(o=i.layout)==null?void 0:o.manual_trace_hints;if(a)for(const s of a)this.add(new qye({for:s.pcb_port_selector,offsets:s.offsets}))}doInitialSourceAddConnectivityMapKey(){Qft(this)}_areChildSubcircuitsRouted(){const t=this.selectAll("group").filter(n=>n.isSubcircuit);for(const n of t)if(n._shouldRouteAsync()&&!n._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){const t=this._getAutorouterConfig();return t.groupMode==="sequential-trace"?!1:!!(t.local&&t.groupMode==="subcircuit"||!t.local)}_hasTracesToRoute(){const t=nv("tscircuit:core:_hasTracesToRoute"),n=this.selectAll("trace");return t(`[${this.getString()}] has ${n.length} traces to route`),n.length>0}async _runEffectMakeHttpAutoroutingRequest(){var u,A,d,f;const{db:t}=this.root,n=nv("tscircuit:core:_runEffectMakeHttpAutoroutingRequest");this._parsedProps;const i=this._getAutorouterConfig(),a=i.serverUrl,o=i.serverMode,s=(g,_)=>{var I;return n("fetching",g),_.headers&&(_.headers["Tscircuit-Core-Version"]=(I=this.root)==null?void 0:I.getCoreVersion()),fetch(g,_)},l=this.root.db.toArray().filter(g=>g.type.startsWith("source_")||g.type.startsWith("pcb_"));if(o==="solve-endpoint"){if(((u=this.props.autorouter)==null?void 0:u.inputFormat)==="simplified"){const{autorouting_result:_}=await s(`${a}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:Xye({db:t,minTraceWidth:((A=this.props.autorouter)==null?void 0:A.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(I=>I.json());this._asyncAutoroutingResult=_,this._markDirty("PcbTraceRender");return}const{autorouting_result:g}=await s(`${a}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:l,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(_=>_.json());this._asyncAutoroutingResult=g,this._markDirty("PcbTraceRender");return}const{autorouting_job:c}=await s(`${a}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:l,provider:"freerouting",autostart:!0,display_name:(d=this.root)==null?void 0:d.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:i.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(g=>g.json());for(;;){const{autorouting_job:g}=await s(`${a}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:c.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(_=>_.json());if(g.is_finished){const{autorouting_job_output:_}=await s(`${a}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:c.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(I=>I.json());this._asyncAutoroutingResult={output_pcb_traces:_.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(g.has_error)throw t.pcb_autorouting_error.insert({pcb_error_id:c.autorouting_job_id,message:((f=g.error)==null?void 0:f.message)??JSON.stringify(g.error)}),new Error(`Autorouting job failed: ${JSON.stringify(g.error)}`);await new Promise(_=>setTimeout(_,100))}}async _runLocalAutorouting(){var l,c,u,A,d;const{db:t}=this.root;this._parsedProps;const n=nv("tscircuit:core:_runLocalAutorouting");n(`[${this.getString()}] starting local autorouting`);const i=this._getAutorouterConfig(),{simpleRouteJson:a}=Xye({db:t,minTraceWidth:((l=this.props.autorouter)==null?void 0:l.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id});(c=this.root)==null||c.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:a});let o;i.algorithmFn?o=await i.algorithmFn(a):o=new _ft(a,{capacityDepth:(u=this.props.autorouter)==null?void 0:u.capacityDepth,targetMinCapacity:(A=this.props.autorouter)==null?void 0:A.targetMinCapacity});const s=new Promise((f,g)=>{o.on("complete",_=>{n(`[${this.getString()}] local autorouting complete`),f(_.traces)}),o.on("error",_=>{n(`[${this.getString()}] local autorouting error: ${_.error.message}`),g(_.error)})});o.on("progress",f=>{var g;(g=this.root)==null||g.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...f})}),o.start();try{const f=await s;this._asyncAutoroutingResult={output_pcb_traces:f},this._markDirty("PcbTraceRender")}catch(f){const{db:g}=this.root;throw g.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,message:f instanceof Error?f.message:String(f)}),(d=this.root)==null||d.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:f instanceof Error?f.message:String(f)},simpleRouteJson:a}),f}finally{o.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(){var n;const t=nv("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!((n=this.root)!=null&&n.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()}}updatePcbTraceRender(){var i;const t=nv("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;const{db:n}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){t(`[${this.getString()}] updating PCB traces from simple route json (${(i=this._asyncAutoroutingResult.output_simple_route_json.traces)==null?void 0:i.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(){const{db:t}=this.root,{traces:n}=this._asyncAutoroutingResult.output_simple_route_json;if(n)for(const i of n)t.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}_updatePcbTraceRenderFromPcbTraces(){const{output_pcb_traces:t}=this._asyncAutoroutingResult;if(!t)return;const{db:n}=this.root;for(const i of t)if(i.type==="pcb_trace"){if(i.subcircuit_id=this.subcircuit_id,i.connection_name){const a=i.connection_name;i.source_trace_id=a}n.pcb_trace.insert(i)}for(const i of t)if(i.type!=="pcb_via"&&i.type==="pcb_trace")for(const a of i.route)a.route_type==="via"&&n.pcb_via.insert({pcb_trace_id:i.pcb_trace_id,x:a.x,y:a.y,hole_diameter:.3,outer_diameter:.6,layers:[a.from_layer,a.to_layer],from_layer:a.from_layer,to_layer:a.to_layer})}doInitialSchematicComponentRender(){var a;if((a=this.root)!=null&&a.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=t.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this._parsedProps.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(const o of this.children)o.schematic_component_id&&t.schematic_component.update(o.schematic_component_id,{schematic_group_id:i.schematic_group_id})}_getSchematicLayoutMode(){var n,i,a;const t=this._parsedProps;return(n=t.schLayout)!=null&&n.matchAdapt?"match-adapt":(i=t.schLayout)!=null&&i.flex?"flex":(a=t.schLayout)!=null&&a.grid?"grid":t.matchAdapt?"match-adapt":t.flex?"flex":t.grid?"grid":"none"}doInitialSchematicLayout(){this._parsedProps;const t=this._getSchematicLayoutMode();t==="match-adapt"&&this._doInitialSchematicLayoutMatchAdapt(),t==="grid"&&this._doInitialSchematicLayoutGrid()}_doInitialSchematicLayoutMatchAdapt(){wft(this)}_doInitialSchematicLayoutGrid(){Mft(this)}_getPcbLayoutMode(){var n,i,a;const t=this._parsedProps;return(n=t.pcbLayout)!=null&&n.matchAdapt?"match-adapt":(i=t.pcbLayout)!=null&&i.flex?"flex":(a=t.pcbLayout)!=null&&a.grid?"grid":t.matchAdapt?"match-adapt":t.flex?"flex":t.grid?"grid":"none"}doInitialPcbLayout(){this._getPcbLayoutMode()==="grid"&&this._doInitialPcbLayoutGrid()}_doInitialPcbLayoutGrid(){Dft(this)}_determineSideFromPosition(t,n){if(!t.center||!n.center)return"left";const i=t.center.x-n.center.x,a=t.center.y-n.center.y;return Math.abs(i)>Math.abs(a)?i>0?"right":"left":a>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,a=1/0,o=-1/0;for(const l of t)n=Math.min(n,l.centerX),i=Math.max(i,l.centerX),a=Math.min(a,l.centerY),o=Math.max(o,l.centerY);const s=2;return{minX:n-s,maxX:i+s,minY:a-s,maxY:o+s}}_getAutorouterConfig(){const t={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0},n=this._parsedProps.autorouter??this.getInheritedProperty("autorouter");return typeof n=="object"?{local:!(n.serverUrl||n.serverMode||n.serverCacheEnabled),...t,...n}:n==="auto-local"?{local:!0,groupMode:"subcircuit"}:n==="sequential-trace"?{local:!0,groupMode:"sequential-trace"}:n==="subcircuit"?{local:!0,groupMode:"subcircuit"}:n==="auto-cloud"?{local:!1,groupMode:"subcircuit",serverUrl:t.serverUrl,serverMode:t.serverMode,serverCacheEnabled:!0}:{local:!0,groupMode:"subcircuit"}}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){var n;if((n=this.root)!=null&&n.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:t}=this.root;if(this.isSubcircuit){const i=new Map;for(const a of this.children)if(!a.isSubcircuit&&a._parsedProps.name){const o=i.get(a._parsedProps.name)||[];o.push(a),i.set(a._parsedProps.name,o)}for(const[a,o]of i.entries())o.length>1&&t.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${a}" in subcircuit "${this._parsedProps.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:o.map(s=>s.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){var n;if((n=this.root)!=null&&n.schematicDisabled)return;const{db:t}=this.root;for(const i of t.schematic_net_label.list()){const a=t.source_net.get(i.source_net_id),o=i.text||(a==null?void 0:a.name)||"";if(i.anchor_side==="top"&&/^gnd/i.test(o)){t.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"ground_down"});continue}i.anchor_side==="bottom"&&/^v/i.test(o)&&t.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"vcc_up"})}}},Rft=class extends hK{constructor(){super(...arguments);Ke(this,"pcb_board_id",null);Ke(this,"_drcChecksComplete",!1);Ke(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:cV}}get boardThickness(){const{_parsedProps:t}=this;return 1.4}get allLayers(){return["top","bottom","inner1","inner2"]}doInitialPcbBoardAutoSize(){var g;if((g=this.root)!=null&&g.pcbDisabled||!this.pcb_board_id)return;const{db:t}=this.root,{_parsedProps:n}=this;if(n.width&&n.height)return;let i=1/0,a=1/0,o=-1/0,s=-1/0;const l=t.pcb_component.list();let c=!1;for(const _ of l){const{width:I,height:E,center:x}=_;I===0||E===0||(c=!0,i=Math.min(i,x.x-I/2),a=Math.min(a,x.y-E/2),o=Math.max(o,x.x+I/2),s=Math.max(s,x.y+E/2))}const u=2,A=c?o-i+u*2:0,d=c?s-a+u*2:0,f={x:c?(i+o)/2+(n.outlineOffsetX??0):n.outlineOffsetX??0,y:c?(a+s)/2+(n.outlineOffsetY??0):n.outlineOffsetY??0};t.pcb_board.update(this.pcb_board_id,{width:A,height:d,center:f})}doInitialPcbComponentRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this;let i=n.width??0,a=n.height??0;if(n.outline){const c=n.outline.map(_=>_.x),u=n.outline.map(_=>_.y),A=Math.min(...c),d=Math.max(...c),f=Math.min(...u),g=Math.max(...u);i=d-A,a=g-f}const o=t.pcb_board.insert({center:{x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)},thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:a,outline:(l=n.outline)==null?void 0:l.map(c=>({x:c.x+(n.outlineOffsetX??0),y:c.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=o.pcb_board_id}removePcbComponentRender(){const{db:t}=this.root;this.pcb_board_id&&(t.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return wy()}doInitialPcbDesignRuleChecks(){var t;(t=this.root)!=null&&t.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){var i;if((i=this.root)!=null&&i.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;const n=Iye(t.toArray());for(const a of n)t.pcb_trace_error.insert(a)}_emitRenderLifecycleEvent(t,n){var i;super._emitRenderLifecycleEvent(t,n),n==="start"&&((i=this.root)==null||i.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t}))}},Nft=new Proxy({},{get:(r,e)=>e}),oQ=Nft,Tft=class extends T1{get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:F0e,sourceFtype:oQ.simple_capacitor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){const e=`${kB(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${e}/${kB(this._parsedProps.maxVoltageRating)}V`:e}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new OS({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new OS({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_capacitor",name:t.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,capacitance:t.capacitance,max_voltage_rating:t.maxVoltageRating,max_decoupling_trace_length:t.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!t.polarized});this.source_component_id=n.source_component_id}},$ye=class extends T1{constructor(){super(...arguments);Ke(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:uV,shouldRenderAsSchematicBox:!0}}doInitialSchematicComponentRender(){const{_parsedProps:t}=this;(t==null?void 0:t.noSchematicRepresentation)!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:n.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){var a;if((a=this.root)!=null&&a.pcbDisabled)return;const{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(){const{_parsedProps:t}=this;if(t.externallyConnectedPins)for(const[n,i]of t.externallyConnectedPins)this.add(new OS({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}},Pft=class extends T1{constructor(){super(...arguments);Ke(this,"pos",this.portMap.pin1);Ke(this,"anode",this.portMap.pin1);Ke(this,"neg",this.portMap.pin2);Ke(this,"cathode",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"diode",componentName:"Diode",zodProps:$0e,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:n.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}},kft=class extends T1{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:xst,sourceFtype:oQ.simple_fuse}}_getSchematicSymbolDisplayValue(){const r=this._parsedProps.currentRating,e=this._parsedProps.voltageRating,t=typeof r=="string"?parseFloat(r):r,n=typeof e=="string"?parseFloat(e):e;return`${kB(t)}A / ${kB(n)}V`}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=typeof e.currentRating=="string"?parseFloat(e.currentRating):e.currentRating,n=typeof e.voltageRating=="string"?parseFloat(e.voltageRating):e.voltageRating,i=r.source_component.insert({name:e.name,ftype:oQ.simple_fuse,current_rating_amps:t,voltage_rating_volts:n,display_current_rating:`${kB(t)}A`,display_voltage_rating:`${kB(n)}V`});this.source_component_id=i.source_component_id}},Uft=class extends T1{constructor(){super(...arguments);Ke(this,"schematicDimensions",null)}get config(){let t="";if(this.props.pinCount&&(t+=`solderjumper${this.props.pinCount||2}`),Array.isArray(this.props.internallyConnectedPins)&&this.props.internallyConnectedPins.length>0){const n=Array.from(new Set(this.props.internallyConnectedPins.flat())).sort().join("");t+=`_bridged${n}`}return{schematicSymbolName:t,componentName:"Jumper",zodProps:D0e,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){const t=super._getSchematicPortArrangement();if(t)return t;const 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(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:n.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){var a;if((a=this.root)!=null&&a.pcbDisabled)return;const{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(){const{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++){const l=n[s],c=t.source_port.get(l.source_port_id);let u="";if(typeof(c==null?void 0:c.pin_number)=="number")u=c.pin_number.toString();else if(Array.isArray(c==null?void 0:c.port_hints)){let A=c.port_hints.find(d=>/^(pin)?\d+$/.test(d));A&&(/^pin\d+$/.test(A)?u=A.replace(/^pin/,""):u=A)}i[u]=l.pcb_port_id}const a=t.pcb_trace.list(),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){const l=s.replace("{PIN","").replace("}","");return i[l]||s}return s};for(const s of a)if(s.route)for(const l of s.route)l.route_type==="wire"&&(l.start_pcb_port_id=o(l.start_pcb_port_id),l.end_pcb_port_id=o(l.end_pcb_port_id))}},Fft=class extends T1{constructor(){super(...arguments);Ke(this,"pos",this.portMap.pin1);Ke(this,"anode",this.portMap.pin1);Ke(this,"neg",this.portMap.pin2);Ke(this,"cathode",this.portMap.pin2)}get config(){return{componentName:"Led",schematicSymbolName:this.props.symbolName??"led",zodProps:eme,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(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_led",name:n.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}},Lft=class extends T1{constructor(){super(...arguments);Ke(this,"pos",this.portMap.pin1);Ke(this,"positive",this.portMap.pin1);Ke(this,"neg",this.portMap.pin2);Ke(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:ome,sourceFtype:"simple_power_source"}}initPorts(){this.add(new GS({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new GS({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:n.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},Gft=class extends T1{get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:T0e,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${kB(this._parsedProps.resistance)}Ω`}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 OS({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new OS({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new OS({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new OS({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_resistor",name:t.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,resistance:t.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},Oft=["leftedge","rightedge","topedge","bottomedge","center"],zft=class extends $v{get config(){return{componentName:"Constraint",zodProps:L0e}}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(){const e=[],t=this.getPrimitiveContainer();function n(i){const a=i.split(" ").pop(),o=Oft.includes(a)?a:void 0,s=o?i.replace(` ${o}`,""):i,l=t.selectOne(s,{pcbPrimitive:!0});l&&e.push({selector:i,component:l,componentSelector:s,edge:o})}for(const i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(const i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},Hft=class extends $v{constructor(){super(...arguments);Ke(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:rme}}doInitialPcbPrimitiveRender(){var l,c;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,n=this.getSubcircuit(),{_parsedProps:i}=this,a=i.layer??"top";if(a!=="top"&&a!=="bottom")throw new Error(`Invalid layer "${a}" for SilkscreenPath. Must be "top" or "bottom".`);const o=this._computePcbGlobalTransformBeforeLayout(),s=t.pcb_fabrication_note_path.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layer:a,color:i.color,route:i.route.map(u=>{const A=ti(o,{x:u.x,y:u.y});return{...u,x:A.x,y:A.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0});this.fabrication_note_path_id=s.pcb_fabrication_note_path_id}},Yft=class extends $v{get config(){return{componentName:"FabricationNoteText",zodProps:nme}}doInitialPcbPrimitiveRender(){var a,o;if((a=this.root)!=null&&a.pcbDisabled)return;const{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==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((o=this.getGroup())==null?void 0:o.pcb_group_id)??void 0})}},Vft=class extends hK{constructor(e){super({...e,subcircuit:!0})}},Kft=class extends $v{constructor(){super(...arguments);Ke(this,"source_net_alias_id")}get config(){return{componentName:"NetAlias",zodProps:J0e}}doInitialSchematicComponentRender(){var o;if((o=this.root)!=null&&o.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i={x:n.schX??0,y:n.schY??0},a=t.schematic_net_label.insert({text:n.net,source_net_id:n.net,anchor_position:i,center:i,anchor_side:"bottom"});this.source_net_alias_id=a.source_net_id}},jft=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_silkscreen_circle_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:fme}}doInitialPcbPrimitiveRender(){var l,c,u;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),a=i(n.layer??"top");if(a!=="top"&&a!=="bottom")throw new Error(`Invalid layer "${a}" for SilkscreenCircle. Must be "top" or "bottom".`);this._computePcbGlobalTransformBeforeLayout();const o=this.getSubcircuit(),s=t.pcb_silkscreen_circle.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layer:a,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((u=this.getGroup())==null?void 0:u.pcb_group_id)??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=s.pcb_silkscreen_circle_id}getPcbSize(){const{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},Jft=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_silkscreen_rect_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:dme}}doInitialPcbPrimitiveRender(){var l,c,u;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),a=i(n.layer??"top");if(a!=="top"&&a!=="bottom")throw new Error(`Invalid layer "${a}" for SilkscreenRect. Must be "top" or "bottom".`);const o=this.getSubcircuit(),s=t.pcb_silkscreen_rect.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layer:a,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((u=this==null?void 0:this.getGroup())==null?void 0:u.pcb_group_id)??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_rect_id=s.pcb_silkscreen_rect_id}getPcbSize(){const{_parsedProps:t}=this;return{width:t.width,height:t.height}}},Wft=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_silkscreen_line_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:Ame}}doInitialPcbPrimitiveRender(){var l,c,u;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),a=i(n.layer??"top");if(a!=="top"&&a!=="bottom")throw new Error(`Invalid layer "${a}" for SilkscreenLine. Must be "top" or "bottom".`);const o=this.getSubcircuit(),s=t.pcb_silkscreen_line.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layer:a,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((u=o==null?void 0:o.getGroup())==null?void 0:u.pcb_group_id)??void 0});this.pcb_silkscreen_line_id=s.pcb_silkscreen_line_id}getPcbSize(){const{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},qft=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_via_id",null);Ke(this,"matchedPort",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Via",zodProps:ime}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){const{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){const{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){const{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),a=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:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((l=this.getGroup())==null?void 0:l.pcb_group_id)??void 0});this.pcb_via_id=o.pcb_via_id}},Zft=class extends $v{constructor(){super(...arguments);Ke(this,"pcb_cutout_id",null);Ke(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:G0e}}doInitialPcbPrimitiveRender(){var l,c;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),a=((c=this.getGroup())==null?void 0:c.pcb_group_id)??void 0,o=this._getGlobalPcbPositionBeforeLayout();let s;if(n.shape==="rect"){const u={shape:"rect",center:o,width:n.width,height:n.height,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:a};s=t.pcb_cutout.insert(u)}else if(n.shape==="circle"){const u={shape:"circle",center:o,radius:n.radius,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:a};s=t.pcb_cutout.insert(u)}else if(n.shape==="polygon"){const u=this._computePcbGlobalTransformBeforeLayout(),d={shape:"polygon",points:n.points.map(f=>ti(u,f)),subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:a};s=t.pcb_cutout.insert(d)}s&&(this.pcb_cutout_id=s.pcb_cutout_id)}getPcbSize(){const{_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,a=1/0,o=-1/0;for(const s of t.points)n=Math.min(n,s.x),i=Math.max(i,s.x),a=Math.min(a,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-a}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();const{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,a=-1/0,o=1/0,s=-1/0;for(const l of n.points)i=Math.min(i,l.x),a=Math.max(a,l.x),o=Math.min(o,l.y),s=Math.max(s,l.y);return{center:{x:(i+a)/2,y:(o+s)/2},bounds:{left:i,top:s,right:a,bottom:o},width:a-i,height:s-o}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(t){if(!this.pcb_cutout_id)return;const{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"){const a=this._getPcbCircuitJsonBounds().center,o=t.x-a.x,s=t.y-a.y,l=i.points.map(c=>({x:c.x+o,y:c.y+s}));n.pcb_cutout.update(this.pcb_cutout_id,{...i,points:l})}}}},Xft=class extends T1{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:K0e,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:t.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}},$ft=class extends T1{get config(){return{componentName:"PinHeader",zodProps:j0e,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){var a;const e=this._parsedProps.pinCount??((a=this._parsedProps.pinLabels)==null?void 0:a.length)??0,t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch;return e>0&&i?!t&&!n?`pinrow${e}_p${i}`:`pinrow${e}_p${i}_id${t}_od${n}`:null}initPorts(){var t,n;const e=this._parsedProps.pinCount??((t=this._parsedProps.pinLabels)==null?void 0:t.length)??1;for(let i=1;i<=e;i++)this.add(new GS({name:`pin${i}`,pinNumber:i,aliases:[(n=this._parsedProps.pinLabels)==null?void 0:n[i-1]].filter(Boolean)}))}_getSchematicPortArrangement(){var i,a,o,s;const e=this._parsedProps.pinCount??1,t=this._parsedProps.facingDirection??"right",n=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:((i=n==null?void 0:n.leftSide)==null?void 0:i.direction)??"top-to-bottom",pins:((a=n==null?void 0:n.leftSide)==null?void 0:a.pins)??Array.from({length:e},(l,c)=>`pin${c+1}`)}}:{rightSide:{direction:((o=n==null?void 0:n.rightSide)==null?void 0:o.direction)??"top-to-bottom",pins:((s=n==null?void 0:n.rightSide)==null?void 0:s.pins)??Array.from({length:e},(l,c)=>`pin${c+1}`)}}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:t.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 eht(r){switch(r){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var tht=class extends T1{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??eht(this.props.pinVariant),zodProps:U0e,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:t.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}},nht=class extends T1{get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:X0e,sourceFtype:oQ.simple_inductor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:t.name,ftype:oQ.simple_inductor,inductance:t.inductance,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function rht(r){switch(r){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var iht=class extends T1{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??rht(this.props.pinVariant),zodProps:P0e,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:t.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},aht=class extends T1{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:W0e,sourceFtype:oQ.simple_push_button}}get defaultInternallyConnectedPinNames(){return[["pin1","pin4"],["pin2","pin3"]]}initPorts(){super.initPorts({pinCount:4,additionalAliases:{pin1:["side1"],pin3:["side2"]}})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:t.name,ftype:oQ.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},oht=class extends T1{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:k0e,sourceFtype:"simple_crystal"}}initPorts(){const 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(){return`${kB(this._parsedProps.frequency)}Hz`}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:t.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}},sht=class extends T1{constructor(){super(...arguments);Ke(this,"emitter",this.portMap.pin1);Ke(this,"collector",this.portMap.pin2);Ke(this,"base",this.portMap.pin3)}get config(){return{componentName:"Transistor",schematicSymbolName:this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor",zodProps:q0e,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){const t=this.props.type==="npn"?{pin1:["emitter","e"],pin2:["collector","c"],pin3:["base","b"]}:{pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:n.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},lht=class extends T1{get config(){const e=this.props.mosfetMode==="depletion"?"d":"e";return{componentName:"Mosfet",schematicSymbolName:`${this.props.channelType}_channel_${e}_mosfet_transistor`,zodProps:Z0e,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:t.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}},cht=class extends T1{_getSwitchType(){const{spst:e,spdt:t,dpst:n,dpdt:i,type:a}=this._parsedProps??{};return i?"dpdt":e?"spst":t?"spdt":n?"dpst":a??"spst"}get config(){const e=this._getSwitchType(),{isNormallyClosed:t}=this._parsedProps??{};return{componentName:"Switch",schematicSymbolName:{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",zodProps:tme,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_switch",name:t.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}},uht=class extends $v{constructor(){super(...arguments);Ke(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:lme}}doInitialSchematicPrimitiveRender(){var i;if((i=this.root)!=null&&i.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this;t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:n.schX,y:n.schY},rotation:n.schRotation??0})}},Aht=class extends $v{constructor(){super(...arguments);Ke(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:sme,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){var I;if((I=this.root)!=null&&I.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=sme.safeParse(t);if(!n.success)throw console.error("Validation failed:",n.error.format()),n.error;const i=.6,a=typeof t.padding=="number"?t.padding:0,o=typeof t.paddingTop=="number"?t.paddingTop:a,s=typeof t.paddingBottom=="number"?t.paddingBottom:a,l=typeof t.paddingLeft=="number"?t.paddingLeft:a,c=typeof t.paddingRight=="number"?t.paddingRight:a,u=t.overlay&&t.overlay.length>0,A=typeof t.width=="number"&&typeof t.height=="number";let d,f,g,_;if(u){const x=t.overlay.map(Re=>({selector:Re,port:this.getSubcircuit().selectOne(Re,{type:"port"})})).filter(({port:Re})=>Re!=null).map(({port:Re})=>({position:Re._getGlobalSchematicPositionAfterLayout()}));if(x.length===0)return;const B=x.map(Re=>Re.position.x),P=x.map(Re=>Re.position.y),L=Math.min(...B),U=Math.max(...B),H=Math.min(...P),G=Math.max(...P),W=U-L,z=G-H,ae=W===0?i:0,te=z===0?i:0,oe=l+ae/2,pe=c+ae/2,Ae=o+te/2,he=s+te/2,Ie=L-oe,ge=U+pe,Me=H-he,Se=G+Ae;d=ge-Ie,f=Se-Me,g=Ie+(t.schX??0),_=Me+(t.schY??0)}else if(A){d=t.width,f=t.height;const E=typeof t.schX=="number"?t.schX:0,x=typeof t.schY=="number"?t.schY:0;g=E-d/2,_=x-f/2}else return;e.schematic_box.insert({height:f,width:d,x:g,y:_,is_dashed:t.strokeStyle==="dashed",schematic_component_id:""})}},dht={version:"0.0.448"},fht=class{constructor({platform:r}={}){Ke(this,"firstChild",null);Ke(this,"children");Ke(this,"db");Ke(this,"root",null);Ke(this,"isRoot",!0);Ke(this,"schematicDisabled",!1);Ke(this,"pcbDisabled",!1);Ke(this,"pcbRoutingDisabled",!1);Ke(this,"name");Ke(this,"platform");Ke(this,"_hasRenderedAtleastOnce",!1);Ke(this,"_eventListeners",{});this.children=[],this.db=o1([]),this.root=this,this.platform=r}add(r){let e;nt.isValidElement(r)?e=Pye(r):e=r,this.children.push(e)}_getBoard(){return this.children.find(r=>r.componentName==="Board")}_guessRootComponent(){if(!this.firstChild){if(this.children.length===1){this.firstChild=this.children[0];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>0){const r=this.children.find(e=>e.componentName==="Board")??null;if(r){this.firstChild=r;return}}throw new Error("Not able to guess root component: RootCircuit has multiple children and no board")}}render(){this.firstChild||this._guessRootComponent();const{firstChild:r,db:e}=this;if(!r)throw new Error("RootCircuit has no root component");r.parent=this,r.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){var r;for((r=this.db.source_project_metadata.list())!=null&&r[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(e=>setTimeout(e,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(r=>r._hasIncompleteAsyncEffects()?!0:r.children.some(e=>e._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(r){const e=await Promise.resolve().then(()=>mHt).catch(t=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
855
855
 
856
856
  "${t.message}"`)});if(r.view==="pcb")return e.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(r.view==="schematic")return e.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${r.view}`)}getCoreVersion(){const[r,e,t]=dht.version.split(".").map(Number);return`${r}.${e}.${t+1}`}async preview(r){throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return wy()}_computePcbGlobalTransformBeforeLayout(){return wy()}selectAll(r){var e;return this._guessRootComponent(),((e=this.firstChild)==null?void 0:e.selectAll(r))??[]}selectOne(r,e){var t;return this._guessRootComponent(),((t=this.firstChild)==null?void 0:t.selectOne(r,e))??null}emit(r,...e){if(this._eventListeners[r])for(const t of this._eventListeners[r])t(...e)}on(r,e){this._eventListeners[r]||(this._eventListeners[r]=[]),this._eventListeners[r].push(e)}removeListener(r,e){this._eventListeners[r]&&(this._eventListeners[r]=this._eventListeners[r].filter(t=>t!==e))}getClientOrigin(){return typeof window<"u"?window.location.origin:typeof self<"u"?self.origin:""}},hht=fht;new Proxy({},{get:(r,e)=>{const t=(...n)=>(n[0],new Proxy({},{get:(i,a)=>`.${e} > .${a}`}));return new Proxy(t,{get:(n,i)=>e==="net"?`net.${i}`:e==="subcircuit"?new Proxy({},{get:(a,o)=>new Proxy({},{get:(s,l)=>`subcircuit.${i} > .${o} > .${l}`})}):`.${e} > .${i}`,apply:(n,i,a)=>new Proxy({},{get:(o,s)=>{const l=`.${e} > .${s}`;return e.startsWith("U")?l:new Proxy(new String(l),{get:(c,u)=>typeof u=="symbol"||u==="toString"?()=>l:`.${e} > .${s} > .${u}`})}})})}}),Dye(Qye),Dye({Bug:$ye});const eve=nv("run-frame"),pht={},tve=r=>{let e;const t=new Set,n=(u,A)=>{const d=typeof u=="function"?u(e):u;if(!Object.is(d,e)){const f=e;e=A??(typeof d!="object"||d===null)?d:Object.assign({},e,d),t.forEach(g=>g(e,f))}},i=()=>e,l={setState:n,getState:i,getInitialState:()=>c,subscribe:u=>(t.add(u),()=>t.delete(u)),destroy:()=>{(pht?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),t.clear()}},c=e=r(n,i,l);return l},nve=r=>r?tve(r):tve;var Ak={exports:{}},pK={},dk={exports:{}},gK={};/**
857
857
  * @license React
@@ -13075,7 +13075,7 @@ ${l.join(`
13075
13075
  `)!==-1&&(r=r.replace(/\r\n/g,`
13076
13076
  `)),r.indexOf(`\\
13077
13077
  `)!==-1&&(r=r.replace(/\\\n/g,""));const t=r.split(`
13078
- `);let n="",i="",a=0,o=[];const s=typeof"".trimLeft=="function";for(let u=0,A=t.length;u<A;u++)if(n=t[u],n=s?n.trimLeft():n.trim(),a=n.length,a!==0&&(i=n.charAt(0),i!=="#"))if(i==="v"){const d=n.split(/\s+/);switch(d[0]){case"v":e.vertices.push(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3])),d.length>=7?e.colors.push(parseFloat(d[4]),parseFloat(d[5]),parseFloat(d[6])):e.colors.push(void 0,void 0,void 0);break;case"vn":e.normals.push(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3]));break;case"vt":e.uvs.push(parseFloat(d[1]),parseFloat(d[2]));break}}else if(i==="f"){const f=n.substr(1).trim().split(/\s+/),g=[];for(let I=0,E=f.length;I<E;I++){const x=f[I];if(x.length>0){const B=x.split("/");g.push(B)}}const _=g[0];for(let I=1,E=g.length-1;I<E;I++){const x=g[I],B=g[I+1];e.addFace(_[0],x[0],B[0],_[1],x[1],B[1],_[2],x[2],B[2])}}else if(i==="l"){const d=n.substring(1).trim().split(" ");let f=[];const g=[];if(n.indexOf("/")===-1)f=d;else for(let _=0,I=d.length;_<I;_++){const E=d[_].split("/");E[0]!==""&&f.push(E[0]),E[1]!==""&&g.push(E[1])}e.addLineGeometry(f,g)}else if(i==="p"){const f=n.substr(1).trim().split(" ");e.addPointGeometry(f)}else if((o=TFt.exec(n))!==null){const d=(" "+o[0].substr(1).trim()).substr(1);e.startObject(d)}else if(kFt.test(n))e.object.startMaterial(n.substring(7).trim(),e.materialLibraries);else if(PFt.test(n))e.materialLibraries.push(n.substring(7).trim());else if(UFt.test(n))console.warn('THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.');else if(i==="s"){if(o=n.split(" "),o.length>1){const f=o[1].trim().toLowerCase();e.object.smooth=f!=="0"&&f!=="off"}else e.object.smooth=!0;const d=e.object.currentMaterial();d&&(d.smooth=e.object.smooth)}else{if(n==="\0")continue;console.warn('THREE.OBJLoader: Unexpected line: "'+n+'"')}e.finalize();const l=new RQ;if(l.materialLibraries=[].concat(e.materialLibraries),!(e.objects.length===1&&e.objects[0].geometry.vertices.length===0)===!0)for(let u=0,A=e.objects.length;u<A;u++){const d=e.objects[u],f=d.geometry,g=d.materials,_=f.type==="Line",I=f.type==="Points";let E=!1;if(f.vertices.length===0)continue;const x=new wf;x.setAttribute("position",new jc(f.vertices,3)),f.normals.length>0&&x.setAttribute("normal",new jc(f.normals,3)),f.colors.length>0&&(E=!0,x.setAttribute("color",new jc(f.colors,3))),f.hasUVIndices===!0&&x.setAttribute("uv",new jc(f.uvs,2));const B=[];for(let L=0,U=g.length;L<U;L++){const H=g[L],G=H.name+"_"+H.smooth+"_"+E;let W=e.materials[G];if(this.materials!==null){if(W=this.materials.create(H.name),_&&W&&!(W instanceof uE)){const z=new uE;ZE.prototype.copy.call(z,W),z.color.copy(W.color),W=z}else if(I&&W&&!(W instanceof FQ)){const z=new FQ({size:10,sizeAttenuation:!1});ZE.prototype.copy.call(z,W),z.color.copy(W.color),z.map=W.map,W=z}}W===void 0&&(_?W=new uE:I?W=new FQ({size:1,sizeAttenuation:!1}):W=new LF,W.name=H.name,W.flatShading=!H.smooth,W.vertexColors=E,e.materials[G]=W),B.push(W)}let P;if(B.length>1){for(let L=0,U=g.length;L<U;L++){const H=g[L];x.addGroup(H.groupStart,H.groupCount,L)}_?P=new OB(x,B):I?P=new uR(x,B):P=new av(x,B)}else _?P=new OB(x,B[0]):I?P=new uR(x,B[0]):P=new av(x,B[0]);P.name=d.name,l.add(P)}else if(e.vertices.length>0){const u=new FQ({size:1,sizeAttenuation:!1}),A=new wf;A.setAttribute("position",new jc(e.vertices,3)),e.colors.length>0&&e.colors[0]!==void 0&&(A.setAttribute("color",new jc(e.colors,3)),u.vertexColors=!0);const d=new uR(A,u);l.add(d)}return l}};function GFt({stlUrl:r,mtlUrl:e,color:t,opacity:n=1}){const i=Wne(DFt,r),a=nt.useRef();return Ve.jsxs("mesh",{ref:a,children:[Ve.jsx("primitive",{object:i,attach:"geometry"}),Ve.jsx("meshStandardMaterial",{color:t,transparent:n!==1,opacity:n})]})}var OFt={version:"0.0.256"};typeof window<"u"&&(window.TSCI_MAIN_CAMERA_ROTATION=new Kx(0,0,0));function zFt(r,e){const t=new v_().setFromEuler(new Kx(r.x,r.y,r.z)),n=new Xn(0,0,1);return n.applyQuaternion(t),n.multiplyScalar(e)}var HFt=({})=>{const r=nt.useRef();return nt.useRef({lastRotation:new Kx}),MR((e,t)=>{if(!r.current)return;const n=window.TSCI_MAIN_CAMERA_ROTATION,i=zFt(n,2);e.camera.position.copy(i),e.camera.lookAt(0,0,0)}),Ve.jsxs("mesh",{ref:r,rotation:[Math.PI/2,0,0],children:[Ve.jsx("boxGeometry",{args:[1,1,1]}),Ve.jsx("meshStandardMaterial",{color:"white"}),Ve.jsx(XQ,{position:[0,0,.51],fontSize:.25,color:"black",children:"Front"}),Ve.jsx(XQ,{position:[0,0,-.51],fontSize:.25,color:"black",rotation:[0,Math.PI,0],children:"Back"}),Ve.jsx(XQ,{position:[.51,0,0],fontSize:.25,color:"black",rotation:[0,Math.PI/2,0],children:"Right"}),Ve.jsx(XQ,{position:[-.51,0,0],fontSize:.25,color:"black",rotation:[0,-Math.PI/2,0],children:"Left"}),Ve.jsx(XQ,{position:[0,.51,0],fontSize:.25,color:"black",rotation:[-Math.PI/2,0,0],children:"Top"}),Ve.jsx(XQ,{position:[0,-.51,0],fontSize:.25,color:"black",rotation:[Math.PI/2,0,0],children:"Bottom"}),Ve.jsx("lineSegments",{args:[new Ane(new cw(1,1,1))],material:new uE({color:0,linewidth:2})})]})},YFt=()=>(MR(({camera:r})=>{window.TSCI_MAIN_CAMERA_ROTATION=r.rotation}),Ve.jsx(Ve.Fragment,{})),L8e=nt.forwardRef(({children:r,initialCameraPosition:e=[5,5,5],autoRotateDisabled:t,clickToInteractEnabled:n=!1},i)=>{const[a,o]=nt.useState(!n);return Ve.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[Ve.jsx("div",{style:{position:"absolute",top:0,left:0,width:120,height:120},children:Ve.jsxs(xMe,{camera:{up:[0,0,1],position:[1,1,1]},style:{zIndex:10},children:[Ve.jsx("ambientLight",{intensity:Math.PI/2}),Ve.jsx(HFt,{})]})}),Ve.jsxs(xMe,{scene:{up:[0,0,1]},camera:{up:[0,0,1],position:e},children:[Ve.jsx(YFt,{}),a&&Ve.jsx(_2t,{autoRotate:!t,autoRotateSpeed:1}),Ve.jsx("ambientLight",{intensity:Math.PI/2}),Ve.jsx("pointLight",{position:[-10,-10,10],decay:0,intensity:Math.PI/4}),Ve.jsx(B2t,{rotation:[Math.PI/2,0,0],infiniteGrid:!0,cellSize:1,sectionSize:10}),Ve.jsx("object3D",{ref:i,children:r})]}),Ve.jsxs("div",{style:{position:"absolute",right:24,bottom:24,fontFamily:"sans-serif",color:"white",WebkitTextStroke:"0.5px rgba(0, 0, 0, 0.5)",fontSize:11},children:["@",OFt.version]}),n&&!a&&Ve.jsx("div",{onClick:()=>o(!0),style:{position:"absolute",inset:0,cursor:"pointer",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center"},children:Ve.jsx("div",{style:{backgroundColor:"rgba(0, 0, 0, 0.8)",color:"white",padding:"12px 24px",borderRadius:"8px",fontSize:"16px",fontFamily:"sans-serif",pointerEvents:"none"},children:"Click to Interact"})})]})}),VFt=FI(k3()),KFt=FI(DN()),vm=.01,pE={copper:[.9,.6,.2],fr4Green:[5/255,163/255,46/255],fr4GreenSolderWithMask:[0/255,152/255,19/255],fr1Copper:[.8,.4,.2],fr1CopperSolderWithMask:[.9,.6,.2]},U3=.001,d9=32,jFt=.035,C6=50,Dae={fr1:pE.fr1Copper,fr4:pE.fr4Green},G8e={fr1:pE.fr1CopperSolderWithMask,fr4:pE.fr4GreenSolderWithMask},JFt=FI(m6()),WFt=FI(k3()),qFt=FI(I6()),O8e=r=>{let e=0;for(let n=0;n<r.length;n++){const i=(n+1)%r.length;e+=r[n][0]*r[i][1],e-=r[i][0]*r[n][1]}return e/2<=0},z8e=(r,e=1.2)=>{const{center:t,outline:n}=r;let i=n.map(s=>[s.x,s.y]);O8e(i)&&(i=i.reverse());const a=(0,WFt.polygon)({points:i});let o=(0,JFt.extrudeLinear)({height:e},a);return o=(0,qFt.translate)([t.x,t.y,-e/2],o),o},ZFt=r=>{const e=sm(r).pcb_board.list()[0];if(!e)return console.warn("No pcb_board found for simplified geometry"),[];let t;const n=1.2;e.outline&&e.outline.length>0?t=z8e({center:e.center,outline:e.outline},n):t=(0,VFt.cuboid)({size:[e.width,e.height,n],center:[e.center.x,e.center.y,0]});const i=Dae[e.material]??pE.fr4Green;return[(0,KFt.colorize)(i,t)]},f9=FI(I6()),ix=FI(k3()),F3=FI(DN()),h9=FI(xae()),lv=FI(k3()),E6=FI(DN()),mB=FI(xae()),TC=.05,H8e=(r,e)=>{if(r.shape||(r.shape="circle"),r.shape==="circle")return(0,E6.colorize)(pE.copper,(0,mB.subtract)((0,mB.union)((0,lv.cylinder)({center:[r.x,r.y,0],radius:r.hole_diameter/2,height:e.pcbThickness}),(0,lv.cylinder)({center:[r.x,r.y,e.pcbThickness/2+TC/2+vm],radius:r.outer_diameter/2,height:TC}),(0,lv.cylinder)({center:[r.x,r.y,-e.pcbThickness/2-TC/2-vm],radius:r.outer_diameter/2,height:TC})),(0,lv.cylinder)({center:[r.x,r.y,0],radius:r.hole_diameter/2-vm,height:1.5})));if(r.shape==="circular_hole_with_rect_pad"){const t=r.rect_pad_width||r.hole_diameter,n=r.rect_pad_height||r.hole_diameter;return(0,E6.colorize)(pE.copper,(0,mB.subtract)((0,mB.union)((0,lv.cuboid)({center:[r.x,r.y,1.2/2],size:[t,n,TC]}),(0,lv.cuboid)({center:[r.x,r.y,-1.2/2],size:[t,n,TC]}),(0,lv.cylinder)({center:[r.x,r.y,0],radius:r.hole_diameter/2,height:1.2})),(0,lv.cylinder)({center:[r.x,r.y,0],radius:Math.max(r.hole_diameter/2-vm,.01),height:1.5})))}if(r.shape==="pill"){const t=r.hole_height>r.hole_width,n=t?r.hole_height:r.hole_width,i=t?r.hole_width:r.hole_height,a=t?r.outer_height||i+.2:r.outer_width||n+.2,o=t?r.outer_width||n+.2:r.outer_height||i+.2,s=i/2,l=o/2,c=Math.abs(n-i),u=Math.abs(a-o),A=(0,lv.cuboid)({center:[r.x,r.y,0],size:t?[i,c,e.pcbThickness]:[c,i,e.pcbThickness]}),d=(0,lv.cylinder)({center:t?[r.x,r.y-c/2,0]:[r.x-c/2,r.y,0],radius:s,height:e.pcbThickness}),f=(0,lv.cylinder)({center:t?[r.x,r.y+c/2,0]:[r.x+c/2,r.y,0],radius:s,height:e.pcbThickness}),g=(0,mB.union)(A,d,f),_=e.pcbThickness/2+TC/2+vm,I=(0,lv.cuboid)({center:[r.x,r.y,_],size:t?[o,u,TC]:[u,o,TC]}),E=(0,lv.cylinder)({center:t?[r.x,r.y-u/2,_]:[r.x-u/2,r.y,_],radius:l,height:TC}),x=(0,lv.cylinder)({center:t?[r.x,r.y+u/2,_]:[r.x+u/2,r.y,_],radius:l,height:TC}),B=(0,mB.union)(I,E,x),P=-e.pcbThickness/2-TC/2-vm,L=(0,lv.cuboid)({center:[r.x,r.y,P],size:t?[o,u,TC]:[u,o,TC]}),U=(0,lv.cylinder)({center:t?[r.x,r.y-u/2,P]:[r.x-u/2,r.y,P],radius:l,height:TC}),H=(0,lv.cylinder)({center:t?[r.x,r.y+u/2,P]:[r.x+u/2,r.y,P],radius:l,height:TC}),G=(0,mB.union)(L,U,H),W=(0,lv.cuboid)({center:[r.x,r.y,0],size:t?[i-2*vm,c,e.pcbThickness+2*vm]:[c,i-2*vm,e.pcbThickness+2*vm]}),z=(0,lv.cylinder)({center:t?[r.x,r.y-c/2,0]:[r.x-c/2,r.y,0],radius:s-vm,height:e.pcbThickness+2*vm}),ae=(0,lv.cylinder)({center:t?[r.x,r.y+c/2,0]:[r.x+c/2,r.y,0],radius:s-vm,height:e.pcbThickness+2*vm}),te=(0,mB.union)(W,z,ae);return(0,E6.colorize)(pE.copper,(0,mB.subtract)((0,mB.union)(g,B,G),te))}if(r.shape==="pill_hole_with_rect_pad"){const t=r.hole_height>r.hole_width,n=t?r.hole_height:r.hole_width,i=t?r.hole_width:r.hole_height,a=i/2,o=Math.abs(n-i),s=r.rect_pad_width||n+.2,l=r.rect_pad_height||i+.2,c=(0,lv.cuboid)({center:[r.x,r.y,0],size:t?[i,o,1.2]:[o,i,1.2]}),u=(0,lv.cylinder)({center:t?[r.x,r.y-o/2,0]:[r.x-o/2,r.y,0],radius:a,height:1.2}),A=(0,lv.cylinder)({center:t?[r.x,r.y+o/2,0]:[r.x+o/2,r.y,0],radius:a,height:1.2}),d=(0,lv.cuboid)({center:[r.x,r.y,1.2/2],size:[s,l,TC]}),f=(0,lv.cuboid)({center:[r.x,r.y,-1.2/2],size:[s,l,TC]}),g=(0,mB.union)((0,lv.cuboid)({center:[r.x,r.y,0],size:t?[i-TC,o,1.5]:[o,i-TC,1.5]}),(0,lv.cylinder)({center:t?[r.x,r.y-o/2,0]:[r.x-o/2,r.y,0],radius:a-TC,height:1.5}),(0,lv.cylinder)({center:t?[r.x,r.y+o/2,0]:[r.x+o/2,r.y,0],radius:a-TC,height:1.5}));return(0,E6.colorize)(pE.copper,(0,mB.subtract)((0,mB.union)(c,u,A,d,f),g))}else throw new Error(`Unsupported plated hole shape: ${r.shape}`)},_6=FI(m6()),Y8e=FI(Bae()),XFt=FI(bae());function V8e(r,e){return Array.isArray(e)?[r.a*e[0]+r.c*e[1]+r.e,r.b*e[0]+r.d*e[1]+r.f]:{x:r.a*e.x+r.c*e.y+r.e,y:r.b*e.x+r.d*e.y+r.f}}function _w(r,e=0){return{a:1,c:0,e:r,b:0,d:1,f:e}}function K8e(...r){r=Array.isArray(r[0])?r[0]:r;const e=(t,n)=>({a:t.a*n.a+t.c*n.b,c:t.a*n.c+t.c*n.d,e:t.a*n.e+t.c*n.f+t.e,b:t.b*n.a+t.d*n.b,d:t.b*n.c+t.d*n.d,f:t.b*n.e+t.d*n.f+t.f});switch(r.length){case 0:throw new Error("no matrices provided");case 1:return r[0];case 2:return e(r[0],r[1]);default:{const[t,n,...i]=r,a=e(t,n);return K8e(a,...i)}}}function j8e(...r){return K8e(...r)}var{cos:$Ft,sin:eLt}=Math;function J8e(r,e,t){const n=$Ft(r),i=eLt(r);return{a:n,c:-i,e:0,b:i,d:n,f:0}}function tLt(r,e){function t(){this.constructor=r}t.prototype=e.prototype,r.prototype=new t}function x6(r,e,t,n){var i=Error.call(this,r);return Object.setPrototypeOf&&Object.setPrototypeOf(i,x6.prototype),i.expected=e,i.found=t,i.location=n,i.name="SyntaxError",i}tLt(x6,Error);function Rae(r,e,t){return t=t||" ",r.length>e?r:(e-=r.length,t+=t.repeat(e),r+t.slice(0,e))}x6.prototype.format=function(r){var e="Error: "+this.message;if(this.location){var t=null,n;for(n=0;n<r.length;n++)if(r[n].source===this.location.source){t=r[n].text.split(/\r\n|\n|\r/g);break}var i=this.location.start,a=this.location.source&&typeof this.location.source.offset=="function"?this.location.source.offset(i):i,o=this.location.source+":"+a.line+":"+a.column;if(t){var s=this.location.end,l=Rae("",a.line.toString().length," "),c=t[i.line-1],u=i.line===s.line?s.column:c.length+1,A=u-i.column||1;e+=`
13078
+ `);let n="",i="",a=0,o=[];const s=typeof"".trimLeft=="function";for(let u=0,A=t.length;u<A;u++)if(n=t[u],n=s?n.trimLeft():n.trim(),a=n.length,a!==0&&(i=n.charAt(0),i!=="#"))if(i==="v"){const d=n.split(/\s+/);switch(d[0]){case"v":e.vertices.push(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3])),d.length>=7?e.colors.push(parseFloat(d[4]),parseFloat(d[5]),parseFloat(d[6])):e.colors.push(void 0,void 0,void 0);break;case"vn":e.normals.push(parseFloat(d[1]),parseFloat(d[2]),parseFloat(d[3]));break;case"vt":e.uvs.push(parseFloat(d[1]),parseFloat(d[2]));break}}else if(i==="f"){const f=n.substr(1).trim().split(/\s+/),g=[];for(let I=0,E=f.length;I<E;I++){const x=f[I];if(x.length>0){const B=x.split("/");g.push(B)}}const _=g[0];for(let I=1,E=g.length-1;I<E;I++){const x=g[I],B=g[I+1];e.addFace(_[0],x[0],B[0],_[1],x[1],B[1],_[2],x[2],B[2])}}else if(i==="l"){const d=n.substring(1).trim().split(" ");let f=[];const g=[];if(n.indexOf("/")===-1)f=d;else for(let _=0,I=d.length;_<I;_++){const E=d[_].split("/");E[0]!==""&&f.push(E[0]),E[1]!==""&&g.push(E[1])}e.addLineGeometry(f,g)}else if(i==="p"){const f=n.substr(1).trim().split(" ");e.addPointGeometry(f)}else if((o=TFt.exec(n))!==null){const d=(" "+o[0].substr(1).trim()).substr(1);e.startObject(d)}else if(kFt.test(n))e.object.startMaterial(n.substring(7).trim(),e.materialLibraries);else if(PFt.test(n))e.materialLibraries.push(n.substring(7).trim());else if(UFt.test(n))console.warn('THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.');else if(i==="s"){if(o=n.split(" "),o.length>1){const f=o[1].trim().toLowerCase();e.object.smooth=f!=="0"&&f!=="off"}else e.object.smooth=!0;const d=e.object.currentMaterial();d&&(d.smooth=e.object.smooth)}else{if(n==="\0")continue;console.warn('THREE.OBJLoader: Unexpected line: "'+n+'"')}e.finalize();const l=new RQ;if(l.materialLibraries=[].concat(e.materialLibraries),!(e.objects.length===1&&e.objects[0].geometry.vertices.length===0)===!0)for(let u=0,A=e.objects.length;u<A;u++){const d=e.objects[u],f=d.geometry,g=d.materials,_=f.type==="Line",I=f.type==="Points";let E=!1;if(f.vertices.length===0)continue;const x=new wf;x.setAttribute("position",new jc(f.vertices,3)),f.normals.length>0&&x.setAttribute("normal",new jc(f.normals,3)),f.colors.length>0&&(E=!0,x.setAttribute("color",new jc(f.colors,3))),f.hasUVIndices===!0&&x.setAttribute("uv",new jc(f.uvs,2));const B=[];for(let L=0,U=g.length;L<U;L++){const H=g[L],G=H.name+"_"+H.smooth+"_"+E;let W=e.materials[G];if(this.materials!==null){if(W=this.materials.create(H.name),_&&W&&!(W instanceof uE)){const z=new uE;ZE.prototype.copy.call(z,W),z.color.copy(W.color),W=z}else if(I&&W&&!(W instanceof FQ)){const z=new FQ({size:10,sizeAttenuation:!1});ZE.prototype.copy.call(z,W),z.color.copy(W.color),z.map=W.map,W=z}}W===void 0&&(_?W=new uE:I?W=new FQ({size:1,sizeAttenuation:!1}):W=new LF,W.name=H.name,W.flatShading=!H.smooth,W.vertexColors=E,e.materials[G]=W),B.push(W)}let P;if(B.length>1){for(let L=0,U=g.length;L<U;L++){const H=g[L];x.addGroup(H.groupStart,H.groupCount,L)}_?P=new OB(x,B):I?P=new uR(x,B):P=new av(x,B)}else _?P=new OB(x,B[0]):I?P=new uR(x,B[0]):P=new av(x,B[0]);P.name=d.name,l.add(P)}else if(e.vertices.length>0){const u=new FQ({size:1,sizeAttenuation:!1}),A=new wf;A.setAttribute("position",new jc(e.vertices,3)),e.colors.length>0&&e.colors[0]!==void 0&&(A.setAttribute("color",new jc(e.colors,3)),u.vertexColors=!0);const d=new uR(A,u);l.add(d)}return l}};function GFt({stlUrl:r,mtlUrl:e,color:t,opacity:n=1}){const i=Wne(DFt,r),a=nt.useRef();return Ve.jsxs("mesh",{ref:a,children:[Ve.jsx("primitive",{object:i,attach:"geometry"}),Ve.jsx("meshStandardMaterial",{color:t,transparent:n!==1,opacity:n})]})}var OFt={version:"0.0.259"};typeof window<"u"&&(window.TSCI_MAIN_CAMERA_ROTATION=new Kx(0,0,0));function zFt(r,e){const t=new v_().setFromEuler(new Kx(r.x,r.y,r.z)),n=new Xn(0,0,1);return n.applyQuaternion(t),n.multiplyScalar(e)}var HFt=({})=>{const r=nt.useRef();return nt.useRef({lastRotation:new Kx}),MR((e,t)=>{if(!r.current)return;const n=window.TSCI_MAIN_CAMERA_ROTATION,i=zFt(n,2);e.camera.position.copy(i),e.camera.lookAt(0,0,0)}),Ve.jsxs("mesh",{ref:r,rotation:[Math.PI/2,0,0],children:[Ve.jsx("boxGeometry",{args:[1,1,1]}),Ve.jsx("meshStandardMaterial",{color:"white"}),Ve.jsx(XQ,{position:[0,0,.51],fontSize:.25,color:"black",children:"Front"}),Ve.jsx(XQ,{position:[0,0,-.51],fontSize:.25,color:"black",rotation:[0,Math.PI,0],children:"Back"}),Ve.jsx(XQ,{position:[.51,0,0],fontSize:.25,color:"black",rotation:[0,Math.PI/2,0],children:"Right"}),Ve.jsx(XQ,{position:[-.51,0,0],fontSize:.25,color:"black",rotation:[0,-Math.PI/2,0],children:"Left"}),Ve.jsx(XQ,{position:[0,.51,0],fontSize:.25,color:"black",rotation:[-Math.PI/2,0,0],children:"Top"}),Ve.jsx(XQ,{position:[0,-.51,0],fontSize:.25,color:"black",rotation:[Math.PI/2,0,0],children:"Bottom"}),Ve.jsx("lineSegments",{args:[new Ane(new cw(1,1,1))],material:new uE({color:0,linewidth:2})})]})},YFt=()=>(MR(({camera:r})=>{window.TSCI_MAIN_CAMERA_ROTATION=r.rotation}),Ve.jsx(Ve.Fragment,{})),L8e=nt.forwardRef(({children:r,initialCameraPosition:e=[5,5,5],autoRotateDisabled:t,clickToInteractEnabled:n=!1},i)=>{const[a,o]=nt.useState(!n);return Ve.jsxs("div",{style:{position:"relative",width:"100%",height:"100%"},children:[Ve.jsx("div",{style:{position:"absolute",top:0,left:0,width:120,height:120},children:Ve.jsxs(xMe,{camera:{up:[0,0,1],position:[1,1,1]},style:{zIndex:10},children:[Ve.jsx("ambientLight",{intensity:Math.PI/2}),Ve.jsx(HFt,{})]})}),Ve.jsxs(xMe,{scene:{up:[0,0,1]},camera:{up:[0,0,1],position:e},children:[Ve.jsx(YFt,{}),a&&Ve.jsx(_2t,{autoRotate:!t,autoRotateSpeed:1}),Ve.jsx("ambientLight",{intensity:Math.PI/2}),Ve.jsx("pointLight",{position:[-10,-10,10],decay:0,intensity:Math.PI/4}),Ve.jsx(B2t,{rotation:[Math.PI/2,0,0],infiniteGrid:!0,cellSize:1,sectionSize:10}),Ve.jsx("object3D",{ref:i,children:r})]}),Ve.jsxs("div",{style:{position:"absolute",right:24,bottom:24,fontFamily:"sans-serif",color:"white",WebkitTextStroke:"0.5px rgba(0, 0, 0, 0.5)",fontSize:11},children:["@",OFt.version]}),n&&!a&&Ve.jsx("div",{onClick:()=>o(!0),style:{position:"absolute",inset:0,cursor:"pointer",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center"},children:Ve.jsx("div",{style:{backgroundColor:"rgba(0, 0, 0, 0.8)",color:"white",padding:"12px 24px",borderRadius:"8px",fontSize:"16px",fontFamily:"sans-serif",pointerEvents:"none"},children:"Click to Interact"})})]})}),VFt=FI(k3()),KFt=FI(DN()),vm=.01,pE={copper:[.9,.6,.2],fr4Green:[5/255,163/255,46/255],fr4GreenSolderWithMask:[0/255,152/255,19/255],fr1Copper:[.8,.4,.2],fr1CopperSolderWithMask:[.9,.6,.2]},U3=.001,d9=32,jFt=.035,C6=50,Dae={fr1:pE.fr1Copper,fr4:pE.fr4Green},G8e={fr1:pE.fr1CopperSolderWithMask,fr4:pE.fr4GreenSolderWithMask},JFt=FI(m6()),WFt=FI(k3()),qFt=FI(I6()),O8e=r=>{let e=0;for(let n=0;n<r.length;n++){const i=(n+1)%r.length;e+=r[n][0]*r[i][1],e-=r[i][0]*r[n][1]}return e/2<=0},z8e=(r,e=1.2)=>{const{center:t,outline:n}=r;let i=n.map(s=>[s.x,s.y]);O8e(i)&&(i=i.reverse());const a=(0,WFt.polygon)({points:i});let o=(0,JFt.extrudeLinear)({height:e},a);return o=(0,qFt.translate)([t.x,t.y,-e/2],o),o},ZFt=r=>{const e=sm(r).pcb_board.list()[0];if(!e)return console.warn("No pcb_board found for simplified geometry"),[];let t;const n=1.2;e.outline&&e.outline.length>0?t=z8e({center:e.center,outline:e.outline},n):t=(0,VFt.cuboid)({size:[e.width,e.height,n],center:[e.center.x,e.center.y,0]});const i=Dae[e.material]??pE.fr4Green;return[(0,KFt.colorize)(i,t)]},f9=FI(I6()),ix=FI(k3()),F3=FI(DN()),h9=FI(xae()),lv=FI(k3()),E6=FI(DN()),mB=FI(xae()),TC=.05,H8e=(r,e)=>{if(r.shape||(r.shape="circle"),r.shape==="circle")return(0,E6.colorize)(pE.copper,(0,mB.subtract)((0,mB.union)((0,lv.cylinder)({center:[r.x,r.y,0],radius:r.hole_diameter/2,height:e.pcbThickness}),(0,lv.cylinder)({center:[r.x,r.y,e.pcbThickness/2+TC/2+vm],radius:r.outer_diameter/2,height:TC}),(0,lv.cylinder)({center:[r.x,r.y,-e.pcbThickness/2-TC/2-vm],radius:r.outer_diameter/2,height:TC})),(0,lv.cylinder)({center:[r.x,r.y,0],radius:r.hole_diameter/2-vm,height:1.5})));if(r.shape==="circular_hole_with_rect_pad"){const t=r.rect_pad_width||r.hole_diameter,n=r.rect_pad_height||r.hole_diameter;return(0,E6.colorize)(pE.copper,(0,mB.subtract)((0,mB.union)((0,lv.cuboid)({center:[r.x,r.y,1.2/2],size:[t,n,TC]}),(0,lv.cuboid)({center:[r.x,r.y,-1.2/2],size:[t,n,TC]}),(0,lv.cylinder)({center:[r.x,r.y,0],radius:r.hole_diameter/2,height:1.2})),(0,lv.cylinder)({center:[r.x,r.y,0],radius:Math.max(r.hole_diameter/2-vm,.01),height:1.5})))}if(r.shape==="pill"){const t=r.hole_height>r.hole_width,n=t?r.hole_height:r.hole_width,i=t?r.hole_width:r.hole_height,a=t?r.outer_height||i+.2:r.outer_width||n+.2,o=t?r.outer_width||n+.2:r.outer_height||i+.2,s=i/2,l=o/2,c=Math.abs(n-i),u=Math.abs(a-o),A=(0,lv.cuboid)({center:[r.x,r.y,0],size:t?[i,c,e.pcbThickness]:[c,i,e.pcbThickness]}),d=(0,lv.cylinder)({center:t?[r.x,r.y-c/2,0]:[r.x-c/2,r.y,0],radius:s,height:e.pcbThickness}),f=(0,lv.cylinder)({center:t?[r.x,r.y+c/2,0]:[r.x+c/2,r.y,0],radius:s,height:e.pcbThickness}),g=(0,mB.union)(A,d,f),_=e.pcbThickness/2+TC/2+vm,I=(0,lv.cuboid)({center:[r.x,r.y,_],size:t?[o,u,TC]:[u,o,TC]}),E=(0,lv.cylinder)({center:t?[r.x,r.y-u/2,_]:[r.x-u/2,r.y,_],radius:l,height:TC}),x=(0,lv.cylinder)({center:t?[r.x,r.y+u/2,_]:[r.x+u/2,r.y,_],radius:l,height:TC}),B=(0,mB.union)(I,E,x),P=-e.pcbThickness/2-TC/2-vm,L=(0,lv.cuboid)({center:[r.x,r.y,P],size:t?[o,u,TC]:[u,o,TC]}),U=(0,lv.cylinder)({center:t?[r.x,r.y-u/2,P]:[r.x-u/2,r.y,P],radius:l,height:TC}),H=(0,lv.cylinder)({center:t?[r.x,r.y+u/2,P]:[r.x+u/2,r.y,P],radius:l,height:TC}),G=(0,mB.union)(L,U,H),W=(0,lv.cuboid)({center:[r.x,r.y,0],size:t?[i-2*vm,c,e.pcbThickness+2*vm]:[c,i-2*vm,e.pcbThickness+2*vm]}),z=(0,lv.cylinder)({center:t?[r.x,r.y-c/2,0]:[r.x-c/2,r.y,0],radius:s-vm,height:e.pcbThickness+2*vm}),ae=(0,lv.cylinder)({center:t?[r.x,r.y+c/2,0]:[r.x+c/2,r.y,0],radius:s-vm,height:e.pcbThickness+2*vm}),te=(0,mB.union)(W,z,ae);return(0,E6.colorize)(pE.copper,(0,mB.subtract)((0,mB.union)(g,B,G),te))}if(r.shape==="pill_hole_with_rect_pad"){const t=r.hole_height>r.hole_width,n=t?r.hole_height:r.hole_width,i=t?r.hole_width:r.hole_height,a=i/2,o=Math.abs(n-i),s=r.rect_pad_width||n+.2,l=r.rect_pad_height||i+.2,c=(0,lv.cuboid)({center:[r.x,r.y,0],size:t?[i,o,1.2]:[o,i,1.2]}),u=(0,lv.cylinder)({center:t?[r.x,r.y-o/2,0]:[r.x-o/2,r.y,0],radius:a,height:1.2}),A=(0,lv.cylinder)({center:t?[r.x,r.y+o/2,0]:[r.x+o/2,r.y,0],radius:a,height:1.2}),d=(0,lv.cuboid)({center:[r.x,r.y,1.2/2],size:[s,l,TC]}),f=(0,lv.cuboid)({center:[r.x,r.y,-1.2/2],size:[s,l,TC]}),g=(0,mB.union)((0,lv.cuboid)({center:[r.x,r.y,0],size:t?[i-TC,o,1.5]:[o,i-TC,1.5]}),(0,lv.cylinder)({center:t?[r.x,r.y-o/2,0]:[r.x-o/2,r.y,0],radius:a-TC,height:1.5}),(0,lv.cylinder)({center:t?[r.x,r.y+o/2,0]:[r.x+o/2,r.y,0],radius:a-TC,height:1.5}));return(0,E6.colorize)(pE.copper,(0,mB.subtract)((0,mB.union)(c,u,A,d,f),g))}else throw new Error(`Unsupported plated hole shape: ${r.shape}`)},_6=FI(m6()),Y8e=FI(Bae()),XFt=FI(bae());function V8e(r,e){return Array.isArray(e)?[r.a*e[0]+r.c*e[1]+r.e,r.b*e[0]+r.d*e[1]+r.f]:{x:r.a*e.x+r.c*e.y+r.e,y:r.b*e.x+r.d*e.y+r.f}}function _w(r,e=0){return{a:1,c:0,e:r,b:0,d:1,f:e}}function K8e(...r){r=Array.isArray(r[0])?r[0]:r;const e=(t,n)=>({a:t.a*n.a+t.c*n.b,c:t.a*n.c+t.c*n.d,e:t.a*n.e+t.c*n.f+t.e,b:t.b*n.a+t.d*n.b,d:t.b*n.c+t.d*n.d,f:t.b*n.e+t.d*n.f+t.f});switch(r.length){case 0:throw new Error("no matrices provided");case 1:return r[0];case 2:return e(r[0],r[1]);default:{const[t,n,...i]=r,a=e(t,n);return K8e(a,...i)}}}function j8e(...r){return K8e(...r)}var{cos:$Ft,sin:eLt}=Math;function J8e(r,e,t){const n=$Ft(r),i=eLt(r);return{a:n,c:-i,e:0,b:i,d:n,f:0}}function tLt(r,e){function t(){this.constructor=r}t.prototype=e.prototype,r.prototype=new t}function x6(r,e,t,n){var i=Error.call(this,r);return Object.setPrototypeOf&&Object.setPrototypeOf(i,x6.prototype),i.expected=e,i.found=t,i.location=n,i.name="SyntaxError",i}tLt(x6,Error);function Rae(r,e,t){return t=t||" ",r.length>e?r:(e-=r.length,t+=t.repeat(e),r+t.slice(0,e))}x6.prototype.format=function(r){var e="Error: "+this.message;if(this.location){var t=null,n;for(n=0;n<r.length;n++)if(r[n].source===this.location.source){t=r[n].text.split(/\r\n|\n|\r/g);break}var i=this.location.start,a=this.location.source&&typeof this.location.source.offset=="function"?this.location.source.offset(i):i,o=this.location.source+":"+a.line+":"+a.column;if(t){var s=this.location.end,l=Rae("",a.line.toString().length," "),c=t[i.line-1],u=i.line===s.line?s.column:c.length+1,A=u-i.column||1;e+=`
13079
13079
  --> `+o+`
13080
13080
  `+l+` |
13081
13081
  `+a.line+" | "+c+`
@@ -13490,7 +13490,7 @@ $1`).replace(/>(\s*)(?=<!--\s*\/)/g,"> ")}return Qse}OVt();function lLe(r,e,t,n=
13490
13490
  &:hover {
13491
13491
  background-color: rgba(255, 255, 255, 0.1);
13492
13492
  }
13493
- `,onClick:n=>{n.stopPropagation(),t()},children:[Ve.jsx("input",{type:"checkbox",checked:e}),Ve.jsx("span",{style:{color:"#eee"},children:r})]}),hWt=({children:r,elements:e})=>{const[t,n]=G1(G=>[G.is_mouse_over_container,G.setIsMouseOverContainer]),[i,a]=nt.useState(!1),[o,s]=nt.useState(!1),[l,c]=nt.useState(!1),[u,A]=G1(G=>[G.selected_layer,G.selectLayer]),[d,f,g,_,I,E]=G1(G=>[G.in_move_footprint_mode,G.in_draw_trace_mode,G.is_showing_rats_nest,G.is_showing_multiple_traces_length,G.is_showing_autorouting,G.is_showing_drc_errors]),x=G1(G=>G.setEditMode),B=G1(G=>G.setIsShowingRatsNest),P=G1(G=>G.setIsShowingMultipleTracesLength),L=G1(G=>G.setIsShowingAutorouting),U=G1(G=>G.setIsShowingDrcErrors);Pw("1",()=>A("top")),Pw("2",()=>A("bottom")),Pw("3",()=>A("inner1")),Pw("4",()=>A("inner2")),Pw("5",()=>A("inner3")),Pw("6",()=>A("inner4")),Pw("7",()=>A("inner5")),Pw("8",()=>A("inner6"));const H=(e==null?void 0:e.filter(G=>G.type.includes("error")).length)??0;return Ve.jsxs("div",{style:{position:"relative"},onMouseEnter:()=>{n(!0)},onMouseLeave:G=>{n(!1),s(!1)},children:[r,Ve.jsxs("div",{style:{position:"absolute",bottom:4,right:8,pointerEvents:"none",color:"white",fontSize:11,opacity:t?.5:0,transition:"opacity 1s",transitionDelay:"2s",fontFamily:"sans-serif"},children:["@tscircuit/pcb-viewer@",dWt.version]}),Ve.jsxs("div",{style:{position:"absolute",opacity:t?1:0,top:16,left:16,transition:t?"opacity 100ms linear":"opacity 1s linear",zIndex:sx.toolbarOverlay,color:"red",display:"flex",fontSize:12,height:100,fontFamily:"sans-serif"},children:[Ve.jsxs(c5,{onClick:()=>{s(!o)},onMouseLeave:()=>{o&&s(!1)},children:[Ve.jsxs("div",{children:["layer:"," ",Ve.jsx("span",{style:{marginLeft:2,fontWeight:500,color:l5[u]},children:u})]}),o&&Ve.jsx("div",{style:{marginTop:4,minWidth:120},children:ule.map(G=>G.replace(/-/g,"")).map(G=>Ve.jsx(fWt,{name:G,selected:G===u,onClick:()=>{A(G.replace(/-/,""))}},G))})]}),Ve.jsxs(c5,{style:H>0?{color:"red"}:{},onClick:()=>c(!l),onMouseLeave:()=>c(!1),children:[Ve.jsxs("div",{children:[H," errors"]}),l&&Ve.jsx("div",{style:{display:"grid",gridTemplateColumns:"100px 300px"},children:e==null?void 0:e.filter(G=>G.type.includes("error")).map((G,W)=>Ve.jsxs(nt.Fragment,{children:[Ve.jsx("div",{children:G.error_type}),Ve.jsx("div",{children:G.message})]},W))})]}),Ve.jsx(c5,{style:{},onClick:()=>{x(f?"off":"draw_trace")},children:Ve.jsxs("div",{children:[f?"✖ ":"","Edit Traces"]})}),Ve.jsx(c5,{style:{},onClick:()=>{x(d?"off":"move_footprint")},children:Ve.jsxs("div",{children:[d?"✖ ":"","Move Components"]})}),Ve.jsx(c5,{style:{},onClick:()=>{B(!g)},children:Ve.jsxs("div",{children:[g?"✖ ":"","Rats Nest"]})}),Ve.jsx(c5,{onClick:()=>{a(!i)},children:Ve.jsxs("div",{children:[Ve.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:["View"," ",Ve.jsx("span",{style:{fontSize:"8px",transform:i?"rotate(180deg)":"rotate(0)",transition:"transform 0.1s ease",display:"inline-block"},children:"▼"})]}),i&&Ve.jsxs("div",{style:{marginTop:4,minWidth:120},children:[Ve.jsx(gle,{label:"Show All Trace Lengths",checked:_,onClick:()=>{P(!_)}}),Ve.jsx(gle,{label:"Show Autorouting Animation",checked:I,onClick:()=>{L(!I)}}),Ve.jsx(gle,{label:"Show DRC Errors",checked:E,onClick:()=>{U(!E)}})]})]})})]})]})},pWt=r=>{const{transform:e,elements:t}=r,[n,i]=nt.useMemo(()=>{const c=r.elements.flatMap(A=>bJt(A,r.elements)),u=FS(r.elements);return[c,u]},[r.elements]),[a,o]=nt.useState({drawingObjectIdsWithMouseOver:new Set,primitiveIdsInMousedOverNet:[]}),s=nt.useMemo(()=>xJt({primitivesWithoutInteractionMetadata:n,drawingObjectIdsWithMouseOver:a.drawingObjectIdsWithMouseOver,primitiveIdsInMousedOverNet:a.primitiveIdsInMousedOverNet}),[n,a]),l=nt.useCallback(c=>{var d,f;const u=[];for(const g of c)if(g._element){const _=i.getNetConnectedToId("pcb_port_id"in g._element?(d=g._element)==null?void 0:d.pcb_port_id:"pcb_trace_id"in g._element?(f=g._element)==null?void 0:f.pcb_trace_id:"");u.push(...i.getIdsConnectedToNet(_))}const A=new Set(c.map(g=>g._pcb_drawing_object_id));o({drawingObjectIdsWithMouseOver:A,primitiveIdsInMousedOverNet:u})},[i]);return Ve.jsx(uWt,{elements:t,transform:e,primitives:n,onMouseHoverOverPrimitives:l,children:Ve.jsx(jJt,{disabled:!r.allowEditing,transform:e,soup:t,cancelPanDrag:r.cancelPanDrag,onCreateEditEvent:r.onCreateEditEvent,onModifyEditEvent:r.onModifyEditEvent,children:Ve.jsx(ZJt,{disabled:!r.allowEditing,transform:e,soup:t,cancelPanDrag:r.cancelPanDrag,onCreateEditEvent:r.onCreateEditEvent,onModifyEditEvent:r.onModifyEditEvent,children:Ve.jsx(VJt,{transform:e,focusOnHover:r.focusOnHover,children:Ve.jsx(hWt,{elements:t,children:Ve.jsx(eWt,{transform:e,elements:t,children:Ve.jsx(AWt,{transform:e,soup:t,children:Ve.jsx(HJt,{transform:e,debugGraphics:r.debugGraphics,children:Ve.jsx(YJt,{transform:e,elements:t,children:Ve.jsx(zJt,{transform:e,primitives:s,width:r.width,height:r.height,grid:r.grid})})})})})})})})})})},gWt=Fu(Od(400,300),N1(40,-40)),mWt=({circuitJson:r,debugGraphics:e,height:t=600,initialState:n,allowEditing:i=!0,editEvents:a,onEditEventsChanged:o,focusOnHover:s=!1,clickToInteractEnabled:l=!1})=>{const[c,u]=nt.useState(!l),[A,d]=hle(),[f,g]=nt.useState(gWt),{ref:_,setTransform:I,cancelDrag:E}=_Jt({transform:f,onSetTransform:g,enabled:c});let[x,B]=nt.useState([]);x=a??x;const P=nt.useRef(!1),L=nt.useRef(null),U=`${(r==null?void 0:r.length)||0}_${(r==null?void 0:r.editCount)||0}`,H=()=>{const te=(d==null?void 0:d.width)>0?d:{width:500,height:500},{center:oe,width:pe,height:Ae}=W.some(ge=>ge.type.startsWith("pcb_"))?fJt(W.filter(ge=>ge.type.startsWith("pcb_"))):{center:{x:0,y:0},width:.001,height:.001},he=Math.min((te.width??0)/pe,(te.height??0)/Ae,100)*.75,Ie=Fu(Od((te.width??0)/2,(te.height??0)/2),N1(he,-he,0,0),Od(-oe.x,-oe.y));I(Ie)};nt.useEffect(()=>{d!=null&&d.width&&r&&r.length!==0&&(P.current||(H(),P.current=!0))},[r,d]);const G=nt.useMemo(()=>(r==null?void 0:r.filter(te=>te.type.startsWith("pcb_")||te.type.startsWith("source_")))??[],[U]),W=nt.useMemo(()=>NYt({circuitJson:G,editEvents:x}),[G,x]),z=te=>{B([...x,te]),o==null||o([...x,te])},ae=te=>{const oe=x.map(pe=>pe.edit_event_id===te.edit_event_id?{...pe,...te}:pe);B(oe),o==null||o(oe)};return Ve.jsxs("div",{ref:_,style:{position:"relative"},children:[Ve.jsx("div",{ref:A,children:Ve.jsxs(pJt,{initialState:n,children:[Ve.jsx(pWt,{transform:f,height:t,width:d.width,allowEditing:i,focusOnHover:s,cancelPanDrag:E,onCreateEditEvent:z,onModifyEditEvent:ae,grid:{spacing:1,view_window:{left:0,right:d.width||500,top:t,bottom:0}},elements:W,debugGraphics:e},d.width),Ve.jsx(mJt,{})]})}),l&&!c&&Ve.jsx("div",{onClick:()=>{u(!0),H()},onTouchStart:te=>{const oe=te.touches[0];L.current={x:oe.clientX,y:oe.clientY}},onTouchEnd:te=>{const oe=te.changedTouches[0],pe=L.current;if(!pe)return;const Ae=Math.abs(oe.clientX-pe.x),he=Math.abs(oe.clientY-pe.y);Ae<10&&he<10&&(te.preventDefault(),u(!0),H()),L.current=null},style:{position:"absolute",inset:0,cursor:"pointer",zIndex:sx.clickToInteractOverlay,display:"flex",alignItems:"center",justifyContent:"center",touchAction:"pan-x pan-y pinch-zoom"},children:Ve.jsx("div",{style:{backgroundColor:"rgba(0, 0, 0, 0.8)",color:"white",padding:"12px 24px",borderRadius:"8px",fontSize:"16px",pointerEvents:"none"},children:typeof window<"u"&&("ontouchstart"in window||navigator.maxTouchPoints>0)?"Touch to Interact":"Click to Interact"})})]})};const yWt=({containerClassName:r,...e})=>{const t=nt.useRef(null),[n,i]=nt.useState(620);return nt.useLayoutEffect(()=>{const a=()=>{if(t.current){const s=t.current.clientHeight,l=window.innerHeight;i(Math.min(Math.max(s,620),l))}};a();const o=new ResizeObserver(a);return t.current&&o.observe(t.current),window.addEventListener("resize",a),()=>{o.disconnect(),window.removeEventListener("resize",a)}},[]),Ve.jsx("div",{ref:t,className:r||"rf-w-full rf-h-full",children:Ve.jsx(mWt,{...e,height:n})})},vWt='*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.17 | MIT License | https://tailwindcss.com*/*,:after,:before{border:0 solid #e5e7eb;box-sizing:border-box}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-tap-highlight-color:transparent}body{line-height:inherit;margin:0}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-size:1em;font-variation-settings:normal}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}button,input,optgroup,select,textarea{color:inherit;font-family:inherit;font-feature-settings:inherit;font-size:100%;font-variation-settings:inherit;font-weight:inherit;letter-spacing:inherit;line-height:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{color:#9ca3af;opacity:1}input::placeholder,textarea::placeholder{color:#9ca3af;opacity:1}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}[hidden]:where(:not([hidden=until-found])){display:none}:root{--radius:0.5rem}.rf-pointer-events-none{pointer-events:none}.rf-invisible{visibility:hidden}.rf-fixed{position:fixed}.rf-absolute{position:absolute}.rf-relative{position:relative}.rf-inset-0{inset:0}.-rf-left-2{left:-.5rem}.-rf-right-10{right:-2.5rem}.-rf-right-2{right:-.5rem}.-rf-right-4{right:-1rem}.-rf-right-6{right:-1.5rem}.-rf-right-7{right:-1.75rem}.-rf-right-8{right:-2rem}.-rf-right-9{right:-2.25rem}.rf-bottom-full{bottom:100%}.rf-left-0{left:0}.rf-left-1{left:.25rem}.rf-left-1\\/2{left:50%}.rf-left-2{left:.5rem}.rf-left-\\[50\\%\\]{left:50%}.rf-right-0{right:0}.rf-right-4{right:1rem}.rf-right-\\[4px\\]{right:4px}.rf-top-0{top:0}.rf-top-1{top:.25rem}.rf-top-2{top:.5rem}.rf-top-2\\.5{top:.625rem}.rf-top-\\[50\\%\\]{top:50%}.rf-top-\\[6px\\]{top:6px}.rf-z-50{z-index:50}.rf-z-\\[100\\]{z-index:100}.-rf-mx-1,.rf--mx-1{margin-left:-.25rem;margin-right:-.25rem}.rf-mx-1{margin-left:.25rem;margin-right:.25rem}.rf-mx-2{margin-left:.5rem;margin-right:.5rem}.rf-mx-auto{margin-left:auto;margin-right:auto}.rf-my-1{margin-bottom:.25rem;margin-top:.25rem}.rf-my-12{margin-bottom:3rem;margin-top:3rem}.rf-my-4{margin-bottom:1rem;margin-top:1rem}.rf-my-auto{margin-bottom:auto;margin-top:auto}.rf-mb-1{margin-bottom:.25rem}.rf-mb-12{margin-bottom:3rem}.rf-mb-2{margin-bottom:.5rem}.rf-mb-3{margin-bottom:.75rem}.rf-mb-4{margin-bottom:1rem}.rf-mb-6{margin-bottom:1.5rem}.rf-mb-8{margin-bottom:2rem}.rf-ml-1{margin-left:.25rem}.rf-ml-2{margin-left:.5rem}.rf-ml-auto{margin-left:auto}.rf-mr-1{margin-right:.25rem}.rf-mr-2{margin-right:.5rem}.rf-mt-0{margin-top:0}.rf-mt-0\\.5{margin-top:.125rem}.rf-mt-1{margin-top:.25rem}.rf-mt-2{margin-top:.5rem}.rf-mt-3{margin-top:.75rem}.rf-mt-4{margin-top:1rem}.rf-mt-5{margin-top:1.25rem}.rf-mt-auto{margin-top:auto}.rf-block{display:block}.rf-inline{display:inline}.rf-flex{display:flex}.rf-inline-flex{display:inline-flex}.rf-grid{display:grid}.rf-hidden{display:none}.rf-aspect-square{aspect-ratio:1/1}.rf-aspect-video{aspect-ratio:16/9}.rf-size-14{height:3.5rem;width:3.5rem}.rf-size-4{height:1rem;width:1rem}.\\!rf-h-2{height:.5rem!important}.\\!rf-h-2\\.5{height:.625rem!important}.\\!rf-h-3{height:.75rem!important}.\\!rf-h-full{height:100%!important}.rf-h-1{height:.25rem}.rf-h-10{height:2.5rem}.rf-h-12{height:3rem}.rf-h-2{height:.5rem}.rf-h-2\\.5{height:.625rem}.rf-h-3{height:.75rem}.rf-h-3\\.5{height:.875rem}.rf-h-4{height:1rem}.rf-h-5{height:1.25rem}.rf-h-6{height:1.5rem}.rf-h-60{height:15rem}.rf-h-64{height:16rem}.rf-h-8{height:2rem}.rf-h-9{height:2.25rem}.rf-h-\\[620px\\]{height:620px}.rf-h-\\[calc\\(100vh-52px\\)\\]{height:calc(100vh - 52px)}.rf-h-\\[calc\\(100vh-96px\\)\\]{height:calc(100vh - 96px)}.rf-h-\\[var\\(--radix-select-trigger-height\\)\\]{height:var(--radix-select-trigger-height)}.rf-h-fit{height:-moz-fit-content;height:fit-content}.rf-h-full{height:100%}.rf-h-px{height:1px}.\\!rf-max-h-\\[40vh\\]{max-height:40vh!important}.\\!rf-max-h-\\[70\\%\\]{max-height:70%!important}.rf-max-h-32{max-height:8rem}.rf-max-h-96{max-height:24rem}.rf-max-h-\\[500px\\]{max-height:500px}.rf-max-h-\\[90vh\\]{max-height:90vh}.rf-min-h-0{min-height:0}.rf-min-h-\\[200px\\]{min-height:200px}.rf-min-h-\\[620px\\]{min-height:620px}.rf-min-h-\\[calc\\(100vh-240px\\)\\]{min-height:calc(100vh - 240px)}.\\!rf-w-2{width:.5rem!important}.\\!rf-w-2\\.5{width:.625rem!important}.rf-w-1{width:.25rem}.rf-w-1\\/2{width:50%}.rf-w-11{width:2.75rem}.rf-w-11\\/12{width:91.666667%}.rf-w-12{width:3rem}.rf-w-16{width:4rem}.rf-w-2{width:.5rem}.rf-w-2\\.5{width:.625rem}.rf-w-3{width:.75rem}.rf-w-3\\.5{width:.875rem}.rf-w-32{width:8rem}.rf-w-4{width:1rem}.rf-w-5{width:1.25rem}.rf-w-6{width:1.5rem}.rf-w-64{width:16rem}.rf-w-72{width:18rem}.rf-w-8{width:2rem}.rf-w-9{width:2.25rem}.rf-w-96{width:24rem}.rf-w-\\[95\\%\\]{width:95%}.rf-w-fit{width:-moz-fit-content;width:fit-content}.rf-w-full{width:100%}.rf-min-w-10{min-width:2.5rem}.rf-min-w-16{min-width:4rem}.rf-min-w-\\[148px\\]{min-width:148px}.rf-min-w-\\[8rem\\]{min-width:8rem}.rf-min-w-\\[var\\(--radix-select-trigger-width\\)\\]{min-width:var(--radix-select-trigger-width)}.\\!rf-max-w-\\[60vw\\]{max-width:60vw!important}.\\!rf-max-w-\\[660px\\]{max-width:660px!important}.rf-max-w-2xl{max-width:42rem}.rf-max-w-3xl{max-width:48rem}.rf-max-w-5xl{max-width:64rem}.rf-max-w-full{max-width:100%}.rf-max-w-lg{max-width:32rem}.rf-max-w-md{max-width:28rem}.rf-max-w-xl{max-width:36rem}.rf-flex-1{flex:1 1 0%}.rf-flex-shrink-0,.rf-shrink-0{flex-shrink:0}.rf-flex-grow{flex-grow:1}.rf-table-auto{table-layout:auto}.-rf-translate-x-1{--tw-translate-x:-0.25rem}.-rf-translate-x-1,.-rf-translate-x-1\\/2{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rf-translate-x-1\\/2{--tw-translate-x:-50%}.-rf-translate-y-1{--tw-translate-y:-0.25rem}.-rf-translate-y-1,.rf--translate-x-1{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rf--translate-x-1{--tw-translate-x:-0.25rem}.rf-translate-x-\\[-50\\%\\]{--tw-translate-x:-50%}.rf-translate-x-\\[-50\\%\\],.rf-translate-y-\\[-50\\%\\]{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rf-translate-y-\\[-50\\%\\]{--tw-translate-y:-50%}.rf-transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes rf-pulse{50%{opacity:.5}}.rf-animate-pulse{animation:rf-pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes rf-spin{to{transform:rotate(1turn)}}.rf-animate-spin{animation:rf-spin 1s linear infinite}.rf-cursor-default{cursor:default}.rf-cursor-not-allowed{cursor:not-allowed}.rf-cursor-pointer{cursor:pointer}.rf-select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.rf-grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.rf-grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.rf-flex-row{flex-direction:row}.rf-flex-col{flex-direction:column}.rf-flex-col-reverse{flex-direction:column-reverse}.rf-flex-wrap{flex-wrap:wrap}.rf-place-items-center{place-items:center}.rf-items-start{align-items:flex-start}.rf-items-end{align-items:flex-end}.rf-items-center{align-items:center}.rf-justify-end{justify-content:flex-end}.rf-justify-center{justify-content:center}.rf-justify-between{justify-content:space-between}.rf-gap-0{gap:0}.rf-gap-1{gap:.25rem}.rf-gap-2{gap:.5rem}.rf-gap-3{gap:.75rem}.rf-gap-4{gap:1rem}.rf-gap-5{gap:1.25rem}.rf-gap-6{gap:1.5rem}.rf-gap-8{gap:2rem}.rf-space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(.5rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(.5rem*var(--tw-space-x-reverse))}.rf-space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.5rem*var(--tw-space-y-reverse));margin-top:calc(.5rem*(1 - var(--tw-space-y-reverse)))}.rf-space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1rem*var(--tw-space-y-reverse));margin-top:calc(1rem*(1 - var(--tw-space-y-reverse)))}.rf-space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1.5rem*var(--tw-space-y-reverse));margin-top:calc(1.5rem*(1 - var(--tw-space-y-reverse)))}.rf-divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse:0;border-bottom-width:calc(1px*var(--tw-divide-y-reverse));border-top-width:calc(1px*(1 - var(--tw-divide-y-reverse)))}.rf-overflow-auto{overflow:auto}.rf-overflow-hidden{overflow:hidden}.rf-overflow-visible{overflow:visible}.rf-overflow-x-auto{overflow-x:auto}.\\!rf-overflow-y-auto{overflow-y:auto!important}.rf-overflow-y-auto{overflow-y:auto}.\\!rf-overflow-x-hidden{overflow-x:hidden!important}.rf-overflow-x-hidden{overflow-x:hidden}.rf-overflow-x-clip{overflow-x:clip}.rf-truncate{overflow:hidden;text-overflow:ellipsis}.rf-truncate,.rf-whitespace-nowrap{white-space:nowrap}.rf-whitespace-pre-wrap{white-space:pre-wrap}.rf-break-words{overflow-wrap:break-word}.rf-rounded{border-radius:.25rem}.rf-rounded-2xl{border-radius:1rem}.rf-rounded-full{border-radius:9999px}.rf-rounded-lg{border-radius:var(--radius)}.rf-rounded-md{border-radius:calc(var(--radius) - 2px)}.rf-rounded-sm{border-radius:calc(var(--radius) - 4px)}.rf-rounded-xl{border-radius:.75rem}.rf-border{border-width:1px}.rf-border-b{border-bottom-width:1px}.rf-border-t{border-top-width:1px}.rf-border-blue-200{--tw-border-opacity:1;border-color:rgb(191 219 254/var(--tw-border-opacity,1))}.rf-border-blue-500{--tw-border-opacity:1;border-color:rgb(59 130 246/var(--tw-border-opacity,1))}.rf-border-blue-600{--tw-border-opacity:1;border-color:rgb(37 99 235/var(--tw-border-opacity,1))}.rf-border-gray-200{--tw-border-opacity:1;border-color:rgb(229 231 235/var(--tw-border-opacity,1))}.rf-border-gray-300{--tw-border-opacity:1;border-color:rgb(209 213 219/var(--tw-border-opacity,1))}.rf-border-green-200{--tw-border-opacity:1;border-color:rgb(187 247 208/var(--tw-border-opacity,1))}.rf-border-input{border-color:hsl(var(--input))}.rf-border-neutral-200{--tw-border-opacity:1;border-color:rgb(229 229 229/var(--tw-border-opacity,1))}.rf-border-primary{border-color:hsl(var(--primary))}.rf-border-red-200{--tw-border-opacity:1;border-color:rgb(254 202 202/var(--tw-border-opacity,1))}.rf-border-red-500{--tw-border-opacity:1;border-color:rgb(239 68 68/var(--tw-border-opacity,1))}.rf-border-zinc-200{--tw-border-opacity:1;border-color:rgb(228 228 231/var(--tw-border-opacity,1))}.rf-border-zinc-900{--tw-border-opacity:1;border-color:rgb(24 24 27/var(--tw-border-opacity,1))}.rf-bg-background{background-color:hsl(var(--background))}.rf-bg-black{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity,1))}.rf-bg-black\\/80{background-color:rgba(0,0,0,.8)}.rf-bg-blue-100{--tw-bg-opacity:1;background-color:rgb(219 234 254/var(--tw-bg-opacity,1))}.rf-bg-blue-50{--tw-bg-opacity:1;background-color:rgb(239 246 255/var(--tw-bg-opacity,1))}.rf-bg-blue-500{--tw-bg-opacity:1;background-color:rgb(59 130 246/var(--tw-bg-opacity,1))}.rf-bg-blue-600{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity,1))}.rf-bg-gray-100{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity,1))}.rf-bg-gray-200{--tw-bg-opacity:1;background-color:rgb(229 231 235/var(--tw-bg-opacity,1))}.rf-bg-gray-300{--tw-bg-opacity:1;background-color:rgb(209 213 219/var(--tw-bg-opacity,1))}.rf-bg-gray-400{--tw-bg-opacity:1;background-color:rgb(156 163 175/var(--tw-bg-opacity,1))}.rf-bg-gray-50{--tw-bg-opacity:1;background-color:rgb(249 250 251/var(--tw-bg-opacity,1))}.rf-bg-gray-500{--tw-bg-opacity:1;background-color:rgb(107 114 128/var(--tw-bg-opacity,1))}.rf-bg-gray-700{--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity,1))}.rf-bg-gray-800{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity,1))}.rf-bg-gray-900{--tw-bg-opacity:1;background-color:rgb(17 24 39/var(--tw-bg-opacity,1))}.rf-bg-green-100{--tw-bg-opacity:1;background-color:rgb(220 252 231/var(--tw-bg-opacity,1))}.rf-bg-green-50{--tw-bg-opacity:1;background-color:rgb(240 253 244/var(--tw-bg-opacity,1))}.rf-bg-muted{background-color:hsl(var(--muted))}.rf-bg-neutral-100{--tw-bg-opacity:1;background-color:rgb(245 245 245/var(--tw-bg-opacity,1))}.rf-bg-neutral-50{--tw-bg-opacity:1;background-color:rgb(250 250 250/var(--tw-bg-opacity,1))}.rf-bg-neutral-800{--tw-bg-opacity:1;background-color:rgb(38 38 38/var(--tw-bg-opacity,1))}.rf-bg-neutral-900{--tw-bg-opacity:1;background-color:rgb(23 23 23/var(--tw-bg-opacity,1))}.rf-bg-orange-400{--tw-bg-opacity:1;background-color:rgb(251 146 60/var(--tw-bg-opacity,1))}.rf-bg-popover{background-color:hsl(var(--popover))}.rf-bg-red-100{--tw-bg-opacity:1;background-color:rgb(254 226 226/var(--tw-bg-opacity,1))}.rf-bg-red-50{--tw-bg-opacity:1;background-color:rgb(254 242 242/var(--tw-bg-opacity,1))}.rf-bg-red-500{--tw-bg-opacity:1;background-color:rgb(239 68 68/var(--tw-bg-opacity,1))}.rf-bg-red-900{--tw-bg-opacity:1;background-color:rgb(127 29 29/var(--tw-bg-opacity,1))}.rf-bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.rf-bg-yellow-100{--tw-bg-opacity:1;background-color:rgb(254 249 195/var(--tw-bg-opacity,1))}.rf-bg-zinc-100{--tw-bg-opacity:1;background-color:rgb(244 244 245/var(--tw-bg-opacity,1))}.rf-bg-zinc-200{--tw-bg-opacity:1;background-color:rgb(228 228 231/var(--tw-bg-opacity,1))}.rf-bg-zinc-50{--tw-bg-opacity:1;background-color:rgb(250 250 250/var(--tw-bg-opacity,1))}.rf-bg-zinc-800{--tw-bg-opacity:1;background-color:rgb(39 39 42/var(--tw-bg-opacity,1))}.rf-bg-zinc-900{--tw-bg-opacity:1;background-color:rgb(24 24 27/var(--tw-bg-opacity,1))}.rf-bg-opacity-50{--tw-bg-opacity:0.5}.rf-fill-current{fill:currentColor}.rf-object-contain{-o-object-fit:contain;object-fit:contain}.\\!rf-p-0{padding:0!important}.rf-p-0{padding:0}.rf-p-1{padding:.25rem}.rf-p-2{padding:.5rem}.rf-p-3{padding:.75rem}.rf-p-4{padding:1rem}.rf-p-5{padding:1.25rem}.rf-p-6{padding:1.5rem}.rf-p-8{padding:2rem}.rf-px-1{padding-left:.25rem;padding-right:.25rem}.rf-px-2{padding-left:.5rem;padding-right:.5rem}.rf-px-3{padding-left:.75rem;padding-right:.75rem}.rf-px-4{padding-left:1rem;padding-right:1rem}.rf-px-6{padding-left:1.5rem;padding-right:1.5rem}.rf-px-8{padding-left:2rem;padding-right:2rem}.rf-py-0{padding-bottom:0;padding-top:0}.rf-py-0\\.5{padding-bottom:.125rem;padding-top:.125rem}.rf-py-1{padding-bottom:.25rem;padding-top:.25rem}.rf-py-1\\.5{padding-bottom:.375rem;padding-top:.375rem}.rf-py-10{padding-bottom:2.5rem;padding-top:2.5rem}.rf-py-12{padding-bottom:3rem;padding-top:3rem}.rf-py-2{padding-bottom:.5rem;padding-top:.5rem}.rf-py-3{padding-bottom:.75rem;padding-top:.75rem}.rf-py-4{padding-bottom:1rem;padding-top:1rem}.rf-py-8{padding-bottom:2rem;padding-top:2rem}.rf-pb-0{padding-bottom:0}.rf-pb-2{padding-bottom:.5rem}.rf-pb-3{padding-bottom:.75rem}.rf-pb-4{padding-bottom:1rem}.rf-pl-2{padding-left:.5rem}.rf-pl-4{padding-left:1rem}.rf-pl-8{padding-left:2rem}.rf-pr-2{padding-right:.5rem}.rf-pt-2{padding-top:.5rem}.rf-pt-4{padding-top:1rem}.rf-text-left{text-align:left}.rf-text-center{text-align:center}.rf-text-right{text-align:right}.rf-font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.rf-text-2xl{font-size:1.5rem;line-height:2rem}.rf-text-3xl{font-size:1.875rem;line-height:2.25rem}.rf-text-\\[8px\\]{font-size:8px}.rf-text-base{font-size:1rem;line-height:1.5rem}.rf-text-lg{font-size:1.125rem;line-height:1.75rem}.rf-text-sm{font-size:.875rem;line-height:1.25rem}.rf-text-xl{font-size:1.25rem;line-height:1.75rem}.rf-text-xs{font-size:.75rem;line-height:1rem}.rf-font-bold{font-weight:700}.rf-font-medium{font-weight:500}.rf-font-semibold{font-weight:600}.rf-capitalize{text-transform:capitalize}.rf-tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.rf-leading-5{line-height:1.25rem}.rf-leading-none{line-height:1}.rf-leading-tight{line-height:1.25}.rf-tracking-widest{letter-spacing:.1em}.rf-text-black{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity,1))}.rf-text-blue-500{--tw-text-opacity:1;color:rgb(59 130 246/var(--tw-text-opacity,1))}.rf-text-blue-600{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.rf-text-blue-700{--tw-text-opacity:1;color:rgb(29 78 216/var(--tw-text-opacity,1))}.rf-text-blue-800{--tw-text-opacity:1;color:rgb(30 64 175/var(--tw-text-opacity,1))}.rf-text-blue-900{--tw-text-opacity:1;color:rgb(30 58 138/var(--tw-text-opacity,1))}.rf-text-current{color:currentColor}.rf-text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175/var(--tw-text-opacity,1))}.rf-text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity,1))}.rf-text-gray-600{--tw-text-opacity:1;color:rgb(75 85 99/var(--tw-text-opacity,1))}.rf-text-gray-700{--tw-text-opacity:1;color:rgb(55 65 81/var(--tw-text-opacity,1))}.rf-text-gray-800{--tw-text-opacity:1;color:rgb(31 41 55/var(--tw-text-opacity,1))}.rf-text-gray-900{--tw-text-opacity:1;color:rgb(17 24 39/var(--tw-text-opacity,1))}.rf-text-green-500{--tw-text-opacity:1;color:rgb(34 197 94/var(--tw-text-opacity,1))}.rf-text-green-600{--tw-text-opacity:1;color:rgb(22 163 74/var(--tw-text-opacity,1))}.rf-text-green-700{--tw-text-opacity:1;color:rgb(21 128 61/var(--tw-text-opacity,1))}.rf-text-green-800{--tw-text-opacity:1;color:rgb(22 101 52/var(--tw-text-opacity,1))}.rf-text-green-900{--tw-text-opacity:1;color:rgb(20 83 45/var(--tw-text-opacity,1))}.rf-text-muted-foreground{color:hsl(var(--muted-foreground))}.rf-text-neutral-50{--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.rf-text-neutral-500{--tw-text-opacity:1;color:rgb(115 115 115/var(--tw-text-opacity,1))}.rf-text-neutral-900{--tw-text-opacity:1;color:rgb(23 23 23/var(--tw-text-opacity,1))}.rf-text-neutral-950{--tw-text-opacity:1;color:rgb(10 10 10/var(--tw-text-opacity,1))}.rf-text-popover-foreground{color:hsl(var(--popover-foreground))}.rf-text-red-200{--tw-text-opacity:1;color:rgb(254 202 202/var(--tw-text-opacity,1))}.rf-text-red-300{--tw-text-opacity:1;color:rgb(252 165 165/var(--tw-text-opacity,1))}.rf-text-red-400{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity,1))}.rf-text-red-500{--tw-text-opacity:1;color:rgb(239 68 68/var(--tw-text-opacity,1))}.rf-text-red-600{--tw-text-opacity:1;color:rgb(220 38 38/var(--tw-text-opacity,1))}.rf-text-red-700{--tw-text-opacity:1;color:rgb(185 28 28/var(--tw-text-opacity,1))}.rf-text-red-800{--tw-text-opacity:1;color:rgb(153 27 27/var(--tw-text-opacity,1))}.rf-text-red-900{--tw-text-opacity:1;color:rgb(127 29 29/var(--tw-text-opacity,1))}.rf-text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.rf-text-yellow-400{--tw-text-opacity:1;color:rgb(250 204 21/var(--tw-text-opacity,1))}.rf-text-yellow-500{--tw-text-opacity:1;color:rgb(234 179 8/var(--tw-text-opacity,1))}.rf-text-yellow-900{--tw-text-opacity:1;color:rgb(113 63 18/var(--tw-text-opacity,1))}.rf-text-zinc-200{--tw-text-opacity:1;color:rgb(228 228 231/var(--tw-text-opacity,1))}.rf-text-zinc-300{--tw-text-opacity:1;color:rgb(212 212 216/var(--tw-text-opacity,1))}.rf-text-zinc-400{--tw-text-opacity:1;color:rgb(161 161 170/var(--tw-text-opacity,1))}.rf-text-zinc-50{--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.rf-text-zinc-500{--tw-text-opacity:1;color:rgb(113 113 122/var(--tw-text-opacity,1))}.rf-text-zinc-900{--tw-text-opacity:1;color:rgb(24 24 27/var(--tw-text-opacity,1))}.rf-text-zinc-950{--tw-text-opacity:1;color:rgb(9 9 11/var(--tw-text-opacity,1))}.rf-underline{text-decoration-line:underline}.rf-line-through{text-decoration-line:line-through}.rf-underline-offset-4{text-underline-offset:4px}.rf-opacity-0{opacity:0}.rf-opacity-25{opacity:.25}.rf-opacity-30{opacity:.3}.rf-opacity-50{opacity:.5}.rf-opacity-60{opacity:.6}.rf-opacity-75{opacity:.75}.rf-shadow{--tw-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px -1px rgba(0,0,0,.1);--tw-shadow-colored:0 1px 3px 0 var(--tw-shadow-color),0 1px 2px -1px var(--tw-shadow-color)}.rf-shadow,.rf-shadow-lg{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.rf-shadow-lg{--tw-shadow:0 10px 15px -3px rgba(0,0,0,.1),0 4px 6px -4px rgba(0,0,0,.1);--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color)}.rf-shadow-md{--tw-shadow:0 4px 6px -1px rgba(0,0,0,.1),0 2px 4px -2px rgba(0,0,0,.1);--tw-shadow-colored:0 4px 6px -1px var(--tw-shadow-color),0 2px 4px -2px var(--tw-shadow-color)}.rf-shadow-md,.rf-shadow-sm{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.rf-shadow-sm{--tw-shadow:0 1px 2px 0 rgba(0,0,0,.05);--tw-shadow-colored:0 1px 2px 0 var(--tw-shadow-color)}.rf-outline-none{outline:2px solid transparent;outline-offset:2px}.rf-ring-2{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.rf-ring-blue-500{--tw-ring-opacity:1;--tw-ring-color:rgb(59 130 246/var(--tw-ring-opacity,1))}.rf-ring-primary{--tw-ring-color:hsl(var(--primary))}.rf-ring-offset-background{--tw-ring-offset-color:hsl(var(--background))}.rf-ring-offset-white{--tw-ring-offset-color:#fff}.rf-transition{transition-duration:.15s;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1)}.rf-transition-all{transition-duration:.15s;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1)}.rf-transition-colors{transition-duration:.15s;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1)}.rf-transition-opacity{transition-duration:.15s;transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1)}.rf-duration-200{transition-duration:.2s}.rf-ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}@keyframes enter{0%{opacity:var(--tw-enter-opacity,1);transform:translate3d(var(--tw-enter-translate-x,0),var(--tw-enter-translate-y,0),0) scale3d(var(--tw-enter-scale,1),var(--tw-enter-scale,1),var(--tw-enter-scale,1)) rotate(var(--tw-enter-rotate,0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity,1);transform:translate3d(var(--tw-exit-translate-x,0),var(--tw-exit-translate-y,0),0) scale3d(var(--tw-exit-scale,1),var(--tw-exit-scale,1),var(--tw-exit-scale,1)) rotate(var(--tw-exit-rotate,0))}}.rf-slide-in-from-left-1{--tw-enter-translate-x:-0.25rem}.rf-slide-out-to-left-1{--tw-exit-translate-x:-0.25rem}.rf-duration-200{animation-duration:.2s}.rf-ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.file\\:rf-border-0::file-selector-button{border-width:0}.file\\:rf-bg-transparent::file-selector-button{background-color:transparent}.file\\:rf-text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\\:rf-font-medium::file-selector-button{font-weight:500}.placeholder\\:rf-text-zinc-500::-moz-placeholder{--tw-text-opacity:1;color:rgb(113 113 122/var(--tw-text-opacity,1))}.placeholder\\:rf-text-zinc-500::placeholder{--tw-text-opacity:1;color:rgb(113 113 122/var(--tw-text-opacity,1))}.hover\\:rf-border-blue-300:hover{--tw-border-opacity:1;border-color:rgb(147 197 253/var(--tw-border-opacity,1))}.hover\\:\\!rf-bg-transparent:hover{background-color:transparent!important}.hover\\:rf-bg-blue-700:hover{--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-opacity,1))}.hover\\:rf-bg-red-500\\/90:hover{background-color:rgba(239,68,68,.9)}.hover\\:rf-bg-zinc-100:hover{--tw-bg-opacity:1;background-color:rgb(244 244 245/var(--tw-bg-opacity,1))}.hover\\:rf-bg-zinc-100\\/80:hover{background-color:hsla(240,5%,96%,.8)}.hover\\:rf-bg-zinc-900\\/90:hover{background-color:rgba(24,24,27,.9)}.hover\\:rf-text-red-400:hover{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity,1))}.hover\\:rf-text-zinc-900:hover{--tw-text-opacity:1;color:rgb(24 24 27/var(--tw-text-opacity,1))}.hover\\:rf-underline:hover{text-decoration-line:underline}.focus\\:rf-bg-gray-100:focus{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity,1))}.focus\\:rf-bg-zinc-100:focus{--tw-bg-opacity:1;background-color:rgb(244 244 245/var(--tw-bg-opacity,1))}.focus\\:rf-text-gray-900:focus{--tw-text-opacity:1;color:rgb(17 24 39/var(--tw-text-opacity,1))}.focus\\:rf-text-zinc-900:focus{--tw-text-opacity:1;color:rgb(24 24 27/var(--tw-text-opacity,1))}.focus\\:rf-outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\\:rf-ring-2:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus\\:rf-ring-ring:focus{--tw-ring-color:hsl(var(--ring))}.focus\\:rf-ring-offset-2:focus{--tw-ring-offset-width:2px}.focus-visible\\:rf-outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\\:rf-ring-1:focus-visible{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus-visible\\:rf-ring-2:focus-visible{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus-visible\\:rf-ring-zinc-950:focus-visible{--tw-ring-opacity:1;--tw-ring-color:rgb(9 9 11/var(--tw-ring-opacity,1))}.focus-visible\\:rf-ring-offset-2:focus-visible{--tw-ring-offset-width:2px}.disabled\\:rf-pointer-events-none:disabled{pointer-events:none}.disabled\\:rf-cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:rf-opacity-50:disabled{opacity:.5}.rf-group\\/bar:hover .group-hover\\/bar\\:rf-opacity-100{opacity:1}.data-\\[disabled\\]\\:rf-pointer-events-none[data-disabled]{pointer-events:none}.data-\\[side\\=bottom\\]\\:rf-translate-y-1[data-side=bottom]{--tw-translate-y:0.25rem}.data-\\[side\\=bottom\\]\\:rf-translate-y-1[data-side=bottom],.data-\\[side\\=left\\]\\:-rf-translate-x-1[data-side=left]{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[side\\=left\\]\\:-rf-translate-x-1[data-side=left]{--tw-translate-x:-0.25rem}.data-\\[side\\=right\\]\\:rf-translate-x-1[data-side=right]{--tw-translate-x:0.25rem}.data-\\[side\\=right\\]\\:rf-translate-x-1[data-side=right],.data-\\[side\\=top\\]\\:-rf-translate-y-1[data-side=top]{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[side\\=top\\]\\:-rf-translate-y-1[data-side=top]{--tw-translate-y:-0.25rem}.data-\\[state\\=active\\]\\:rf-bg-white[data-state=active]{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.data-\\[state\\=checked\\]\\:rf-bg-zinc-900[data-state=checked]{--tw-bg-opacity:1;background-color:rgb(24 24 27/var(--tw-bg-opacity,1))}.data-\\[state\\=open\\]\\:rf-bg-zinc-100[data-state=open]{--tw-bg-opacity:1;background-color:rgb(244 244 245/var(--tw-bg-opacity,1))}.data-\\[state\\=active\\]\\:rf-text-zinc-950[data-state=active]{--tw-text-opacity:1;color:rgb(9 9 11/var(--tw-text-opacity,1))}.data-\\[state\\=checked\\]\\:rf-text-zinc-50[data-state=checked]{--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.data-\\[disabled\\]\\:rf-opacity-50[data-disabled]{opacity:.5}.data-\\[state\\=active\\]\\:rf-shadow[data-state=active]{--tw-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px -1px rgba(0,0,0,.1);--tw-shadow-colored:0 1px 3px 0 var(--tw-shadow-color),0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.data-\\[state\\=open\\]\\:rf-animate-in[data-state=open]{animation-duration:.15s;animation-name:enter;--tw-enter-opacity:initial;--tw-enter-scale:initial;--tw-enter-rotate:initial;--tw-enter-translate-x:initial;--tw-enter-translate-y:initial}.data-\\[state\\=closed\\]\\:rf-animate-out[data-state=closed]{animation-duration:.15s;animation-name:exit;--tw-exit-opacity:initial;--tw-exit-scale:initial;--tw-exit-rotate:initial;--tw-exit-translate-x:initial;--tw-exit-translate-y:initial}.data-\\[state\\=closed\\]\\:rf-fade-out-0[data-state=closed]{--tw-exit-opacity:0}.data-\\[state\\=open\\]\\:rf-fade-in-0[data-state=open]{--tw-enter-opacity:0}.data-\\[state\\=closed\\]\\:rf-zoom-out-95[data-state=closed]{--tw-exit-scale:.95}.data-\\[state\\=open\\]\\:rf-zoom-in-95[data-state=open]{--tw-enter-scale:.95}.data-\\[side\\=bottom\\]\\:rf-slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y:-0.5rem}.data-\\[side\\=left\\]\\:rf-slide-in-from-right-2[data-side=left]{--tw-enter-translate-x:0.5rem}.data-\\[side\\=right\\]\\:rf-slide-in-from-left-2[data-side=right]{--tw-enter-translate-x:-0.5rem}.data-\\[side\\=top\\]\\:rf-slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y:0.5rem}.data-\\[state\\=closed\\]\\:rf-slide-out-to-left-1\\/2[data-state=closed]{--tw-exit-translate-x:-50%}.data-\\[state\\=closed\\]\\:rf-slide-out-to-top-\\[48\\%\\][data-state=closed]{--tw-exit-translate-y:-48%}.data-\\[state\\=open\\]\\:rf-slide-in-from-left-1\\/2[data-state=open]{--tw-enter-translate-x:-50%}.data-\\[state\\=open\\]\\:rf-slide-in-from-top-\\[48\\%\\][data-state=open]{--tw-enter-translate-y:-48%}.dark\\:rf-border-zinc-50:is(.rf-dark *){--tw-border-opacity:1;border-color:rgb(250 250 250/var(--tw-border-opacity,1))}.dark\\:rf-border-zinc-800:is(.rf-dark *){--tw-border-opacity:1;border-color:rgb(39 39 42/var(--tw-border-opacity,1))}.dark\\:rf-bg-red-900:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(127 29 29/var(--tw-bg-opacity,1))}.dark\\:rf-bg-zinc-50:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(250 250 250/var(--tw-bg-opacity,1))}.dark\\:rf-bg-zinc-800:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(39 39 42/var(--tw-bg-opacity,1))}.dark\\:rf-bg-zinc-950:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(9 9 11/var(--tw-bg-opacity,1))}.dark\\:rf-text-zinc-400:is(.rf-dark *){--tw-text-opacity:1;color:rgb(161 161 170/var(--tw-text-opacity,1))}.dark\\:rf-text-zinc-50:is(.rf-dark *){--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.dark\\:rf-text-zinc-900:is(.rf-dark *){--tw-text-opacity:1;color:rgb(24 24 27/var(--tw-text-opacity,1))}.dark\\:rf-placeholder-zinc-400:is(.rf-dark *)::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(161 161 170/var(--tw-placeholder-opacity,1))}.dark\\:rf-placeholder-zinc-400:is(.rf-dark *)::placeholder{--tw-placeholder-opacity:1;color:rgb(161 161 170/var(--tw-placeholder-opacity,1))}.dark\\:rf-ring-offset-zinc-950:is(.rf-dark *){--tw-ring-offset-color:#09090b}.dark\\:hover\\:rf-bg-red-900\\/90:hover:is(.rf-dark *){background-color:rgba(127,29,29,.9)}.dark\\:hover\\:rf-bg-zinc-50\\/90:hover:is(.rf-dark *){background-color:hsla(0,0%,98%,.9)}.dark\\:hover\\:rf-bg-zinc-800:hover:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(39 39 42/var(--tw-bg-opacity,1))}.dark\\:hover\\:rf-bg-zinc-800\\/80:hover:is(.rf-dark *){background-color:rgba(39,39,42,.8)}.dark\\:hover\\:rf-text-zinc-50:hover:is(.rf-dark *){--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.dark\\:focus\\:rf-bg-zinc-800:focus:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(39 39 42/var(--tw-bg-opacity,1))}.dark\\:focus\\:rf-text-zinc-50:focus:is(.rf-dark *){--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.dark\\:focus-visible\\:rf-ring-zinc-300:focus-visible:is(.rf-dark *){--tw-ring-opacity:1;--tw-ring-color:rgb(212 212 216/var(--tw-ring-opacity,1))}.dark\\:data-\\[state\\=active\\]\\:rf-bg-zinc-950[data-state=active]:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(9 9 11/var(--tw-bg-opacity,1))}.dark\\:data-\\[state\\=checked\\]\\:rf-bg-zinc-50[data-state=checked]:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(250 250 250/var(--tw-bg-opacity,1))}.dark\\:data-\\[state\\=open\\]\\:rf-bg-zinc-800[data-state=open]:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(39 39 42/var(--tw-bg-opacity,1))}.dark\\:data-\\[state\\=active\\]\\:rf-text-zinc-50[data-state=active]:is(.rf-dark *){--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.dark\\:data-\\[state\\=checked\\]\\:rf-text-zinc-900[data-state=checked]:is(.rf-dark *){--tw-text-opacity:1;color:rgb(24 24 27/var(--tw-text-opacity,1))}@media (min-width:640px){.sm\\:rf-mt-0{margin-top:0}.sm\\:rf-flex-row{flex-direction:row}.sm\\:rf-justify-end{justify-content:flex-end}.sm\\:rf-space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(.5rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(.5rem*var(--tw-space-x-reverse))}.sm\\:rf-rounded-lg{border-radius:var(--radius)}.sm\\:rf-text-left{text-align:left}}@media (min-width:768px){.md\\:rf-grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}.\\[\\&\\>span\\]\\:rf-line-clamp-1>span{display:-webkit-box;overflow:hidden;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\\[\\&\\>svg\\]\\:rf-size-4>svg{height:1rem;width:1rem}.\\[\\&\\>svg\\]\\:rf-shrink-0>svg{flex-shrink:0}.\\[\\&\\>svg\\]\\:rf-text-red-300>svg{--tw-text-opacity:1;color:rgb(252 165 165/var(--tw-text-opacity,1))}.\\[\\&\\>svg\\]\\:hover\\:rf-text-red-400:hover>svg{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity,1))}.\\[\\&_svg\\]\\:rf-pointer-events-none svg{pointer-events:none}.\\[\\&_svg\\]\\:rf-size-4 svg{height:1rem;width:1rem}.\\[\\&_svg\\]\\:rf-shrink-0 svg{flex-shrink:0}',IWt=()=>{nt.useEffect(()=>{if(document.querySelector('style[data-styles="tscircuit-runframe"]'))return;const e=document.createElement("style");e.setAttribute("data-styles","tscircuit-runframe"),e.textContent=vWt,document.head.appendChild(e)},[])},EGe=r=>`hsl(${Hx.indexOf(r)*137.5%360}, 70%, 50%)`,CWt=({phaseTimings:r})=>{if(!r)return null;const e=Object.values(r).reduce((t,n)=>t+n,0);return Ve.jsxs("div",{className:"rf-space-y-2 rf-w-full rf-px-4",children:[Ve.jsx("div",{className:"rf-relative rf-h-8 rf-flex rf-rounded-sm",children:Hx.map(t=>{const n=r[t]||0,i=n/e*100;return Ve.jsx("div",{className:"rf-group/bar rf-relative rf-overflow-visible",style:{width:`${i}%`,backgroundColor:EGe(t)},children:Ve.jsxs("div",{className:"rf-opacity-0 group-hover/bar:rf-opacity-100 rf-transition-opacity rf-absolute rf-bottom-full rf-left-1/2 rf-transform -rf-translate-x-1/2 rf-mb-2 rf-px-2 rf-py-1 rf-text-xs rf-whitespace-nowrap rf-rounded rf-bg-gray-900 rf-text-white rf-pointer-events-none",children:[t,": ",n.toFixed(1),"ms"]})},t)})}),Ve.jsxs("div",{className:"rf-text-xs rf-text-gray-500",children:["Total: ",e.toFixed(2),"ms"]})]})},EWt=({renderLog:r})=>{const[e,t]=nt.useState("chronological");if(!r)return Ve.jsx("div",{className:"rf-p-4 rf-bg-gray-100 rf-rounded-md",children:"No render log, make sure this tab is open when you render (TODO add a rerender button here)"});const n=Object.entries((r==null?void 0:r.phaseTimings)??{});e==="chronological"?n.sort((a,o)=>Hx.indexOf(a[0])-Hx.indexOf(o[0])):n.sort((a,o)=>o[1]-a[1]);const i=n.reduce((a,[o,s])=>a+s,0);return Ve.jsxs("div",{className:"rf-bg-white",children:[Ve.jsxs("div",{className:"rf-flex rf-justify-between rf-items-center",children:[Ve.jsx("div",{children:"Render Logs"}),Ve.jsxs("div",{className:"rf-mb-4 rf-pr-2 rf-flex rf-text-xs rf-items-center",children:[Ve.jsx("div",{className:"rf-mr-2",children:"Sort by:"}),Ve.jsxs("select",{value:e,onChange:a=>t(a.target.value),className:"rf-px-2 rf-py-1 rf-border rf-rounded rf-text-xs",children:[Ve.jsx("option",{value:"chronological",children:"Phase Order"}),Ve.jsx("option",{value:"longest",children:"Duration"})]})]})]}),Ve.jsx(CWt,{phaseTimings:r.phaseTimings}),Ve.jsxs("table",{className:"rf-w-full rf-text-xs",children:[Ve.jsx("thead",{children:Ve.jsxs("tr",{children:[Ve.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase Order"}),Ve.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase"}),Ve.jsx("th",{className:"rf-text-left rf-p-2",children:"Duration (ms)"})]})}),Ve.jsx("tbody",{children:n.map(([a,o])=>Ve.jsxs("tr",{children:[Ve.jsx("td",{className:"rf-p-2",children:Hx.indexOf(a)}),Ve.jsx("td",{className:"rf-p-2",children:a}),Ve.jsx("td",{className:"rf-p-2",children:Ve.jsx("div",{className:"rf-w-8",children:Ve.jsx("div",{className:"rf-h-2 rf-rounded-sm",style:{backgroundColor:EGe(a),width:`${o/i*100}%`}})})}),Ve.jsx("td",{className:"rf-p-2",children:Ve.jsxs("div",{className:"rf-flex w-full",children:[Ve.jsxs("span",{className:"rf-flex-grow",children:[o,"ms"]}),Ve.jsxs("span",{className:"rf-text-gray-500 rf-pr-2",children:[(o/i*100).toFixed(1),"%"]})]})})]},a))})]})]})},_Wt="0.0.550",xWt=["assembly","bom","circuit_json","errors","render_log"],BWt=({code:r,onRunClicked:e=void 0,errorMessage:t,errorStack:n,circuitJson:i,autoroutingGraphics:a,showRightHeaderContent:o=!0,showCodeTab:s=!1,codeTabContent:l,showJsonTab:c=!0,showRenderLogTab:u=!0,onActiveTabChange:A,renderLog:d,showImportAndFormatButtons:f=!0,className:g,headerClassName:_,leftHeaderContent:I,readOnly:E,isStreaming:x,autoroutingLog:B,onReportAutoroutingLog:P,isRunningCode:L,hasCodeChangedSinceLastRun:U,onEditEvent:H,editEvents:G,defaultActiveTab:W,autoRotate3dViewerDisabled:z,showSchematicDebugGrid:ae=!1,showToggleFullScreen:te=!0,defaultToFullScreen:oe=!1})=>{var we;IWt();const pe=nt.useMemo(()=>i?i.filter(Ge=>Ge&&"error_type"in Ge||Ge.type.includes("error")):null,[i]),[Ae,he]=nt.useState(W??"pcb"),[Ie,ge]=nt.useState(oe),Me=nt.useCallback(Ge=>{he(Ge),A==null||A(Ge)},[A]),Se=()=>{ge(!Ie)};nt.useEffect(()=>{t&&Me("errors")},[t]),nt.useEffect(()=>{(Ae==="code"||Ae==="errors")&&i&&!t&&Me(W??"pcb")},[i]);const Re=nt.useCallback(Ge=>{window.TSCIRCUIT_3D_OBJECT_REF=Ge===null?void 0:Ge},[]);return Ve.jsx("div",{className:Mp("flex flex-col relative rf-overflow-x-hidden",g),children:Ve.jsx("div",{className:Mp("rf-md:sticky rf-md:top-2",Ie&&"rf-fixed rf-top-0 rf-left-0 rf-w-full rf-bg-white"),children:Ve.jsxs(qve,{value:Ae,onValueChange:Me,className:"rf-flex-grow rf-flex rf-flex-col",children:[Ve.jsxs("div",{className:Mp("rf-flex rf-items-center rf-gap-2 rf-p-2 rf-pb-0",_),children:[I,I&&Ve.jsx("div",{className:"rf-flex-grow"}),!I&&L&&Ve.jsx(G3,{className:"rf-w-4 rf-h-4 rf-animate-spin"}),!I&&Ve.jsx("div",{className:"rf-flex-grow"}),d&&d.progress!==1&&!t&&Ve.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[d.lastRenderEvent&&Ve.jsx("div",{className:"rf-text-xs rf-text-gray-500",children:((we=d.lastRenderEvent)==null?void 0:we.phase)??""}),Ve.jsx("div",{className:"rf-w-4 rf-h-4 rf-bg-blue-500 rf-opacity-50 rf-rounded-full rf-text-white",children:Ve.jsx(G3,{className:"rf-w-4 rf-h-4 rf-animate-spin"})}),Ve.jsxs("div",{className:"rf-text-xs rf-font-bold rf-text-gray-700 rf-tabular-nums",children:[((d.progress??0)*100).toFixed(1),"%"]})]}),o&&Ve.jsxs(RK,{children:[s&&Ve.jsx($2,{value:"code",children:"Code"}),Ve.jsxs($2,{value:"pcb",className:"rf-whitespace-nowrap",children:[i&&Ve.jsx("span",{className:Mp("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",U?"rf-bg-gray-500":"rf-bg-blue-500")}),"PCB"]}),Ve.jsxs($2,{value:"schematic",className:"rf-whitespace-nowrap",children:[i&&Ve.jsx("span",{className:Mp("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",U?"rf-bg-gray-500":"rf-bg-blue-500")}),"Schematic"]}),Ve.jsxs($2,{value:"cad",children:[i&&Ve.jsx("span",{className:Mp("inline-flex items-center justify-center w-2 h-2 mr-1 text-xs font-bold text-white rounded-full",U?"rf-bg-gray-500":"rf-bg-blue-500")}),"3D"]}),!["pcb","cad","schematic"].includes(Ae)&&Ve.jsx($2,{value:Ae,children:Wve(Ae)}),Ve.jsxs(boe,{children:[Ve.jsx(Soe,{asChild:!0,children:Ve.jsxs("div",{className:"rf-whitespace-nowrap rf-p-2 rf-mr-1 rf-cursor-pointer rf-relative",children:[Ve.jsx(r6t,{className:"rf-w-4 rf-h-4"}),(pe&&pe.length>0||t)&&Ve.jsx("span",{className:"rf-inline-flex rf-absolute rf-top-[6px] rf-right-[4px] rf-items-center rf-justify-center rf-w-1 rf-h-1 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full"})]})}),Ve.jsxs(J6,{className:"rf-*:text-xs",children:[xWt.map(Ge=>Ve.jsxs(yb,{onSelect:()=>Me(Ge),children:[Ae!==Ge&&Ve.jsx(lPe,{className:"rf-w-3 rf-h-3 rf-opacity-30"}),Ae===Ge&&Ve.jsx(Tae,{className:"rf-w-3 rf-h-3"}),Ve.jsx("div",{className:"rf-pr-2",children:Wve(Ge)}),Ge==="errors"&&(pe&&pe.length>0||t)&&Ve.jsx("span",{className:"rf-inline-flex rf-items-center rf-justify-center rf-w-3 rf-h-3 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full",children:t?1:pe==null?void 0:pe.length})]},Ge)),Ve.jsx(yb,{disabled:!0,className:"rf-opacity-60 rf-cursor-default rf-select-none",children:Ve.jsxs("div",{className:"rf-pr-2 rf-text-xs rf-text-gray-500",children:["@tscircuit/runframe@",_Wt.split(".").map((Ge,$e)=>$e===2?parseInt(Ge)+1:Ge).join(".")]})})]})]})]}),te&&Ve.jsx(w_,{onClick:Se,variant:"ghost",children:Ie?Ve.jsx(s6t,{size:16}):Ve.jsx(a6t,{size:16})})]}),s&&Ve.jsx(jb,{value:"code",className:"rf-flex-grow rf-overflow-hidden",children:Ve.jsx("div",{className:"rf-h-full",children:l})}),Ve.jsx(jb,{value:"pcb",children:Ve.jsx("div",{className:Mp("rf-overflow-hidden",Ie?"rf-h-[calc(100vh-52px)]":"rf-h-[620px]"),children:Ve.jsx(L3,{fallbackRender:({error:Ge})=>Ve.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:Ve.jsxs("div",{className:"rf-p-4",children:[Ve.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading PCB viewer"}),Ve.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ge==null?void 0:Ge.message)||"An unknown error occurred"})]})}),children:i?Ve.jsx(yWt,{focusOnHover:!1,circuitJson:i,debugGraphics:a,containerClassName:Mp("rf-h-full rf-w-full",Ie?"rf-min-h-[calc(100vh-240px)]":"rf-min-h-[620px]"),onEditEventsChanged:Ge=>{H&&Ge.forEach($e=>H($e))}}):Ve.jsx(v9,{onRunClicked:e})})})}),Ve.jsx(jb,{value:"assembly",children:Ve.jsx("div",{className:Mp("rf-overflow-auto",Ie?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:Ve.jsx(L3,{fallback:Ve.jsx("div",{children:"Error loading Assembly"}),children:i?Ve.jsx(NHt,{circuitJson:i,containerStyle:{height:"100%"},editingEnabled:!0,debugGrid:!0}):Ve.jsx(v9,{onRunClicked:e})})})}),Ve.jsx(jb,{value:"schematic",children:Ve.jsx("div",{className:Mp("rf-overflow-auto rf-bg-white",Ie?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:Ve.jsx(L3,{fallbackRender:({error:Ge})=>Ve.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:Ve.jsxs("div",{className:"rf-p-4",children:[Ve.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Schematic"}),Ve.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ge==null?void 0:Ge.message)||"An unknown error occurred"})]})}),children:i?Ve.jsx(MHt,{circuitJson:i,containerStyle:{height:"100%"},editingEnabled:!0,onEditEvent:Ge=>{H==null||H(Ge)},debugGrid:ae}):Ve.jsx(v9,{onRunClicked:e})})})}),Ve.jsx(jb,{value:"cad",children:Ve.jsx("div",{className:Mp("rf-overflow-auto",Ie?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:Ve.jsx(L3,{FallbackComponent:YLt,children:i?Ve.jsx(zLt,{ref:Re,circuitJson:i,autoRotateDisabled:z}):Ve.jsx(v9,{onRunClicked:e})})})}),Ve.jsx(jb,{value:"bom",children:Ve.jsx("div",{className:Mp("rf-overflow-auto",Ie?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:Ve.jsx(L3,{fallbackRender:({error:Ge})=>Ve.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:Ve.jsxs("div",{className:"rf-p-4",children:[Ve.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Bill of Materials"}),Ve.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ge==null?void 0:Ge.message)||"An unknown error occurred"})]})}),children:i?Ve.jsx(FHt,{circuitJson:i}):Ve.jsx(v9,{onRunClicked:e})})})}),Ve.jsx(jb,{value:"circuit_json",children:Ve.jsx("div",{className:Mp("rf-overflow-auto",Ie?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:Ve.jsx(L3,{fallback:Ve.jsx("div",{children:"Error loading JSON viewer"}),children:i?Ve.jsx(kHt,{elements:i}):Ve.jsx(v9,{onRunClicked:e})})})}),Ve.jsx(jb,{value:"errors",children:Ve.jsx("div",{className:Mp("rf-overflow-auto",Ie?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:t||pe&&pe.length>0?Ve.jsx(tzt,{code:r,circuitJsonErrors:pe,errorMessage:t,errorStack:n,autoroutingLog:B,onReportAutoroutingLog:P}):Ve.jsx(v9,{onRunClicked:e})})}),u&&Ve.jsx(jb,{value:"render_log",children:Ve.jsx(EWt,{renderLog:d})})]})})})};var YG="Dialog",[_Ge,xGe]=HS(YG),[bWt,Eb]=_Ge(YG),BGe=r=>{const{__scopeDialog:e,children:t,open:n,defaultOpen:i,onOpenChange:a,modal:o=!0}=r,s=nt.useRef(null),l=nt.useRef(null),[c,u]=IM({prop:n,defaultProp:i??!1,onChange:a,caller:YG});return Ve.jsx(bWt,{scope:e,triggerRef:s,contentRef:l,contentId:YS(),titleId:YS(),descriptionId:YS(),open:c,onOpenChange:u,onOpenToggle:nt.useCallback(()=>u(A=>!A),[u]),modal:o,children:t})};BGe.displayName=YG;var bGe="DialogTrigger",SGe=nt.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Eb(bGe,t),a=s1(e,i.triggerRef);return Ve.jsx(Bv.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":vle(i.open),...n,ref:a,onClick:Oh(r.onClick,i.onOpenToggle)})});SGe.displayName=bGe;var mle="DialogPortal",[SWt,wGe]=_Ge(mle,{forceMount:void 0}),QGe=r=>{const{__scopeDialog:e,forceMount:t,children:n,container:i}=r,a=Eb(mle,e);return Ve.jsx(SWt,{scope:e,forceMount:t,children:nt.Children.map(n,o=>Ve.jsx(Vb,{present:t||a.open,children:Ve.jsx(uoe,{asChild:!0,container:i,children:o})}))})};QGe.displayName=mle;var VG="DialogOverlay",MGe=nt.forwardRef((r,e)=>{const t=wGe(VG,r.__scopeDialog),{forceMount:n=t.forceMount,...i}=r,a=Eb(VG,r.__scopeDialog);return a.modal?Ve.jsx(Vb,{present:n||a.open,children:Ve.jsx(QWt,{...i,ref:e})}):null});MGe.displayName=VG;var wWt=vM("DialogOverlay.RemoveScroll"),QWt=nt.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Eb(VG,t);return Ve.jsx(goe,{as:wWt,allowPinchZoom:!0,shards:[i.contentRef],children:Ve.jsx(Bv.div,{"data-state":vle(i.open),...n,ref:e,style:{pointerEvents:"auto",...n.style}})})}),w9="DialogContent",DGe=nt.forwardRef((r,e)=>{const t=wGe(w9,r.__scopeDialog),{forceMount:n=t.forceMount,...i}=r,a=Eb(w9,r.__scopeDialog);return Ve.jsx(Vb,{present:n||a.open,children:a.modal?Ve.jsx(MWt,{...i,ref:e}):Ve.jsx(DWt,{...i,ref:e})})});DGe.displayName=w9;var MWt=nt.forwardRef((r,e)=>{const t=Eb(w9,r.__scopeDialog),n=nt.useRef(null),i=s1(e,t.contentRef,n);return nt.useEffect(()=>{const a=n.current;if(a)return fke(a)},[]),Ve.jsx(RGe,{...r,ref:i,trapFocus:t.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Oh(r.onCloseAutoFocus,a=>{var o;a.preventDefault(),(o=t.triggerRef.current)==null||o.focus()}),onPointerDownOutside:Oh(r.onPointerDownOutside,a=>{const o=a.detail.originalEvent,s=o.button===0&&o.ctrlKey===!0;(o.button===2||s)&&a.preventDefault()}),onFocusOutside:Oh(r.onFocusOutside,a=>a.preventDefault())})}),DWt=nt.forwardRef((r,e)=>{const t=Eb(w9,r.__scopeDialog),n=nt.useRef(!1),i=nt.useRef(!1);return Ve.jsx(RGe,{...r,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{var o,s;(o=r.onCloseAutoFocus)==null||o.call(r,a),a.defaultPrevented||(n.current||(s=t.triggerRef.current)==null||s.focus(),a.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:a=>{var l,c;(l=r.onInteractOutside)==null||l.call(r,a),a.defaultPrevented||(n.current=!0,a.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const o=a.target;((c=t.triggerRef.current)==null?void 0:c.contains(o))&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&i.current&&a.preventDefault()}})}),RGe=nt.forwardRef((r,e)=>{const{__scopeDialog:t,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:a,...o}=r,s=Eb(w9,t),l=nt.useRef(null),c=s1(e,l);return wPe(),Ve.jsxs(Ve.Fragment,{children:[Ve.jsx(Wae,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:a,children:Ve.jsx(Vae,{role:"dialog",id:s.contentId,"aria-describedby":s.descriptionId,"aria-labelledby":s.titleId,"data-state":vle(s.open),...o,ref:c,onDismiss:()=>s.onOpenChange(!1)})}),Ve.jsxs(Ve.Fragment,{children:[Ve.jsx(NWt,{titleId:s.titleId}),Ve.jsx(PWt,{contentRef:l,descriptionId:s.descriptionId})]})]})}),yle="DialogTitle",NGe=nt.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Eb(yle,t);return Ve.jsx(Bv.h2,{id:i.titleId,...n,ref:e})});NGe.displayName=yle;var TGe="DialogDescription",PGe=nt.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Eb(TGe,t);return Ve.jsx(Bv.p,{id:i.descriptionId,...n,ref:e})});PGe.displayName=TGe;var kGe="DialogClose",UGe=nt.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Eb(kGe,t);return Ve.jsx(Bv.button,{type:"button",...n,ref:e,onClick:Oh(r.onClick,()=>i.onOpenChange(!1))})});UGe.displayName=kGe;function vle(r){return r?"open":"closed"}var FGe="DialogTitleWarning",[RWt,LGe]=Rht(FGe,{contentName:w9,titleName:yle,docsSlug:"dialog"}),NWt=({titleId:r})=>{const e=LGe(FGe),t=`\`${e.contentName}\` requires a \`${e.titleName}\` for the component to be accessible for screen reader users.
13493
+ `,onClick:n=>{n.stopPropagation(),t()},children:[Ve.jsx("input",{type:"checkbox",checked:e}),Ve.jsx("span",{style:{color:"#eee"},children:r})]}),hWt=({children:r,elements:e})=>{const[t,n]=G1(G=>[G.is_mouse_over_container,G.setIsMouseOverContainer]),[i,a]=nt.useState(!1),[o,s]=nt.useState(!1),[l,c]=nt.useState(!1),[u,A]=G1(G=>[G.selected_layer,G.selectLayer]),[d,f,g,_,I,E]=G1(G=>[G.in_move_footprint_mode,G.in_draw_trace_mode,G.is_showing_rats_nest,G.is_showing_multiple_traces_length,G.is_showing_autorouting,G.is_showing_drc_errors]),x=G1(G=>G.setEditMode),B=G1(G=>G.setIsShowingRatsNest),P=G1(G=>G.setIsShowingMultipleTracesLength),L=G1(G=>G.setIsShowingAutorouting),U=G1(G=>G.setIsShowingDrcErrors);Pw("1",()=>A("top")),Pw("2",()=>A("bottom")),Pw("3",()=>A("inner1")),Pw("4",()=>A("inner2")),Pw("5",()=>A("inner3")),Pw("6",()=>A("inner4")),Pw("7",()=>A("inner5")),Pw("8",()=>A("inner6"));const H=(e==null?void 0:e.filter(G=>G.type.includes("error")).length)??0;return Ve.jsxs("div",{style:{position:"relative"},onMouseEnter:()=>{n(!0)},onMouseLeave:G=>{n(!1),s(!1)},children:[r,Ve.jsxs("div",{style:{position:"absolute",bottom:4,right:8,pointerEvents:"none",color:"white",fontSize:11,opacity:t?.5:0,transition:"opacity 1s",transitionDelay:"2s",fontFamily:"sans-serif"},children:["@tscircuit/pcb-viewer@",dWt.version]}),Ve.jsxs("div",{style:{position:"absolute",opacity:t?1:0,top:16,left:16,transition:t?"opacity 100ms linear":"opacity 1s linear",zIndex:sx.toolbarOverlay,color:"red",display:"flex",fontSize:12,height:100,fontFamily:"sans-serif"},children:[Ve.jsxs(c5,{onClick:()=>{s(!o)},onMouseLeave:()=>{o&&s(!1)},children:[Ve.jsxs("div",{children:["layer:"," ",Ve.jsx("span",{style:{marginLeft:2,fontWeight:500,color:l5[u]},children:u})]}),o&&Ve.jsx("div",{style:{marginTop:4,minWidth:120},children:ule.map(G=>G.replace(/-/g,"")).map(G=>Ve.jsx(fWt,{name:G,selected:G===u,onClick:()=>{A(G.replace(/-/,""))}},G))})]}),Ve.jsxs(c5,{style:H>0?{color:"red"}:{},onClick:()=>c(!l),onMouseLeave:()=>c(!1),children:[Ve.jsxs("div",{children:[H," errors"]}),l&&Ve.jsx("div",{style:{display:"grid",gridTemplateColumns:"100px 300px"},children:e==null?void 0:e.filter(G=>G.type.includes("error")).map((G,W)=>Ve.jsxs(nt.Fragment,{children:[Ve.jsx("div",{children:G.error_type}),Ve.jsx("div",{children:G.message})]},W))})]}),Ve.jsx(c5,{style:{},onClick:()=>{x(f?"off":"draw_trace")},children:Ve.jsxs("div",{children:[f?"✖ ":"","Edit Traces"]})}),Ve.jsx(c5,{style:{},onClick:()=>{x(d?"off":"move_footprint")},children:Ve.jsxs("div",{children:[d?"✖ ":"","Move Components"]})}),Ve.jsx(c5,{style:{},onClick:()=>{B(!g)},children:Ve.jsxs("div",{children:[g?"✖ ":"","Rats Nest"]})}),Ve.jsx(c5,{onClick:()=>{a(!i)},children:Ve.jsxs("div",{children:[Ve.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:["View"," ",Ve.jsx("span",{style:{fontSize:"8px",transform:i?"rotate(180deg)":"rotate(0)",transition:"transform 0.1s ease",display:"inline-block"},children:"▼"})]}),i&&Ve.jsxs("div",{style:{marginTop:4,minWidth:120},children:[Ve.jsx(gle,{label:"Show All Trace Lengths",checked:_,onClick:()=>{P(!_)}}),Ve.jsx(gle,{label:"Show Autorouting Animation",checked:I,onClick:()=>{L(!I)}}),Ve.jsx(gle,{label:"Show DRC Errors",checked:E,onClick:()=>{U(!E)}})]})]})})]})]})},pWt=r=>{const{transform:e,elements:t}=r,[n,i]=nt.useMemo(()=>{const c=r.elements.flatMap(A=>bJt(A,r.elements)),u=FS(r.elements);return[c,u]},[r.elements]),[a,o]=nt.useState({drawingObjectIdsWithMouseOver:new Set,primitiveIdsInMousedOverNet:[]}),s=nt.useMemo(()=>xJt({primitivesWithoutInteractionMetadata:n,drawingObjectIdsWithMouseOver:a.drawingObjectIdsWithMouseOver,primitiveIdsInMousedOverNet:a.primitiveIdsInMousedOverNet}),[n,a]),l=nt.useCallback(c=>{var d,f;const u=[];for(const g of c)if(g._element){const _=i.getNetConnectedToId("pcb_port_id"in g._element?(d=g._element)==null?void 0:d.pcb_port_id:"pcb_trace_id"in g._element?(f=g._element)==null?void 0:f.pcb_trace_id:"");u.push(...i.getIdsConnectedToNet(_))}const A=new Set(c.map(g=>g._pcb_drawing_object_id));o({drawingObjectIdsWithMouseOver:A,primitiveIdsInMousedOverNet:u})},[i]);return Ve.jsx(uWt,{elements:t,transform:e,primitives:n,onMouseHoverOverPrimitives:l,children:Ve.jsx(jJt,{disabled:!r.allowEditing,transform:e,soup:t,cancelPanDrag:r.cancelPanDrag,onCreateEditEvent:r.onCreateEditEvent,onModifyEditEvent:r.onModifyEditEvent,children:Ve.jsx(ZJt,{disabled:!r.allowEditing,transform:e,soup:t,cancelPanDrag:r.cancelPanDrag,onCreateEditEvent:r.onCreateEditEvent,onModifyEditEvent:r.onModifyEditEvent,children:Ve.jsx(VJt,{transform:e,focusOnHover:r.focusOnHover,children:Ve.jsx(hWt,{elements:t,children:Ve.jsx(eWt,{transform:e,elements:t,children:Ve.jsx(AWt,{transform:e,soup:t,children:Ve.jsx(HJt,{transform:e,debugGraphics:r.debugGraphics,children:Ve.jsx(YJt,{transform:e,elements:t,children:Ve.jsx(zJt,{transform:e,primitives:s,width:r.width,height:r.height,grid:r.grid})})})})})})})})})})},gWt=Fu(Od(400,300),N1(40,-40)),mWt=({circuitJson:r,debugGraphics:e,height:t=600,initialState:n,allowEditing:i=!0,editEvents:a,onEditEventsChanged:o,focusOnHover:s=!1,clickToInteractEnabled:l=!1})=>{const[c,u]=nt.useState(!l),[A,d]=hle(),[f,g]=nt.useState(gWt),{ref:_,setTransform:I,cancelDrag:E}=_Jt({transform:f,onSetTransform:g,enabled:c});let[x,B]=nt.useState([]);x=a??x;const P=nt.useRef(!1),L=nt.useRef(null),U=`${(r==null?void 0:r.length)||0}_${(r==null?void 0:r.editCount)||0}`,H=()=>{const te=(d==null?void 0:d.width)>0?d:{width:500,height:500},{center:oe,width:pe,height:Ae}=W.some(ge=>ge.type.startsWith("pcb_"))?fJt(W.filter(ge=>ge.type.startsWith("pcb_"))):{center:{x:0,y:0},width:.001,height:.001},he=Math.min((te.width??0)/pe,(te.height??0)/Ae,100)*.75,Ie=Fu(Od((te.width??0)/2,(te.height??0)/2),N1(he,-he,0,0),Od(-oe.x,-oe.y));I(Ie)};nt.useEffect(()=>{d!=null&&d.width&&r&&r.length!==0&&(P.current||(H(),P.current=!0))},[r,d]);const G=nt.useMemo(()=>(r==null?void 0:r.filter(te=>te.type.startsWith("pcb_")||te.type.startsWith("source_")))??[],[U]),W=nt.useMemo(()=>NYt({circuitJson:G,editEvents:x}),[G,x]),z=te=>{B([...x,te]),o==null||o([...x,te])},ae=te=>{const oe=x.map(pe=>pe.edit_event_id===te.edit_event_id?{...pe,...te}:pe);B(oe),o==null||o(oe)};return Ve.jsxs("div",{ref:_,style:{position:"relative"},children:[Ve.jsx("div",{ref:A,children:Ve.jsxs(pJt,{initialState:n,children:[Ve.jsx(pWt,{transform:f,height:t,width:d.width,allowEditing:i,focusOnHover:s,cancelPanDrag:E,onCreateEditEvent:z,onModifyEditEvent:ae,grid:{spacing:1,view_window:{left:0,right:d.width||500,top:t,bottom:0}},elements:W,debugGraphics:e},d.width),Ve.jsx(mJt,{})]})}),l&&!c&&Ve.jsx("div",{onClick:()=>{u(!0),H()},onTouchStart:te=>{const oe=te.touches[0];L.current={x:oe.clientX,y:oe.clientY}},onTouchEnd:te=>{const oe=te.changedTouches[0],pe=L.current;if(!pe)return;const Ae=Math.abs(oe.clientX-pe.x),he=Math.abs(oe.clientY-pe.y);Ae<10&&he<10&&(te.preventDefault(),u(!0),H()),L.current=null},style:{position:"absolute",inset:0,cursor:"pointer",zIndex:sx.clickToInteractOverlay,display:"flex",alignItems:"center",justifyContent:"center",touchAction:"pan-x pan-y pinch-zoom"},children:Ve.jsx("div",{style:{backgroundColor:"rgba(0, 0, 0, 0.8)",color:"white",padding:"12px 24px",borderRadius:"8px",fontSize:"16px",pointerEvents:"none"},children:typeof window<"u"&&("ontouchstart"in window||navigator.maxTouchPoints>0)?"Touch to Interact":"Click to Interact"})})]})};const yWt=({containerClassName:r,...e})=>{const t=nt.useRef(null),[n,i]=nt.useState(620);return nt.useLayoutEffect(()=>{const a=()=>{if(t.current){const s=t.current.clientHeight,l=window.innerHeight;i(Math.min(Math.max(s,620),l))}};a();const o=new ResizeObserver(a);return t.current&&o.observe(t.current),window.addEventListener("resize",a),()=>{o.disconnect(),window.removeEventListener("resize",a)}},[]),Ve.jsx("div",{ref:t,className:r||"rf-w-full rf-h-full",children:Ve.jsx(mWt,{...e,height:n})})},vWt='*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.17 | MIT License | https://tailwindcss.com*/*,:after,:before{border:0 solid #e5e7eb;box-sizing:border-box}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-tap-highlight-color:transparent}body{line-height:inherit;margin:0}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-size:1em;font-variation-settings:normal}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}button,input,optgroup,select,textarea{color:inherit;font-family:inherit;font-feature-settings:inherit;font-size:100%;font-variation-settings:inherit;font-weight:inherit;letter-spacing:inherit;line-height:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{color:#9ca3af;opacity:1}input::placeholder,textarea::placeholder{color:#9ca3af;opacity:1}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}[hidden]:where(:not([hidden=until-found])){display:none}:root{--radius:0.5rem}.rf-pointer-events-none{pointer-events:none}.rf-invisible{visibility:hidden}.rf-fixed{position:fixed}.rf-absolute{position:absolute}.rf-relative{position:relative}.rf-inset-0{inset:0}.-rf-left-2{left:-.5rem}.-rf-right-10{right:-2.5rem}.-rf-right-2{right:-.5rem}.-rf-right-4{right:-1rem}.-rf-right-6{right:-1.5rem}.-rf-right-7{right:-1.75rem}.-rf-right-8{right:-2rem}.-rf-right-9{right:-2.25rem}.rf-bottom-full{bottom:100%}.rf-left-0{left:0}.rf-left-1{left:.25rem}.rf-left-1\\/2{left:50%}.rf-left-2{left:.5rem}.rf-left-\\[50\\%\\]{left:50%}.rf-right-0{right:0}.rf-right-4{right:1rem}.rf-right-\\[4px\\]{right:4px}.rf-top-0{top:0}.rf-top-1{top:.25rem}.rf-top-2{top:.5rem}.rf-top-2\\.5{top:.625rem}.rf-top-\\[50\\%\\]{top:50%}.rf-top-\\[6px\\]{top:6px}.rf-z-50{z-index:50}.rf-z-\\[100\\]{z-index:100}.-rf-mx-1,.rf--mx-1{margin-left:-.25rem;margin-right:-.25rem}.rf-mx-1{margin-left:.25rem;margin-right:.25rem}.rf-mx-2{margin-left:.5rem;margin-right:.5rem}.rf-mx-auto{margin-left:auto;margin-right:auto}.rf-my-1{margin-bottom:.25rem;margin-top:.25rem}.rf-my-12{margin-bottom:3rem;margin-top:3rem}.rf-my-4{margin-bottom:1rem;margin-top:1rem}.rf-my-auto{margin-bottom:auto;margin-top:auto}.rf-mb-1{margin-bottom:.25rem}.rf-mb-12{margin-bottom:3rem}.rf-mb-2{margin-bottom:.5rem}.rf-mb-3{margin-bottom:.75rem}.rf-mb-4{margin-bottom:1rem}.rf-mb-6{margin-bottom:1.5rem}.rf-mb-8{margin-bottom:2rem}.rf-ml-1{margin-left:.25rem}.rf-ml-2{margin-left:.5rem}.rf-ml-auto{margin-left:auto}.rf-mr-1{margin-right:.25rem}.rf-mr-2{margin-right:.5rem}.rf-mt-0{margin-top:0}.rf-mt-0\\.5{margin-top:.125rem}.rf-mt-1{margin-top:.25rem}.rf-mt-2{margin-top:.5rem}.rf-mt-3{margin-top:.75rem}.rf-mt-4{margin-top:1rem}.rf-mt-5{margin-top:1.25rem}.rf-mt-auto{margin-top:auto}.rf-block{display:block}.rf-inline{display:inline}.rf-flex{display:flex}.rf-inline-flex{display:inline-flex}.rf-grid{display:grid}.rf-hidden{display:none}.rf-aspect-square{aspect-ratio:1/1}.rf-aspect-video{aspect-ratio:16/9}.rf-size-14{height:3.5rem;width:3.5rem}.rf-size-4{height:1rem;width:1rem}.\\!rf-h-2{height:.5rem!important}.\\!rf-h-2\\.5{height:.625rem!important}.\\!rf-h-3{height:.75rem!important}.\\!rf-h-full{height:100%!important}.rf-h-1{height:.25rem}.rf-h-10{height:2.5rem}.rf-h-12{height:3rem}.rf-h-2{height:.5rem}.rf-h-2\\.5{height:.625rem}.rf-h-3{height:.75rem}.rf-h-3\\.5{height:.875rem}.rf-h-4{height:1rem}.rf-h-5{height:1.25rem}.rf-h-6{height:1.5rem}.rf-h-60{height:15rem}.rf-h-64{height:16rem}.rf-h-8{height:2rem}.rf-h-9{height:2.25rem}.rf-h-\\[620px\\]{height:620px}.rf-h-\\[calc\\(100vh-52px\\)\\]{height:calc(100vh - 52px)}.rf-h-\\[calc\\(100vh-96px\\)\\]{height:calc(100vh - 96px)}.rf-h-\\[var\\(--radix-select-trigger-height\\)\\]{height:var(--radix-select-trigger-height)}.rf-h-fit{height:-moz-fit-content;height:fit-content}.rf-h-full{height:100%}.rf-h-px{height:1px}.\\!rf-max-h-\\[40vh\\]{max-height:40vh!important}.\\!rf-max-h-\\[70\\%\\]{max-height:70%!important}.rf-max-h-32{max-height:8rem}.rf-max-h-96{max-height:24rem}.rf-max-h-\\[500px\\]{max-height:500px}.rf-max-h-\\[90vh\\]{max-height:90vh}.rf-min-h-0{min-height:0}.rf-min-h-\\[200px\\]{min-height:200px}.rf-min-h-\\[620px\\]{min-height:620px}.rf-min-h-\\[calc\\(100vh-240px\\)\\]{min-height:calc(100vh - 240px)}.\\!rf-w-2{width:.5rem!important}.\\!rf-w-2\\.5{width:.625rem!important}.rf-w-1{width:.25rem}.rf-w-1\\/2{width:50%}.rf-w-11{width:2.75rem}.rf-w-11\\/12{width:91.666667%}.rf-w-12{width:3rem}.rf-w-16{width:4rem}.rf-w-2{width:.5rem}.rf-w-2\\.5{width:.625rem}.rf-w-3{width:.75rem}.rf-w-3\\.5{width:.875rem}.rf-w-32{width:8rem}.rf-w-4{width:1rem}.rf-w-5{width:1.25rem}.rf-w-6{width:1.5rem}.rf-w-64{width:16rem}.rf-w-72{width:18rem}.rf-w-8{width:2rem}.rf-w-9{width:2.25rem}.rf-w-96{width:24rem}.rf-w-\\[95\\%\\]{width:95%}.rf-w-fit{width:-moz-fit-content;width:fit-content}.rf-w-full{width:100%}.rf-min-w-10{min-width:2.5rem}.rf-min-w-16{min-width:4rem}.rf-min-w-\\[148px\\]{min-width:148px}.rf-min-w-\\[8rem\\]{min-width:8rem}.rf-min-w-\\[var\\(--radix-select-trigger-width\\)\\]{min-width:var(--radix-select-trigger-width)}.\\!rf-max-w-\\[60vw\\]{max-width:60vw!important}.\\!rf-max-w-\\[660px\\]{max-width:660px!important}.rf-max-w-2xl{max-width:42rem}.rf-max-w-3xl{max-width:48rem}.rf-max-w-5xl{max-width:64rem}.rf-max-w-full{max-width:100%}.rf-max-w-lg{max-width:32rem}.rf-max-w-md{max-width:28rem}.rf-max-w-xl{max-width:36rem}.rf-flex-1{flex:1 1 0%}.rf-flex-shrink-0,.rf-shrink-0{flex-shrink:0}.rf-flex-grow{flex-grow:1}.rf-table-auto{table-layout:auto}.-rf-translate-x-1{--tw-translate-x:-0.25rem}.-rf-translate-x-1,.-rf-translate-x-1\\/2{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rf-translate-x-1\\/2{--tw-translate-x:-50%}.-rf-translate-y-1{--tw-translate-y:-0.25rem}.-rf-translate-y-1,.rf--translate-x-1{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rf--translate-x-1{--tw-translate-x:-0.25rem}.rf-translate-x-\\[-50\\%\\]{--tw-translate-x:-50%}.rf-translate-x-\\[-50\\%\\],.rf-translate-y-\\[-50\\%\\]{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rf-translate-y-\\[-50\\%\\]{--tw-translate-y:-50%}.rf-transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes rf-pulse{50%{opacity:.5}}.rf-animate-pulse{animation:rf-pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes rf-spin{to{transform:rotate(1turn)}}.rf-animate-spin{animation:rf-spin 1s linear infinite}.rf-cursor-default{cursor:default}.rf-cursor-not-allowed{cursor:not-allowed}.rf-cursor-pointer{cursor:pointer}.rf-select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.rf-grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.rf-grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.rf-flex-row{flex-direction:row}.rf-flex-col{flex-direction:column}.rf-flex-col-reverse{flex-direction:column-reverse}.rf-flex-wrap{flex-wrap:wrap}.rf-place-items-center{place-items:center}.rf-items-start{align-items:flex-start}.rf-items-end{align-items:flex-end}.rf-items-center{align-items:center}.rf-justify-end{justify-content:flex-end}.rf-justify-center{justify-content:center}.rf-justify-between{justify-content:space-between}.rf-gap-0{gap:0}.rf-gap-1{gap:.25rem}.rf-gap-2{gap:.5rem}.rf-gap-3{gap:.75rem}.rf-gap-4{gap:1rem}.rf-gap-5{gap:1.25rem}.rf-gap-6{gap:1.5rem}.rf-gap-8{gap:2rem}.rf-space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(.5rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(.5rem*var(--tw-space-x-reverse))}.rf-space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.5rem*var(--tw-space-y-reverse));margin-top:calc(.5rem*(1 - var(--tw-space-y-reverse)))}.rf-space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1rem*var(--tw-space-y-reverse));margin-top:calc(1rem*(1 - var(--tw-space-y-reverse)))}.rf-space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1.5rem*var(--tw-space-y-reverse));margin-top:calc(1.5rem*(1 - var(--tw-space-y-reverse)))}.rf-divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse:0;border-bottom-width:calc(1px*var(--tw-divide-y-reverse));border-top-width:calc(1px*(1 - var(--tw-divide-y-reverse)))}.rf-overflow-auto{overflow:auto}.rf-overflow-hidden{overflow:hidden}.rf-overflow-visible{overflow:visible}.rf-overflow-x-auto{overflow-x:auto}.\\!rf-overflow-y-auto{overflow-y:auto!important}.rf-overflow-y-auto{overflow-y:auto}.\\!rf-overflow-x-hidden{overflow-x:hidden!important}.rf-overflow-x-hidden{overflow-x:hidden}.rf-overflow-x-clip{overflow-x:clip}.rf-truncate{overflow:hidden;text-overflow:ellipsis}.rf-truncate,.rf-whitespace-nowrap{white-space:nowrap}.rf-whitespace-pre-wrap{white-space:pre-wrap}.rf-break-words{overflow-wrap:break-word}.rf-rounded{border-radius:.25rem}.rf-rounded-2xl{border-radius:1rem}.rf-rounded-full{border-radius:9999px}.rf-rounded-lg{border-radius:var(--radius)}.rf-rounded-md{border-radius:calc(var(--radius) - 2px)}.rf-rounded-sm{border-radius:calc(var(--radius) - 4px)}.rf-rounded-xl{border-radius:.75rem}.rf-border{border-width:1px}.rf-border-b{border-bottom-width:1px}.rf-border-t{border-top-width:1px}.rf-border-blue-200{--tw-border-opacity:1;border-color:rgb(191 219 254/var(--tw-border-opacity,1))}.rf-border-blue-500{--tw-border-opacity:1;border-color:rgb(59 130 246/var(--tw-border-opacity,1))}.rf-border-blue-600{--tw-border-opacity:1;border-color:rgb(37 99 235/var(--tw-border-opacity,1))}.rf-border-gray-200{--tw-border-opacity:1;border-color:rgb(229 231 235/var(--tw-border-opacity,1))}.rf-border-gray-300{--tw-border-opacity:1;border-color:rgb(209 213 219/var(--tw-border-opacity,1))}.rf-border-green-200{--tw-border-opacity:1;border-color:rgb(187 247 208/var(--tw-border-opacity,1))}.rf-border-input{border-color:hsl(var(--input))}.rf-border-neutral-200{--tw-border-opacity:1;border-color:rgb(229 229 229/var(--tw-border-opacity,1))}.rf-border-primary{border-color:hsl(var(--primary))}.rf-border-red-200{--tw-border-opacity:1;border-color:rgb(254 202 202/var(--tw-border-opacity,1))}.rf-border-red-500{--tw-border-opacity:1;border-color:rgb(239 68 68/var(--tw-border-opacity,1))}.rf-border-zinc-200{--tw-border-opacity:1;border-color:rgb(228 228 231/var(--tw-border-opacity,1))}.rf-border-zinc-900{--tw-border-opacity:1;border-color:rgb(24 24 27/var(--tw-border-opacity,1))}.rf-bg-background{background-color:hsl(var(--background))}.rf-bg-black{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity,1))}.rf-bg-black\\/80{background-color:rgba(0,0,0,.8)}.rf-bg-blue-100{--tw-bg-opacity:1;background-color:rgb(219 234 254/var(--tw-bg-opacity,1))}.rf-bg-blue-50{--tw-bg-opacity:1;background-color:rgb(239 246 255/var(--tw-bg-opacity,1))}.rf-bg-blue-500{--tw-bg-opacity:1;background-color:rgb(59 130 246/var(--tw-bg-opacity,1))}.rf-bg-blue-600{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity,1))}.rf-bg-gray-100{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity,1))}.rf-bg-gray-200{--tw-bg-opacity:1;background-color:rgb(229 231 235/var(--tw-bg-opacity,1))}.rf-bg-gray-300{--tw-bg-opacity:1;background-color:rgb(209 213 219/var(--tw-bg-opacity,1))}.rf-bg-gray-400{--tw-bg-opacity:1;background-color:rgb(156 163 175/var(--tw-bg-opacity,1))}.rf-bg-gray-50{--tw-bg-opacity:1;background-color:rgb(249 250 251/var(--tw-bg-opacity,1))}.rf-bg-gray-500{--tw-bg-opacity:1;background-color:rgb(107 114 128/var(--tw-bg-opacity,1))}.rf-bg-gray-700{--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity,1))}.rf-bg-gray-800{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity,1))}.rf-bg-gray-900{--tw-bg-opacity:1;background-color:rgb(17 24 39/var(--tw-bg-opacity,1))}.rf-bg-green-100{--tw-bg-opacity:1;background-color:rgb(220 252 231/var(--tw-bg-opacity,1))}.rf-bg-green-50{--tw-bg-opacity:1;background-color:rgb(240 253 244/var(--tw-bg-opacity,1))}.rf-bg-muted{background-color:hsl(var(--muted))}.rf-bg-neutral-100{--tw-bg-opacity:1;background-color:rgb(245 245 245/var(--tw-bg-opacity,1))}.rf-bg-neutral-50{--tw-bg-opacity:1;background-color:rgb(250 250 250/var(--tw-bg-opacity,1))}.rf-bg-neutral-800{--tw-bg-opacity:1;background-color:rgb(38 38 38/var(--tw-bg-opacity,1))}.rf-bg-neutral-900{--tw-bg-opacity:1;background-color:rgb(23 23 23/var(--tw-bg-opacity,1))}.rf-bg-orange-400{--tw-bg-opacity:1;background-color:rgb(251 146 60/var(--tw-bg-opacity,1))}.rf-bg-popover{background-color:hsl(var(--popover))}.rf-bg-red-100{--tw-bg-opacity:1;background-color:rgb(254 226 226/var(--tw-bg-opacity,1))}.rf-bg-red-50{--tw-bg-opacity:1;background-color:rgb(254 242 242/var(--tw-bg-opacity,1))}.rf-bg-red-500{--tw-bg-opacity:1;background-color:rgb(239 68 68/var(--tw-bg-opacity,1))}.rf-bg-red-900{--tw-bg-opacity:1;background-color:rgb(127 29 29/var(--tw-bg-opacity,1))}.rf-bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.rf-bg-yellow-100{--tw-bg-opacity:1;background-color:rgb(254 249 195/var(--tw-bg-opacity,1))}.rf-bg-zinc-100{--tw-bg-opacity:1;background-color:rgb(244 244 245/var(--tw-bg-opacity,1))}.rf-bg-zinc-200{--tw-bg-opacity:1;background-color:rgb(228 228 231/var(--tw-bg-opacity,1))}.rf-bg-zinc-50{--tw-bg-opacity:1;background-color:rgb(250 250 250/var(--tw-bg-opacity,1))}.rf-bg-zinc-800{--tw-bg-opacity:1;background-color:rgb(39 39 42/var(--tw-bg-opacity,1))}.rf-bg-zinc-900{--tw-bg-opacity:1;background-color:rgb(24 24 27/var(--tw-bg-opacity,1))}.rf-bg-opacity-50{--tw-bg-opacity:0.5}.rf-fill-current{fill:currentColor}.rf-object-contain{-o-object-fit:contain;object-fit:contain}.\\!rf-p-0{padding:0!important}.rf-p-0{padding:0}.rf-p-1{padding:.25rem}.rf-p-2{padding:.5rem}.rf-p-3{padding:.75rem}.rf-p-4{padding:1rem}.rf-p-5{padding:1.25rem}.rf-p-6{padding:1.5rem}.rf-p-8{padding:2rem}.rf-px-1{padding-left:.25rem;padding-right:.25rem}.rf-px-2{padding-left:.5rem;padding-right:.5rem}.rf-px-3{padding-left:.75rem;padding-right:.75rem}.rf-px-4{padding-left:1rem;padding-right:1rem}.rf-px-6{padding-left:1.5rem;padding-right:1.5rem}.rf-px-8{padding-left:2rem;padding-right:2rem}.rf-py-0{padding-bottom:0;padding-top:0}.rf-py-0\\.5{padding-bottom:.125rem;padding-top:.125rem}.rf-py-1{padding-bottom:.25rem;padding-top:.25rem}.rf-py-1\\.5{padding-bottom:.375rem;padding-top:.375rem}.rf-py-10{padding-bottom:2.5rem;padding-top:2.5rem}.rf-py-12{padding-bottom:3rem;padding-top:3rem}.rf-py-2{padding-bottom:.5rem;padding-top:.5rem}.rf-py-3{padding-bottom:.75rem;padding-top:.75rem}.rf-py-4{padding-bottom:1rem;padding-top:1rem}.rf-py-8{padding-bottom:2rem;padding-top:2rem}.rf-pb-0{padding-bottom:0}.rf-pb-2{padding-bottom:.5rem}.rf-pb-3{padding-bottom:.75rem}.rf-pb-4{padding-bottom:1rem}.rf-pl-2{padding-left:.5rem}.rf-pl-4{padding-left:1rem}.rf-pl-8{padding-left:2rem}.rf-pr-2{padding-right:.5rem}.rf-pt-2{padding-top:.5rem}.rf-pt-4{padding-top:1rem}.rf-text-left{text-align:left}.rf-text-center{text-align:center}.rf-text-right{text-align:right}.rf-font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.rf-text-2xl{font-size:1.5rem;line-height:2rem}.rf-text-3xl{font-size:1.875rem;line-height:2.25rem}.rf-text-\\[8px\\]{font-size:8px}.rf-text-base{font-size:1rem;line-height:1.5rem}.rf-text-lg{font-size:1.125rem;line-height:1.75rem}.rf-text-sm{font-size:.875rem;line-height:1.25rem}.rf-text-xl{font-size:1.25rem;line-height:1.75rem}.rf-text-xs{font-size:.75rem;line-height:1rem}.rf-font-bold{font-weight:700}.rf-font-medium{font-weight:500}.rf-font-semibold{font-weight:600}.rf-capitalize{text-transform:capitalize}.rf-tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.rf-leading-5{line-height:1.25rem}.rf-leading-none{line-height:1}.rf-leading-tight{line-height:1.25}.rf-tracking-widest{letter-spacing:.1em}.rf-text-black{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity,1))}.rf-text-blue-500{--tw-text-opacity:1;color:rgb(59 130 246/var(--tw-text-opacity,1))}.rf-text-blue-600{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.rf-text-blue-700{--tw-text-opacity:1;color:rgb(29 78 216/var(--tw-text-opacity,1))}.rf-text-blue-800{--tw-text-opacity:1;color:rgb(30 64 175/var(--tw-text-opacity,1))}.rf-text-blue-900{--tw-text-opacity:1;color:rgb(30 58 138/var(--tw-text-opacity,1))}.rf-text-current{color:currentColor}.rf-text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175/var(--tw-text-opacity,1))}.rf-text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity,1))}.rf-text-gray-600{--tw-text-opacity:1;color:rgb(75 85 99/var(--tw-text-opacity,1))}.rf-text-gray-700{--tw-text-opacity:1;color:rgb(55 65 81/var(--tw-text-opacity,1))}.rf-text-gray-800{--tw-text-opacity:1;color:rgb(31 41 55/var(--tw-text-opacity,1))}.rf-text-gray-900{--tw-text-opacity:1;color:rgb(17 24 39/var(--tw-text-opacity,1))}.rf-text-green-500{--tw-text-opacity:1;color:rgb(34 197 94/var(--tw-text-opacity,1))}.rf-text-green-600{--tw-text-opacity:1;color:rgb(22 163 74/var(--tw-text-opacity,1))}.rf-text-green-700{--tw-text-opacity:1;color:rgb(21 128 61/var(--tw-text-opacity,1))}.rf-text-green-800{--tw-text-opacity:1;color:rgb(22 101 52/var(--tw-text-opacity,1))}.rf-text-green-900{--tw-text-opacity:1;color:rgb(20 83 45/var(--tw-text-opacity,1))}.rf-text-muted-foreground{color:hsl(var(--muted-foreground))}.rf-text-neutral-50{--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.rf-text-neutral-500{--tw-text-opacity:1;color:rgb(115 115 115/var(--tw-text-opacity,1))}.rf-text-neutral-900{--tw-text-opacity:1;color:rgb(23 23 23/var(--tw-text-opacity,1))}.rf-text-neutral-950{--tw-text-opacity:1;color:rgb(10 10 10/var(--tw-text-opacity,1))}.rf-text-popover-foreground{color:hsl(var(--popover-foreground))}.rf-text-red-200{--tw-text-opacity:1;color:rgb(254 202 202/var(--tw-text-opacity,1))}.rf-text-red-300{--tw-text-opacity:1;color:rgb(252 165 165/var(--tw-text-opacity,1))}.rf-text-red-400{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity,1))}.rf-text-red-500{--tw-text-opacity:1;color:rgb(239 68 68/var(--tw-text-opacity,1))}.rf-text-red-600{--tw-text-opacity:1;color:rgb(220 38 38/var(--tw-text-opacity,1))}.rf-text-red-700{--tw-text-opacity:1;color:rgb(185 28 28/var(--tw-text-opacity,1))}.rf-text-red-800{--tw-text-opacity:1;color:rgb(153 27 27/var(--tw-text-opacity,1))}.rf-text-red-900{--tw-text-opacity:1;color:rgb(127 29 29/var(--tw-text-opacity,1))}.rf-text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.rf-text-yellow-400{--tw-text-opacity:1;color:rgb(250 204 21/var(--tw-text-opacity,1))}.rf-text-yellow-500{--tw-text-opacity:1;color:rgb(234 179 8/var(--tw-text-opacity,1))}.rf-text-yellow-900{--tw-text-opacity:1;color:rgb(113 63 18/var(--tw-text-opacity,1))}.rf-text-zinc-200{--tw-text-opacity:1;color:rgb(228 228 231/var(--tw-text-opacity,1))}.rf-text-zinc-300{--tw-text-opacity:1;color:rgb(212 212 216/var(--tw-text-opacity,1))}.rf-text-zinc-400{--tw-text-opacity:1;color:rgb(161 161 170/var(--tw-text-opacity,1))}.rf-text-zinc-50{--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.rf-text-zinc-500{--tw-text-opacity:1;color:rgb(113 113 122/var(--tw-text-opacity,1))}.rf-text-zinc-900{--tw-text-opacity:1;color:rgb(24 24 27/var(--tw-text-opacity,1))}.rf-text-zinc-950{--tw-text-opacity:1;color:rgb(9 9 11/var(--tw-text-opacity,1))}.rf-underline{text-decoration-line:underline}.rf-line-through{text-decoration-line:line-through}.rf-underline-offset-4{text-underline-offset:4px}.rf-opacity-0{opacity:0}.rf-opacity-25{opacity:.25}.rf-opacity-30{opacity:.3}.rf-opacity-50{opacity:.5}.rf-opacity-60{opacity:.6}.rf-opacity-75{opacity:.75}.rf-shadow{--tw-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px -1px rgba(0,0,0,.1);--tw-shadow-colored:0 1px 3px 0 var(--tw-shadow-color),0 1px 2px -1px var(--tw-shadow-color)}.rf-shadow,.rf-shadow-lg{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.rf-shadow-lg{--tw-shadow:0 10px 15px -3px rgba(0,0,0,.1),0 4px 6px -4px rgba(0,0,0,.1);--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color)}.rf-shadow-md{--tw-shadow:0 4px 6px -1px rgba(0,0,0,.1),0 2px 4px -2px rgba(0,0,0,.1);--tw-shadow-colored:0 4px 6px -1px var(--tw-shadow-color),0 2px 4px -2px var(--tw-shadow-color)}.rf-shadow-md,.rf-shadow-sm{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.rf-shadow-sm{--tw-shadow:0 1px 2px 0 rgba(0,0,0,.05);--tw-shadow-colored:0 1px 2px 0 var(--tw-shadow-color)}.rf-outline-none{outline:2px solid transparent;outline-offset:2px}.rf-ring-2{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.rf-ring-blue-500{--tw-ring-opacity:1;--tw-ring-color:rgb(59 130 246/var(--tw-ring-opacity,1))}.rf-ring-primary{--tw-ring-color:hsl(var(--primary))}.rf-ring-offset-background{--tw-ring-offset-color:hsl(var(--background))}.rf-ring-offset-white{--tw-ring-offset-color:#fff}.rf-transition{transition-duration:.15s;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1)}.rf-transition-all{transition-duration:.15s;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1)}.rf-transition-colors{transition-duration:.15s;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1)}.rf-transition-opacity{transition-duration:.15s;transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1)}.rf-duration-200{transition-duration:.2s}.rf-ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}@keyframes enter{0%{opacity:var(--tw-enter-opacity,1);transform:translate3d(var(--tw-enter-translate-x,0),var(--tw-enter-translate-y,0),0) scale3d(var(--tw-enter-scale,1),var(--tw-enter-scale,1),var(--tw-enter-scale,1)) rotate(var(--tw-enter-rotate,0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity,1);transform:translate3d(var(--tw-exit-translate-x,0),var(--tw-exit-translate-y,0),0) scale3d(var(--tw-exit-scale,1),var(--tw-exit-scale,1),var(--tw-exit-scale,1)) rotate(var(--tw-exit-rotate,0))}}.rf-slide-in-from-left-1{--tw-enter-translate-x:-0.25rem}.rf-slide-out-to-left-1{--tw-exit-translate-x:-0.25rem}.rf-duration-200{animation-duration:.2s}.rf-ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.file\\:rf-border-0::file-selector-button{border-width:0}.file\\:rf-bg-transparent::file-selector-button{background-color:transparent}.file\\:rf-text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\\:rf-font-medium::file-selector-button{font-weight:500}.placeholder\\:rf-text-zinc-500::-moz-placeholder{--tw-text-opacity:1;color:rgb(113 113 122/var(--tw-text-opacity,1))}.placeholder\\:rf-text-zinc-500::placeholder{--tw-text-opacity:1;color:rgb(113 113 122/var(--tw-text-opacity,1))}.hover\\:rf-border-blue-300:hover{--tw-border-opacity:1;border-color:rgb(147 197 253/var(--tw-border-opacity,1))}.hover\\:\\!rf-bg-transparent:hover{background-color:transparent!important}.hover\\:rf-bg-blue-700:hover{--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-opacity,1))}.hover\\:rf-bg-red-500\\/90:hover{background-color:rgba(239,68,68,.9)}.hover\\:rf-bg-zinc-100:hover{--tw-bg-opacity:1;background-color:rgb(244 244 245/var(--tw-bg-opacity,1))}.hover\\:rf-bg-zinc-100\\/80:hover{background-color:hsla(240,5%,96%,.8)}.hover\\:rf-bg-zinc-900\\/90:hover{background-color:rgba(24,24,27,.9)}.hover\\:rf-text-red-400:hover{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity,1))}.hover\\:rf-text-zinc-900:hover{--tw-text-opacity:1;color:rgb(24 24 27/var(--tw-text-opacity,1))}.hover\\:rf-underline:hover{text-decoration-line:underline}.focus\\:rf-bg-gray-100:focus{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity,1))}.focus\\:rf-bg-zinc-100:focus{--tw-bg-opacity:1;background-color:rgb(244 244 245/var(--tw-bg-opacity,1))}.focus\\:rf-text-gray-900:focus{--tw-text-opacity:1;color:rgb(17 24 39/var(--tw-text-opacity,1))}.focus\\:rf-text-zinc-900:focus{--tw-text-opacity:1;color:rgb(24 24 27/var(--tw-text-opacity,1))}.focus\\:rf-outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\\:rf-ring-2:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus\\:rf-ring-ring:focus{--tw-ring-color:hsl(var(--ring))}.focus\\:rf-ring-offset-2:focus{--tw-ring-offset-width:2px}.focus-visible\\:rf-outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\\:rf-ring-1:focus-visible{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus-visible\\:rf-ring-2:focus-visible{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus-visible\\:rf-ring-zinc-950:focus-visible{--tw-ring-opacity:1;--tw-ring-color:rgb(9 9 11/var(--tw-ring-opacity,1))}.focus-visible\\:rf-ring-offset-2:focus-visible{--tw-ring-offset-width:2px}.disabled\\:rf-pointer-events-none:disabled{pointer-events:none}.disabled\\:rf-cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:rf-opacity-50:disabled{opacity:.5}.rf-group\\/bar:hover .group-hover\\/bar\\:rf-opacity-100{opacity:1}.data-\\[disabled\\]\\:rf-pointer-events-none[data-disabled]{pointer-events:none}.data-\\[side\\=bottom\\]\\:rf-translate-y-1[data-side=bottom]{--tw-translate-y:0.25rem}.data-\\[side\\=bottom\\]\\:rf-translate-y-1[data-side=bottom],.data-\\[side\\=left\\]\\:-rf-translate-x-1[data-side=left]{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[side\\=left\\]\\:-rf-translate-x-1[data-side=left]{--tw-translate-x:-0.25rem}.data-\\[side\\=right\\]\\:rf-translate-x-1[data-side=right]{--tw-translate-x:0.25rem}.data-\\[side\\=right\\]\\:rf-translate-x-1[data-side=right],.data-\\[side\\=top\\]\\:-rf-translate-y-1[data-side=top]{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[side\\=top\\]\\:-rf-translate-y-1[data-side=top]{--tw-translate-y:-0.25rem}.data-\\[state\\=active\\]\\:rf-bg-white[data-state=active]{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.data-\\[state\\=checked\\]\\:rf-bg-zinc-900[data-state=checked]{--tw-bg-opacity:1;background-color:rgb(24 24 27/var(--tw-bg-opacity,1))}.data-\\[state\\=open\\]\\:rf-bg-zinc-100[data-state=open]{--tw-bg-opacity:1;background-color:rgb(244 244 245/var(--tw-bg-opacity,1))}.data-\\[state\\=active\\]\\:rf-text-zinc-950[data-state=active]{--tw-text-opacity:1;color:rgb(9 9 11/var(--tw-text-opacity,1))}.data-\\[state\\=checked\\]\\:rf-text-zinc-50[data-state=checked]{--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.data-\\[disabled\\]\\:rf-opacity-50[data-disabled]{opacity:.5}.data-\\[state\\=active\\]\\:rf-shadow[data-state=active]{--tw-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px -1px rgba(0,0,0,.1);--tw-shadow-colored:0 1px 3px 0 var(--tw-shadow-color),0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.data-\\[state\\=open\\]\\:rf-animate-in[data-state=open]{animation-duration:.15s;animation-name:enter;--tw-enter-opacity:initial;--tw-enter-scale:initial;--tw-enter-rotate:initial;--tw-enter-translate-x:initial;--tw-enter-translate-y:initial}.data-\\[state\\=closed\\]\\:rf-animate-out[data-state=closed]{animation-duration:.15s;animation-name:exit;--tw-exit-opacity:initial;--tw-exit-scale:initial;--tw-exit-rotate:initial;--tw-exit-translate-x:initial;--tw-exit-translate-y:initial}.data-\\[state\\=closed\\]\\:rf-fade-out-0[data-state=closed]{--tw-exit-opacity:0}.data-\\[state\\=open\\]\\:rf-fade-in-0[data-state=open]{--tw-enter-opacity:0}.data-\\[state\\=closed\\]\\:rf-zoom-out-95[data-state=closed]{--tw-exit-scale:.95}.data-\\[state\\=open\\]\\:rf-zoom-in-95[data-state=open]{--tw-enter-scale:.95}.data-\\[side\\=bottom\\]\\:rf-slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y:-0.5rem}.data-\\[side\\=left\\]\\:rf-slide-in-from-right-2[data-side=left]{--tw-enter-translate-x:0.5rem}.data-\\[side\\=right\\]\\:rf-slide-in-from-left-2[data-side=right]{--tw-enter-translate-x:-0.5rem}.data-\\[side\\=top\\]\\:rf-slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y:0.5rem}.data-\\[state\\=closed\\]\\:rf-slide-out-to-left-1\\/2[data-state=closed]{--tw-exit-translate-x:-50%}.data-\\[state\\=closed\\]\\:rf-slide-out-to-top-\\[48\\%\\][data-state=closed]{--tw-exit-translate-y:-48%}.data-\\[state\\=open\\]\\:rf-slide-in-from-left-1\\/2[data-state=open]{--tw-enter-translate-x:-50%}.data-\\[state\\=open\\]\\:rf-slide-in-from-top-\\[48\\%\\][data-state=open]{--tw-enter-translate-y:-48%}.dark\\:rf-border-zinc-50:is(.rf-dark *){--tw-border-opacity:1;border-color:rgb(250 250 250/var(--tw-border-opacity,1))}.dark\\:rf-border-zinc-800:is(.rf-dark *){--tw-border-opacity:1;border-color:rgb(39 39 42/var(--tw-border-opacity,1))}.dark\\:rf-bg-red-900:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(127 29 29/var(--tw-bg-opacity,1))}.dark\\:rf-bg-zinc-50:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(250 250 250/var(--tw-bg-opacity,1))}.dark\\:rf-bg-zinc-800:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(39 39 42/var(--tw-bg-opacity,1))}.dark\\:rf-bg-zinc-950:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(9 9 11/var(--tw-bg-opacity,1))}.dark\\:rf-text-zinc-400:is(.rf-dark *){--tw-text-opacity:1;color:rgb(161 161 170/var(--tw-text-opacity,1))}.dark\\:rf-text-zinc-50:is(.rf-dark *){--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.dark\\:rf-text-zinc-900:is(.rf-dark *){--tw-text-opacity:1;color:rgb(24 24 27/var(--tw-text-opacity,1))}.dark\\:rf-placeholder-zinc-400:is(.rf-dark *)::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(161 161 170/var(--tw-placeholder-opacity,1))}.dark\\:rf-placeholder-zinc-400:is(.rf-dark *)::placeholder{--tw-placeholder-opacity:1;color:rgb(161 161 170/var(--tw-placeholder-opacity,1))}.dark\\:rf-ring-offset-zinc-950:is(.rf-dark *){--tw-ring-offset-color:#09090b}.dark\\:hover\\:rf-bg-red-900\\/90:hover:is(.rf-dark *){background-color:rgba(127,29,29,.9)}.dark\\:hover\\:rf-bg-zinc-50\\/90:hover:is(.rf-dark *){background-color:hsla(0,0%,98%,.9)}.dark\\:hover\\:rf-bg-zinc-800:hover:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(39 39 42/var(--tw-bg-opacity,1))}.dark\\:hover\\:rf-bg-zinc-800\\/80:hover:is(.rf-dark *){background-color:rgba(39,39,42,.8)}.dark\\:hover\\:rf-text-zinc-50:hover:is(.rf-dark *){--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.dark\\:focus\\:rf-bg-zinc-800:focus:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(39 39 42/var(--tw-bg-opacity,1))}.dark\\:focus\\:rf-text-zinc-50:focus:is(.rf-dark *){--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.dark\\:focus-visible\\:rf-ring-zinc-300:focus-visible:is(.rf-dark *){--tw-ring-opacity:1;--tw-ring-color:rgb(212 212 216/var(--tw-ring-opacity,1))}.dark\\:data-\\[state\\=active\\]\\:rf-bg-zinc-950[data-state=active]:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(9 9 11/var(--tw-bg-opacity,1))}.dark\\:data-\\[state\\=checked\\]\\:rf-bg-zinc-50[data-state=checked]:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(250 250 250/var(--tw-bg-opacity,1))}.dark\\:data-\\[state\\=open\\]\\:rf-bg-zinc-800[data-state=open]:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(39 39 42/var(--tw-bg-opacity,1))}.dark\\:data-\\[state\\=active\\]\\:rf-text-zinc-50[data-state=active]:is(.rf-dark *){--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.dark\\:data-\\[state\\=checked\\]\\:rf-text-zinc-900[data-state=checked]:is(.rf-dark *){--tw-text-opacity:1;color:rgb(24 24 27/var(--tw-text-opacity,1))}@media (min-width:640px){.sm\\:rf-mt-0{margin-top:0}.sm\\:rf-flex-row{flex-direction:row}.sm\\:rf-justify-end{justify-content:flex-end}.sm\\:rf-space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(.5rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(.5rem*var(--tw-space-x-reverse))}.sm\\:rf-rounded-lg{border-radius:var(--radius)}.sm\\:rf-text-left{text-align:left}}@media (min-width:768px){.md\\:rf-grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}.\\[\\&\\>span\\]\\:rf-line-clamp-1>span{display:-webkit-box;overflow:hidden;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\\[\\&\\>svg\\]\\:rf-size-4>svg{height:1rem;width:1rem}.\\[\\&\\>svg\\]\\:rf-shrink-0>svg{flex-shrink:0}.\\[\\&\\>svg\\]\\:rf-text-red-300>svg{--tw-text-opacity:1;color:rgb(252 165 165/var(--tw-text-opacity,1))}.\\[\\&\\>svg\\]\\:hover\\:rf-text-red-400:hover>svg{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity,1))}.\\[\\&_svg\\]\\:rf-pointer-events-none svg{pointer-events:none}.\\[\\&_svg\\]\\:rf-size-4 svg{height:1rem;width:1rem}.\\[\\&_svg\\]\\:rf-shrink-0 svg{flex-shrink:0}',IWt=()=>{nt.useEffect(()=>{if(document.querySelector('style[data-styles="tscircuit-runframe"]'))return;const e=document.createElement("style");e.setAttribute("data-styles","tscircuit-runframe"),e.textContent=vWt,document.head.appendChild(e)},[])},EGe=r=>`hsl(${Hx.indexOf(r)*137.5%360}, 70%, 50%)`,CWt=({phaseTimings:r})=>{if(!r)return null;const e=Object.values(r).reduce((t,n)=>t+n,0);return Ve.jsxs("div",{className:"rf-space-y-2 rf-w-full rf-px-4",children:[Ve.jsx("div",{className:"rf-relative rf-h-8 rf-flex rf-rounded-sm",children:Hx.map(t=>{const n=r[t]||0,i=n/e*100;return Ve.jsx("div",{className:"rf-group/bar rf-relative rf-overflow-visible",style:{width:`${i}%`,backgroundColor:EGe(t)},children:Ve.jsxs("div",{className:"rf-opacity-0 group-hover/bar:rf-opacity-100 rf-transition-opacity rf-absolute rf-bottom-full rf-left-1/2 rf-transform -rf-translate-x-1/2 rf-mb-2 rf-px-2 rf-py-1 rf-text-xs rf-whitespace-nowrap rf-rounded rf-bg-gray-900 rf-text-white rf-pointer-events-none",children:[t,": ",n.toFixed(1),"ms"]})},t)})}),Ve.jsxs("div",{className:"rf-text-xs rf-text-gray-500",children:["Total: ",e.toFixed(2),"ms"]})]})},EWt=({renderLog:r})=>{const[e,t]=nt.useState("chronological");if(!r)return Ve.jsx("div",{className:"rf-p-4 rf-bg-gray-100 rf-rounded-md",children:"No render log, make sure this tab is open when you render (TODO add a rerender button here)"});const n=Object.entries((r==null?void 0:r.phaseTimings)??{});e==="chronological"?n.sort((a,o)=>Hx.indexOf(a[0])-Hx.indexOf(o[0])):n.sort((a,o)=>o[1]-a[1]);const i=n.reduce((a,[o,s])=>a+s,0);return Ve.jsxs("div",{className:"rf-bg-white",children:[Ve.jsxs("div",{className:"rf-flex rf-justify-between rf-items-center",children:[Ve.jsx("div",{children:"Render Logs"}),Ve.jsxs("div",{className:"rf-mb-4 rf-pr-2 rf-flex rf-text-xs rf-items-center",children:[Ve.jsx("div",{className:"rf-mr-2",children:"Sort by:"}),Ve.jsxs("select",{value:e,onChange:a=>t(a.target.value),className:"rf-px-2 rf-py-1 rf-border rf-rounded rf-text-xs",children:[Ve.jsx("option",{value:"chronological",children:"Phase Order"}),Ve.jsx("option",{value:"longest",children:"Duration"})]})]})]}),Ve.jsx(CWt,{phaseTimings:r.phaseTimings}),Ve.jsxs("table",{className:"rf-w-full rf-text-xs",children:[Ve.jsx("thead",{children:Ve.jsxs("tr",{children:[Ve.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase Order"}),Ve.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase"}),Ve.jsx("th",{className:"rf-text-left rf-p-2",children:"Duration (ms)"})]})}),Ve.jsx("tbody",{children:n.map(([a,o])=>Ve.jsxs("tr",{children:[Ve.jsx("td",{className:"rf-p-2",children:Hx.indexOf(a)}),Ve.jsx("td",{className:"rf-p-2",children:a}),Ve.jsx("td",{className:"rf-p-2",children:Ve.jsx("div",{className:"rf-w-8",children:Ve.jsx("div",{className:"rf-h-2 rf-rounded-sm",style:{backgroundColor:EGe(a),width:`${o/i*100}%`}})})}),Ve.jsx("td",{className:"rf-p-2",children:Ve.jsxs("div",{className:"rf-flex w-full",children:[Ve.jsxs("span",{className:"rf-flex-grow",children:[o,"ms"]}),Ve.jsxs("span",{className:"rf-text-gray-500 rf-pr-2",children:[(o/i*100).toFixed(1),"%"]})]})})]},a))})]})]})},_Wt="0.0.552",xWt=["assembly","bom","circuit_json","errors","render_log"],BWt=({code:r,onRunClicked:e=void 0,errorMessage:t,errorStack:n,circuitJson:i,autoroutingGraphics:a,showRightHeaderContent:o=!0,showCodeTab:s=!1,codeTabContent:l,showJsonTab:c=!0,showRenderLogTab:u=!0,onActiveTabChange:A,renderLog:d,showImportAndFormatButtons:f=!0,className:g,headerClassName:_,leftHeaderContent:I,readOnly:E,isStreaming:x,autoroutingLog:B,onReportAutoroutingLog:P,isRunningCode:L,hasCodeChangedSinceLastRun:U,onEditEvent:H,editEvents:G,defaultActiveTab:W,autoRotate3dViewerDisabled:z,showSchematicDebugGrid:ae=!1,showToggleFullScreen:te=!0,defaultToFullScreen:oe=!1})=>{var we;IWt();const pe=nt.useMemo(()=>i?i.filter(Ge=>Ge&&"error_type"in Ge||Ge.type.includes("error")):null,[i]),[Ae,he]=nt.useState(W??"pcb"),[Ie,ge]=nt.useState(oe),Me=nt.useCallback(Ge=>{he(Ge),A==null||A(Ge)},[A]),Se=()=>{ge(!Ie)};nt.useEffect(()=>{t&&Me("errors")},[t]),nt.useEffect(()=>{(Ae==="code"||Ae==="errors")&&i&&!t&&Me(W??"pcb")},[i]);const Re=nt.useCallback(Ge=>{window.TSCIRCUIT_3D_OBJECT_REF=Ge===null?void 0:Ge},[]);return Ve.jsx("div",{className:Mp("flex flex-col relative rf-overflow-x-hidden",g),children:Ve.jsx("div",{className:Mp("rf-md:sticky rf-md:top-2",Ie&&"rf-fixed rf-top-0 rf-left-0 rf-w-full rf-bg-white"),children:Ve.jsxs(qve,{value:Ae,onValueChange:Me,className:"rf-flex-grow rf-flex rf-flex-col",children:[Ve.jsxs("div",{className:Mp("rf-flex rf-items-center rf-gap-2 rf-p-2 rf-pb-0",_),children:[I,I&&Ve.jsx("div",{className:"rf-flex-grow"}),!I&&L&&Ve.jsx(G3,{className:"rf-w-4 rf-h-4 rf-animate-spin"}),!I&&Ve.jsx("div",{className:"rf-flex-grow"}),d&&d.progress!==1&&!t&&Ve.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[d.lastRenderEvent&&Ve.jsx("div",{className:"rf-text-xs rf-text-gray-500",children:((we=d.lastRenderEvent)==null?void 0:we.phase)??""}),Ve.jsx("div",{className:"rf-w-4 rf-h-4 rf-bg-blue-500 rf-opacity-50 rf-rounded-full rf-text-white",children:Ve.jsx(G3,{className:"rf-w-4 rf-h-4 rf-animate-spin"})}),Ve.jsxs("div",{className:"rf-text-xs rf-font-bold rf-text-gray-700 rf-tabular-nums",children:[((d.progress??0)*100).toFixed(1),"%"]})]}),o&&Ve.jsxs(RK,{children:[s&&Ve.jsx($2,{value:"code",children:"Code"}),Ve.jsxs($2,{value:"pcb",className:"rf-whitespace-nowrap",children:[i&&Ve.jsx("span",{className:Mp("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",U?"rf-bg-gray-500":"rf-bg-blue-500")}),"PCB"]}),Ve.jsxs($2,{value:"schematic",className:"rf-whitespace-nowrap",children:[i&&Ve.jsx("span",{className:Mp("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",U?"rf-bg-gray-500":"rf-bg-blue-500")}),"Schematic"]}),Ve.jsxs($2,{value:"cad",children:[i&&Ve.jsx("span",{className:Mp("inline-flex items-center justify-center w-2 h-2 mr-1 text-xs font-bold text-white rounded-full",U?"rf-bg-gray-500":"rf-bg-blue-500")}),"3D"]}),!["pcb","cad","schematic"].includes(Ae)&&Ve.jsx($2,{value:Ae,children:Wve(Ae)}),Ve.jsxs(boe,{children:[Ve.jsx(Soe,{asChild:!0,children:Ve.jsxs("div",{className:"rf-whitespace-nowrap rf-p-2 rf-mr-1 rf-cursor-pointer rf-relative",children:[Ve.jsx(r6t,{className:"rf-w-4 rf-h-4"}),(pe&&pe.length>0||t)&&Ve.jsx("span",{className:"rf-inline-flex rf-absolute rf-top-[6px] rf-right-[4px] rf-items-center rf-justify-center rf-w-1 rf-h-1 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full"})]})}),Ve.jsxs(J6,{className:"rf-*:text-xs",children:[xWt.map(Ge=>Ve.jsxs(yb,{onSelect:()=>Me(Ge),children:[Ae!==Ge&&Ve.jsx(lPe,{className:"rf-w-3 rf-h-3 rf-opacity-30"}),Ae===Ge&&Ve.jsx(Tae,{className:"rf-w-3 rf-h-3"}),Ve.jsx("div",{className:"rf-pr-2",children:Wve(Ge)}),Ge==="errors"&&(pe&&pe.length>0||t)&&Ve.jsx("span",{className:"rf-inline-flex rf-items-center rf-justify-center rf-w-3 rf-h-3 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full",children:t?1:pe==null?void 0:pe.length})]},Ge)),Ve.jsx(yb,{disabled:!0,className:"rf-opacity-60 rf-cursor-default rf-select-none",children:Ve.jsxs("div",{className:"rf-pr-2 rf-text-xs rf-text-gray-500",children:["@tscircuit/runframe@",_Wt.split(".").map((Ge,$e)=>$e===2?parseInt(Ge)+1:Ge).join(".")]})})]})]})]}),te&&Ve.jsx(w_,{onClick:Se,variant:"ghost",children:Ie?Ve.jsx(s6t,{size:16}):Ve.jsx(a6t,{size:16})})]}),s&&Ve.jsx(jb,{value:"code",className:"rf-flex-grow rf-overflow-hidden",children:Ve.jsx("div",{className:"rf-h-full",children:l})}),Ve.jsx(jb,{value:"pcb",children:Ve.jsx("div",{className:Mp("rf-overflow-hidden",Ie?"rf-h-[calc(100vh-52px)]":"rf-h-[620px]"),children:Ve.jsx(L3,{fallbackRender:({error:Ge})=>Ve.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:Ve.jsxs("div",{className:"rf-p-4",children:[Ve.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading PCB viewer"}),Ve.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ge==null?void 0:Ge.message)||"An unknown error occurred"})]})}),children:i?Ve.jsx(yWt,{focusOnHover:!1,circuitJson:i,debugGraphics:a,containerClassName:Mp("rf-h-full rf-w-full",Ie?"rf-min-h-[calc(100vh-240px)]":"rf-min-h-[620px]"),onEditEventsChanged:Ge=>{H&&Ge.forEach($e=>H($e))}}):Ve.jsx(v9,{onRunClicked:e})})})}),Ve.jsx(jb,{value:"assembly",children:Ve.jsx("div",{className:Mp("rf-overflow-auto",Ie?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:Ve.jsx(L3,{fallback:Ve.jsx("div",{children:"Error loading Assembly"}),children:i?Ve.jsx(NHt,{circuitJson:i,containerStyle:{height:"100%"},editingEnabled:!0,debugGrid:!0}):Ve.jsx(v9,{onRunClicked:e})})})}),Ve.jsx(jb,{value:"schematic",children:Ve.jsx("div",{className:Mp("rf-overflow-auto rf-bg-white",Ie?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:Ve.jsx(L3,{fallbackRender:({error:Ge})=>Ve.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:Ve.jsxs("div",{className:"rf-p-4",children:[Ve.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Schematic"}),Ve.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ge==null?void 0:Ge.message)||"An unknown error occurred"})]})}),children:i?Ve.jsx(MHt,{circuitJson:i,containerStyle:{height:"100%"},editingEnabled:!0,onEditEvent:Ge=>{H==null||H(Ge)},debugGrid:ae}):Ve.jsx(v9,{onRunClicked:e})})})}),Ve.jsx(jb,{value:"cad",children:Ve.jsx("div",{className:Mp("rf-overflow-auto",Ie?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:Ve.jsx(L3,{FallbackComponent:YLt,children:i?Ve.jsx(zLt,{ref:Re,circuitJson:i,autoRotateDisabled:z}):Ve.jsx(v9,{onRunClicked:e})})})}),Ve.jsx(jb,{value:"bom",children:Ve.jsx("div",{className:Mp("rf-overflow-auto",Ie?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:Ve.jsx(L3,{fallbackRender:({error:Ge})=>Ve.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:Ve.jsxs("div",{className:"rf-p-4",children:[Ve.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Bill of Materials"}),Ve.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ge==null?void 0:Ge.message)||"An unknown error occurred"})]})}),children:i?Ve.jsx(FHt,{circuitJson:i}):Ve.jsx(v9,{onRunClicked:e})})})}),Ve.jsx(jb,{value:"circuit_json",children:Ve.jsx("div",{className:Mp("rf-overflow-auto",Ie?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:Ve.jsx(L3,{fallback:Ve.jsx("div",{children:"Error loading JSON viewer"}),children:i?Ve.jsx(kHt,{elements:i}):Ve.jsx(v9,{onRunClicked:e})})})}),Ve.jsx(jb,{value:"errors",children:Ve.jsx("div",{className:Mp("rf-overflow-auto",Ie?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:t||pe&&pe.length>0?Ve.jsx(tzt,{code:r,circuitJsonErrors:pe,errorMessage:t,errorStack:n,autoroutingLog:B,onReportAutoroutingLog:P}):Ve.jsx(v9,{onRunClicked:e})})}),u&&Ve.jsx(jb,{value:"render_log",children:Ve.jsx(EWt,{renderLog:d})})]})})})};var YG="Dialog",[_Ge,xGe]=HS(YG),[bWt,Eb]=_Ge(YG),BGe=r=>{const{__scopeDialog:e,children:t,open:n,defaultOpen:i,onOpenChange:a,modal:o=!0}=r,s=nt.useRef(null),l=nt.useRef(null),[c,u]=IM({prop:n,defaultProp:i??!1,onChange:a,caller:YG});return Ve.jsx(bWt,{scope:e,triggerRef:s,contentRef:l,contentId:YS(),titleId:YS(),descriptionId:YS(),open:c,onOpenChange:u,onOpenToggle:nt.useCallback(()=>u(A=>!A),[u]),modal:o,children:t})};BGe.displayName=YG;var bGe="DialogTrigger",SGe=nt.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Eb(bGe,t),a=s1(e,i.triggerRef);return Ve.jsx(Bv.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":vle(i.open),...n,ref:a,onClick:Oh(r.onClick,i.onOpenToggle)})});SGe.displayName=bGe;var mle="DialogPortal",[SWt,wGe]=_Ge(mle,{forceMount:void 0}),QGe=r=>{const{__scopeDialog:e,forceMount:t,children:n,container:i}=r,a=Eb(mle,e);return Ve.jsx(SWt,{scope:e,forceMount:t,children:nt.Children.map(n,o=>Ve.jsx(Vb,{present:t||a.open,children:Ve.jsx(uoe,{asChild:!0,container:i,children:o})}))})};QGe.displayName=mle;var VG="DialogOverlay",MGe=nt.forwardRef((r,e)=>{const t=wGe(VG,r.__scopeDialog),{forceMount:n=t.forceMount,...i}=r,a=Eb(VG,r.__scopeDialog);return a.modal?Ve.jsx(Vb,{present:n||a.open,children:Ve.jsx(QWt,{...i,ref:e})}):null});MGe.displayName=VG;var wWt=vM("DialogOverlay.RemoveScroll"),QWt=nt.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Eb(VG,t);return Ve.jsx(goe,{as:wWt,allowPinchZoom:!0,shards:[i.contentRef],children:Ve.jsx(Bv.div,{"data-state":vle(i.open),...n,ref:e,style:{pointerEvents:"auto",...n.style}})})}),w9="DialogContent",DGe=nt.forwardRef((r,e)=>{const t=wGe(w9,r.__scopeDialog),{forceMount:n=t.forceMount,...i}=r,a=Eb(w9,r.__scopeDialog);return Ve.jsx(Vb,{present:n||a.open,children:a.modal?Ve.jsx(MWt,{...i,ref:e}):Ve.jsx(DWt,{...i,ref:e})})});DGe.displayName=w9;var MWt=nt.forwardRef((r,e)=>{const t=Eb(w9,r.__scopeDialog),n=nt.useRef(null),i=s1(e,t.contentRef,n);return nt.useEffect(()=>{const a=n.current;if(a)return fke(a)},[]),Ve.jsx(RGe,{...r,ref:i,trapFocus:t.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Oh(r.onCloseAutoFocus,a=>{var o;a.preventDefault(),(o=t.triggerRef.current)==null||o.focus()}),onPointerDownOutside:Oh(r.onPointerDownOutside,a=>{const o=a.detail.originalEvent,s=o.button===0&&o.ctrlKey===!0;(o.button===2||s)&&a.preventDefault()}),onFocusOutside:Oh(r.onFocusOutside,a=>a.preventDefault())})}),DWt=nt.forwardRef((r,e)=>{const t=Eb(w9,r.__scopeDialog),n=nt.useRef(!1),i=nt.useRef(!1);return Ve.jsx(RGe,{...r,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{var o,s;(o=r.onCloseAutoFocus)==null||o.call(r,a),a.defaultPrevented||(n.current||(s=t.triggerRef.current)==null||s.focus(),a.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:a=>{var l,c;(l=r.onInteractOutside)==null||l.call(r,a),a.defaultPrevented||(n.current=!0,a.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const o=a.target;((c=t.triggerRef.current)==null?void 0:c.contains(o))&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&i.current&&a.preventDefault()}})}),RGe=nt.forwardRef((r,e)=>{const{__scopeDialog:t,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:a,...o}=r,s=Eb(w9,t),l=nt.useRef(null),c=s1(e,l);return wPe(),Ve.jsxs(Ve.Fragment,{children:[Ve.jsx(Wae,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:a,children:Ve.jsx(Vae,{role:"dialog",id:s.contentId,"aria-describedby":s.descriptionId,"aria-labelledby":s.titleId,"data-state":vle(s.open),...o,ref:c,onDismiss:()=>s.onOpenChange(!1)})}),Ve.jsxs(Ve.Fragment,{children:[Ve.jsx(NWt,{titleId:s.titleId}),Ve.jsx(PWt,{contentRef:l,descriptionId:s.descriptionId})]})]})}),yle="DialogTitle",NGe=nt.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Eb(yle,t);return Ve.jsx(Bv.h2,{id:i.titleId,...n,ref:e})});NGe.displayName=yle;var TGe="DialogDescription",PGe=nt.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Eb(TGe,t);return Ve.jsx(Bv.p,{id:i.descriptionId,...n,ref:e})});PGe.displayName=TGe;var kGe="DialogClose",UGe=nt.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Eb(kGe,t);return Ve.jsx(Bv.button,{type:"button",...n,ref:e,onClick:Oh(r.onClick,()=>i.onOpenChange(!1))})});UGe.displayName=kGe;function vle(r){return r?"open":"closed"}var FGe="DialogTitleWarning",[RWt,LGe]=Rht(FGe,{contentName:w9,titleName:yle,docsSlug:"dialog"}),NWt=({titleId:r})=>{const e=LGe(FGe),t=`\`${e.contentName}\` requires a \`${e.titleName}\` for the component to be accessible for screen reader users.
13494
13494
 
13495
13495
  If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.
13496
13496