@tscircuit/runframe 0.0.529 → 0.0.530

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.
@@ -13465,4 +13465,4 @@ $1`).replace(/>(\s*)(?=<!--\s*\/)/g,"> ")}return tae}a7t();function MUe(r,e,t,n=
13465
13465
  `)}},Yke=(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,o=new qHt({showAxisLabels:e.showAxisLabels,gridScaleX:t,gridScaleY:n}),a=[];for(const s of r.chips){if(s.isPassive){a.push(s);continue}const l=s.getWidth(),c=s.getHeight(),u=Math.round(c*e.gridScaleY);if(e.chipLabels&&s.topPinCount===0){const h=s.y+s.getHeight(),m=s.chipId;for(let C=s.x,E=0;E<m.length;E++,C+=i)o.putOverlay(C,h,m[E])}const A=Math.round(s.x*e.gridScaleX),d=Math.round(s.y*e.gridScaleY);for(let h=0;h<u;++h){let m=" ",C=" ",E=" ";const _=h===0,x=h===u-1,Q=l*e.gridScaleX;if(_)m="└",C="─".repeat(Q),E="┘";else if(x)m="┌",C="─".repeat(Q),E="┐";else{const O=d+h;let z,Y;for(const J of s.leftPins){const se=s.getPinLocation(J.pinNumber);if(Math.round(se.y*e.gridScaleY)===O){z=J;break}}for(const J of s.rightPins){const se=s.getPinLocation(J.pinNumber);if(Math.round(se.y*e.gridScaleY)===O){Y=J;break}}m=z?"┤":"│",E=Y?"├":"│";const V=z?String(z.pinNumber):null,Z=Y?String(Y.pinNumber):null;if(V&&Z){const J=Q-V.length-Z.length;C=V+" ".repeat(Math.max(1,J))+Z}else V?C=V+" ".repeat(Math.max(0,Q-V.length)):Z?C=" ".repeat(Math.max(0,Q-Z.length))+Z:C=" ".repeat(Math.max(0,Q))}const P=m+(C.length===l-2?C:C.padEnd(l-2," "))+E;for(let O=0;O<P.length;++O){const z=(A+O)/e.gridScaleX,Y=(d+h)/e.gridScaleY;o.putOverlay(z,Y,P[O])}}}for(const s of r.netLabels)if(s.netId.length>0){const l=s.netId[0];o.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;o.addEdge(l,c,c<u?"up":"down"),o.addEdge(l,u,c<u?"down":"up");const h=Math.round(A*e.gridScaleY),m=Math.round(d*e.gridScaleY);for(let C=h+1;C<m;C++){const E=C/e.gridScaleY;o.addEdge(l,E,"up"),o.addEdge(l,E,"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;o.addEdge(c,l,c<u?"right":"left"),o.addEdge(u,l,c<u?"left":"right");const h=Math.round(A*e.gridScaleX),m=Math.round(d*e.gridScaleX);for(let C=h+1;C<m;C++){const E=C/e.gridScaleX;o.addEdge(E,l,"left"),o.addEdge(E,l,"right")}}for(const s of r.connectionPoints)s.showAsIntersection&&o.putOverlay(s.x,s.y,"●");for(const s of a)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]&&o.putOverlay(c+A,s.y,s.chipId[d]):A===0?o.putOverlay(c+A,s.y,"["):A>=s.getWidth()-1/e.gridScaleX?o.putOverlay(c+A,s.y,"]"):s.chipId[d-1]&&o.putOverlay(c+A,s.y,s.chipId[d-1])}else o.putOverlay(s.x,s.y-s.getHeight()/2,"┬"),o.putOverlay(s.x,s.y,s.chipId[0]),s.chipId[1]&&o.putOverlay(s.x+1/e.gridScaleX,s.y,s.chipId[1]),o.putOverlay(s.x,s.y+s.getHeight()/2,"┴");return o},jae=(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,iS=r=>"boxId"in r?`box[${r.boxId}].${r.pinNumber}`:"junctionId"in r?`junction[${r.junctionId}]`:`netlabel[${r.netId},${r.netLabelId}]`,Jae=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}`)},XHt=r=>{const e=[],t=[],n=[],i=[];for(const o of r.chips){o.pinPositionsAreSet||o.setPinPositions();const a=[],s=[...o.leftPins,...o.bottomPins,...o.rightPins,...o.topPins];for(const c of s){const u=o.getPinLocation(c.pinNumber);a.push({pinNumber:c.pinNumber,x:u.x,y:u.y})}const l=o.getCenter();e.push({boxId:o.chipId,leftPinCount:o.leftPinCount,rightPinCount:o.rightPinCount,topPinCount:o.topPinCount,bottomPinCount:o.bottomPinCount,centerX:l.x,centerY:l.y,pins:a})}for(const o of r.netLabels)t.push({netLabelId:o.netLabelId,netId:o.netId,x:o.x,y:o.y,anchorPosition:o.anchorSide});for(const o of r.paths){const a=r.lines.filter(A=>A.pathId===o.pathId),s=new Set(a.flatMap(A=>[iS(A.start.fromJunctionId?{junctionId:A.start.fromJunctionId}:A.start.ref),iS(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;iS(a[0].start.ref)===u&&([c,u]=[u,c]),n.push({points:a.flatMap(A=>[{x:A.start.x,y:A.start.y},{x:A.end.x,y:A.end.y}]),from:Jae(c),to:Jae(u)})}for(const o of r.connectionPoints)i.push({junctionId:o.junctionId,x:o.x,y:o.y});return{boxes:e,netLabels:t,paths:n,junctions:i}},Vke="ABCDEFGHIJKLMNOPQRSTUVWXYZ",$Ht=class u7e{constructor(e={}){Le(this,"chips",[]);Le(this,"netLabels",[]);Le(this,"lines",[]);Le(this,"paths",[]);Le(this,"connectionPoints",[]);Le(this,"defaultChipWidth",2);Le(this,"defaultSingleSidedChipWidth",2);Le(this,"defaultPinSpacing",.2);Le(this,"defaultPassiveWidth",1);Le(this,"defaultPassiveHeight",.2);Le(this,"autoLabelCounter",1);Le(this,"name");Le(this,"_pathCounter",1);Le(this,"_netLabelCounter",1);Le(this,"_junctionCounter",1);this.name=e.name??"Circuit"}clone(){const e=new u7e({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 Kae(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=(o,a,s)=>Array.from({length:o},(l,c)=>{const u=new Vae(n,a+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 Kae(this,e);return this.chips.push(t),t}passive(e){const t=e??`R${this.chips.length+1}`,n=new Kae(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 a of this.connectionPoints)if(a.x===e&&a.y===t)return a;const o={junctionId:`XX${this._junctionCounter++}`,x:e,y:t,pinRef:n,showAsIntersection:i};return this.connectionPoints.push(o),o}toString(){return Yke(this,{chipLabels:!0,showAxisLabels:!0,gridScaleX:2,gridScaleY:5}).toString()}getNetlist(){const e=new GHt;for(const a of this.chips)e.addBox({boxId:a.chipId,leftPinCount:a.leftPinCount||0,rightPinCount:a.rightPinCount||0,topPinCount:a.topPinCount||0,bottomPinCount:a.bottomPinCount||0});for(const a of this.netLabels)e.addNet({netId:a.netId}),e.connect(a.fromRef,{netId:a.netId,netLabelId:a.netLabelId});for(const a of this.lines)jae(a.start.ref,a.end.ref)||e.connect(a.start.ref,a.end.ref);const t=(a,s,l)=>{const c=a.get(s)??[];c.push(l),a.set(s,c)},n=new Map;for(const a of this.connectionPoints)t(n,`${a.x},${a.y}`,a.pinRef);const i=new Set;for(const a of this.connectionPoints)i.add(`${a.x},${a.y}`);for(const a of this.lines)t(n,`${a.start.x},${a.start.y}`,a.start.ref),t(n,`${a.end.x},${a.end.y}`,a.end.ref);for(const[a,s]of n.entries())if(i.has(a))for(let l=0;l<s.length;++l)for(let c=l+1;c<s.length;++c)e.connect(s[l],s[c]);const o=(a,s,l)=>{if(l.start.x===l.end.x){if(a!==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 a>=c&&a<=u}return!1};for(const a of this.connectionPoints)for(const s of this.lines)o(a.x,a.y,s)&&e.connect(a.pinRef,s.start.ref);return e.getNetlist()}getReadableNetlist(){return $N(this.getNetlist())}flipX(){return WHt(this)}generateAutoLabel(){return Vke[this.autoLabelCounter++-1]??`L${this.autoLabelCounter-Vke.length}`}getGrid(){return Yke(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 XHt(this)}};function n2(r={}){return new $Ht({name:r.name})}function eYt(r){const e=r.candidateNetlist.boxes[r.candidateBoxIndex],t=r.targetNetlist.boxes[r.targetBoxIndex],n=[];for(const i of Yae){const o=e[`${i}PinCount`]??0,a=t[`${i}PinCount`]??0;o!==a&&n.push({type:"matched_box_side_has_wrong_pin_count",candidateBoxIndex:r.candidateBoxIndex,targetBoxIndex:r.targetBoxIndex})}return n}var $G=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(o=>"boxIndex"in o?{boxId:`box${o.boxIndex}`,pinNumber:o.pinNumber}:{netId:`net${o.netIndex}`})}));return{boxes:e,nets:t,connections:n}};function Wae(r){const{netlist:e,chipId:t,pinNumber:n}=r,i=`${t}.pin${n}`,o=[{boxId:i,leftPinCount:0,rightPinCount:1,topPinCount:0,bottomPinCount:0}],a=[],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 h of u.connectedPorts)if("boxId"in h){if(h.boxId===t&&h.pinNumber===n)continue;if(d.push({boxId:h.boxId,pinNumber:h.pinNumber}),!l.has(h.boxId)){const m=e.boxes.find(C=>C.boxId===h.boxId);m&&o.push(m),l.add(h.boxId)}}else"netId"in h&&(d.push({netId:h.netId}),c.has(h.netId)||(a.push({netId:h.netId}),c.add(h.netId)));d.length>1&&s.push({connectedPorts:d})}return{boxes:o,nets:a,connections:s}}var Zae=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(""),qae=r=>{const{netlist:e,chipId:t,pinNumber:n}=r,i=new Set;for(const o of e.connections)if(o.connectedPorts.some(s=>"boxId"in s&&s.boxId===t&&s.pinNumber===n))for(const s of o.connectedPorts)"boxId"in s&&s.boxId!==t&&i.add(s.boxId);return`box_count_${i.size}`},Xae=r=>{let e;if("pinShapeNetlist"in r)e=r.pinShapeNetlist;else{const{netlist:n,chipId:i,pinNumber:o}=r;e=Wae({chipId:i,pinNumber:o,netlist:n})}return`${cQ(e).normalizedNetlist.boxes.map(n=>Zae(n)).join(",")}`};function tYt(r){const e=$G(r.candidateNetlist),t=$G(r.targetNetlist),n=[],i=e.boxes[r.candidateBoxIndex],o=t.boxes[r.targetBoxIndex],a=i.leftPinCount+i.rightPinCount+i.topPinCount+i.bottomPinCount,s=a===2&&Math.max(i.leftPinCount,i.rightPinCount,i.topPinCount,i.bottomPinCount)===1;for(let d=0;d<a;d++){const h=d+1,m=Wae({netlist:e,chipId:i.boxId,pinNumber:h});n.push({side:rS(h,i).side,signature:Xae({pinShapeNetlist:m})})}const l=[...n],c=[],u=o.leftPinCount+o.rightPinCount+o.topPinCount+o.bottomPinCount,A=u===2&&Math.max(o.leftPinCount,o.rightPinCount,o.topPinCount,o.bottomPinCount)===1;for(let d=0;d<u;d++){const h=d+1,m=Wae({netlist:t,chipId:o.boxId,pinNumber:h});if(m.connections.length===0)continue;const C={signature:Xae({pinShapeNetlist:m}),side:rS(h,o).side},E=A&&s,_=l.findIndex(x=>x.signature===C.signature&&(x.side===C.side||E));if(_!==-1){l.splice(_,1);continue}c.push({type:"matched_box_missing_pin_shape_on_side",candidateBoxIndex:r.candidateBoxIndex,targetBoxIndex:r.targetBoxIndex,targetPinNumber:h,targetPinShapeSignature:C.signature,candidateShapeSignatures:l.map(x=>x.signature),side:C.side})}return c}function nYt(r){const{candidateNetlist:e,targetNetlist:t,candidateBoxIndex:n,targetBoxIndex:i}=r,o=[],a=$G(e),s=$G(t),l=a.boxes[n],c=s.boxes[i];if(!l||!c)return o;const u=[],A=l.leftPinCount+l.rightPinCount+l.topPinCount+l.bottomPinCount;for(let C=0;C<A;C++){const E=C+1,_=qae({netlist:a,chipId:l.boxId,pinNumber:E});u.push({side:rS(E,l).side,signature:_})}const d=[...u],h=c.leftPinCount+c.rightPinCount+c.topPinCount+c.bottomPinCount;if(A===2&&h===2&&Math.max(l.leftPinCount,l.rightPinCount,l.topPinCount,l.bottomPinCount)===1&&Math.max(c.leftPinCount,c.rightPinCount,c.topPinCount,c.bottomPinCount)===1){const C=u.map(_=>_.signature).filter(_=>_!=="box_count_0").sort(),E=[];for(let _=0;_<h;_++){const x=_+1,Q=qae({netlist:s,chipId:c.boxId,pinNumber:x});Q!=="box_count_0"&&E.push(Q)}E.sort(),C.length>0&&E.length>0&&C.join(",")!==E.join(",")&&o.push({type:"matched_box_missing_pin_shape_box_count_on_side",candidateBoxIndex:n,targetBoxIndex:i,side:"left",targetPinNumber:-1,targetBoxCountSignature:E.join(","),candidateBoxCountSignatures:C})}else for(let C=0;C<h;C++){const E=C+1,_=qae({netlist:s,chipId:c.boxId,pinNumber:E});if(_==="box_count_0")continue;const x={signature:_,side:rS(E,c).side},Q=d.findIndex(P=>P.signature===x.signature&&P.side===x.side);if(Q===-1){const P=u.filter(O=>O.side===x.side).map(O=>O.signature);o.push({type:"matched_box_missing_pin_shape_box_count_on_side",candidateBoxIndex:n,targetBoxIndex:i,side:x.side,targetPinNumber:E,targetBoxCountSignature:_,candidateBoxCountSignatures:P})}else d.splice(Q,1)}return o}var rYt=[eYt,tYt,nYt];function iYt(r){const e=[];for(const t of rYt)e.push(...t(r));return e}function Kke(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 oYt(r){return{...r,leftPinCount:r.topPinCount,rightPinCount:r.bottomPinCount,topPinCount:r.leftPinCount,bottomPinCount:r.rightPinCount}}function aYt(r){return{...r,leftPinCount:r.rightPinCount,rightPinCount:r.leftPinCount,topPinCount:r.bottomPinCount,bottomPinCount:r.topPinCount}}function sYt(r){const{targetNetlist:e,candidateNetlist:t,targetBoxIndex:n,candidateBoxIndex:i}=r,o=e.boxes[n],a=t.boxes[i];if(!o||!a)return[{netlist:e,rotation:0}];if(!Kke(o)||!Kke(a))return[{netlist:e,rotation:0}];const s=[];let l={...o},c=0;for(let m=0;m<4&&!(l.leftPinCount===a.leftPinCount&&l.rightPinCount===a.rightPinCount&&l.topPinCount===a.topPinCount&&l.bottomPinCount===a.bottomPinCount);m++)l=oYt(l),c=(c+90)%360;const u={...e,boxes:e.boxes.map((m,C)=>C===n?l:m)};s.push({netlist:u,rotation:c});const A=aYt(l),d={...e,boxes:e.boxes.map((m,C)=>C===n?A:m)},h=(c+180)%360;return s.push({netlist:d,rotation:h}),s}function e6(r){const{candidateNetlist:e,targetNetlist:t}=r,n=[],i=new Set;for(let o=0;o<t.boxes.length;o++){const a=new Map;for(let c=0;c<e.boxes.length;c++){if(i.has(c))continue;const u=sYt({targetNetlist:t,candidateNetlist:e,targetBoxIndex:o,candidateBoxIndex:c});let A=[],d=1/0,h=0;for(const{netlist:m,rotation:C}of u){const E=iYt({candidateNetlist:e,targetNetlist:m,candidateBoxIndex:c,targetBoxIndex:o,alreadyMatchedBoxes:n}),_=Hae(E);_<d&&(d=_,A=E,h=C)}a.set({targetBoxIndex:o,candidateBoxIndex:c},{issues:A,similarityDistance:d,rotation:h})}let s=null,l=1/0;for(const[c,{similarityDistance:u}]of a.entries())u<l&&(l=u,s=c);if(s){const{candidateBoxIndex:c}=s,{issues:u,similarityDistance:A,rotation:d}=a.get(s);i.add(c),n.push({targetBoxIndex:o,candidateBoxIndex:c,issues:u,score:A,targetBoxRotationCcw:d})}}return n}function $ae(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 lYt(r,e){const{chipId:t,pinNumber:n,netName:i}=e,o=r.chips.find(A=>A.chipId===t);if(!o||n<1||n>o.totalPinCount)return;const a=o.pin(n);if(!a||typeof a.line!="function")return;const{side:s}=rS(n,o),{dx:l,dy:c}=$ae(s);a.line(l*2,c*2);const u=i||r.generateAutoLabel();a.label(u)}function cYt(r,e){const{chipId:t,pinNumber:n}=e,i=o=>"boxId"in o&&o.boxId===t&&o.pinNumber===n;r.lines=r.lines.filter(o=>!i(o.start.ref)&&!i(o.end.ref)),r.connectionPoints=r.connectionPoints.filter(o=>!i(o.pinRef)),r.netLabels=r.netLabels.filter(o=>!i(o.fromRef))}function uYt(r,e){const{chipId:t,pinNumber:n}=e,i=r.chips.find(a=>a.chipId===t);if(!i)return;const o=i.pin(n);if(o.lastDx===0&&o.lastDy===0&&!o.lastCreatedLine){const a=$ae(o.side);o.line(a.dx*2,a.dy*2)}o.passive()}function AYt(r,e){const{chipId:t,pinNumber:n,labelNetId:i}=e,o=r.chips.find(l=>l.chipId===t);if(!o)return;const a=o.pin(n);if(a.lastDx===0&&a.lastDy===0&&!a.lastCreatedLine){const l=$ae(a.side);a.line(l.dx*2,l.dy*2)}a.passive().label(i)}function dYt(r,e){const{chipId:t}=e;r.chips=r.chips.filter(o=>o.chipId!==t);const n=o=>"boxId"in o&&o.boxId===t,i=r.lines.filter(o=>n(o.start.ref)||n(o.end.ref));r.lines=r.lines.filter(o=>!(n(o.start.ref)&&n(o.end.ref)));for(const o of i){if(n(o.start.ref)&&n(o.end.ref))continue;const a=n(o.start.ref)?o.start:o.end,s=n(o.start.ref)?o.end:o.start;jke(r,s.x,s.y,o)?r.lines=r.lines.filter(c=>c!==o):(r.lines=r.lines.filter(c=>c!==o),Jke(r,s.x,s.y,s.ref,a.ref))}r.connectionPoints=r.connectionPoints.filter(o=>!n(o.pinRef)),r.netLabels=r.netLabels.filter(o=>!n(o.fromRef))}function jke(r,e,t,n){let i=0;for(const o of r.lines)o!==n&&(o.start.x===e&&o.start.y===t||o.end.x===e&&o.end.y===t)&&i++;for(const o of r.connectionPoints)if(o.x===e&&o.y===t){i++;break}return i>=2}function Jke(r,e,t,n,i){const o=r.lines.filter(a=>{const s=a.start.x===e&&a.start.y===t&&!jae(a.start.ref,i),l=a.end.x===e&&a.end.y===t&&!jae(a.end.ref,i);return s||l});for(const a of o){const s=a.start.x===e&&a.start.y===t?a.end:a.start;if(jke(r,s.x,s.y,a))return;r.lines=r.lines.filter(c=>c!==a),Jke(r,s.x,s.y,s.ref,i)}}var fYt=(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 hYt(r,e){const{chipId:t,side:n,pinNumber:i}=e,o=r.chips.find(Q=>Q.chipId===t);if(!o)return;const a=o.totalPinCount;if(i<1||i>a)throw new Error(`Invalid pin number: ${i} for chip ${o.chipId} with dimensions ${o.leftPinCount}x${o.bottomPinCount}x${o.rightPinCount}x${o.topPinCount}`);o.pinPositionsAreSet||o.setPinPositions();const s=new Map;for(let Q=1;Q<=a;++Q)s.set(Q,o.getPinLocation(Q));const l=Q=>"boxId"in Q&&Q.boxId===t&&Q.pinNumber===i;r.lines=r.lines.filter(Q=>!l(Q.start.ref)&&!l(Q.end.ref)),r.connectionPoints=r.connectionPoints.filter(Q=>!l(Q.pinRef)),r.netLabels=r.netLabels.filter(Q=>!l(Q.fromRef));let c,u;switch(n){case"left":c=o.leftPins,u="leftPinCount";break;case"right":c=o.rightPins,u="rightPinCount";break;case"top":c=o.topPins,u="topPinCount";break;case"bottom":c=o.bottomPins,u="bottomPinCount";break;default:return}const A=c.findIndex(Q=>Q.pinNumber===i);if(A===-1)throw new Error(`Pin number ${i} not found on side ${n} of chip ${o.chipId}`);c.splice(A,1),o[u]--;const d=new Map;for(let Q=1;Q<=a;++Q)Q!==i&&(Q<i?d.set(Q,Q):d.set(Q,Q-1));const h=[...o.leftPins,...o.bottomPins,...o.rightPins,...o.topPins];for(const Q of h){const P=Q.pinNumber,O=d.get(P);O!==void 0&&(Q.pinNumber=O)}const{side:m,indexOnSide:C}=rS(i,{leftPinCount:o.leftPinCount+(n==="left"?1:0),rightPinCount:o.rightPinCount+(n==="right"?1:0),topPinCount:o.topPinCount+(n==="top"?1:0),bottomPinCount:o.bottomPinCount+(n==="bottom"?1:0)}),E={};for(const[Q,P]of d.entries())o.pinMargins[Q]&&(E[P]={...o.pinMargins[Q]});for(const[Q,P]of d.entries()){const O=rS(Q,{leftPinCount:o.leftPinCount+(n==="left"?1:0),rightPinCount:o.rightPinCount+(n==="right"?1:0),topPinCount:o.topPinCount+(n==="top"?1:0),bottomPinCount:o.bottomPinCount+(n==="bottom"?1:0)});if(O.side===m&&O.indexOnSide>C){const z=E[P]||{marginTop:.2,marginLeft:.2};n==="left"||n==="right"?E[P]={...z,marginTop:z.marginTop+.2}:E[P]={...z,marginLeft:z.marginLeft+.2}}}o.pinMargins=E;const _=new Map;for(const[Q,P]of d.entries())Q!==P&&_.set(Q,P);_.size>0&&fYt(r,o.chipId,_),o.pinPositionsAreSet=!1,o.setPinPositions();const x=new Map;for(let Q=1;Q<=a;++Q){if(Q===i)continue;const P=d.get(Q),O=s.get(Q),z=o.getPinLocation(P),Y=z.x-O.x,V=z.y-O.y;(Y!==0||V!==0)&&x.set(P,{dx:Y,dy:V})}if(x.size>0){const Q=P=>"boxId"in P&&P.boxId===t&&x.has(P.pinNumber)?x.get(P.pinNumber):null;for(const P of r.lines){const O=Q(P.start.ref),z=Q(P.end.ref);(O??z)&&(O&&(P.start.x+=O.dx,P.start.y+=O.dy),z&&(P.end.x+=z.dx,P.end.y+=z.dy))}for(const P of r.connectionPoints){const O=Q(P.pinRef);O&&(P.x+=O.dx,P.y+=O.dy)}for(const P of r.netLabels){const O=Q(P.fromRef);O&&(P.x+=O.dx,P.y+=O.dy)}}}var pYt=(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 gYt(r,e){const{chipId:t,side:n,betweenPinNumbers:i}=e,o=r.chips.find(Q=>Q.chipId===t);if(!o)return;const a=o.totalPinCount,s=new Map;for(let Q=1;Q<=a;++Q)s.set(Q,o.getPinLocation(Q));const l=Math.min(...i),c=n==="left"?o.leftPins:n==="right"?o.rightPins:n==="top"?o.topPins:o.bottomPins,u=c.findIndex(Q=>Q.pinNumber===l)+1;if(l!==0&&u===0)return;o[`${n}PinCount`]+=1;const A=l+1,d=new Vae(o,A);c.splice(u,0,d);const h=new Map,m=o.totalPinCount-1;for(let Q=1;Q<=m;++Q)Q>l&&h.set(Q,Q+1);const C=new Set([d]),E=Q=>Q.forEach(P=>{C.has(P)||h.has(P.pinNumber)&&(P.pinNumber=h.get(P.pinNumber))});E(o.leftPins),E(o.rightPins),E(o.topPins),E(o.bottomPins),pYt(r,t,h),o.pinPositionsAreSet=!1,o.setPinPositions();const _=new Map;for(let Q=1;Q<=a;++Q){const P=s.get(Q),O=h.get(Q)??Q,z=o.getPinLocation(O),Y=z.x-P.x,V=z.y-P.y;(Y||V)&&_.set(O,{dx:Y,dy:V})}const x=Q=>"boxId"in Q&&Q.boxId===t&&_.has(Q.pinNumber)?_.get(Q.pinNumber):null;for(const Q of r.lines){const P=x(Q.start.ref)??x(Q.end.ref);P&&(Q.start.x+=P.dx,Q.start.y+=P.dy,Q.end.x+=P.dx,Q.end.y+=P.dy)}for(const Q of r.connectionPoints){const P=x(Q.pinRef);P&&(Q.x+=P.dx,Q.y+=P.dy)}for(const Q of r.netLabels){const P=x(Q.fromRef);P&&(Q.x+=P.dx,Q.y+=P.dy)}}function mYt(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 yYt(r,e){const{fromChipId:t,fromPinNumber:n,toChipId:i,toPinNumber:o,netName:a}=e,s=r.chips.find(h=>h.chipId===t),l=r.chips.find(h=>h.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(o);if(!c)throw new Error(`Could not find pin ${n} on chip ${t}`);if(!u)throw new Error(`Could not find pin ${o} on chip ${i}`);const A=l.getPinLocation(o),d=a||`connection_${t}_${n}_to_${i}_${o}`;c.pathTo(A.x,A.y).mark(d),u.connectToMark(d)}function UD(r,e){switch(e.type){case"add_label_to_pin":lYt(r,e);break;case"add_passive_to_pin":uYt(r,e);break;case"add_passive_with_label_to_pin":AYt(r,e);break;case"clear_pin":cYt(r,e);break;case"add_pin_to_side":gYt(r,e);break;case"remove_pin_from_side":hYt(r,e);break;case"remove_chip":dYt(r,e);break;case"change_passive_orientation":mYt(r,e);break;case"draw_line_between_pins":yYt(r,e);break}}function eT(r){const e=[],{template:t,target:n}=r,i=t.getNetlist(),o=cQ(i),a=cQ(n),s=o.normalizedNetlist,l=a.normalizedNetlist,c=e6({candidateNetlist:s,targetNetlist:l}).map(u=>{var A,d;return{...u,candidateChipId:(A=Object.entries(o.transform.boxIdToBoxIndex).find(([h,m])=>m===u.candidateBoxIndex))==null?void 0:A[0],targetChipId:(d=Object.entries(a.transform.boxIdToBoxIndex).find(([h,m])=>m===u.targetBoxIndex))==null?void 0:d[0]}});for(const u of t.chips){if(c.some(h=>h.candidateChipId===u.chipId))continue;const d={type:"remove_chip",chipId:u.chipId};UD(t,d),e.push(d);break}return{appliedOperations:e,matchedBoxes:c}}function vYt(r){const{template:e,target:t,matchedBoxes:n}=r,i=[],o=t.boxes;for(const{candidateChipId:a,targetChipId:s}of n){const l=e.chips.find(u=>u.chipId===a),c=o.find(u=>u.boxId===s);if(!(!c||!l)&&!l.isPassive)for(const u of Yae){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 h={type:"add_pin_to_side",chipId:l.chipId,side:u,betweenPinNumbers:[d,d+1]};return UD(e,h),i.push(h),{appliedOperations:i}}if(l[`${u}PinCount`]>A){const d=IYt({template:e,target:t,chipId:l.chipId,side:u}),h={type:"remove_pin_from_side",chipId:l.chipId,side:u,pinNumber:d};return UD(e,h),i.push(h),{appliedOperations:i}}}}return{appliedOperations:i}}function IYt(r){const{template:e,target:t,chipId:n,side:i}=r,o=e.chips.find(u=>u.chipId===n);if(!o)throw new Error(`Chip ${n} not found`);const s={left:o.leftPins,right:o.rightPins,top:o.topPins,bottom:o.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};UD(A,d);const h=CYt(A,t);h<c&&(c=h,l=u.pinNumber)}catch{continue}return l}function CYt(r,e){try{const t=cQ(r.getNetlist()),n=cQ(e),o=e6({candidateNetlist:t.normalizedNetlist,targetNetlist:n.normalizedNetlist}).flatMap(a=>a.issues||[]);return Hae(o)}catch{return Number.POSITIVE_INFINITY}}function EYt(r){const{template:e,target:t,matchedBoxes:n}=r,i=[];for(const{candidateChipId:o,targetChipId:a}of n){const s=e.chips.find(u=>u.chipId===o),l=t.boxes.find(u=>u.boxId===a);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 h=A-d,m=_Yt({template:e,chipId:o,side:u,pinsToRemove:h});if(m.length>0){const C=m[0];return UD(e,C),i.push(C),{appliedOperations:i}}}}}return{appliedOperations:i}}function _Yt(r){const{template:e,chipId:t,side:n,pinsToRemove:i}=r,o=e.chips.find(c=>c.chipId===t);if(!o)return[];const s={left:o.leftPins,right:o.rightPins,top:o.topPins,bottom:o.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 xYt(r){const e=[],{template:t,target:n,matchedBoxes:i}=r,o=n.connections||[];for(const a of o){const s=a.connectedPorts.filter(_=>"boxId"in _);if(s.length!==2)continue;const[l,c]=s;if(!l||!c)continue;const u=i.find(_=>{var x,Q;return((Q=(x=n.boxes)==null?void 0:x[_.targetBoxIndex])==null?void 0:Q.boxId)===l.boxId}),A=i.find(_=>{var x,Q;return((Q=(x=n.boxes)==null?void 0:x[_.targetBoxIndex])==null?void 0:Q.boxId)===c.boxId});if(!(u!=null&&u.candidateChipId)||!(A!=null&&A.candidateChipId))continue;const d=u.candidateChipId,h=A.candidateChipId;if(!(t.getNetlist().connections||[]).some(_=>{const x=_.connectedPorts.filter(O=>"boxId"in O),Q=x.some(O=>O.boxId===d&&O.pinNumber===l.pinNumber),P=x.some(O=>O.boxId===h&&O.pinNumber===c.pinNumber);return Q&&P})){const _={type:"draw_line_between_pins",fromChipId:d,fromPinNumber:l.pinNumber,toChipId:h,toPinNumber:c.pinNumber};try{UD(t,_),e.push(_);break}catch(x){console.warn("Failed to apply draw line operation:",x)}}}return{appliedOperations:e}}var BYt=class extends ND{constructor(e){super();Le(this,"inputTemplate");Le(this,"targetNetlist");Le(this,"transformedTarget",null);Le(this,"outputAdaptedTemplate",null);Le(this,"outputAppliedOperations",[]);Le(this,"phase","transform-target");Le(this,"matchedBoxes",[]);Le(this,"stepCount",0);Le(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=HHt(this.outputAdaptedTemplate,this.targetNetlist),this.phase="remove-unmatched-chips-1";break;case"remove-unmatched-chips-1":{const n=eT({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=eT({template:this.outputAdaptedTemplate,target:this.transformedTarget}),i=vYt({template:this.outputAdaptedTemplate,target:this.transformedTarget,matchedBoxes:n.matchedBoxes});if(i.appliedOperations.length>0){const o=i.appliedOperations[0];this.outputAppliedOperations.push(o)}else this.phase="fix-matched-box-pin-shapes";break}case"fix-matched-box-pin-shapes":{const n=eT({template:this.outputAdaptedTemplate,target:this.transformedTarget}),i=EYt({template:this.outputAdaptedTemplate,target:this.transformedTarget,matchedBoxes:n.matchedBoxes});if(i.appliedOperations.length>0){const o=i.appliedOperations[0];this.outputAppliedOperations.push(o)}else this.phase="remove-unmatched-chips-2";break}case"remove-unmatched-chips-2":{const n=eT({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=eT({template:this.outputAdaptedTemplate,target:this.transformedTarget}),i=xYt({template:this.outputAdaptedTemplate,target:this.transformedTarget,matchedBoxes:n.matchedBoxes});if(i.appliedOperations.length>0){const o=i.appliedOperations[0];this.outputAppliedOperations.push(o)}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:$N(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"}]}},bYt=class extends ND{constructor(e){super();Le(this,"matchedTemplates");Le(this,"adaptationSolvers",[]);Le(this,"currentAdaptationIndex",0);Le(this,"outputAdaptedTemplates",[]);this.matchedTemplates=e.matchedTemplates,this.adaptationSolvers=this.matchedTemplates.map(t=>new BYt({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}},SYt=()=>{const r=n2({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},QYt=()=>{const r=n2({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},wYt=()=>{const r=n2({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},MYt=()=>{const r=n2({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},DYt=()=>{const r=n2({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},RYt=()=>{const r=n2({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},NYt=()=>{const r=n2({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},TYt=()=>{const r=n2({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},PYt=()=>{const r=n2({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},UYt={template1:SYt,template2:QYt,template3:wYt,template4:MYt,template5:DYt,template6:RYt,template7:NYt,template8:TYt,template9:PYt},FYt=Object.values(UYt);function Wke(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 kYt(r,e,t){if(t===0)return r;const{side:n,indexOnSide:i}=rS(r,e),o=Wke(e,t);let a;switch(t){case 90:switch(n){case"left":a="top";break;case"bottom":a="left";break;case"right":a="bottom";break;case"top":a="right";break;default:a=n}break;case 180:switch(n){case"left":a="right";break;case"right":a="left";break;case"top":a="bottom";break;case"bottom":a="top";break;default:a=n}break;case 270:switch(n){case"left":a="bottom";break;case"bottom":a="right";break;case"right":a="top";break;case"top":a="left";break;default:a=n}break;default:a=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=o[`${A}PinCount`];if(d){if(A===a)return c+s;c+=d}}throw new Error(`Could not map pin ${r} after ${t}° rotation`)}function LYt(r){const{inputNetlist:e,matchedBoxes:t}=r,n=new Map;for(const a of t)n.set(a.targetBoxIndex,a.targetBoxRotationCcw);const i=e.boxes.map((a,s)=>{const l=n.get(s);return l?Wke(a,l):a}),o=e.connections.map(a=>{const s=a.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=kYt(l.pinNumber,A,u);return{...l,pinNumber:d}}}}return l});return{...a,connectedPorts:s}});return{...e,boxes:i,connections:o}}function GYt(r,e,t,n=45){if(!t)return[`Box ${r} (no transform)`];const i=Object.keys(t.boxIdToBoxIndex).find(C=>t.boxIdToBoxIndex[C]===r);if(!i)return[`Box ${r} (not found)`];const o=e.boxes.find(C=>C.boxId===i);if(!o)return[`Box ${i} (not found)`];const a=[],{leftPinCount:s,rightPinCount:l,topPinCount:c,bottomPinCount:u}=o,A=Math.min(n-4,16),d=2,h=Math.max(s,l,1);let m=i;if(i.length>A-2&&(m=`${i.substring(0,A-3)}…`),c>0){let C="";for(let Q=0;Q<c;Q++){const P=s+u+l+Q+1;C+=P.toString().padStart(2)}const E=C.substring(0,A),_=Math.floor((A-E.length)/2),x=" ".repeat(_)+E;a.push(`${" ".repeat(d+1)}${x}`)}a.push(`${" ".repeat(d)}┌${"─".repeat(A)}┐`);for(let C=0;C<h;C++){const E=C<s?(C+1).toString():"",_=C<l?(s+u+(l-1-C)+1).toString():"";let x="";if(C===Math.floor((h-1)/2)){const Q=Math.floor((A-m.length)/2),P=A-m.length-Q;x=" ".repeat(Q)+m+" ".repeat(P)}else x=" ".repeat(A);a.push(`${E.padStart(d)}│${x}│${_.padEnd(d)}`)}if(a.push(`${" ".repeat(d)}└${"─".repeat(A)}┘`),u>0){let C="";for(let Q=0;Q<u;Q++){const P=s+Q+1;C+=P.toString().padStart(2)}const E=C.substring(0,A),_=Math.floor((A-E.length)/2),x=" ".repeat(_)+E;a.push(`${" ".repeat(d+1)}${x}`)}return a}function OYt(r){const{candidateNetlist:e,targetNetlist:t}=r,n=[],i=new Map;for(let o=0;o<e.boxes.length;o++){const a=e.boxes[o],s=Zae({leftPinCount:a.leftPinCount,bottomPinCount:a.bottomPinCount,rightPinCount:a.rightPinCount,topPinCount:a.topPinCount});i.has(s)||i.set(s,[]),i.get(s).push(o)}for(let o=0;o<t.boxes.length;o++){const a=t.boxes[o],s=Zae({leftPinCount:a.leftPinCount,bottomPinCount:a.bottomPinCount,rightPinCount:a.rightPinCount,topPinCount:a.topPinCount});(i.get(s)||[]).length===0&&n.push({type:"no_box_matching_pin_counts",candidateBoxIndex:-1,targetBoxIndex:o})}return n}function zYt(r){const{candidateNetlist:e,targetNetlist:t}=r,n=OYt({candidateNetlist:e,targetNetlist:t}),i=e6({candidateNetlist:e,targetNetlist:t});return[...n,...i.flatMap(o=>o.issues)]}var Zke=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 o=Xae({netlist:r,chipId:t.boxId,pinNumber:i});e.push({boxId:t.boxId,pinNumber:i,pinShapeSignature:o})}}return e},HYt=({targetNetlist:r,candidateNetlist:e,matchedBoxes:t,targetTransform:n,candidateTransform:i})=>{const o=Zke(r),a=Zke(e),s=[];for(const l of t){const c=Object.keys(n.boxIdToBoxIndex).find(m=>n.boxIdToBoxIndex[m]===l.targetBoxIndex),u=Object.keys(i.boxIdToBoxIndex).find(m=>i.boxIdToBoxIndex[m]===l.candidateBoxIndex);if(!c||!u)continue;const A=o.filter(m=>m.boxId===c),d=a.filter(m=>m.boxId===u),h=new Set([...A.map(m=>m.pinNumber),...d.map(m=>m.pinNumber)]);for(const m of h){const C=A.find(_=>_.pinNumber===m),E=d.find(_=>_.pinNumber===m);s.push({targetBoxIdPinNumber:C?`${c}.${m}`:"",candidateBoxIdPinNumber:E?`${u}.${m}`:"",targetPinShapeSignature:(C==null?void 0:C.pinShapeSignature)||"",candidatePinShapeSignature:(E==null?void 0:E.pinShapeSignature)||""})}}return s},YYt=class extends ND{constructor(e){super();Le(this,"inputNetlist");Le(this,"template");Le(this,"inputNetlistWithRotations",null);Le(this,"outputIssues",[]);Le(this,"outputSimilarityDistance",1/0);Le(this,"candidateTransform",null);Le(this,"targetTransform",null);Le(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=cQ(e),n=cQ(structuredClone(this.inputNetlist)),i=t.normalizedNetlist,o=n.normalizedNetlist;this.matchedBoxes=e6({candidateNetlist:i,targetNetlist:o});for(const A of this.matchedBoxes)A._targetBoxId=n.transform.boxIndexToBoxId[A.targetBoxIndex],A._candidateBoxId=t.transform.boxIndexToBoxId[A.candidateBoxIndex];const a=LYt({inputNetlist:structuredClone(this.inputNetlist),matchedBoxes:this.matchedBoxes});this.inputNetlistWithRotations=a;const s=cQ(a),l=s.normalizedNetlist;this.candidateTransform=t.transform,this.targetTransform=s.transform,this.outputIssues=zYt({candidateNetlist:i,targetNetlist:l}),this.outputSimilarityDistance=Hae(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(o=>n.boxIdToBoxIndex[o]===e);return i?`${e} (${i})`:e.toString()}getAsciiForNetlistBoxHelper(e,t,n=45){const i=t?this.template.getNetlist():this.inputNetlistWithRotations,o=t?this.candidateTransform:this.targetTransform;return o?GYt(e,i,o,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),o=Math.max(n.length,i.length);for(;n.length<o;)n.push(" ".repeat(48));for(;i.length<o;)i.push(" ".repeat(48));const a=`Target ${this.getBoxNameFromIndex(t.targetBoxIndex,!1)}`.padEnd(48),s=`Template ${this.getBoxNameFromIndex(t.candidateBoxIndex,!0)}`.padEnd(48);e.push(`${a} → ${s}`),e.push(`${"─".repeat(48)} → ${"─".repeat(48)}`);for(let l=0;l<o;l++){const c=n[l]||"",u=i[l]||"",A=l===Math.floor(o/2)?" → ":" ";e.push(`${c.padEnd(48)}${A}${u.padEnd(48)}`)}e.push("")}return e.join(`
13466
13466
  `)}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:HYt({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:$N(this.inputNetlist)},this.inputNetlistWithRotations&&{title:"targetReadableNetlistWithRotations",ascii:$N(this.inputNetlistWithRotations)}].filter(Boolean)}},VYt=class extends ND{constructor(e){var t;super();Le(this,"inputNetlist");Le(this,"templates");Le(this,"scoringSolvers",[]);Le(this,"currentScoringIndex",0);Le(this,"outputBestMatchTemplate",null);Le(this,"templateMatchResults",[]);this.inputNetlist=e.inputNetlist,this.templates=((t=e.templateFns)==null?void 0:t.map(n=>n()))||FYt.map(n=>n()),this.scoringSolvers=this.templates.map(n=>new YYt({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:$N(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}))}]}},KYt=class extends ND{constructor(e){super();Le(this,"inputNetlists");Le(this,"currentInputNetlistIndex",0);Le(this,"templateFns");Le(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 VYt({inputNetlist:this.inputNetlists[this.currentInputNetlistIndex],templateFns:this.templateFns}))}};function qke(r,e,t,n={}){return{solverName:r,solverClass:e,getConstructorParams:t,onSolved:n.onSolved}}var jYt=class extends ND{constructor(e){super();Le(this,"inputNetlist");Le(this,"templateFnsOverride");Le(this,"matchPhaseSolver");Le(this,"adaptPhaseSolver");Le(this,"startTimeOfPhase",{});Le(this,"endTimeOfPhase",{});Le(this,"timeSpentOnPhase",{});Le(this,"pipelineDef",[qke("matchPhaseSolver",KYt,()=>[{inputNetlists:[this.inputNetlist],templateFns:this.templateFnsOverride}]),qke("adaptPhaseSolver",bYt,()=>{var e;return[{matchedTemplates:(e=this.matchPhaseSolver)==null?void 0:e.outputMatchedTemplates}]})]);Le(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()}},JYt=r=>{switch(r){case"left":return"left";case"right":return"right";case"up":return"top";case"down":return"bottom"}},WYt=r=>{const e=WB(r),t=xB(r).source_component.list().map(a=>({source_component:a,schematic_component:xB(r).schematic_component.getWhere({source_component_id:a.source_component_id}),source_ports:xB(r).source_port.list().filter(s=>s.source_component_id===a.source_component_id).map(s=>{const l=e.getNetConnectedToId(s.source_port_id),c=xB(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:xB(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:a,schematic_component:s,source_ports:l}of t){const c={boxId:a.name,leftPinCount:0,rightPinCount:0,topPinCount:0,bottomPinCount:0};for(const{source_port:u,schematic_port:A,pin_number:d}of l){const h=JYt(A.facing_direction);c[`${h}PinCount`]++;const m=e.getNetConnectedToId(u.source_port_id);let C=i.find(E=>E._connectivityNetId===m);C||(C={_connectivityNetId:m,connectedPorts:[]},i.push(C)),C.connectedPorts.push({boxId:a.name,pinNumber:(A==null?void 0:A.true_ccw_index)!=null?A.true_ccw_index+1:d})}n.push(c)}const o=[];for(const a of i){if(a.connectedPorts.length<2)continue;let s=a._connectivityNetId;const l=e.getIdsConnectedToNet(s).map(c=>qge(r,c));for(const c of l)if((c==null?void 0:c.type)==="source_net"){s=c.name;break}a.connectedPorts.push({netId:s}),o.push({netId:s})}return{boxes:n,connections:i,nets:o}},ZYt=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(a=>a.type==="schematic_port"&&a.schematic_component_id===n.schematic_component_id&&a.true_ccw_index!==void 0);if(i.length===0)continue;i.sort((a,s)=>a.true_ccw_index-s.true_ccw_index);const o={};i.forEach((a,s)=>{o[a.pin_number]=s+1});for(const a of i){const s=o[a.pin_number];a.pin_number=s}for(const a of i){const s=e.find(l=>l.type==="source_port"&&l.source_port_id===a.source_port_id);s&&(s.pin_number=a.pin_number)}if(n.port_arrangement){const a=s=>{var l;(l=n.port_arrangement[s])!=null&&l.pins&&(n.port_arrangement[s].pins=n.port_arrangement[s].pins.map(c=>o[c]||c))};a("left_side"),a("right_side"),a("top_side"),a("bottom_side")}if(n.port_labels){const a={};for(const[s,l]of Object.entries(n.port_labels)){const c=parseInt(s.replace("pin","")),u=o[c];u!==void 0?a[`pin${u}`]=l:a[s]=l}n.port_labels=a}if(n.pin_styles){const a={};for(const[s,l]of Object.entries(n.pin_styles)){const c=parseInt(s.replace("pin","")),u=o[c];u!==void 0?a[`pin${u}`]=l:a[s]=l}n.pin_styles=a}}return e},qYt=Object.defineProperty,XYt=(r,e)=>{for(var t in e)qYt(r,t,{get:e[t],enumerable:!0})},Xke={};XYt(Xke,{Battery:()=>fKt,Board:()=>jVt,Capacitor:()=>WVt,Chip:()=>ILe,Constraint:()=>rKt,Crystal:()=>CKt,Cutout:()=>dKt,Diode:()=>ZVt,FabricationNotePath:()=>iKt,FabricationNoteText:()=>oKt,Footprint:()=>CVt,Fuse:()=>qVt,Group:()=>Ase,Hole:()=>cLe,Inductor:()=>mKt,Jumper:()=>XVt,Keepout:()=>ose,Led:()=>$Vt,Mosfet:()=>_Kt,Net:()=>oLe,NetAlias:()=>sKt,NormalComponent:()=>N1,PcbTrace:()=>lLe,PinHeader:()=>hKt,PlatedHole:()=>ise,Port:()=>r2,Potentiometer:()=>vKt,PowerSource:()=>eKt,PrimitiveComponent:()=>$v,PushButton:()=>IKt,Renderable:()=>$ke,Resistor:()=>tKt,Resonator:()=>gKt,SchematicBox:()=>bKt,SchematicText:()=>BKt,SilkscreenCircle:()=>lKt,SilkscreenLine:()=>uKt,SilkscreenPath:()=>sLe,SilkscreenRect:()=>cKt,SilkscreenText:()=>ase,SmtPad:()=>rse,Subcircuit:()=>aKt,Switch:()=>xKt,Trace:()=>i9,TraceHint:()=>yLe,Transistor:()=>EKt,Via:()=>AKt});var $Yt=Rm("tscircuit:renderable"),LB=["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"],eVt=0,$ke=class{constructor(r){Le(this,"renderPhaseStates");Le(this,"shouldBeRemoved",!1);Le(this,"children");Le(this,"isPcbPrimitive",!1);Le(this,"isSchematicPrimitive",!1);Le(this,"_renderId");Le(this,"_currentRenderPhase",null);Le(this,"_asyncEffects",[]);Le(this,"parent",null);this._renderId=`${eVt++}`,this.children=[],this.renderPhaseStates={};for(const e of LB)this.renderPhaseStates[e]={initialized:!1,dirty:!1}}_markDirty(r){var t;this.renderPhaseStates[r].dirty=!0;const e=LB.indexOf(r);for(let n=e+1;n<LB.length;n++)this.renderPhaseStates[LB[n]].dirty=!0;(t=this.parent)!=null&&t._markDirty&&this.parent._markDirty(r)}_queueAsyncEffect(r,e){const t={promise:e(),phase:this._currentRenderPhase,effectName:r,complete:!1};this._asyncEffects.push(t),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:r,componentDisplayName:this.getString(),phase:t.phase}),t.promise.then(()=>{t.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:r,componentDisplayName:this.getString(),phase:t.phase})}).catch(n=>{console.error(`Async effect error in ${t.phase} "${r}":
13467
13467
  ${n.stack}`),t.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:r,componentDisplayName:this.getString(),phase:t.phase,error:n.toString()})})}_emitRenderLifecycleEvent(r,e){$Yt(`${r}:${e} ${this.getString()}`);const t=`renderable:renderLifecycle:${r}:${e}`,n={renderId:this._renderId,componentDisplayName:this.getString(),type:t};"root"in this&&this.root&&(this.root.emit(t,n),this.root.emit("renderable:renderLifecycle:anyEvent",{...n,type:t}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(r=>!r.complete)}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(r=>r.getRenderGraph())}}runRenderCycle(){for(const r of LB)this.runRenderPhaseForChildren(r),this.runRenderPhase(r)}runRenderPhase(r){var o,a,s;this._currentRenderPhase=r;const e=this.renderPhaseStates[r],t=e.initialized,n=e.dirty;if(!t&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&t){this._emitRenderLifecycleEvent(r,"start"),(o=this==null?void 0:this[`remove${r}`])==null||o.call(this),e.initialized=!1,e.dirty=!1,this._emitRenderLifecycleEvent(r,"end");return}const i=LB.indexOf(r)-1;if(i>=0){const l=LB[i];if(this._asyncEffects.filter(u=>u.phase===l).some(u=>!u.complete))return}if(this._emitRenderLifecycleEvent(r,"start"),t){n&&((a=this==null?void 0:this[`update${r}`])==null||a.call(this),e.dirty=!1),this._emitRenderLifecycleEvent(r,"end");return}e.dirty=!1,(s=this==null?void 0:this[`doInitial${r}`])==null||s.call(this),e.initialized=!0,this._emitRenderLifecycleEvent(r,"end")}runRenderPhaseForChildren(r){for(const e of this.children)e.runRenderPhaseForChildren(r),e.runRenderPhase(r)}renderError(r){throw typeof r=="string"?new Error(r):new Error(JSON.stringify(r,null,2))}},t6={},eLe=r=>{const e=Object.fromEntries(Object.entries(r).map(([t,n])=>[t.toLowerCase(),n]));Object.assign(t6,r),Object.assign(t6,e)},tVt=class extends Error{constructor(r,e,t){let n;const o=Object.keys(t).filter(a=>a!=="_errors").map(a=>t[a]._errors[0]?`${a} (${t[a]._errors[0]})`:`${a} (${JSON.stringify(t[a])})`).join(", ");"name"in e?n=`Invalid props for ${r} "${e.name}": ${o}`:"footprint"in e&&typeof e.footprint=="string"?n=`Invalid props for ${r} (unnamed ${e.footprint} component): ${o}`:n=`Invalid props for ${r} (unnamed): ${o}`,super(n),this.componentName=r,this.originalProps=e,this.formattedError=t}};function ese(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,...o]=e.split(/(?=[#.[])/);return i==="pin"&&(i="port"),i&&i!=="*"&&r.lowercaseComponentName!==i.toLowerCase()?!1:o.every(a=>{if(a.startsWith("#"))return r.props.id===a.slice(1);if(a.startsWith("."))return r.isMatchingNameOrAlias(a.slice(1));const s=a.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!s)return!0;const[,l,c]=s;return r.props[l].toString()===c})}var tse={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 o of i.children)n(o)};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=tse.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},nVt={...tse,getChildren:r=>r.children.filter(e=>!e.isSubcircuit)},tLe={...tse,getChildren:r=>r.children.filter(e=>e.isSubcircuit)},nLe=r=>r.replace(/ pin/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").trim(),nse={adapter:nVt,cacheResults:!0},$v=class extends $ke{constructor(e){super(e);Le(this,"parent",null);Le(this,"children");Le(this,"childrenPendingRemoval");Le(this,"props");Le(this,"_parsedProps");Le(this,"externallyAddedAliases");Le(this,"isPrimitiveContainer",!1);Le(this,"source_group_id",null);Le(this,"source_component_id",null);Le(this,"schematic_component_id",null);Le(this,"pcb_component_id",null);Le(this,"cad_component_id",null);Le(this,"_cachedSelectAllQueries",new Map);Le(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=e??{},this.externallyAddedAliases=[];const t=this.config.zodProps.safeParse(e??{});if(t.success)this._parsedProps=t.data;else throw new tVt(this.lowercaseComponentName,this.props,t.error.format())}get config(){return{componentName:"",zodProps:In({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(e){var n;let t=this;for(;t;){if(t._parsedProps&&e in t._parsedProps)return t._parsedProps[e];t=t.parent}if((n=this.root)!=null&&n.platform&&e in this.root.platform)return this.root.platform[e]}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){var e;return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&((e=this==null?void 0:this.parent)==null?void 0:e.isRoot)}get isGroup(){return this.lowercaseComponentName==="group"}setProps(e){var i,o;const t=this.config.zodProps.parse({...this.props,...e}),n=this.props;this.props=t,this._parsedProps=this.config.zodProps.parse(e),this.onPropsChange({oldProps:n,newProps:t,changedProps:Object.keys(e)}),(o=(i=this.parent)==null?void 0:i.onChildChanged)==null||o.call(i,this)}computePcbPropsTransform(){const{_parsedProps:e}=this;return Uc(JA(e.pcbX??0,e.pcbY??0),l_((e.pcbRotation??0)*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){var n,i,o;const{_parsedProps:e}=this,t=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(t&&this.props.pcbX===void 0&&this.props.pcbY===void 0)return Uc(((n=this.parent)==null?void 0:n._computePcbGlobalTransformBeforeLayout())??a0(),Uc(JA(t.x,t.y),l_((e.pcbRotation??0)*Math.PI/180)));if(this.isPcbPrimitive){const a=this.getPrimitiveContainer();if(a){const s=a._parsedProps.layer==="bottom",l=a._getGlobalPcbPositionBeforeLayout();if(s)return Uc(JA(l.x,l.y),CQ(),JA(-l.x,-l.y)),Uc(((i=this.parent)==null?void 0:i._computePcbGlobalTransformBeforeLayout())??a0(),CQ(),this.computePcbPropsTransform())}}return Uc(((o=this.parent)==null?void 0:o._computePcbGlobalTransformBeforeLayout())??a0(),this.computePcbPropsTransform())}getPrimitiveContainer(){var e,t;return this.isPrimitiveContainer?this:((t=(e=this.parent)==null?void 0:e.getPrimitiveContainer)==null?void 0:t.call(e))??null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){const e=this.getPrimitiveContainer(),t=e?e._parsedProps.layer==="bottom":!1;return{isFlipped:t,maybeFlipLayer:i=>t?i==="top"?"bottom":"top":i}}_setPositionFromLayout(e){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){const{_parsedProps:e}=this;return Uc(JA(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){var t,n;const e=this._getSchematicGlobalManualPlacementTransform(this);return e||Uc(((n=(t=this.parent)==null?void 0:t.computeSchematicGlobalTransform)==null?void 0:n.call(t))??a0(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){const{_parsedProps:e}=this,t=this.config.schematicSymbolName;let n=e.schRotation;if(n===void 0&&(n=0),n=n%360,n<0&&(n+=360),e.schRotation!==void 0&&n%90!==0)throw new Error(`Schematic rotation ${e.schRotation} is not supported for ${this.componentName}`);const i=`${t}_horz`,o=`${t}_vert`,a=`${t}_up`,s=`${t}_down`,l=`${t}_left`,c=`${t}_right`;if(c in l0&&n===0)return c;if(a in l0&&n===90)return a;if(l in l0&&n===180)return l;if(s in l0&&n===270)return s;if(i in l0&&(n===0||n===180))return i;if(o in l0&&(n===90||n===270))return o;if(t in l0)return t}_getSchematicSymbolNameOrThrow(){const e=this._getSchematicSymbolName();if(!e)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return e}getSchematicSymbol(){const e=this._getSchematicSymbolName();return e?l0[e]??null:null}_getPcbManualPlacementForComponent(e){var o;if(!this.isSubcircuit)return null;const t=this.props.layout,n=this.props.manualEdits;if(!t&&!n)return null;const i=((o=t==null?void 0:t.manual_pcb_placement_config)==null?void 0:o.positions)||(n==null?void 0:n.pcb_placements);if(!i)return null;for(const a of i)if(t&&ese(e,a.selector)||e.props.name===a.selector)return ei(this._computePcbGlobalTransformBeforeLayout(),a.center);return null}_getSchematicManualPlacementForComponent(e){if(!this.isSubcircuit)return null;const t=this.props.manualEdits;if(!t)return null;const n=t.schematic_placements;if(!n)return null;for(const i of n)if(ese(e,i.selector)||e.props.name===i.selector)return ei(this.computeSchematicGlobalTransform(),i.center);return null}_getSchematicGlobalManualPlacementTransform(e){var n,i;const t=(n=this.getSubcircuit())==null?void 0:n._parsedProps.manualEdits;if(!t)return null;for(const o of t.schematic_placements??[])if((ese(e,o.selector)||e.props.name===o.selector)&&o.relative_to==="group_center")return Uc(((i=this.parent)==null?void 0:i._computePcbGlobalTransformBeforeLayout())??a0(),JA(o.center.x,o.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return ei(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return ei(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){var e;return((e=this.parent)==null?void 0:e.root)??null}onAddToParent(e){this.parent=e}onPropsChange(e){}onChildChanged(e){var t,n;(n=(t=this.parent)==null?void 0:t.onChildChanged)==null||n.call(t,e)}add(e){if(!e.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(e)}"`);e.onAddToParent(this),e.parent=this,this.children.push(e)}addAll(e){for(const t of e)this.add(t)}remove(e){this.children=this.children.filter(t=>t!==e),this.childrenPendingRemoval.push(e),e.shouldBeRemoved=!0}getSubcircuitSelector(){const e=this._parsedProps.name,t=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?t:`${this.parent.getSubcircuitSelector()} > ${t}`}getFullPathSelector(){var i,o;const e=this._parsedProps.name,t=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName,n=(o=(i=this.parent)==null?void 0:i.getFullPathSelector)==null?void 0:o.call(i);return n?`${n} > ${t}`:t}getNameAndAliases(){return[this._parsedProps.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(e){return this.getNameAndAliases().includes(e)}isMatchingAnyOf(e){return this.getNameAndAliases().some(t=>e.map(n=>n.toString()).includes(t))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(e){const t=[this.componentName,this.lowercaseComponentName],n=[this._parsedProps.name].filter(Boolean),i=e.trim().split(/\> /)[0],o=i[0];return i.length>1?!1:!!(e==="*"||e[0]==="#"&&e.slice(1)===this.props.id||e[0]==="."&&n.includes(e.slice(1))||/^[a-zA-Z0-9_]/.test(o)&&t.includes(o))}getSubcircuit(){var t,n;if(this.isSubcircuit)return this;const e=(n=(t=this.parent)==null?void 0:t.getSubcircuit)==null?void 0:n.call(t);if(!e)throw new Error("Component is not inside an opaque group (no board?)");return e}getGroup(){var e,t;return this.isGroup?this:((t=(e=this.parent)==null?void 0:e.getGroup)==null?void 0:t.call(e))??null}doInitialOptimizeSelectorCache(){var t;if(!this.isSubcircuit)return;const e=this.selectAll("port");for(const n of e){const i=(t=n.parent)==null?void 0:t.getNameAndAliases(),o=n.getNameAndAliases();if(i)for(const a of i)for(const s of o){const l=[`.${a} > .${s}`,`.${a} .${s}`];for(const c of l){const u=this._cachedSelectAllQueries.get(c);u?u.push(n):this._cachedSelectAllQueries.set(c,[n])}}}for(const[n,i]of this._cachedSelectAllQueries.entries())i.length===1&&this._cachedSelectOneQueries.set(n,i[0])}selectAll(e){if(this._cachedSelectAllQueries.has(e))return this._cachedSelectAllQueries.get(e);const t=nLe(e),n=R9(t,this,nse);if(n.length>0)return this._cachedSelectAllQueries.set(e,n),n;const[i,...o]=t.split(" "),a=CS(i,this,{adapter:tLe});if(!a)return[];const s=a.selectAll(o.join(" "));return this._cachedSelectAllQueries.set(e,s),s}selectOne(e,t){if(this._cachedSelectOneQueries.has(e))return this._cachedSelectOneQueries.get(e);const n=nLe(e);t!=null&&t.port&&(t.type="port");let i=null;if(t!=null&&t.type&&(i=R9(n,this,nse).find(c=>c.lowercaseComponentName===t.type)),i??(i=CS(n,this,nse)),i)return this._cachedSelectOneQueries.set(e,i),i;const[o,...a]=n.split(" "),s=CS(o,this,{adapter:tLe});return s?(i=s.selectOne(a.join(" "),t),this._cachedSelectOneQueries.set(e,i),i):null}getAvailablePcbLayers(){var e,t;if(this.isPcbPrimitive){const{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[n(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?((t=(e=this.root)==null?void 0:e._getBoard())==null?void 0:t.allLayers)??["top","bottom"]:[]}return[]}getDescendants(){const e=[];for(const t of this.children)e.push(t),e.push(...t.getDescendants());return e}getSelectableDescendants(){const e=[];for(const t of this.children)t.isSubcircuit?e.push(t):(e.push(t),e.push(...t.getSelectableDescendants()));return e}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;const{_parsedProps:e}=this;return{schWidth:e.schWidth,schHeight:e.schHeight}}renderError(e){var t;if(typeof e=="string")return super.renderError(e);(t=this.root)==null||t.db.pcb_placement_error.insert(e)}getString(){var i,o;const{lowercaseComponentName:e,_parsedProps:t,parent:n}=this;return(t==null?void 0:t.pinNumber)!==void 0&&((i=n==null?void 0:n.props)!=null&&i.name)&&(t!=null&&t.name)?`<${e}#${this._renderId}(pin:${t.pinNumber} .${n==null?void 0:n.props.name}>.${t.name}) />`:(o=n==null?void 0:n.props)!=null&&o.name&&(t!=null&&t.name)?`<${e}#${this._renderId}(.${n==null?void 0:n.props.name}>.${t==null?void 0:t.name}) />`:t!=null&&t.from&&(t!=null&&t.to)?`<${e}#${this._renderId}(from:${t.from} to:${t==null?void 0:t.to}) />`:t!=null&&t.name?`<${e}#${this._renderId} name=".${t==null?void 0:t.name}" />`:t!=null&&t.portHints?`<${e}#${this._renderId}(${t.portHints.map(a=>`.${a}`).join(", ")}) />`:`<${e}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},rVt=class extends $v{constructor(r,e){super(r),this._parsedProps={...r,error:e,type:r.type||"unknown",component_name:r.name,error_type:"source_failed_to_create_component_error",message:e instanceof Error?e.message:String(e),pcbX:r.pcbX,pcbY:r.pcbY,schX:r.schX,schY:r.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:In({}).passthrough()}}doInitialSourceRender(){var r,e,t,n;if((r=this.root)!=null&&r.db){const i=this._getGlobalPcbPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,message:((n=(t=(e=this._parsedProps.error)==null?void 0:e.formattedError)==null?void 0:t._errors)==null?void 0:n.join("; "))||this._parsedProps.message,pcb_center:i,schematic_center:o})}}};function iVt(r,e){return new rVt(r,e)}function oVt(r,e){const t=r;return t.__tsci={...e},r}var rLe={supportsMutation:!0,createInstance(r,e){const t=t6[r];if(!t)throw Object.keys(t6).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 oVt(new t(e),{})}catch(n){return iVt(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:()=>IS.DefaultEventPriority,getCurrentUpdatePriority:()=>IS.DefaultEventPriority,resolveUpdatePriority:()=>IS.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},r9;ah.version.startsWith("19.")?r9=N7(rLe):r9=U7(rLe);var aVt=r=>{const e={children:[],props:{name:"$root"},add(o){o.parent=this,this.children.push(o)},computePcbGlobalTransform(){return a0()}},t=[],n=r9.createContainer(e,0,null,!1,null,"tsci",o=>{console.log("Error in createContainer"),console.error(o),t.push(o)},null);if(ah.version.startsWith("19.")?(r9.updateContainerSync(r,n,null,()=>{}),r9.flushSyncWork()):r9.updateContainer(r,n,null,()=>{}),t.length>0)throw t[0];const i=r9.getPublicRootInstance(n);return i||e.children[0]},tT=(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}"`)},sVt=(r,e)=>{if(!r)return;const t={},n={};for(const[i,o]of Object.entries(r)){const a=tT(i,e);n[a]={...n[a],...o}}for(const[i,o]of Object.entries(n)){const a=`pin${i}`;t[a]={bottom_margin:o.bottomMargin,left_margin:o.leftMargin,right_margin:o.rightMargin,top_margin:o.topMargin}}return t},lVt=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 iLe(r){const e=[];for(let t=0;t<r.length-1;t++)e.push([r[t],r[t+1]]);return e}var cVt=In({name:Fe()}),oLe=class extends $v{constructor(){super(...arguments);Le(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:cVt}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_net.insert({name:t.name,member_source_group_ids:[]});this.source_net_id=n.source_net_id}doInitialSourceParentAttachment(){const e=this.getSubcircuit();if(!e)return;const{db:t}=this.root;t.source_net.update(this.source_net_id,{subcircuit_id:e.subcircuit_id})}getAllConnectedPorts(){const e=this.getSubcircuit().selectAll("port"),t=[];for(const n of e){const i=n._getDirectlyConnectedTraces();for(const o of i)if(o._isExplicitlyConnectedToNet(this)){t.push(n);break}}return t}_getAllDirectlyConnectedTraces(){const e=this.getSubcircuit().selectAll("trace"),t=[];for(const n of e)n._isExplicitlyConnectedToNet(this)&&t.push(n);return t}doInitialPcbRouteNetIslands(){var a;if((a=this.root)!=null&&a.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getAllDirectlyConnectedTraces().filter(s=>{var l;return(((l=s._portsRoutedOnPcb)==null?void 0:l.length)??0)>0}),i=[];for(const s of n){const l=s._portsRoutedOnPcb,c=i.find(u=>l.some(A=>u.ports.includes(A)));if(!c){i.push({ports:[...l],traces:[s]});continue}c.traces.push(s),c.ports.push(...l)}if(i.length===0)return;const o=iLe(i);for(const[s,l]of o){const c=s.ports.map(x=>x._getGlobalPcbPositionBeforeLayout()),u=l.ports.map(x=>x._getGlobalPcbPositionBeforeLayout());let A=1/0,d=[-1,-1];for(let x=0;x<c.length;x++){const Q=c[x];for(let P=0;P<u.length;P++){const O=u[P],z=Math.sqrt((Q.x-O.x)**2+(Q.y-O.y)**2);z<A&&(A=z,d=[x,P])}}const h=s.ports[d[0]],m=l.ports[d[1]],C=e.toArray().filter(x=>x.type==="pcb_smtpad"||x.type==="pcb_trace"||x.type==="pcb_plated_hole"||x.type==="pcb_hole"||x.type==="source_port"||x.type==="pcb_port"),{solution:E}=XH(C.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[h.source_port_id,m.source_port_id]}])),_=E[0];if(!_){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[h.pcb_component_id,m.pcb_component_id].filter(Boolean),pcb_port_ids:[h.pcb_port_id,m.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}e.pcb_trace.insert(_)}}renderError(e){var t;if(typeof e=="string")return super.renderError(e);(t=this.root)==null||t.db.pcb_trace_error.insert(e)}},aLe=(r,e)=>{for(const t of e)if(typeof t=="string"&&t.startsWith("net.")){const n=r.getSubcircuit();if(!n.selectOne(t)){const i=new oLe({name:t.split("net.")[1]});n.add(i)}}},rse=class extends $v{constructor(){super(...arguments);Le(this,"pcb_smtpad_id",null);Le(this,"matchedPort",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:YPe}}getPcbSize(){const{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="rect")return{width:e.width,height:e.height};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){var t;const e=(t=this.getPrimitiveContainer())==null?void 0:t.selectAll("port");if(this.props.portHints){for(const n of e)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){var d,h,m,C,E,_,x,Q,P,O;if((d=this.root)!=null&&d.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;if(!t.portHints)return;const n=this.getPrimitiveContainer(),i=this.getSubcircuit(),o=this._getGlobalPcbPositionBeforeLayout();n==null||n._getGlobalPcbPositionBeforeLayout();const a=IQ(this._computePcbGlobalTransformBeforeLayout()),s=Math.abs(a.rotation.angle*(180/Math.PI)-90)%180<.01,{maybeFlipLayer:l}=this._getPcbPrimitiveFlippedHelpers(),c=(n==null?void 0:n._parsedProps.pcbRotation)??0;let u=null;const A=((h=this.parent)==null?void 0:h.pcb_component_id)??((m=this.getPrimitiveContainer())==null?void 0:m.pcb_component_id);t.shape==="circle"?(u=e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:(C=this.matchedPort)==null?void 0:C.pcb_port_id,layer:l(t.layer??"top"),shape:"circle",radius:t.radius,port_hints:t.portHints.map(z=>z.toString()),x:o.x,y:o.y,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0}),e.pcb_solder_paste.insert({layer:u.layer,shape:"circle",radius:u.radius*.7,x:u.x,y:u.y,pcb_component_id:u.pcb_component_id,pcb_smtpad_id:u.pcb_smtpad_id,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((E=this.getGroup())==null?void 0:E.pcb_group_id)??void 0})):t.shape==="rect"&&(u=c===0||s?e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:(_=this.matchedPort)==null?void 0:_.pcb_port_id,layer:l(t.layer??"top"),shape:"rect",width:s?t.height:t.width,height:s?t.width:t.height,port_hints:t.portHints.map(z=>z.toString()),x:o.x,y:o.y,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((x=this.getGroup())==null?void 0:x.pcb_group_id)??void 0}):e.pcb_smtpad.insert({pcb_component_id:A,layer:l(t.layer??"top"),shape:"rotated_rect",width:t.width,height:t.height,x:o.x,y:o.y,ccw_rotation:c,port_hints:t.portHints.map(z=>z.toString()),subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((Q=this.getGroup())==null?void 0:Q.pcb_group_id)??void 0}),u.shape==="rect"&&e.pcb_solder_paste.insert({layer:l(t.layer??"top"),shape:"rect",width:u.width*.7,height:u.height*.7,x:u.x,y:u.y,pcb_component_id:u.pcb_component_id,pcb_smtpad_id:u.pcb_smtpad_id,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((P=this.getGroup())==null?void 0:P.pcb_group_id)??void 0}),u.shape==="rotated_rect"&&e.pcb_solder_paste.insert({layer:l(t.layer??"top"),shape:"rotated_rect",width:u.width*.7,height:u.height*.7,x:u.x,y:u.y,ccw_rotation:c,pcb_component_id:u.pcb_component_id,pcb_smtpad_id:u.pcb_smtpad_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})),u&&(this.pcb_smtpad_id=u.pcb_smtpad_id)}doInitialPcbPortAttachment(){var t,n;if((t=this.root)!=null&&t.pcbDisabled)return;const{db:e}=this.root;e.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:(n=this.matchedPort)==null?void 0:n.pcb_port_id})}_getPcbCircuitJsonBounds(){const{db:e}=this.root,t=e.pcb_smtpad.get(this.pcb_smtpad_id);if(t.shape==="rect")return{center:{x:t.x,y:t.y},bounds:{left:t.x-t.width/2,top:t.y+t.height/2,right:t.x+t.width/2,bottom:t.y-t.height/2},width:t.width,height:t.height};if(t.shape==="rotated_rect"){const n=t.ccw_rotation*Math.PI/180,i=Math.cos(n),o=Math.sin(n),a=t.width/2,s=t.height/2,l=Math.abs(a*i)+Math.abs(s*o),c=Math.abs(a*o)+Math.abs(s*i);return{center:{x:t.x,y:t.y},bounds:{left:t.x-l,right:t.x+l,top:t.y-c,bottom:t.y+c},width:l*2,height:c*2}}if(t.shape==="circle")return{center:{x:t.x,y:t.y},bounds:{left:t.x-t.radius,top:t.y-t.radius,right:t.x+t.radius,bottom:t.y+t.radius},width:t.radius*2,height:t.radius*2};throw new Error(`circuitJson bounds calculation not implemented for shape "${t.shape}"`)}_setPositionFromLayout(e){var i;const{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{x:e.x,y:e.y});const n=t.pcb_solder_paste.list().find(o=>o.pcb_smtpad_id===this.pcb_smtpad_id);t.pcb_solder_paste.update(n==null?void 0:n.pcb_solder_paste_id,{x:e.x,y:e.y}),(i=this.matchedPort)==null||i._setPositionFromLayout(e)}},sLe=class extends $v{constructor(){super(...arguments);Le(this,"pcb_silkscreen_path_id",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:f8e}}doInitialPcbPrimitiveRender(){var l,c,u;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenPath. Must be "top" or "bottom".`);const o=this._computePcbGlobalTransformBeforeLayout(),a=this.getSubcircuit(),s=e.pcb_silkscreen_path.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layer:i,route:t.route.map(A=>{const d=ei(o,{x:A.x,y:A.y});return{...A,x:d.x,y:d.y}}),stroke_width:t.strokeWidth??.1,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});this.pcb_silkscreen_path_id=s.pcb_silkscreen_path_id}getPcbSize(){const{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let t=1/0,n=-1/0,i=1/0,o=-1/0;for(const a of e.route)t=Math.min(t,a.x),n=Math.max(n,a.x),i=Math.min(i,a.y),o=Math.max(o,a.y);return{width:n-t,height:o-i}}},uVt=In({route:hi(fR),source_trace_id:Fe().optional()}),lLe=class extends $v{constructor(){super(...arguments);Le(this,"pcb_trace_id",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:uVt}}doInitialPcbPrimitiveRender(){var c,u;if((c=this.root)!=null&&c.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this.getSubcircuit(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),a=this._computePcbGlobalTransformBeforeLayout(),s=t.route.map(A=>{const{x:d,y:h,...m}=A,C=ei(a,{x:d,y:h});return A.route_type==="wire"&&A.layer?{...C,...m,layer:o(A.layer)}:{...C,...m}}),l=e.pcb_trace.insert({pcb_component_id:n.pcb_component_id,source_trace_id:t.source_trace_id,route:s,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((u=this.getGroup())==null?void 0:u.pcb_group_id)??void 0});this.pcb_trace_id=l.pcb_trace_id}getPcbSize(){const{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let t=1/0,n=-1/0,i=1/0,o=-1/0;for(const a of e.route)t=Math.min(t,a.x),n=Math.max(n,a.x),i=Math.min(i,a.y),o=Math.max(o,a.y),a.route_type==="wire"&&(t=Math.min(t,a.x-a.width/2),n=Math.max(n,a.x+a.width/2),i=Math.min(i,a.y-a.width/2),o=Math.max(o,a.y+a.width/2));return t===1/0||n===-1/0||i===1/0||o===-1/0?{width:0,height:0}:{width:n-t,height:o-i}}},ise=class extends $v{constructor(){super(...arguments);Le(this,"pcb_plated_hole_id",null);Le(this,"matchedPort",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:PPe}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){const{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.outerDiameter,height:e.outerDiameter};if(e.shape==="oval"||e.shape==="pill")return{width:e.outerWidth,height:e.outerHeight};if(e.shape==="circular_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};if(e.shape==="pill_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){const{db:e}=this.root,t=e.pcb_plated_hole.get(this.pcb_plated_hole_id),n=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-n.width/2,top:t.y+n.height/2,right:t.x+n.width/2,bottom:t.y-n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(e){var n;const{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:e.x,y:e.y}),(n=this.matchedPort)==null||n._setPositionFromLayout(e)}doInitialPortMatching(){var t;const e=(t=this.getPrimitiveContainer())==null?void 0:t.selectAll("port");if(this.props.portHints){for(const n of e)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){var a,s,l,c,u,A,d,h,m,C,E,_,x,Q,P;if((a=this.root)!=null&&a.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getGlobalPcbPositionBeforeLayout(),i=((s=this.parent)==null?void 0:s.pcb_component_id)??((l=this.getPrimitiveContainer())==null?void 0:l.pcb_component_id),o=this.getSubcircuit();if(t.shape==="circle"){const O=e.pcb_plated_hole.insert({pcb_component_id:i,pcb_port_id:(c=this.matchedPort)==null?void 0:c.pcb_port_id,outer_diameter:t.outerDiameter,hole_diameter:t.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:n.x,y:n.y,layers:["top","bottom"],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});this.pcb_plated_hole_id=O.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:t.outerDiameter/2,x:n.x,y:n.y,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}),e.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:t.outerDiameter/2,x:n.x,y:n.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})}else if(t.shape==="pill"||t.shape==="oval"){const O=e.pcb_plated_hole.insert({pcb_component_id:i,pcb_port_id:(h=this.matchedPort)==null?void 0:h.pcb_port_id,outer_width:t.outerWidth,outer_height:t.outerHeight,hole_width:t.holeWidth,hole_height:t.holeHeight,shape:t.shape,port_hints:this.getNameAndAliases(),x:n.x,y:n.y,layers:["top","bottom"],subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((m=this.getGroup())==null?void 0:m.pcb_group_id)??void 0});this.pcb_plated_hole_id=O.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:t.shape,width:t.outerWidth,height:t.outerHeight,x:n.x,y:n.y,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((C=this.getGroup())==null?void 0:C.pcb_group_id)??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:t.shape,width:t.outerWidth,height:t.outerHeight,x:n.x,y:n.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(t.shape==="circular_hole_with_rect_pad"){const O=e.pcb_plated_hole.insert({pcb_component_id:i,pcb_port_id:(_=this.matchedPort)==null?void 0:_.pcb_port_id,hole_diameter:t.holeDiameter,rect_pad_width:t.rectPadWidth,rect_pad_height:t.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:n.x,y:n.y,layers:["top","bottom"],subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((x=this.getGroup())==null?void 0:x.pcb_group_id)??void 0});this.pcb_plated_hole_id=O.pcb_plated_hole_id}else if(t.shape==="pill_hole_with_rect_pad"){const O=e.pcb_plated_hole.insert({pcb_component_id:i,pcb_port_id:(Q=this.matchedPort)==null?void 0:Q.pcb_port_id,hole_width:t.holeWidth,hole_height:t.holeHeight,rect_pad_width:t.rectPadWidth,rect_pad_height:t.rectPadHeight,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:n.x,y:n.y,layers:["top","bottom"],subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((P=this.getGroup())==null?void 0:P.pcb_group_id)??void 0});this.pcb_plated_hole_id=O.pcb_plated_hole_id}}doInitialPcbPortAttachment(){var t,n;if((t=this.root)!=null&&t.pcbDisabled)return;const{db:e}=this.root;e.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:(n=this.matchedPort)==null?void 0:n.pcb_port_id})}},ose=class extends $v{constructor(){super(...arguments);Le(this,"pcb_keepout_id",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:l8e}}doInitialPcbPrimitiveRender(){var l,c,u;if((l=this.root)!=null&&l.pcbDisabled)return;const e=this.getSubcircuit(),{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),o=IQ(this._computePcbGlobalTransformBeforeLayout()),a=Math.abs(o.rotation.angle*(180/Math.PI)-90)%180<.01;let s=null;n.shape==="circle"?s=t.pcb_keepout.insert({layers:["top"],shape:"circle",radius:n.radius,center:{x:i.x,y:i.y},subcircuit_id:(e==null?void 0:e.subcircuit_id)??void 0,pcb_group_id:((c=e==null?void 0:e.getGroup())==null?void 0:c.pcb_group_id)??void 0}):n.shape==="rect"&&(s=t.pcb_keepout.insert({layers:["top"],shape:"rect",...a?{width:n.height,height:n.width}:{width:n.width,height:n.height},center:{x:i.x,y:i.y},subcircuit_id:(e==null?void 0:e.subcircuit_id)??void 0,pcb_group_id:((u=e==null?void 0:e.getGroup())==null?void 0:u.pcb_group_id)??void 0})),s&&(this.pcb_keepout_id=s.pcb_keepout_id)}},cLe=class extends $v{constructor(){super(...arguments);Le(this,"pcb_hole_id",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:VPe}}getPcbSize(){const{_parsedProps:e}=this;return{width:e.diameter,height:e.diameter}}doInitialPcbPrimitiveRender(){var a,s;if((a=this.root)!=null&&a.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getSubcircuit(),i=this._getGlobalPcbPositionBeforeLayout(),o=e.pcb_hole.insert({hole_shape:"circle",hole_diameter:t.diameter,x:i.x,y:i.y,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0,pcb_group_id:((s=n==null?void 0:n.getGroup())==null?void 0:s.pcb_group_id)??void 0});this.pcb_hole_id=o.pcb_hole_id}_getPcbCircuitJsonBounds(){const{db:e}=this.root,t=e.pcb_hole.get(this.pcb_hole_id),n=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-n.width/2,top:t.y-n.height/2,right:t.x+n.width/2,bottom:t.y+n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(e){const{db:t}=this.root;t.pcb_hole.update(this.pcb_hole_id,{x:e.x,y:e.y})}},ase=class extends $v{constructor(){super(...arguments);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:d8e}}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),a=this.getSubcircuit();e.pcb_silkscreen_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:i.x,y:i.y},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:o(t.layer??"top"),text:t.text??"",ccw_rotation:t.pcbRotation,pcb_component_id:n.pcb_component_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})}getPcbSize(){const{_parsedProps:e}=this,t=e.fontSize??1,i=(e.text??"").length*t,o=t;return{width:i*t,height:o*t}}},AVt=({elm:r,pinLabels:e,readableRotation:t,anchorAlignment:n})=>{var a;const i=r.text.replace(/[{}]/g,"").toLowerCase();let o=i;if(Array.isArray(e)){const s=parseInt(i.replace(/[^\d]/g,""),10)-1;o=e[s]??i}else typeof e=="object"&&(o=((a=e[i])==null?void 0:a[0])??i);return new ase({anchorAlignment:n||"center",text:o??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})},dVt=(r,e)=>((-parseInt(r||"0",10)+(e??0))%360+360)%360,uLe=({componentName:r,componentRotation:e,footprint:t,pinLabels:n},i)=>{const o=[];for(const a of i)if(a.type==="pcb_smtpad"&&a.shape==="rect")o.push(new rse({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"rect",height:a.height,width:a.width,portHints:a.port_hints}));else if(a.type==="pcb_smtpad"&&a.shape==="circle")o.push(new rse({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"circle",radius:a.radius,portHints:a.port_hints}));else if(a.type==="pcb_silkscreen_path")o.push(new sLe({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?o.push(new ise({pcbX:a.x,pcbY:a.y,shape:"circle",holeDiameter:a.hole_diameter,outerDiameter:a.outer_diameter,portHints:a.port_hints})):a.shape==="circular_hole_with_rect_pad"&&o.push(new ise({pcbX:a.x,pcbY:a.y,shape:"circular_hole_with_rect_pad",holeDiameter:a.hole_diameter,rectPadHeight:a.rect_pad_height,rectPadWidth:a.rect_pad_width,portHints:a.port_hints}));else if(a.type==="pcb_keepout"&&a.shape==="circle")o.push(new ose({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius}));else if(a.type==="pcb_keepout"&&a.shape==="rect")o.push(new ose({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height}));else if(a.type==="pcb_hole"&&a.hole_shape==="circle")o.push(new cLe({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_silkscreen_text"){const s=dVt(e,a.ccw_rotation);t.includes("pinrow")&&a.text.includes("PIN")?o.push(AVt({elm:a,pinLabels:n,readableRotation:s,anchorAlignment:a.anchor_alignment})):o.push(new ase({anchorAlignment:a.anchor_alignment||"center",text:r,fontSize:a.font_size+.2,pcbX:isNaN(a.anchor_position.x)?0:a.anchor_position.x,pcbY:a.anchor_position.y,pcbRotation:s??0}))}else a.type==="pcb_trace"&&o.push(new lLe({route:a.route}));return o};function sse(r){let e=1/0,t=1/0,n=-1/0,i=-1/0,o=!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),o=!0}else if(l.children.length>0){const c=sse(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),o=!0)}if(!o)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let a=n-e,s=i-t;return a<0&&(a=0),s<0&&(s=0),{minX:e,minY:t,maxX:n,maxY:i,width:a,height:s}}function fVt(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 hVt=r=>{if(r.length<=1)return!0;const e=r.map(o=>{const a=o._getPcbCircuitJsonBounds();return{left:a.bounds.left,right:a.bounds.right,top:a.bounds.top,bottom:a.bounds.bottom}}),t=Array(e.length).fill(!1).map(()=>Array(e.length).fill(!1));for(let o=0;o<e.length;o++)for(let a=o+1;a<e.length;a++){const s=e[o],l=e[a];t[o][a]=t[a][o]=!(s.right<l.left||s.left>l.right||s.bottom>l.top||s.top<l.bottom)}const n=new Set,i=o=>{n.add(o);for(let a=0;a<e.length;a++)t[o][a]&&!n.has(a)&&i(a)};return i(0),n.size===e.length},pVt=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,o)=>i+o.x,0),n=e.reduce((i,o)=>i+o.y,0);return{x:t/e.length,y:n/e.length}},gVt=In({name:Fe().optional(),pinNumber:ur().optional(),aliases:hi(Fe()).optional()}),r2=class extends $v{constructor(e,t={}){if(!e.name&&e.pinNumber!==void 0&&(e.name=`pin${e.pinNumber}`),!e.name)throw new Error("Port must have a name or a pinNumber");super(e);Le(this,"source_port_id",null);Le(this,"pcb_port_id",null);Le(this,"schematic_port_id",null);Le(this,"schematicSymbolPortDef",null);Le(this,"matchedComponents");Le(this,"facingDirection",null);Le(this,"originDescription",null);t.originDescription&&(this.originDescription=t.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:gVt}}_getGlobalPcbPositionBeforeLayout(){const e=this.matchedComponents.find(n=>n.isPcbPrimitive),t=this.parent;if(t&&!t.props.footprint)throw new Error(`${t.componentName} "${t.props.name}" does not have a footprint. Add a footprint prop, e.g. <${t.componentName.toLowerCase()} footprint="..." />`);if(!e)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return(e==null?void 0:e._getGlobalPcbPositionBeforeLayout())??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();const{db:e}=this.root,t=e.pcb_port.get(this.pcb_port_id);return{center:{x:t.x,y:t.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){const e=this.parent;if(!e||!e._getInternallyConnectedPins)return[];const t=e._getInternallyConnectedPins();for(const n of t)if(n.some(i=>i===this))return n;return[]}_hasSchematicPort(){var n,i;if((n=this.parent)==null?void 0:n.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(a=>a.schematicSymbolPortDef));const t=(i=this==null?void 0:this.parent)==null?void 0:i._getSchematicBoxDimensions();return!!(t&&this.props.pinNumber!==void 0&&t.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){var n,i,o;const e=(n=this.parent)==null?void 0:n.getSchematicSymbol();if(e){let a=this.schematicSymbolPortDef;if(!a&&(a=((i=this._getPortsInternallyConnectedToThisPort().find(l=>l.schematicSymbolPortDef))==null?void 0:i.schematicSymbolPortDef)??null,!a))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 s=Uc(this.parent.computeSchematicGlobalTransform(),JA(-e.center.x,-e.center.y));return ei(s,a)}const t=(o=this==null?void 0:this.parent)==null?void 0:o._getSchematicBoxDimensions();if(t&&this.props.pinNumber!==void 0){const a=t.getPortPositionByPinNumber(this.props.pinNumber);if(!a)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return ei(this.parent.computeSchematicGlobalTransform(),a)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){const{db:e}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);const t=e.schematic_port.get(this.schematic_port_id);if(!t)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return t.center}registerMatch(e){this.matchedComponents.push(e)}getNameAndAliases(){const{_parsedProps:e}=this;return Array.from(new Set([...e.aliases??[],...e.name?[e.name]:[],...typeof e.pinNumber=="number"?[`pin${e.pinNumber}`,e.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}isMatchingPort(e){return this.isMatchingAnyOf(e.getNameAndAliases())}getPortSelector(){var e;return`.${(e=this.parent)==null?void 0:e.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){return Array.from(new Set(this.matchedComponents.flatMap(e=>e.getAvailablePcbLayers())))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(n=>n._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){var o,a;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getNameAndAliases(),i=e.source_port.insert({name:t.name,pin_number:t.pinNumber,port_hints:n,source_component_id:(o=this.parent)==null?void 0:o.source_component_id,subcircuit_id:(a=this.getSubcircuit())==null?void 0:a.subcircuit_id});this.source_port_id=i.source_port_id}doInitialSourceParentAttachment(){var t,n,i,o,a;const{db:e}=this.root;if(!((t=this.parent)!=null&&t.source_component_id))throw new Error(`${this.getString()} has no parent source component (parent: ${(n=this.parent)==null?void 0:n.getString()})`);e.source_port.update(this.source_port_id,{source_component_id:(i=this.parent)==null?void 0:i.source_component_id,subcircuit_id:(o=this.getSubcircuit())==null?void 0:o.subcircuit_id}),this.source_component_id=(a=this.parent)==null?void 0:a.source_component_id}doInitialPcbPortRender(){var o,a,s,l,c;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{matchedComponents:t}=this;if(!((a=this.parent)!=null&&a.pcb_component_id))throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${(s=this.parent)==null?void 0:s.getString()})`);const n=t.filter(u=>u.isPcbPrimitive);if(n.length===0)return;let i=null;if(n.length===1&&(i=n[0]._getPcbCircuitJsonBounds().center),n.length>1){if(!hVt(n))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${n.map(u=>u.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)`);i=pVt(n)}if(i){const u=this.getSubcircuit(),A=e.pcb_port.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:(u==null?void 0:u.subcircuit_id)??void 0,pcb_group_id:((c=this.getGroup())==null?void 0:c.pcb_group_id)??void 0,...i,source_port_id:this.source_port_id});this.pcb_port_id=A.pcb_port_id}else{const u=n[0];throw new Error(`${u.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}doInitialSchematicPortRender(){var A;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer();if(!n||!this._hasSchematicPort())return;const i=n._getGlobalSchematicPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout();let a=null;const s=n._getSchematicBoxDimensions();s&&t.pinNumber!==void 0&&(a=s.getPortPositionByPinNumber(t.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&e.schematic_debug_object.insert({shape:"rect",center:o,size:{width:.1,height:.1},label:"obstacle"}),a!=null&&a.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[a.side]:this.facingDirection=fVt(i,o);const l=e.source_port.get(this.source_port_id);let c;for(const d of(l==null?void 0:l.port_hints)??[])d.match(/^(pin)?\d+$/)||d.match(/^(left|right)/)&&!(l!=null&&l.name.match(/^(left|right)/))||(c=d);const u=e.schematic_port.insert({schematic_component_id:(A=this.parent)==null?void 0:A.schematic_component_id,center:o,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:a==null?void 0:a.side,pin_number:t.pinNumber,true_ccw_index:a==null?void 0:a.trueIndex,display_pin_label:c});this.schematic_port_id=u.schematic_port_id}_setPositionFromLayout(e){const{db:t}=this.root;this.pcb_port_id&&t.pcb_port.update(this.pcb_port_id,{x:e.x,y:e.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(e=>e.isPcbPrimitive)}},ALe=r=>{const e=r.find(t=>/^(pin)?\d+$/.test(t));return e?Number.parseInt(e.replace(/^pin/,"")):null};function nT(r,e){var o;const t=ALe(r);if(!t)return null;const i=[...r.filter(a=>a.toString()!==t.toString()&&a!==`pin${t}`),...((o=e==null?void 0:e.additionalAliases)==null?void 0:o[`pin${t}`])??[]];return new r2({pinNumber:t,aliases:i})}var mVt=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},yVt=r=>{var o,a,s,l;if(mVt(r))return{leftSize:((o=r.leftSide)==null?void 0:o.pins.length)??0,rightSize:((a=r.rightSide)==null?void 0:a.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 dLe(r){return r.leftSide!==void 0}var vVt=r=>{var E,_,x,Q,P,O,z,Y;const e=r.portDistanceFromEdge??.4;let t=r.schPortArrangement?yVt(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 V=Math.floor(i/2);t={leftSize:i-V,rightSize:V,topSize:0,bottomSize:0}}t||(t={leftSize:0,rightSize:0,topSize:0,bottomSize:0});const o=({side:V,sideIndex:Z,truePinIndex:J})=>{var xe,fe,Ee,Ie;if(!r.schPortArrangement||!dLe(r.schPortArrangement))return J+1;const se={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[V],ae=((fe=(xe=r.schPortArrangement)==null?void 0:xe[`${V}Side`])==null?void 0:fe.direction)??se,ue=(Ie=(Ee=r.schPortArrangement)==null?void 0:Ee[`${V}Side`])==null?void 0:Ie.pins;let ve=Z;return ae!==se&&(ve=ue.length-Z-1),tT(ue[ve],r.pinLabels)},a=[];let s=0,l=0;for(let V=0;V<t.leftSize;V++){const Z=o({side:"left",sideIndex:V,truePinIndex:l}),J=((E=r.numericSchPinStyle)==null?void 0:E[`pin${Z}`])??((_=r.numericSchPinStyle)==null?void 0:_[Z]);J!=null&&J.topMargin&&(s+=J.topMargin),a.push({trueIndex:l,pinNumber:Z,side:"left",distanceFromOrthogonalEdge:s}),J!=null&&J.bottomMargin&&(s+=J.bottomMargin),V===t.leftSize-1?n.left=s:s+=r.schPinSpacing,l++}s=0;for(let V=0;V<t.bottomSize;V++){const Z=o({side:"bottom",sideIndex:V,truePinIndex:l}),J=((x=r.numericSchPinStyle)==null?void 0:x[`pin${Z}`])??((Q=r.numericSchPinStyle)==null?void 0:Q[Z]);J!=null&&J.leftMargin&&(s+=J.leftMargin),a.push({trueIndex:l,pinNumber:Z,side:"bottom",distanceFromOrthogonalEdge:s}),J!=null&&J.rightMargin&&(s+=J.rightMargin),V===t.bottomSize-1?n.bottom=s:s+=r.schPinSpacing,l++}s=0;for(let V=0;V<t.rightSize;V++){const Z=o({side:"right",sideIndex:V,truePinIndex:l}),J=((P=r.numericSchPinStyle)==null?void 0:P[`pin${Z}`])??((O=r.numericSchPinStyle)==null?void 0:O[Z]);J!=null&&J.bottomMargin&&(s+=J.bottomMargin),a.push({trueIndex:l,pinNumber:Z,side:"right",distanceFromOrthogonalEdge:s}),J!=null&&J.topMargin&&(s+=J.topMargin),V===t.rightSize-1?n.right=s:s+=r.schPinSpacing,l++}s=0;for(let V=0;V<t.topSize;V++){const Z=o({side:"top",sideIndex:V,truePinIndex:l}),J=((z=r.numericSchPinStyle)==null?void 0:z[`pin${Z}`])??((Y=r.numericSchPinStyle)==null?void 0:Y[Z]);J!=null&&J.rightMargin&&(s+=J.rightMargin),a.push({trueIndex:l,pinNumber:Z,side:"top",distanceFromOrthogonalEdge:s}),J!=null&&J.leftMargin&&(s+=J.leftMargin),V===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(V=>V.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 h={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}},m={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},C=a.map(V=>{const{distanceFromOrthogonalEdge:Z,side:J}=V,se=h[J],ae=m[J];return{x:se.x+Z*ae.x,y:se.y+Z*ae.y,...V}});return{getPortPositionByPinNumber(V){const Z=C.find(J=>J.pinNumber.toString()===V.toString());return Z||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}},IVt=Rm("tscircuit:core:footprint"),CVt=class extends $v{get config(){return{componentName:"Footprint",zodProps:JPe}}doInitialPcbFootprintLayout(){var A,d,h,m,C;if((A=this.root)!=null&&A.pcbDisabled)return;const r=this.children.filter(E=>E.componentName==="Constraint");if(r.length===0)return;const{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers(),t=E=>e&&"left"in E&&"right"in E?{...E,left:E.right,right:E.left}:E,n=r.flatMap(E=>E._getAllReferencedComponents().componentsWithSelectors).map(({component:E,selector:_,componentSelector:x,edge:Q})=>({component:E,selector:_,componentSelector:x,edge:Q,bounds:E._getPcbCircuitJsonBounds()}));if(n.some(E=>E.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function i(E){return n.find(({selector:_})=>_===E)}const o=new aY,a={};function s(E){return E in a||(a[E]=new BR(E),o.addEditVariable(a[E],ay.weak)),a[E]}for(const{selector:E,bounds:_}of n){const x=s(`${E}_x`),Q=s(`${E}_y`);o.suggestValue(x,_.center.x),o.suggestValue(Q,_.center.y)}for(const E of r){const _=E._parsedProps;if("xDist"in _){const{xDist:x,left:Q,right:P,edgeToEdge:O,centerToCenter:z}=t(_),Y=s(`${Q}_x`),V=s(`${P}_x`),Z=(d=i(Q))==null?void 0:d.bounds,J=(h=i(P))==null?void 0:h.bounds;if(z){const se=new Nm(V,[-1,Y]);o.addConstraint(new _1(se,mI.Eq,_.xDist,ay.required))}else if(O){const se=new Nm(V,-J.width/2,[-1,Y],-Z.width/2);o.addConstraint(new _1(se,mI.Eq,_.xDist,ay.required))}}else if("yDist"in _){const{yDist:x,top:Q,bottom:P,edgeToEdge:O,centerToCenter:z}=_,Y=s(`${Q}_y`),V=s(`${P}_y`),Z=(m=i(Q))==null?void 0:m.bounds,J=(C=i(P))==null?void 0:C.bounds;if(z){const se=new Nm(Y,[-1,V]);o.addConstraint(new _1(se,mI.Eq,_.yDist,ay.required))}else if(O){const se=new Nm(Y,Z.height/2,[-1,V],-J.height/2);o.addConstraint(new _1(se,mI.Eq,_.yDist,ay.required))}}else if("sameY"in _){const{for:x}=_;if(x.length<2)continue;const Q=x.map(O=>s(`${O}_y`)),P=new Nm(...Q.slice(1));o.addConstraint(new _1(P,mI.Eq,Q[0],ay.required))}else if("sameX"in _){const{for:x}=_;if(x.length<2)continue;const Q=x.map(O=>s(`${O}_x`)),P=new Nm(...Q.slice(1));o.addConstraint(new _1(P,mI.Eq,Q[0],ay.required))}}o.updateVariables(),IVt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(a).map(([E,_])=>({var:E,val:_.value()}))));const l={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(const{selector:E,bounds:{width:_,height:x}}of n){const Q=s(`${E}_x`),P=s(`${E}_y`),O=Q.value()-_/2,z=Q.value()+_/2,Y=P.value()+x/2,V=P.value()-x/2;l.left=Math.min(l.left,O),l.right=Math.max(l.right,z),l.top=Math.max(l.top,Y),l.bottom=Math.min(l.bottom,V)}const c={x:-(l.right+l.left)/2,y:-(l.top+l.bottom)/2},u=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();c.x+=u.x,c.y+=u.y;for(const{component:E,selector:_}of n){const x=s(`${_}_x`),Q=s(`${_}_y`);E._setPositionFromLayout({x:x.value()+c.x,y:Q.value()+c.y})}}},EVt=(r,e)=>{if(!r)return;const t={};for(const[n,i]of Object.entries(r)){const o=tT(n,e),a={leftMargin:i.marginLeft??i.leftMargin,rightMargin:i.marginRight??i.rightMargin,topMargin:i.marginTop??i.topMargin,bottomMargin:i.marginBottom??i.bottomMargin};t[`pin${o}`]={...t[`pin${o}`],...a}}return t},fLe=class{constructor({input:r}){Le(this,"input");this.input=r}solveAndMapToTraces(){const r=[];for(const e of this.input.connections){if(e.pointsToConnect.length!==2)continue;const[t,n]=e.pointsToConnect,i={type:"pcb_trace",pcb_trace_id:"",connection_name:e.name,route:[{route_type:"wire",x:t.x,y:t.y,layer:"top",width:.1},{route_type:"wire",x:n.x,y:n.y,layer:"top",width:.1}]};r.push(i)}return r}},_Vt=r=>{const e=Math.min(...r.map(o=>o.center.x)),t=Math.max(...r.map(o=>o.center.x)),n=Math.min(...r.map(o=>o.center.y)),i=Math.max(...r.map(o=>o.center.y));return{minX:e,maxX:t,minY:n,maxY:i}},hLe=["top","bottom","inner1","inner2"],n6=(r,e=[])=>{var s;const t=[];if(e.length===0){const l=r[0].layers;for(const c of l)t.push(...n6(r.slice(1),[c]));return t}if(r.length===0)return[];const n=r[0],i=n.via||n.optional_via,o=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(o)?[{layer_path:[...e,o]}]:[]}if(!i)return n.layers&&!n.layers.includes(o)?[]:n6(r.slice(1),e.concat([o]));const a=(n.optional_via?hLe:hLe.filter(l=>l!==o)).filter(l=>{var c;return!n.layers||((c=n.layers)==null?void 0:c.includes(l))});for(const l of a)t.push(...n6(r.slice(1),e.concat(l)));return t};function pLe(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 FD(r,e){return Math.hypot(r.x-e.x,r.y-e.y)}var xVt=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],o=r[1][r[1].length-1],a=Math.min(FD(t,i),FD(t,o)),s=Math.min(FD(n,i),FD(n,o));a<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],h=FD(c,A),m=FD(c,d);h<m?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},BVt=(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 bVt(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 o=BVt(r,i);o<n&&(t=i,n=o)}return t}var SVt=(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],o=e[n],a=Math.abs(i.from.x-i.to.x)<.01,s=Math.abs(o.from.x-o.to.x)<.01;a!==s&&t++}return t},lse=r=>({up:"bottom",down:"top",left:"right",right:"left"})[r]??null,cse=({firstEdge:r,firstEdgePort:e,firstDominantDirection:t,lastEdge:n,lastEdgePort:i,lastDominantDirection:o})=>{if(r&&e)return cse({lastEdge:{from:r.to,to:r.from},lastEdgePort:e,lastDominantDirection:t}).reverse().map(s=>({from:s.to,to:s.from}));let a=[];if(n&&i){const s={x:n.to.x,y:n.to.y};o==="left"||o==="right"?(s.x=i.position.x,a.push({from:n.to,to:{...s}}),a.push({from:s,to:{...i.position}})):(s.y=i.position.y,a.push({from:n.to,to:{...s}}),a.push({from:s,to:{...i.position}}))}return a=a.filter(s=>ix(s.from,s.to)>.01),a};function QVt(r){try{return[r(),null]}catch(e){return[null,e]}}function wVt(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 o=i.x-n.x,a=i.y-n.y;e+=Math.sqrt(o*o+a*a)}}else n.route_type==="via"&&(e+=1.6)}return e}var MVt=r=>{var s,l;const e={left:{x:-.5,y:0},up:{x:.5,y:.5},right:{x:.5,y:0},down:{x:0,y:-.5}}[r.facingDirection],t=(s=r.parent)!=null&&s.config.shouldRenderAsSchematicBox?3:1,n=(l=r.parent)!=null&&l.config.shouldRenderAsSchematicBox&&(r.facingDirection==="left"||r.facingDirection==="right")?3:1,i=e.x,o=e.y,a=r.facingDirection==="up"?.5:0;return{schBoxVertOffset:t,schBoxHorzOffset:n,horzPortDirection:i,vertPortDirectionOffset:o,handleUp:a}},r6=({port:r,anchorPos:e,schDisplayLabel:t,source_trace_id:n},{db:i})=>{const o=MVt(r),a=r.facingDirection==="left"||r.facingDirection==="right",s={x:e.x+o.horzPortDirection*o.schBoxHorzOffset,y:e.y+o.vertPortDirectionOffset*o.schBoxVertOffset},l=a?{x:s.x,y:s.y-.5}:s;i.schematic_net_label.insert({anchor_side:"top",center:l,source_net_id:r.source_port_id,text:t,anchor_position:l,symbol_name:"ground_horz"});const c=[{from:{x:e.x,y:e.y},to:{x:e.x,y:e.y+o.handleUp*o.schBoxVertOffset}},{from:{x:e.x,y:e.y},to:s}];a&&c.push({from:s,to:l}),i.schematic_trace.insert({edges:c,junctions:[],source_trace_id:n})},i6=({db:r,source_trace_id:e,sameNetOnly:t,differentNetOnly:n})=>{!t&&!n&&(n=!0);const i=r.source_trace.get(e),o=[];for(const a of r.schematic_trace.list()){if(a.source_trace_id===e)continue;const s=r.source_trace.get(a.source_trace_id),l=(s==null?void 0:s.subcircuit_connectivity_map_key)===i.subcircuit_connectivity_map_key;n&&l||t&&!l||o.push(a)}return o},gLe=({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],o=Math.abs(i.from.x-i.to.x)<.01?"vertical":i.from.y===i.to.y?"horizontal":"not-orthogonal";if(o==="not-orthogonal")continue;const a=[];for(const C of e){const E=C.from.x===C.to.x?"vertical":C.from.y===C.to.y?"horizontal":"not-orthogonal";if(E==="not-orthogonal"||o===E)continue;if(F9([i.from,i.to],[C.from,C.to],{lineThickness:.01})){const x=o==="vertical"?i.from.x:C.from.x,Q=o==="vertical"?C.from.y:i.from.y,P={x,y:Q};a.push({otherEdge:C,crossingPoint:P,distanceFromEdgeFrom:ix(i.from,P)})}}if(a.length===0)continue;let s=a[0];for(const C of a)C.distanceFromEdgeFrom<s.distanceFromEdgeFrom&&(s=C);const l=s.crossingPoint,c=.075;if(l.x===i.from.x&&l.y===i.from.y)continue;const u=sY(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},h=ix(d,i.to)<c,m=[{from:i.from,to:A},{from:A,to:d,is_crossing:!0},{from:d,to:i.to}];t.splice(n,1,...m),n+=m.length-2,h&&n++}return t},DVt=(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,h=A*u+d;return u>=Math.min(e.from.x,e.to.x)&&u<=Math.max(e.from.x,e.to.x)&&h>=Math.min(e.from.y,e.to.y)&&h<=Math.max(e.from.y,e.to.y)?{x:u,y:h}: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,h=A*u+d;return u>=Math.min(r.from.x,r.to.x)&&u<=Math.max(r.from.x,r.to.x)&&h>=Math.min(r.from.y,r.to.y)&&h<=Math.max(r.from.y,r.to.y)?{x:u,y:h}: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),o=e.from.y-i*e.from.x;if(t===i)return null;const a=(o-n)/(t-i),s=t*a+n,l=a>=Math.min(r.from.x,r.to.x)&&a<=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=a>=Math.min(e.from.x,e.to.x)&&a<=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:a,y:s}:null},mLe=({edges:r,db:e,source_trace_id:t})=>{const n=i6({db:e,source_trace_id:t,sameNetOnly:!0}).flatMap(i=>i.edges);for(const i of r)for(const o of n){const a=DVt(i,o);if(a)return`${a.x}${a.y}`,[{x:a.x,y:a.y}]}return[]},RVt=(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 o=e.source_component.get(i.source_component_id);return(o==null?void 0:o.ftype)==="simple_capacitor"?o.max_decoupling_trace_length:null}).filter(n=>n!==null);if(t.length!==0)return Math.min(...t)};function NVt(r){var o,a,s,l,c,u,A,d,h;let e=1/0,t=1/0,n=-1/0,i=-1/0;for(const m of r){let C,E,_,x;m.type==="schematic_component"?(C=(o=m.center)==null?void 0:o.x,E=(a=m.center)==null?void 0:a.y,_=(s=m.size)==null?void 0:s.width,x=(l=m.size)==null?void 0:l.height):m.type==="schematic_box"?(C=m.x,E=m.y,_=m.width,x=m.height):m.type==="schematic_port"?(C=(c=m.center)==null?void 0:c.x,E=(u=m.center)==null?void 0:u.y,_=.2,x=.2):m.type==="schematic_text"&&(C=(A=m.position)==null?void 0:A.x,E=(d=m.position)==null?void 0:d.y,_=(((h=m.text)==null?void 0:h.length)??0)*.1,x=.2),typeof C=="number"&&typeof E=="number"&&typeof _=="number"&&typeof x=="number"&&(e=Math.min(e,C-_/2),n=Math.max(n,C+_/2),t=Math.min(t,E-x/2),i=Math.max(i,E+x/2))}return{minX:e,maxX:n,minY:t,maxY:i}}function TVt(r,e={}){const{minX:t,maxX:n,minY:i,maxY:o}=r,a=e.padding??1;if(!isFinite(t)||!isFinite(n)||!isFinite(i)||!isFinite(o))return[];const s=t-a,l=n+a,c=o+a,u=i-a,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 PVt=r=>{var a;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?lY(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:(((a=s.text)==null?void 0:a.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 o=NVt(e.toArray());return i.push(...TVt(o,{padding:1})),i};function UVt({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 FVt=({edges:r,db:e,source_trace_id:t})=>{e.source_trace.get(t);const n=i6({db:e,source_trace_id:t,differentNetOnly:!0}).flatMap(o=>o.edges),i=o=>{const{from:a,to:s}=o;return a.x===s.x?"vertical":"horizontal"};for(const o of r){const a=i(o),s=()=>n.find(c=>i(c)===a&&F9([o.from,o.to],[c.from,c.to],{lineThickness:.05}));let l=s();for(;l;)a==="horizontal"?(o.from.y+=.1,o.to.y+=.1):(o.from.x+=.1,o.to.x+=.1),l=s()}},kVt=(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 h=0,m=A.length-1;h<A.length;m=h++){const C=A[h].x,E=A[h].y,_=A[m].x,x=A[m].y;E>u.y!=x>u.y&&u.x<(_-C)*(u.y-E)/(x-E)+C&&(d=!d)}return d};return r.some(u=>!c(u,l))}const n=t.width,i=t.height,o=t.center.x,a=t.center.y;return r.some(l=>l.x<o-n/2||l.y<a-i/2||l.x>o+n/2||l.y>a+i/2)},o6=r=>({...r._getGlobalPcbPositionAfterLayout(),layers:r.getAvailablePcbLayers()}),i9=class extends $v{constructor(e){super(e);Le(this,"source_trace_id",null);Le(this,"pcb_trace_id",null);Le(this,"schematic_trace_id",null);Le(this,"_portsRoutedOnPcb");Le(this,"subcircuit_connectivity_map_key",null);Le(this,"_traceConnectionHash",null);this._portsRoutedOnPcb=[]}get config(){return{zodProps:jPe,componentName:"Trace"}}_getTracePortOrNetSelectorListFromProps(){return"from"in this.props&&"to"in this.props?[typeof this.props.from=="string"?this.props.from:this.props.from.getPortSelector(),typeof this.props.to=="string"?this.props.to:this.props.to.getPortSelector()]:"path"in this.props?this.props.path.map(e=>typeof e=="string"?e:e.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>!e.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>e.includes("net."))}_findConnectedPorts(){const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)throw new Error("Trace has no parent");const o=this.getTracePortPathSelectors().map(a=>({selector:a,port:this.getSubcircuit().selectOne(a,{type:"port"})??null}));for(const{selector:a,port:s}of o)if(!s){const l=a.replace(/(\> )?[^ ]+$/,""),c=this.getSubcircuit().selectOne(l);c?this.renderError(`Could not find port for selector "${a}" (did you forget to include the pin name?)
13468
- searched component ${c.getString()}, which has ports: ${c.children.filter(u=>u.componentName==="Port").map(u=>`${u.getString()}(${u.getNameAndAliases().join(",")})`).join(" & ")}`):this.renderError(`Could not find port for selector "${a}"`)}return o.some(a=>!a.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:o,ports:o.map(({port:a})=>a)}}_findConnectedNets(){const e=this.getTracePathNetSelectors().map(n=>({selector:n,net:this.getSubcircuit().selectOne(n,{type:"net"})})),t=e.filter(n=>!n.net);return t.length>0&&this.renderError(`Could not find net for selector "${t[0].selector}" inside ${this}`),{netsWithSelectors:e,nets:e.map(n=>n.net)}}_getAllTracesConnectedToSameNet(){const e=this.getSubcircuit().selectAll("trace"),t=this._findConnectedNets().nets,n=this._findConnectedPorts().ports??[];return e.filter(i=>{if(i===this)return!1;const o=i._findConnectedNets().nets,a=i._findConnectedPorts().ports??[];return o.some(s=>t.includes(s))||a.some(s=>n.includes(s))})}_isExplicitlyConnectedToPort(e){const{allPortsFound:t,portsWithSelectors:n}=this._findConnectedPorts();return t?n.map(o=>o.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){aLe(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();return!e||!t?null:[...t].sort((o,a)=>(o.pcb_port_id||"").localeCompare(a.pcb_port_id||"")).map(o=>o.pcb_port_id).join(",")}doInitialSourceTraceRender(){var A;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n){this.renderError("Trace has no parent");return}const{allPortsFound:i,portsWithSelectors:o}=this._findConnectedPorts();if(!i)return;this._traceConnectionHash=this._computeTraceConnectionHash();const s=e.source_trace.list().find(d=>d.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&d.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(s){this.source_trace_id=s.source_trace_id;return}const l=this._findConnectedNets().nets,c=UVt({ports:o,nets:l}),u=e.source_trace.insert({connected_source_port_ids:o.map(d=>d.port.source_port_id),connected_source_net_ids:l.map(d=>d.source_net_id),subcircuit_id:(A=this.getSubcircuit())==null?void 0:A.subcircuit_id,max_length:RVt(o.map(d=>d.port),{db:e})??t.maxLength,display_name:c,min_trace_thickness:t.thickness});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(e,t){const{db:n}=this.root;kVt(e,{db:n})&&n.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:t.map(o=>o.pcb_port_id)})}doInitialPcbTraceRender(){var V,Z,J,se;if((V=this.root)!=null&&V.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this,i=this.getSubcircuit();if(!n)throw new Error("Trace has no parent");if(i._parsedProps.routingDisabled)return;const o=(Z=i._parsedProps.pcbRouteCache)==null?void 0:Z.pcbTraces;if(o){const ae=e.pcb_trace.insert({route:o.flatMap(ue=>ue.route),source_trace_id:this.source_trace_id,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((J=this.getGroup())==null?void 0:J.pcb_group_id)??void 0});this.pcb_trace_id=ae.pcb_trace_id;return}if(!i._shouldUseTraceByTraceRouting())return;const{allPortsFound:a,ports:s}=this._findConnectedPorts();if(!a)return;const l=[];for(const ae of s)ae._hasMatchedPcbPrimitive()||l.push(ae);if(l.length>0){e.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: ${l.map(ae=>ae.getString()).join(", ")}`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(ae=>ae.pcb_port_id).filter(Boolean)});return}const c=this._findConnectedNets().netsWithSelectors;if(s.length===0&&c.length===2){this.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(s.length===1&&c.length===1){const ae=s[0],ve=c[0].net.getAllConnectedPorts().filter(fe=>fe!==ae);if(ve.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}const xe=bVt(ae,ve);s.push(xe)}else if(s.length>1&&c.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 u=s.flatMap(ae=>ae.matchedComponents.filter(ue=>ue.componentName==="TraceHint")),A=(this._parsedProps.pcbRouteHints??[]).concat(u.flatMap(ae=>ae.getPcbRouteHints()));if(s.length>2){this.renderError(`Trace has more than two ports (${s.map(ae=>ae.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(this.getSubcircuit().selectAll("trace").filter(ae=>ae.renderPhaseStates.PcbTraceRender.initialized).some(ae=>ae._portsRoutedOnPcb.length===s.length&&ae._portsRoutedOnPcb.every(ue=>s.includes(ue))))return;let m=[];A.length===0?m=[o6(s[0]),o6(s[1])]:m=[o6(s[0]),...A,o6(s[1])];const C=n6(m),E=WB(this.root.db.toArray()),[_,x]=QVt(()=>P9(this.root.db.toArray()));if(x){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: ${x.message}`,source_trace_id:this.source_trace_id,center:{x:0,y:0},pcb_port_ids:s.map(ae=>ae.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[]});return}for(const ae of _)if(ae.connectedTo.length>0){const ve=E.getNetConnectedToId(ae.connectedTo[0]);ve&&ae.connectedTo.push(ve)}let Q=[];if(C.length===0)Q=m;else{const ae=C[0].layer_path;Q=m.map((ue,ve)=>ue.via?{...ue,via_to_layer:ae[ve]}:{...ue,layers:[ae[ve]]})}Q[0].pcb_port_id=s[0].pcb_port_id,Q[Q.length-1].pcb_port_id=s[1].pcb_port_id;const P=[];for(const[ae,ue]of iLe(Q)){const ve="via_to_layer"in ae?ae.via_to_layer:null,xe=2,fe="layers"in ae&&ae.layers.length===1?ae.layers[0]:ve??"top",Ee="layers"in ue&&ue.layers.length===1?ue.layers[0]:ve??"top",Ie="pcb_port_id"in ae?ae.pcb_port_id:null,Qe="pcb_port_id"in ue?ue.pcb_port_id:null,Me=this.getSubcircuit()._parsedProps.minTraceWidth??.16,ke=new T9({OBSTACLE_MARGIN:Me*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(Ie&&Qe),connMap:E,input:{obstacles:_,minTraceWidth:Me,connections:[{name:this.source_trace_id,pointsToConnect:[{...ae,layer:fe,pcb_port_id:Ie},{...ue,layer:Ee,pcb_port_id:Qe}]}],layerCount:2,bounds:{minX:Math.min(ae.x,ue.x)-xe,maxX:Math.max(ae.x,ue.x)+xe,minY:Math.min(ae.y,ue.y)-xe,maxY:Math.max(ae.y,ue.y)+xe}}});let Ue=null;try{Ue=ke.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:(ae.x+ue.x)/2,y:(ae.y+ue.y)/2},pcb_port_ids:s.map(Et=>Et.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:s.map(Et=>Et.pcb_component_id)})}if(!Ue)return;if(Ue.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:(ae.x+ue.x)/2,y:(ae.y+ue.y)/2},pcb_port_ids:s.map(ht=>ht.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:s.map(ht=>ht.pcb_component_id)});return}const[it]=Ue;ve&&(it.route=it.route.map(ht=>(ht.route_type==="wire"&&!ht.layer&&(ht.layer=ve),ht))),Ie&&it.route[0].route_type==="wire"&&(it.route[0].start_pcb_port_id=Ie);const nt=it.route[it.route.length-1];Qe&&nt.route_type==="wire"&&(nt.end_pcb_port_id=Qe),P.push(it.route)}const O=xVt(P),z=wVt(O),Y=e.pcb_trace.insert({route:O,source_trace_id:this.source_trace_id,subcircuit_id:(se=this.getSubcircuit())==null?void 0:se.subcircuit_id,trace_length:z});this._portsRoutedOnPcb=s,this.pcb_trace_id=Y.pcb_trace_id;for(const ae of O)ae.route_type==="via"&&e.pcb_via.insert({pcb_trace_id:Y.pcb_trace_id,x:ae.x,y:ae.y,hole_diameter:.3,outer_diameter:.6,layers:[ae.from_layer,ae.to_layer],from_layer:ae.from_layer,to_layer:ae.to_layer});this._insertErrorIfTraceIsOutsideBoard(O,s)}_doInitialSchematicTraceRenderWithDisplayLabel(){var P,O,z,Y;if((P=this.root)!=null&&P.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)throw new Error("Trace has no parent");const{allPortsFound:i,portsWithSelectors:o}=this._findConnectedPorts();if(!i)return;const a=o.map(({port:V})=>({port:V,position:V._getGlobalSchematicPositionAfterLayout(),schematic_port_id:V.schematic_port_id,facingDirection:V.facingDirection}));if(a.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let s,l;const c=a[0].position,u=a[0].port;if("path"in this.props){if(this.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[s,l]=this.props.path}else{if(!("from"in this.props&&"to"in this.props))throw new Error("Missing 'from' or 'to' properties in props.");s=this.props.from,l=this.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${s}).`);const A=a[1].position,d=a[1].port;if(!d.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${l}).`);const h=e.schematic_net_label.list().find(V=>V.source_net_id===u.source_port_id),m=e.schematic_net_label.list().find(V=>V.source_net_id===d.source_port_id),[C,E]=o.map(({port:V})=>V),x=((O=C.parent)==null?void 0:O.config.shouldRenderAsSchematicBox)?`${(z=C==null?void 0:C.parent)==null?void 0:z.props.name}_${C==null?void 0:C.props.name}`:`${(Y=E==null?void 0:E.parent)==null?void 0:Y.props.name}_${E==null?void 0:E.props.name}`,Q=this.props.schDisplayLabel??x;if(h&&h.text!==Q&&(h.text=`${Q} / ${h.text}`),m&&(m==null?void 0:m.text)!==Q&&(m.text=`${Q} / ${m.text}`),Q!=null&&Q.toLocaleLowerCase().includes("gnd")||Q!=null&&Q.toLocaleLowerCase().includes("ground")){!h&&!m?(r6({port:u,anchorPos:c,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e}),r6({port:d,anchorPos:A,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e})):h?m||r6({port:d,anchorPos:A,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e}):r6({port:u,anchorPos:c,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e});return}m||e.schematic_net_label.insert({text:this.props.schDisplayLabel??x,source_net_id:d.source_port_id,anchor_position:A,center:A,anchor_side:lse(d.facingDirection)??"bottom"}),h||e.schematic_net_label.insert({text:this.props.schDisplayLabel??x,source_net_id:u.source_port_id,anchor_position:c,center:c,anchor_side:lse(u.facingDirection)??"bottom"})}_isSymbolToChipConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const o=n.parent.config.shouldRenderAsSchematicBox,a=i.parent.config.shouldRenderAsSchematicBox;return o&&!a||!o&&a}_isSymbolToSymbolConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const o=!n.parent.config.shouldRenderAsSchematicBox,a=!i.parent.config.shouldRenderAsSchematicBox;return o&&a}_isChipToChipConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const o=n.parent.config.shouldRenderAsSchematicBox,a=i.parent.config.shouldRenderAsSchematicBox;return o&&a}doInitialSchematicTraceRender(){var fe,Ee,Ie;if((fe=this.root)!=null&&fe.schematicDisabled||((Ee=this.getGroup())==null?void 0:Ee._getSchematicLayoutMode())==="match-adapt")return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)throw new Error("Trace has no parent");const{allPortsFound:i,portsWithSelectors:o}=this._findConnectedPorts(),{netsWithSelectors:a}=this._findConnectedNets();if(!i)return;const l=o.map(Qe=>Qe.port.schematic_port_id).sort().join(","),c=(Ie=this.root)==null?void 0:Ie._getBoard();if(c!=null&&c._connectedSchematicPortPairs&&c._connectedSchematicPortPairs.has(l))return;if(this.props.schDisplayLabel&&("from"in this.props&&"to"in this.props||"path"in this.props)){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const u={name:this.source_trace_id,pointsToConnect:[]},A=PVt(this),d=o.map(({port:Qe})=>({port:Qe,position:Qe._getGlobalSchematicPositionAfterLayout(),schematic_port_id:Qe.schematic_port_id??void 0,facingDirection:Qe.facingDirection}));if(d.length===1&&a.length===1){const Qe=a[0].net,{port:Me,position:ke}=d[0];e.schematic_net_label.insert({text:Qe._parsedProps.name,source_net_id:Qe.source_net_id,anchor_position:ke,center:ke,anchor_side:lse(Me.facingDirection)??"bottom"});return}if(d.length<2)return;u.pointsToConnect=d.map(({position:Qe})=>({...Qe,layer:"top"}));const m=_Vt(A),C=2,E={minTraceWidth:.1,obstacles:A,connections:[u],bounds:{minX:m.minX-C,maxX:m.maxX+C,minY:m.minY-C,maxY:m.maxY+C},layerCount:1};let _=T9,x=!1;this.getSubcircuit().props._schDirectLineRoutingEnabled&&(_=fLe,x=!0);let P=new _({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(P.length===0){if(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection()){this._doInitialSchematicTraceRenderWithDisplayLabel();return}P=new fLe({input:E}).solveAndMapToTraces(),x=!0}const[{route:O}]=P;let z=[];for(let Qe=0;Qe<O.length-1;Qe++)z.push({from:O[Qe],to:O[Qe+1]});const Y=this.source_trace_id;let V=[];if(!x){FVt({edges:z,db:e,source_trace_id:Y});const Qe=i6({db:e,source_trace_id:Y,differentNetOnly:!0}).flatMap(Me=>Me.edges);z=gLe({edges:z,otherEdges:Qe}),V=mLe({edges:z,db:e,source_trace_id:this.source_trace_id})}const Z=z[z.length-1],J=d[d.length-1],se=pLe(Z);z.push(...cse({lastEdge:Z,lastEdgePort:J,lastDominantDirection:se}));const ae=z[0],ue=d[0],ve=pLe(ae);if(z.unshift(...cse({firstEdge:ae,firstEdgePort:ue,firstDominantDirection:ve})),!this.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(this.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&SVt(V,z)>=5&&(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection())){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const xe=e.schematic_trace.insert({source_trace_id:this.source_trace_id,edges:z,junctions:V});this.schematic_trace_id=xe.schematic_trace_id,c!=null&&c._connectedSchematicPortPairs&&c._connectedSchematicPortPairs.add(l)}},LVt=Rm("tscircuit:core"),GVt=In({x:xC,y:xC,z:xC}),N1=class extends $v{constructor(e){super(e);Le(this,"reactSubtrees",[]);Le(this,"_impliedFootprint");Le(this,"isPrimitiveContainer",!0);Le(this,"_asyncSupplierPartNumbers");Le(this,"pcb_missing_footprint_error_id");Le(this,"_hasStartedFootprintUrlLoad",!1);this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames}initPorts(e={}){var a,s,l,c,u,A,d,h,m,C;if((a=this.root)!=null&&a.schematicDisabled)return;const{config:t}=this,n=[],i=this._getSchematicPortArrangement();if(i&&!this._parsedProps.pinLabels){for(const x in i){const Q=i[x].pins;if(Array.isArray(Q))for(const P of Q){const O=tT(P,this._parsedProps.pinLabels);n.push(new r2({pinNumber:O,aliases:((s=e.additionalAliases)==null?void 0:s[`pin${O}`])??[]},{originDescription:`schPortArrangement:${x}`}))}}const E=["left","right","top","bottom"];let _=1;for(const x of E){const Q=i[`${x}Size`];for(let P=0;P<Q;P++)n.push(new r2({pinNumber:_++,aliases:((l=e.additionalAliases)==null?void 0:l[`pin${_}`])??[]},{originDescription:`schPortArrangement:${x}`}))}}const o=this._parsedProps.pinLabels;if(o)for(let[E,_]of Object.entries(o)){E=E.replace("pin","");let x=n.find(O=>O._parsedProps.pinNumber===Number(E));const Q=Array.isArray(_)?_[0]:_,P=Array.isArray(_)?_.slice(1):[];x?(x.externallyAddedAliases.push(Q,...P),x.props.name=Q):(x=new r2({pinNumber:parseInt(E),name:Q,aliases:[...P,...((c=e.additionalAliases)==null?void 0:c[`pin${parseInt(E)}`])??[]]},{originDescription:`pinLabels:pin${E}`}),n.push(x))}if(t.schematicSymbolName){const E=l0[this._getSchematicSymbolNameOrThrow()];if(!E)return;for(const _ of E.ports){const x=ALe(_.labels);if(!x)continue;const Q=n.find(P=>P._parsedProps.pinNumber===Number(x));if(Q)Q.schematicSymbolPortDef=_;else{const P=nT(_.labels.concat(((u=e.additionalAliases)==null?void 0:u[`pin${x}`])??[]));P&&(P.originDescription=`schematicSymbol:labels[0]:${_.labels[0]}`,P.schematicSymbolPortDef=_,n.push(P))}}this.addAll(n)}if(!this._getSchematicPortArrangement()){const E=this.getPortsFromFootprint(e);for(const _ of E)n.some(x=>x.isMatchingAnyOf(_.getNameAndAliases()))||n.push(_)}for(let E=1;E<=(e.pinCount??this._getPinCount());E++){if(!i||n.find(x=>x._parsedProps.pinNumber===E))continue;let _=[...((A=i.leftSide)==null?void 0:A.pins)??[],...((d=i.rightSide)==null?void 0:d.pins)??[],...((h=i.topSide)==null?void 0:h.pins)??[],...((m=i.bottomSide)==null?void 0:m.pins)??[]].map(x=>tT(x,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(x=>x in i)&&(_=Array.from({length:this._getPinCount()},(x,Q)=>Q+1)),_.includes(E)&&n.push(new r2({pinNumber:E,aliases:((C=e.additionalAliases)==null?void 0:C[`pin${E}`])??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${E}`}))}n.length>0&&this.addAll(n)}_getImpliedFootprintString(){return null}_isFootprintUrl(e){return e.startsWith("http://")||e.startsWith("https://")}_addChildrenFromStringFootprint(){var o;const{name:e,pcbRotation:t,pinLabels:n}=this.props;let{footprint:i}=this.props;if(i??(i=(o=this._getImpliedFootprintString)==null?void 0:o.call(this)),!!i&&typeof i=="string"){if(this._isFootprintUrl(i))return;const a=S9.string(i).soup(),s=uLe({componentName:e,componentRotation:t,footprint:i,pinLabels:n},a);this.addAll(s)}}get portMap(){return new Proxy({},{get:(e,t)=>{const n=this.children.find(i=>i.componentName==="Port"&&i.isMatchingNameOrAlias(t));if(!n)throw new Error(`There was an issue finding the port "${t.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return n}})}getInstanceForReactElement(e){for(const t of this.reactSubtrees)if(t.element===e)return t.component;return null}doInitialSourceRender(){const e=this.config.sourceFtype;if(!e)return;const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:e,name:n.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialSchematicComponentRender(){var i,o,a;if((i=this.root)!=null&&i.schematicDisabled)return;const{db:e}=this.root,{schematicSymbolName:t}=this.config;t?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();const n=(o=this.getSubcircuit())==null?void 0:o._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&n){if(!this.schematic_component_id)return;const s=AR.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:(a=this.getSubcircuit())==null?void 0:a.subcircuit_id});e.schematic_manual_edit_conflict_warning.insert(s)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];const e=[];for(const t of this.internallyConnectedPinNames){const n=[];for(const i of t)n.push(this.portMap[i]);e.push(n)}return e}_doInitialSchematicComponentRenderWithSymbol(){var a;if((a=this.root)!=null&&a.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getSchematicSymbolNameOrThrow(),i=l0[n],o=this._getGlobalSchematicPositionBeforeLayout();if(i){const s=e.schematic_component.insert({center:o,size:i.size,source_component_id:this.source_component_id,symbol_name:n,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=s.schematic_component_id}}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){var A;if((A=this.root)!=null&&A.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getSchematicBoxDimensions(),i={};if(Array.isArray(t.pinLabels))t.pinLabels.forEach((d,h)=>{i[String(h+1)]=d});else for(const[d,h]of Object.entries(t.pinLabels??{}))i[d]=Array.isArray(h)?h[0]:h;const o=this._getGlobalSchematicPositionBeforeLayout(),a=this._getSchematicPortArrangement(),s=e.schematic_component.insert({center:o,rotation:t.schRotation??0,size:n.getSize(),port_arrangement:lVt(a),pin_spacing:t.schPinSpacing??.2,pin_styles:sVt(t.schPinStyle,t.pinLabels),port_labels:i,source_component_id:this.source_component_id}),l=(a==null?void 0:a.topSide)!==void 0||(a==null?void 0:a.bottomSide)!==void 0,c=n==null?void 0:n.getSize().width,u=n==null?void 0:n.getSize().height;e.schematic_text.insert({text:t.manufacturerPartNumber??"",schematic_component_id:s.schematic_component_id,anchor:"left",rotation:0,position:{x:l?o.x+(c??0)/2+.1:o.x-(c??0)/2,y:l?o.y+(u??0)/2+.35:o.y-(u??0)/2-.13},color:"#006464",font_size:.18}),e.schematic_text.insert({text:t.name??"",schematic_component_id:s.schematic_component_id,anchor:"left",rotation:0,position:{x:l?o.x+(c??0)/2+.1:o.x-(c??0)/2,y:l?o.y+(u??0)/2+.55:o.y+(u??0)/2+.13},color:"#006464",font_size:.18}),this.schematic_component_id=s.schematic_component_id}doInitialPcbComponentRender(){var a;if((a=this.root)!=null&&a.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getSubcircuit(),i=e.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:n.subcircuit_id??void 0});if(!t.footprint&&!this.isGroup){const s=e.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=s.pcb_missing_footprint_error_id}this.pcb_component_id=i.pcb_component_id;const o=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&o){const s=hR.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:n.subcircuit_id??void 0});e.pcb_manual_edit_conflict_warning.insert(s)}}doInitialPcbComponentSizeCalculation(){var o;if((o=this.root)!=null&&o.pcbDisabled||!this.pcb_component_id)return;const{db:e}=this.root,{_parsedProps:t}=this,n=sse(this.children);if(n.width===0||n.height===0)return;const i={x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2};e.pcb_component.update(this.pcb_component_id,{center:i,width:n.width,height:n.height})}_renderReactSubtree(e){return{element:e,component:aVt(e)}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){}doInitialPcbFootprintStringRender(){var o;let{footprint:e}=this.props;if(e??(e=(o=this._getImpliedFootprintString)==null?void 0:o.call(this)),!e)return;const{name:t,pcbRotation:n,pinLabels:i}=this.props;if(typeof e=="string"&&this._isFootprintUrl(e)){if(this._hasStartedFootprintUrlLoad)return;this._hasStartedFootprintUrlLoad=!0;const a=e;this._queueAsyncEffect("load-footprint-url",async()=>{const l=await(await fetch(a)).json(),c=uLe({componentName:t,componentRotation:n,footprint:a,pinLabels:i},l);this.addAll(c),this._markDirty("InitializePortsFromChildren")});return}if(yt.isValidElement(e)){if(this.reactSubtrees.some(s=>s.element===e))return;const a=this._renderReactSubtree(e);this.reactSubtrees.push(a),this.add(a.component);return}!yt.isValidElement(e)&&e.componentName==="Footprint"&&this.add(e)}_hasExistingPortExactly(e){return this.children.filter(n=>n.componentName==="Port").some(n=>{const i=e.getNameAndAliases(),o=n.getNameAndAliases();return i.length===o.length&&i.every(a=>o.includes(a))})}add(e){let t;if(yt.isValidElement(e)){const n=this._renderReactSubtree(e);this.reactSubtrees.push(n),t=n.component}else t=e;if(t.componentName==="Port"){if(this._hasExistingPortExactly(t))return;const i=this.children.filter(o=>o.componentName==="Port").find(o=>o.isMatchingAnyOf(t.getNameAndAliases()));i&&LVt(`Similar ports added. Port 1: ${i}, Port 2: ${t}`)}super.add(t)}getPortsFromFootprint(e){let{footprint:t}=this.props;if((!t||yt.isValidElement(t))&&(t=this.children.find(i=>i.componentName==="Footprint")),typeof t=="string"){if(this._isFootprintUrl(t))return[];const i=S9.string(t).soup(),o=[];for(const a of i)if("port_hints"in a&&a.port_hints){const s=nT(a.port_hints,e);if(!s)continue;s.originDescription=`footprint:string:${t}:port_hints[0]:${a.port_hints[0]}`,o.push(s)}return o}if(!yt.isValidElement(t)&&t&&t.componentName==="Footprint"){const i=t;let o=1;const a=[];for(const s of i.children){if(!s.props.portHints)continue;let l=s.props.portHints;l.some(A=>A.startsWith("pin"))||(l=[...l,`pin${o}`]),o++;const u=nT(l);u&&(u.originDescription=`footprint:${t}`,a.push(u))}return a}const n=[];if(!t){for(const i of this.children)if(i.props.portHints&&i.isPcbPrimitive){const o=nT(i.props.portHints);o&&n.push(o)}}return n}getPortsFromSchematicSymbol(){var i;if((i=this.root)!=null&&i.schematicDisabled)return[];const{config:e}=this;if(!e.schematicSymbolName)return[];const t=l0[e.schematicSymbolName];if(!t)return[];const n=[];for(const o of t.ports){const a=nT(o.labels);a&&(a.schematicSymbolPortDef=o,n.push(a))}return n}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){const{_parsedProps:e}=this,t=[];if(e.connections)for(const[n,i]of Object.entries(e.connections)){const o=Array.isArray(i)?i:[i];for(const a of o)t.push(a)}return t}_createNetsFromProps(e){aLe(this,e)}_getPcbCircuitJsonBounds(){const{db:e}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();const t=e.pcb_component.get(this.pcb_component_id);return{center:{x:t.center.x,y:t.center.y},bounds:{left:t.center.x-t.width/2,top:t.center.y-t.height/2,right:t.center.x+t.width/2,bottom:t.center.y+t.height/2},width:t.width,height:t.height}}_getPinCountFromSchematicPortArrangement(){const e=this._getSchematicPortArrangement();if(!e)return 0;if(!dLe(e))return(e.leftSize??e.leftPinCount??0)+(e.rightSize??e.rightPinCount??0)+(e.topSize??e.topPinCount??0)+(e.bottomSize??e.bottomPinCount??0);const{leftSide:n,rightSide:i,topSide:o,bottomSide:a}=e;return Math.max(...(n==null?void 0:n.pins)??[],...(i==null?void 0:i.pins)??[],...(o==null?void 0:o.pins)??[],...(a==null?void 0:a.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:e}=this,t=this._getPinCount(),n=e.schPinSpacing??.2;return vVt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:n,numericSchPinStyle:EVt(e.schPinStyle,e.pinLabels),pinCount:t,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:e.pinLabels})}doInitialCadModelRender(){var c;const{db:e}=this.root,{boardThickness:t=0}=((c=this.root)==null?void 0:c._getBoard())??{},n=this._parsedProps.cadModel;if(!this.pcb_component_id||!n&&!this.props.footprint||n===null)return;const i=this._getPcbCircuitJsonBounds(),o=e.pcb_component.get(this.pcb_component_id);if(typeof n=="string")throw new Error("String cadModel not yet implemented");const a=GVt.parse({x:0,y:0,z:typeof(n==null?void 0:n.rotationOffset)=="number"?n.rotationOffset:0,...typeof(n==null?void 0:n.rotationOffset)=="object"?n.rotationOffset??{}:{}}),s=m2.parse({x:0,y:0,z:0,...typeof(n==null?void 0:n.positionOffset)=="object"?n.positionOffset:{}}),l=this.props.layer==="bottom"?"bottom":"top";e.cad_component.insert({position:{x:i.center.x+s.x,y:i.center.y+s.y,z:(l==="bottom"?-t/2:t/2)+s.z},rotation:{x:a.x,y:(l==="top"?0:180)+a.y,z:l==="bottom"?-(((o==null?void 0:o.rotation)??0)+a.z)+180:((o==null?void 0:o.rotation)??0)+a.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(n??{})?this._addCachebustToModelUrl(n.stlUrl):void 0,model_obj_url:"objUrl"in(n??{})?this._addCachebustToModelUrl(n.objUrl):void 0,model_jscad:"jscad"in(n??{})?n.jscad:void 0,footprinter_string:typeof this.props.footprint=="string"&&!n?this.props.footprint:void 0})}_addCachebustToModelUrl(e){var n;if(!e||!e.includes("modelcdn.tscircuit.com"))return e;const t=((n=this.root)==null?void 0:n.getClientOrigin())??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(t)}`}_getPartsEngineCacheKey(e,t){return JSON.stringify({ftype:e.ftype,name:e.name,manufacturer_part_number:e.manufacturer_part_number,footprinterString:t})}async _getSupplierPartNumbers(e,t,n){var l,c;if(this.props.doNotPlace)return{};const i=(c=(l=this.root)==null?void 0:l.platform)==null?void 0:c.localCacheEngine,o=this._getPartsEngineCacheKey(t,n);if(i){const u=await i.getItem(o);if(u)try{return JSON.parse(u)}catch{}}const a=await Promise.resolve(e.findPart({sourceComponent:t,footprinterString:n})),s=a==="Not found"?{}:a;if(i)try{await i.setItem(o,JSON.stringify(s))}catch{}return s}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;const e=this.getInheritedProperty("partsEngine");if(!e)return;const{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(!n||n.supplier_part_numbers)return;let i;this.props.footprint&&typeof this.props.footprint=="string"&&(i=this.props.footprint);const o=this._getSupplierPartNumbers(e,n,i);if(!(o instanceof Promise)){t.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:e}=this.root,t=e.source_component.get(this.source_component_id);if(t&&!t.supplier_part_numbers&&this._asyncSupplierPartNumbers){e.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){const{_parsedProps:e}=this;if(e.connections)for(const[t,n]of Object.entries(e.connections)){const i=Array.isArray(n)?n:[n];for(const o of i)this.add(new i9({from:`${this.getSubcircuitSelector()} > port.${t}`,to:o}))}}},OVt=class{constructor(r,e={}){Le(this,"input");Le(this,"isRouting",!1);Le(this,"solver");Le(this,"eventHandlers",{complete:[],error:[],progress:[]});Le(this,"cycleCount",0);Le(this,"stepDelay");Le(this,"timeoutId");this.input=r;const{capacityDepth:t,targetMinCapacity:n,stepDelay:i=0}=e;this.solver=new UY(r,{capacityDepth:t,targetMinCapacity:n,cacheProvider:null}),this.stepDelay=i}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){var r;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 e=Date.now(),t=this.solver.iterations;for(;Date.now()-e<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();const n=(this.solver.iterations-t)/(Date.now()-e)*1e3;this.cycleCount++;const i=((r=this.solver)==null?void 0:r.preview())||void 0,o=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,progress:o,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(e){this.emitEvent({type:"error",error:e instanceof Error?e:new Error(String(e))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(r,e){r==="complete"?this.eventHandlers.complete.push(e):r==="error"?this.eventHandlers.error.push(e):r==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(r){if(r.type==="complete")for(const e of this.eventHandlers.complete)e(r);else if(r.type==="error")for(const e of this.eventHandlers.error)e(r);else if(r.type==="progress")for(const e of this.eventHandlers.progress)e(r)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new Error(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},yLe=class extends $v{constructor(){super(...arguments);Le(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:y8e}}doInitialPortMatching(){const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)return;if(n.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!n)throw new Error("TraceHint has no parent");if(!t.for){this.renderError(`TraceHint has no for property (${this})`);return}const i=n.selectOne(t.for,{type:"port"});i||this.renderError(`${this} could not find port for selector "${t.for}"`),this.matchedPort=i,i.registerMatch(this)}getPcbRouteHints(){const{_parsedProps:e}=this,t=e.offset?[e.offset]:e.offsets;if(!t)return[];const n=this._computePcbGlobalTransformBeforeLayout();return t.map(i=>({...ei(n,i),via:i.via,to_layer:i.to_layer,trace_width:i.trace_width}))}doInitialPcbTraceHintRender(){var n,i,o;if((n=this.root)!=null&&n.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;e.pcb_trace_hint.insert({pcb_component_id:(i=this.matchedPort)==null?void 0:i.pcb_component_id,pcb_port_id:(o=this.matchedPort)==null?void 0:o.pcb_port_id,route:this.getPcbRouteHints()})}},zVt=(r,e)=>{const t=r.source_group.list(),n=[],i=o=>{const a=t.filter(s=>s.parent_subcircuit_id===o);for(const s of a)s.subcircuit_id&&(n.push(s.subcircuit_id),i(s.subcircuit_id))};return i(e),n},vLe=({db:r,circuitJson:e,subcircuit_id:t,minTraceWidth:n=.1})=>{if(!r&&e&&(r=q1(e)),!r)throw new Error("db or circuitJson is required");const i=r.pcb_trace_hint.list(),o=t?new Set([t]):null;if(t){const C=zVt(r,t);for(const E of C)o.add(E)}const a=(e??r.toArray()).filter(C=>!t||"subcircuit_id"in C&&o.has(C.subcircuit_id)),s=r.pcb_board.list()[0];r=q1(a);const l=WB(a),c=P9([...r.pcb_component.list(),...r.pcb_smtpad.list(),...r.pcb_plated_hole.list(),...r.pcb_hole.list(),...r.pcb_via.list()].filter(C=>!t||(o==null?void 0:o.has(C.subcircuit_id))),l);for(const C of c){const E=C.connectedTo.flatMap(_=>l.getIdsConnectedToNet(_));C.connectedTo.push(...E)}const u=c.flatMap(C=>[{x:C.center.x-C.width/2,y:C.center.y-C.height/2},{x:C.center.x+C.width/2,y:C.center.y+C.height/2}]);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(C=>C.x))-1,maxX:Math.max(...u.map(C=>C.x))+1,minY:Math.min(...u.map(C=>C.y))-1,maxY:Math.max(...u.map(C=>C.y))+1};const d=r.source_trace.list().map(C=>{var Y,V,Z;const E=C.connected_source_port_ids.map(J=>{const se=r.source_port.get(J),ae=r.pcb_port.getWhere({source_port_id:J});return{...se,...ae}});if(E.length<2)return null;const[_,x]=E,Q=((Y=_.layers)==null?void 0:Y[0])??"top",P=((V=x.layers)==null?void 0:V[0])??"top",O=i.filter(J=>J.pcb_port_id===_.pcb_port_id||J.pcb_port_id===x.pcb_port_id),z=[];for(const J of O){const se=r.pcb_port.get(J.pcb_port_id),ae=((Z=se==null?void 0:se.layers)==null?void 0:Z[0])??"top";for(const ue of J.route)z.push({x:ue.x,y:ue.y,layer:ae})}return{name:C.source_trace_id??l.getNetConnectedToId(C.source_trace_id)??"",source_trace_id:C.source_trace_id,pointsToConnect:[{x:_.x,y:_.y,layer:Q},...z,{x:x.x,y:x.y,layer:P}]}}).filter(C=>C!==null),h=r.source_net.list().filter(C=>!t||(o==null?void 0:o.has(C.subcircuit_id))),m=[];for(const C of h){const E=r.source_trace.list().filter(_=>{var x;return(x=_.connected_source_net_ids)==null?void 0:x.includes(C.source_net_id)});m.push({name:C.source_net_id??l.getNetConnectedToId(C.source_net_id),pointsToConnect:E.flatMap(_=>r.pcb_port.list().filter(Q=>_.connected_source_port_ids.includes(Q.source_port_id)).map(Q=>{var P;return{x:Q.x,y:Q.y,layer:((P=Q.layers)==null?void 0:P[0])??"top",pcb_port_id:Q.pcb_port_id}}))})}return{simpleRouteJson:{bounds:A,obstacles:c,connections:[...d,...m],layerCount:2,minTraceWidth:n},connMap:l}};function use(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 o=e.source_port.getWhere({source_component_id:i.source_component_id,pin_number:n});return{subcircuit_connectivity_map_key:(o==null?void 0:o.subcircuit_connectivity_map_key)??null,source_port_id:o.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 HVt({path:r,db:e,layoutConnMap:t}){let n=use(r.to,e)??use(r.from,e);if(!n){const o=t.getNetConnectedToId(iS(r.to));n=t.getIdsConnectedToNet(o).map(s=>Jae(s)).map(s=>use(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 o of i)if(o.connected_source_port_ids.includes(n.source_port_id))return o.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 YVt(r){const{db:e}=r.root;let t=structuredClone(e.toArray());t=ZYt(t);const n=WYt(t),i=new jYt({inputNetlist:n});let o=null;try{i.solve(),o=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:a,junctions:s,netLabels:l,paths:c}=o,u=new xQ({});for(const A of c)u.addConnections([[iS(A.from),iS(A.to)]]);for(const A of s)for(const d of c)for(const h of d.points)Math.abs(h.x-A.x)<.001&&Math.abs(h.y-A.y)<.001&&u.addConnections([[iS(d.from),iS(A)],[iS(d.to),iS(A)]]);for(const A of a){const d=e.source_component.list().find(_=>_.name===A.boxId);if(!d)continue;const h=e.schematic_component.getWhere({source_component_id:d.source_component_id});if(!h)continue;const m={x:A.centerX-h.center.x+.1,y:A.centerY-h.center.y-.1};e.schematic_component.update(h.schematic_component_id,{center:{x:h.center.x+m.x,y:h.center.y+m.y}});const C=e.schematic_port.list({schematic_component_id:h.schematic_component_id});for(const _ of C)e.schematic_port.update(_.schematic_port_id,{center:{x:_.center.x+m.x,y:_.center.y+m.y}});const E=e.schematic_text.list({schematic_component_id:h.schematic_component_id});for(const _ of E)e.schematic_text.update(_.schematic_text_id,{position:{x:_.position.x+m.x,y:_.position.y+m.y}})}for(const A of l){const d=e.source_net.list().find(h=>h.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=HVt({path:A,db:xB(t),layoutConnMap:u});let h=[];for(let E=0;E<A.points.length-1;E++)h.push({from:{x:A.points[E].x,y:A.points[E].y},to:{x:A.points[E+1].x,y:A.points[E+1].y}});const m=i6({db:e,source_trace_id:d,differentNetOnly:!0}).flatMap(E=>E.edges);m.length>0&&(h=gLe({edges:h,otherEdges:m}));const C=mLe({edges:h,db:e,source_trace_id:d});e.schematic_trace.insert({source_trace_id:d,edges:h,junctions:C})}}function VVt(r){if(!r.isSubcircuit)return;const{db:e}=r.root,t=r.selectAll("trace"),n=new xQ({});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 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_port_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_port.update(s,{subcircuit_connectivity_map_key:c})}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_net_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_net.update(s,{subcircuit_connectivity_map_key:c})}}function KVt(r){var x;const{db:e}=r.root,t=r._parsedProps,n=r.children.filter(Q=>Q.schematic_component_id);if(n.length===0)return;let i=0,o=0;for(const Q of n){const P=e.schematic_component.get(Q.schematic_component_id);P!=null&&P.size&&(i=Math.max(i,P.size.width),o=Math.max(o,P.size.height))}i===0&&n.length>0&&(i=1),o===0&&n.length>0&&(o=1);let a=t.gridCols,s,l=t.gridGap;(x=t.schLayout)!=null&&x.grid&&(a=t.schLayout.grid.cols??a,s=t.schLayout.grid.rows,l=t.schLayout.grid.gap??l);let c,u;a!==void 0&&s!==void 0?(c=a,u=s):a!==void 0?(c=a,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 h=c*i+Math.max(0,c-1)*A,m=u*o+Math.max(0,u-1)*d,C=r._getGlobalSchematicPositionBeforeLayout(),E=C.x-h/2+i/2,_=C.y+m/2-o/2;for(let Q=0;Q<n.length;Q++){const P=n[Q];if(!P.schematic_component_id)continue;const O=Math.floor(Q/c),z=Q%c;if(O>=u||z>=c){console.warn(`Schematic grid layout: Child ${P.getString()} at index ${Q} (row ${O}, col ${z}) exceeds specified grid dimensions (${u}x${c}). Skipping placement.`);continue}const Y=E+z*(i+A),V=_-O*(o+d),Z=e.schematic_component.get(P.schematic_component_id);if(Z){const J=Z.center,se={x:Y,y:V};e.schematic_component.update(P.schematic_component_id,{center:se});const ae=se.x-J.x,ue=se.y-J.y,ve=e.schematic_port.list({schematic_component_id:P.schematic_component_id});for(const fe of ve)e.schematic_port.update(fe.schematic_port_id,{center:{x:fe.center.x+ae,y:fe.center.y+ue}});const xe=e.schematic_text.list({schematic_component_id:P.schematic_component_id});for(const fe of xe)e.schematic_text.update(fe.schematic_text_id,{position:{x:fe.position.x+ae,y:fe.position.y+ue}})}}r.schematic_group_id&&e.schematic_group.update(r.schematic_group_id,{width:h,height:m,center:C})}var Ase=class extends N1{constructor(){super(...arguments);Le(this,"pcb_group_id",null);Le(this,"schematic_group_id",null);Le(this,"subcircuit_id",null);Le(this,"_hasStartedAsyncAutorouting",!1);Le(this,"_asyncAutoroutingResult",null)}get config(){return{zodProps:NPe,componentName:"Group"}}doInitialSourceRender(){const{db:e}=this.root,t=e.source_group.insert({name:this._parsedProps.name,is_subcircuit:this.isSubcircuit});this.subcircuit_id=`subcircuit_${t.source_group_id}`,this.source_group_id=t.source_group_id,e.source_group.update(t.source_group_id,{subcircuit_id:this.subcircuit_id});for(const n of this.children)e.source_component.update(n.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){var n,i,o;const{db:e}=this.root;if(!this.isSubcircuit)return;const t=(o=(i=(n=this.parent)==null?void 0:n.getSubcircuit)==null?void 0:i.call(n))==null?void 0:o.subcircuit_id;t&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:t})}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.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=n.pcb_group_id;for(const o of this.children)e.pcb_component.update(o.pcb_component_id,{pcb_group_id:n.pcb_group_id})}doInitialPcbPrimitiveRender(){var n;if((n=this.root)!=null&&n.pcbDisabled)return;const{db:e}=this.root,t=sse(this.children);this.pcb_group_id&&e.pcb_group.update(this.pcb_group_id,{width:t.width,height:t.height,center:{x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2}})}doInitialCreateTraceHintsFromProps(){var o;const{_parsedProps:e}=this,{db:t}=this.root,n=e;if(!this.isSubcircuit)return;const i=(o=n.layout)==null?void 0:o.manual_trace_hints;if(i)for(const a of i)this.add(new yLe({for:a.pcb_port_selector,offsets:a.offsets}))}doInitialSourceAddConnectivityMapKey(){VVt(this)}_areChildSubcircuitsRouted(){const e=this.selectAll("group").filter(t=>t.isSubcircuit);for(const t of e)if(t._shouldRouteAsync()&&!t._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){const e=this._getAutorouterConfig();return e.groupMode==="sequential-trace"?!1:!!(e.local&&e.groupMode==="subcircuit"||!e.local)}_hasTracesToRoute(){const e=Rm("tscircuit:core:_hasTracesToRoute"),t=this.selectAll("trace");return e(`[${this.getString()}] has ${t.length} traces to route`),t.length>0}async _runEffectMakeHttpAutoroutingRequest(){var c,u,A,d;const{db:e}=this.root,t=Rm("tscircuit:core:_runEffectMakeHttpAutoroutingRequest");this._parsedProps;const n=this._getAutorouterConfig(),i=n.serverUrl,o=n.serverMode,a=(h,m)=>{var C;return t("fetching",h),m.headers&&(m.headers["Tscircuit-Core-Version"]=(C=this.root)==null?void 0:C.getCoreVersion()),fetch(h,m)},s=this.root.db.toArray().filter(h=>h.type.startsWith("source_")||h.type.startsWith("pcb_"));if(o==="solve-endpoint"){if(((c=this.props.autorouter)==null?void 0:c.inputFormat)==="simplified"){const{autorouting_result:m}=await a(`${i}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:vLe({db:e,minTraceWidth:((u=this.props.autorouter)==null?void 0:u.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(C=>C.json());this._asyncAutoroutingResult=m,this._markDirty("PcbTraceRender");return}const{autorouting_result:h}=await a(`${i}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:s,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(m=>m.json());this._asyncAutoroutingResult=h,this._markDirty("PcbTraceRender");return}const{autorouting_job:l}=await a(`${i}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:s,provider:"freerouting",autostart:!0,display_name:(A=this.root)==null?void 0:A.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:n.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());for(;;){const{autorouting_job:h}=await a(`${i}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(m=>m.json());if(h.is_finished){const{autorouting_job_output:m}=await a(`${i}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(C=>C.json());this._asyncAutoroutingResult={output_pcb_traces:m.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(h.has_error)throw e.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,message:((d=h.error)==null?void 0:d.message)??JSON.stringify(h.error)}),new Error(`Autorouting job failed: ${JSON.stringify(h.error)}`);await new Promise(m=>setTimeout(m,100))}}async _runLocalAutorouting(){var s,l,c,u,A;const{db:e}=this.root;this._parsedProps;const t=Rm("tscircuit:core:_runLocalAutorouting");t(`[${this.getString()}] starting local autorouting`);const n=this._getAutorouterConfig(),{simpleRouteJson:i}=vLe({db:e,minTraceWidth:((s=this.props.autorouter)==null?void 0:s.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id});(l=this.root)==null||l.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:i});let o;n.algorithmFn?o=await n.algorithmFn(i):o=new OVt(i,{capacityDepth:(c=this.props.autorouter)==null?void 0:c.capacityDepth,targetMinCapacity:(u=this.props.autorouter)==null?void 0:u.targetMinCapacity});const a=new Promise((d,h)=>{o.on("complete",m=>{t(`[${this.getString()}] local autorouting complete`),d(m.traces)}),o.on("error",m=>{t(`[${this.getString()}] local autorouting error: ${m.error.message}`),h(m.error)})});o.on("progress",d=>{var h;(h=this.root)==null||h.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...d})}),o.start();try{const d=await a;this._asyncAutoroutingResult={output_pcb_traces:d},this._markDirty("PcbTraceRender")}catch(d){const{db:h}=this.root;throw h.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,message:d instanceof Error?d.message:String(d)}),(A=this.root)==null||A.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:d instanceof Error?d.message:String(d)},simpleRouteJson:i}),d}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 t;const e=Rm("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!((t=this.root)!=null&&t.pcbDisabled)&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){e(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}e(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}updatePcbTraceRender(){var n;const e=Rm("tscircuit:core:updatePcbTraceRender");if(e(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(e(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;const{db:t}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){e(`[${this.getString()}] updating PCB traces from simple route json (${(n=this._asyncAutoroutingResult.output_simple_route_json.traces)==null?void 0:n.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){e(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){const{db:e}=this.root,{traces:t}=this._asyncAutoroutingResult.output_simple_route_json;if(t)for(const n of t)e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:n.route})}_updatePcbTraceRenderFromPcbTraces(){const{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;const{db:t}=this.root;for(const n of e)if(n.type==="pcb_trace"){if(n.subcircuit_id=this.subcircuit_id,n.connection_name){const i=n.connection_name;n.source_trace_id=i}t.pcb_trace.insert(n)}for(const n of e)if(n.type!=="pcb_via"&&n.type==="pcb_trace")for(const i of n.route)i.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:n.pcb_trace_id,x:i.x,y:i.y,hole_diameter:.3,outer_diameter:.6,layers:[i.from_layer,i.to_layer],from_layer:i.from_layer,to_layer:i.to_layer})}doInitialSchematicComponentRender(){var i;if((i=this.root)!=null&&i.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.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=n.schematic_group_id;for(const o of this.children)o.schematic_component_id&&e.schematic_component.update(o.schematic_component_id,{schematic_group_id:n.schematic_group_id})}_getSchematicLayoutMode(){var t,n,i;const e=this._parsedProps;return(t=e.schLayout)!=null&&t.matchAdapt?"match-adapt":(n=e.schLayout)!=null&&n.flex?"flex":(i=e.schLayout)!=null&&i.grid?"grid":e.matchAdapt?"match-adapt":e.flex?"flex":e.grid?"grid":"none"}doInitialSchematicLayout(){this._parsedProps;const e=this._getSchematicLayoutMode();e==="match-adapt"&&this._doInitialSchematicLayoutMatchAdapt(),e==="grid"&&this._doInitialSchematicLayoutGrid()}_doInitialSchematicLayoutMatchAdapt(){YVt(this)}_doInitialSchematicLayoutGrid(){KVt(this)}_determineSideFromPosition(e,t){if(!e.center||!t.center)return"left";const n=e.center.x-t.center.x,i=e.center.y-t.center.y;return Math.abs(n)>Math.abs(i)?n>0?"right":"left":i>0?"bottom":"top"}_calculateSchematicBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let t=1/0,n=-1/0,i=1/0,o=-1/0;for(const s of e)t=Math.min(t,s.centerX),n=Math.max(n,s.centerX),i=Math.min(i,s.centerY),o=Math.max(o,s.centerY);const a=2;return{minX:t-a,maxX:n+a,minY:i-a,maxY:o+a}}_getAutorouterConfig(){const e={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0},t=this._parsedProps.autorouter??this.getInheritedProperty("autorouter");return typeof t=="object"?{local:!(t.serverUrl||t.serverMode||t.serverCacheEnabled),...e,...t}:t==="auto-local"?{local:!0,groupMode:"subcircuit"}:t==="sequential-trace"?{local:!0,groupMode:"sequential-trace"}:t==="subcircuit"?{local:!0,groupMode:"subcircuit"}:t==="auto-cloud"?{local:!1,groupMode:"subcircuit",serverUrl:e.serverUrl,serverMode:e.serverMode,serverCacheEnabled:!0}:{local:!0,groupMode:"subcircuit"}}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){var t;if((t=this.root)!=null&&t.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:e}=this.root;if(this.isSubcircuit){const n=new Map;for(const i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){const o=n.get(i._parsedProps.name)||[];o.push(i),n.set(i._parsedProps.name,o)}for(const[i,o]of n.entries())o.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" 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(a=>a.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}},jVt=class extends Ase{constructor(){super(...arguments);Le(this,"pcb_board_id",null);Le(this,"_drcChecksComplete",!1);Le(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:Aoe}}get boardThickness(){const{_parsedProps:e}=this;return 1.4}get allLayers(){return["top","bottom","inner1","inner2"]}doInitialPcbBoardAutoSize(){var h;if((h=this.root)!=null&&h.pcbDisabled||!this.pcb_board_id)return;const{db:e}=this.root,{_parsedProps:t}=this;if(t.width&&t.height)return;let n=1/0,i=1/0,o=-1/0,a=-1/0;const s=e.pcb_component.list();let l=!1;for(const m of s){const{width:C,height:E,center:_}=m;C===0||E===0||(l=!0,n=Math.min(n,_.x-C/2),i=Math.min(i,_.y-E/2),o=Math.max(o,_.x+C/2),a=Math.max(a,_.y+E/2))}const c=2,u=l?o-n+c*2:0,A=l?a-i+c*2:0,d={x:l?(n+o)/2+(t.outlineOffsetX??0):t.outlineOffsetX??0,y:l?(i+a)/2+(t.outlineOffsetY??0):t.outlineOffsetY??0};e.pcb_board.update(this.pcb_board_id,{width:u,height:A,center:d})}doInitialPcbComponentRender(){var a,s;if((a=this.root)!=null&&a.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;let n=t.width??0,i=t.height??0;if(t.outline){const l=t.outline.map(m=>m.x),c=t.outline.map(m=>m.y),u=Math.min(...l),A=Math.max(...l),d=Math.min(...c),h=Math.max(...c);n=A-u,i=h-d}const o=e.pcb_board.insert({center:{x:(t.pcbX??0)+(t.outlineOffsetX??0),y:(t.pcbY??0)+(t.outlineOffsetY??0)},thickness:this.boardThickness,num_layers:this.allLayers.length,width:n,height:i,outline:(s=t.outline)==null?void 0:s.map(l=>({x:l.x+(t.outlineOffsetX??0),y:l.y+(t.outlineOffsetY??0)})),material:t.material});this.pcb_board_id=o.pcb_board_id}removePcbComponentRender(){const{db:e}=this.root;this.pcb_board_id&&(e.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return a0()}doInitialPcbDesignRuleChecks(){var e;(e=this.root)!=null&&e.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){var n;if((n=this.root)!=null&&n.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:e}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;const t=zY(e.toArray());for(const i of t)e.pcb_trace_error.insert(i)}_emitRenderLifecycleEvent(e,t){var n;super._emitRenderLifecycleEvent(e,t),t==="start"&&((n=this.root)==null||n.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e}))}},JVt=new Proxy({},{get:(r,e)=>e}),o9=JVt,WVt=class extends N1{get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:OPe,sourceFtype:o9.simple_capacitor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){const r=`${x1(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${r}/${x1(this._parsedProps.maxVoltageRating)}V`:r}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new i9({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new i9({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_capacitor",name:e.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,capacitance:e.capacitance,max_voltage_rating:e.maxVoltageRating,max_decoupling_trace_length:e.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!e.polarized});this.source_component_id=t.source_component_id}},ILe=class extends N1{constructor(){super(...arguments);Le(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:doe,shouldRenderAsSchematicBox:!0}}doInitialSchematicComponentRender(){const{_parsedProps:e}=this;(e==null?void 0:e.noSchematicRepresentation)!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_chip",name:t.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=n.pcb_component_id}doInitialCreateTracesFromProps(){const{_parsedProps:e}=this;if(e.externallyConnectedPins)for(const[t,n]of e.externallyConnectedPins)this.add(new i9({from:`${this.getSubcircuitSelector()} > port.${t}`,to:`${this.getSubcircuitSelector()} > port.${n}`}));this._createTracesFromConnectionsProp()}},ZVt=class extends N1{constructor(){super(...arguments);Le(this,"pos",this.portMap.pin1);Le(this,"anode",this.portMap.pin1);Le(this,"neg",this.portMap.pin2);Le(this,"cathode",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"diode",componentName:"Diode",zodProps:n8e,sourceFtype:"simple_diode"}}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({ftype:"simple_diode",name:t.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},qVt=class extends N1{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:NLt,sourceFtype:o9.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`${x1(t)}A / ${x1(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:o9.simple_fuse,current_rating_amps:t,voltage_rating_volts:n,display_current_rating:`${x1(t)}A`,display_voltage_rating:`${x1(n)}V`});this.source_component_id=i.source_component_id}},XVt=class extends N1{constructor(){super(...arguments);Le(this,"schematicDimensions",null)}get config(){let e="";if(this.props.pinCount&&(e+=`solderjumper${this.props.pinCount||2}`),Array.isArray(this.props.internallyConnectedPins)&&this.props.internallyConnectedPins.length>0){const t=Array.from(new Set(this.props.internallyConnectedPins.flat())).sort().join("");e+=`_bridged${t}`}return{schematicSymbolName:e,componentName:"Jumper",zodProps:TPe,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){const e=super._getSchematicPortArrangement();if(e)return e;const t=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),n=this._parsedProps.schDirection??"right";return{leftSize:n==="left"?t:0,rightSize:n==="right"?t:0}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_chip",name:t.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=n.pcb_component_id}doInitialPcbTraceRender(){const{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),n={};for(let a=0;a<t.length;a++){const s=t[a],l=e.source_port.get(s.source_port_id);let c="";if(typeof(l==null?void 0:l.pin_number)=="number")c=l.pin_number.toString();else if(Array.isArray(l==null?void 0:l.port_hints)){let u=l.port_hints.find(A=>/^(pin)?\d+$/.test(A));u&&(/^pin\d+$/.test(u)?c=u.replace(/^pin/,""):c=u)}n[c]=s.pcb_port_id}const i=e.pcb_trace.list(),o=a=>{if(a&&typeof a=="string"&&a.startsWith("{PIN")){const s=a.replace("{PIN","").replace("}","");return n[s]||a}return a};for(const a of i)if(a.route)for(const s of a.route)s.route_type==="wire"&&(s.start_pcb_port_id=o(s.start_pcb_port_id),s.end_pcb_port_id=o(s.end_pcb_port_id))}},$Vt=class extends N1{constructor(){super(...arguments);Le(this,"pos",this.portMap.pin1);Le(this,"anode",this.portMap.pin1);Le(this,"neg",this.portMap.pin2);Le(this,"cathode",this.portMap.pin2)}get config(){return{componentName:"Led",schematicSymbolName:this.props.symbolName??"led",zodProps:r8e,sourceFtype:"simple_led"}}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({ftype:"simple_led",name:t.name,wave_length:t.wavelength,color:t.color,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},eKt=class extends N1{constructor(){super(...arguments);Le(this,"pos",this.portMap.pin1);Le(this,"positive",this.portMap.pin1);Le(this,"neg",this.portMap.pin2);Le(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:c8e,sourceFtype:"simple_power_source"}}initPorts(){this.add(new r2({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new r2({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_power_source",name:t.name,voltage:t.voltage,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},tKt=class extends N1{get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:FPe,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${x1(this._parsedProps.resistance)}Ω`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new i9({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new i9({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_resistor",name:e.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,resistance:e.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}},nKt=["leftedge","rightedge","topedge","bottomedge","center"],rKt=class extends $v{get config(){return{componentName:"Constraint",zodProps:zPe}}constructor(r){if(super(r),("xdist"in r||"ydist"in r)&&!("edgeToEdge"in r)&&!("centerToCenter"in r))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in r&&r.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){const r=[],e=this.getPrimitiveContainer();function t(n){const i=n.split(" ").pop(),o=nKt.includes(i)?i:void 0,a=o?n.replace(` ${o}`,""):n,s=e.selectOne(a,{pcbPrimitive:!0});s&&r.push({selector:n,component:s,componentSelector:a,edge:o})}for(const n of["left","right","top","bottom"])n in this._parsedProps&&t(this._parsedProps[n]);if("for"in this._parsedProps)for(const n of this._parsedProps.for)t(n);return{componentsWithSelectors:r}}},iKt=class extends $v{constructor(){super(...arguments);Le(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:a8e}}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,t=this.getSubcircuit(),{_parsedProps:n}=this,i=n.layer??"top";if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenPath. Must be "top" or "bottom".`);const o=this._computePcbGlobalTransformBeforeLayout(),a=e.pcb_fabrication_note_path.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,color:n.color,route:n.route.map(c=>{const u=ei(o,{x:c.x,y:c.y});return{...c,x:u.x,y:u.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:(t==null?void 0:t.subcircuit_id)??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},oKt=class extends $v{get config(){return{componentName:"FabricationNoteText",zodProps:o8e}}doInitialPcbPrimitiveRender(){var i,o;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:r}=this.root,{_parsedProps:e}=this,t=this.getPrimitiveContainer(),n=this.getSubcircuit();r.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:e.pcbX??0,y:e.pcbY??0},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:e.text??"",pcb_component_id:t.pcb_component_id,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0,pcb_group_id:((o=this.getGroup())==null?void 0:o.pcb_group_id)??void 0})}},aKt=class extends Ase{constructor(r){super({...r,subcircuit:!0})}},sKt=class extends $v{constructor(){super(...arguments);Le(this,"source_net_alias_id")}get config(){return{componentName:"NetAlias",zodProps:qPe}}doInitialSchematicComponentRender(){var o;if((o=this.root)!=null&&o.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n={x:t.schX??0,y:t.schY??0},i=e.schematic_net_label.insert({text:t.net,source_net_id:t.net,anchor_position:n,center:n,anchor_side:"bottom"});this.source_net_alias_id=i.source_net_id}},lKt=class extends $v{constructor(){super(...arguments);Le(this,"pcb_silkscreen_circle_id",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:g8e}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenCircle. Must be "top" or "bottom".`);this._computePcbGlobalTransformBeforeLayout();const o=this.getSubcircuit(),a=e.pcb_silkscreen_circle.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,center:{x:t.pcbX??0,y:t.pcbY??0},radius:t.radius,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((c=this.getGroup())==null?void 0:c.pcb_group_id)??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_circle_id=a.pcb_silkscreen_circle_id}getPcbSize(){const{_parsedProps:e}=this,t=e.radius*2;return{width:t,height:t}}},cKt=class extends $v{constructor(){super(...arguments);Le(this,"pcb_silkscreen_rect_id",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:p8e}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenRect. Must be "top" or "bottom".`);const o=this.getSubcircuit(),a=e.pcb_silkscreen_rect.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,center:{x:t.pcbX??0,y:t.pcbY??0},width:t.width,height:t.height,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((c=this==null?void 0:this.getGroup())==null?void 0:c.pcb_group_id)??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){const{_parsedProps:e}=this;return{width:e.width,height:e.height}}},uKt=class extends $v{constructor(){super(...arguments);Le(this,"pcb_silkscreen_line_id",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:h8e}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenLine. Must be "top" or "bottom".`);const o=this.getSubcircuit(),a=e.pcb_silkscreen_line.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,stroke_width:t.strokeWidth??.1,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((c=o==null?void 0:o.getGroup())==null?void 0:c.pcb_group_id)??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){const{_parsedProps:e}=this,t=Math.abs(e.x2-e.x1),n=Math.abs(e.y2-e.y1);return{width:t,height:n}}},AKt=class extends $v{constructor(){super(...arguments);Le(this,"pcb_via_id",null);Le(this,"matchedPort",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Via",zodProps:s8e}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){const{_parsedProps:e}=this;return{width:e.outerDiameter,height:e.outerDiameter}}_getPcbCircuitJsonBounds(){const{db:e}=this.root,t=e.pcb_via.get(this.pcb_via_id),n=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-n.width/2,top:t.y-n.height/2,right:t.x+n.width/2,bottom:t.y+n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(e){const{db:t}=this.root;t.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}doInitialPcbPrimitiveRender(){var a,s;if((a=this.root)!=null&&a.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getGlobalPcbPositionBeforeLayout(),i=this.getSubcircuit(),o=e.pcb_via.insert({x:n.x,y:n.y,hole_diameter:t.holeDiameter,outer_diameter:t.outerDiameter,layers:["bottom","top"],from_layer:t.fromLayer||"bottom",to_layer:t.toLayer||"top",subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((s=this.getGroup())==null?void 0:s.pcb_group_id)??void 0});this.pcb_via_id=o.pcb_via_id}},dKt=class extends $v{constructor(){super(...arguments);Le(this,"pcb_cutout_id",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:HPe}}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getSubcircuit(),i=((l=this.getGroup())==null?void 0:l.pcb_group_id)??void 0,o=this._getGlobalPcbPositionBeforeLayout();let a;if(t.shape==="rect"){const c={shape:"rect",center:o,width:t.width,height:t.height,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0,pcb_group_id:i};a=e.pcb_cutout.insert(c)}else if(t.shape==="circle"){const c={shape:"circle",center:o,radius:t.radius,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0,pcb_group_id:i};a=e.pcb_cutout.insert(c)}else if(t.shape==="polygon"){const c=this._computePcbGlobalTransformBeforeLayout(),A={shape:"polygon",points:t.points.map(d=>ei(c,d)),subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0,pcb_group_id:i};a=e.pcb_cutout.insert(A)}a&&(this.pcb_cutout_id=a.pcb_cutout_id)}getPcbSize(){const{_parsedProps:e}=this;if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="polygon"){if(e.points.length===0)return{width:0,height:0};let t=1/0,n=-1/0,i=1/0,o=-1/0;for(const a of e.points)t=Math.min(t,a.x),n=Math.max(n,a.x),i=Math.min(i,a.y),o=Math.max(o,a.y);return{width:n-t,height:o-i}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();const{db:e}=this.root,t=e.pcb_cutout.get(this.pcb_cutout_id);if(!t)return super._getPcbCircuitJsonBounds();if(t.shape==="rect")return{center:t.center,bounds:{left:t.center.x-t.width/2,top:t.center.y+t.height/2,right:t.center.x+t.width/2,bottom:t.center.y-t.height/2},width:t.width,height:t.height};if(t.shape==="circle")return{center:t.center,bounds:{left:t.center.x-t.radius,top:t.center.y+t.radius,right:t.center.x+t.radius,bottom:t.center.y-t.radius},width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){if(t.points.length===0)return super._getPcbCircuitJsonBounds();let n=1/0,i=-1/0,o=1/0,a=-1/0;for(const s of t.points)n=Math.min(n,s.x),i=Math.max(i,s.x),o=Math.min(o,s.y),a=Math.max(a,s.y);return{center:{x:(n+i)/2,y:(o+a)/2},bounds:{left:n,top:a,right:i,bottom:o},width:i-n,height:a-o}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(e){if(!this.pcb_cutout_id)return;const{db:t}=this.root,n=t.pcb_cutout.get(this.pcb_cutout_id);if(n){if(n.shape==="rect"||n.shape==="circle")t.pcb_cutout.update(this.pcb_cutout_id,{...n,center:e});else if(n.shape==="polygon"){const i=this._getPcbCircuitJsonBounds().center,o=e.x-i.x,a=e.y-i.y,s=n.points.map(l=>({x:l.x+o,y:l.y+a}));t.pcb_cutout.update(this.pcb_cutout_id,{...n,points:s})}}}},fKt=class extends N1{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:WPe,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=t.source_component_id}},hKt=class extends N1{get config(){return{componentName:"PinHeader",zodProps:ZPe,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){var i;const r=this._parsedProps.pinCount??((i=this._parsedProps.pinLabels)==null?void 0:i.length)??0,e=this._parsedProps.holeDiameter,t=this._parsedProps.platedDiameter,n=this._parsedProps.pitch;return r>0&&n?!e&&!t?`pinrow${r}_p${n}`:`pinrow${r}_p${n}_id${e}_od${t}`:null}initPorts(){var e,t;const r=this._parsedProps.pinCount??((e=this._parsedProps.pinLabels)==null?void 0:e.length)??1;for(let n=1;n<=r;n++)this.add(new r2({name:`pin${n}`,pinNumber:n,aliases:[(t=this._parsedProps.pinLabels)==null?void 0:t[n-1]].filter(Boolean)}))}_getSchematicPortArrangement(){var n,i,o,a;const r=this._parsedProps.pinCount??1,e=this._parsedProps.facingDirection??"right",t=this._parsedProps.schPinArrangement;return e==="left"?{leftSide:{direction:((n=t==null?void 0:t.leftSide)==null?void 0:n.direction)??"top-to-bottom",pins:((i=t==null?void 0:t.leftSide)==null?void 0:i.pins)??Array.from({length:r},(s,l)=>`pin${l+1}`)}}:{rightSide:{direction:((o=t==null?void 0:t.rightSide)==null?void 0:o.direction)??"top-to-bottom",pins:((a=t==null?void 0:t.rightSide)==null?void 0:a.pins)??Array.from({length:r},(s,l)=>`pin${l+1}`)}}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_pin_header",name:e.name,supplier_part_numbers:e.supplierPartNumbers,pin_count:e.pinCount,gender:e.gender,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}};function pKt(r){switch(r){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var gKt=class extends N1{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??pKt(this.props.pinVariant),zodProps:GPe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"no_ground",n=r.source_component.insert({ftype:"simple_resonator",name:e.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:t,are_pins_interchangeable:t==="no_ground"||t==="ground_pin"});this.source_component_id=n.source_component_id}},mKt=class extends N1{get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:t8e,sourceFtype:o9.simple_inductor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:o9.simple_inductor,inductance:e.inductance,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}};function yKt(r){switch(r){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var vKt=class extends N1{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??yKt(this.props.pinVariant),zodProps:kPe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"two_pin",n=r.source_component.insert({ftype:"simple_potentiometer",name:e.name,max_resistance:e.maxResistance,pin_variant:t,are_pins_interchangeable:t==="two_pin"});this.source_component_id=n.source_component_id}},IKt=class extends N1{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:XPe,sourceFtype:o9.simple_push_button}}get defaultInternallyConnectedPinNames(){return[["pin1","pin4"],["pin2","pin3"]]}initPorts(){super.initPorts({pinCount:4,additionalAliases:{pin1:["side1"],pin3:["side2"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:o9.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}},CKt=class extends N1{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:LPe,sourceFtype:"simple_crystal"}}initPorts(){const r=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:r})}_getSchematicSymbolDisplayValue(){return`${x1(this._parsedProps.frequency)}Hz`}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:"simple_crystal",frequency:e.frequency,load_capacitance:e.loadCapacitance,pin_variant:e.pinVariant||"two_pin",are_pins_interchangeable:(e.pinVariant||"two_pin")==="two_pin"});this.source_component_id=t.source_component_id}},EKt=class extends N1{constructor(){super(...arguments);Le(this,"emitter",this.portMap.pin1);Le(this,"collector",this.portMap.pin2);Le(this,"base",this.portMap.pin3)}get config(){return{componentName:"Transistor",schematicSymbolName:this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor",zodProps:$Pe,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){const e=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:e})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_transistor",name:t.name,transistor_type:t.type});this.source_component_id=n.source_component_id}},_Kt=class extends N1{get config(){const r=this.props.mosfetMode==="depletion"?"d":"e";return{componentName:"Mosfet",schematicSymbolName:`${this.props.channelType}_channel_${r}_mosfet_transistor`,zodProps:e8e,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_mosfet",name:e.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=t.source_component_id}},xKt=class extends N1{_getSwitchType(){const{spst:r,spdt:e,dpst:t,dpdt:n,type:i}=this._parsedProps??{};return n?"dpdt":r?"spst":e?"spdt":t?"dpst":i??"spst"}get config(){const r=this._getSwitchType(),{isNormallyClosed:e}=this._parsedProps??{};return{componentName:"Switch",schematicSymbolName:{spst:e?"spst_normally_closed_switch":"spst_switch",spdt:e?"spdt_normally_closed_switch":"spdt_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"}[r]??"spst_switch",zodProps:i8e,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_switch",name:e.name,switch_type:e.type,is_normally_closed:e.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=t.source_component_id}},BKt=class extends $v{constructor(){super(...arguments);Le(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:A8e}}doInitialSchematicPrimitiveRender(){var n;if((n=this.root)!=null&&n.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;e.schematic_text.insert({anchor:t.anchor??"center",text:t.text,font_size:t.fontSize,color:t.color||"#000000",position:{x:t.schX,y:t.schY},rotation:t.schRotation??0})}},bKt=class extends $v{constructor(){super(...arguments);Le(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:u8e,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){var E;if((E=this.root)!=null&&E.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=u8e.safeParse(t);if(!n.success)throw console.error("Validation failed:",n.error.format()),n.error;const i=.6,o=typeof t.padding=="number"?t.padding:0,a=typeof t.paddingTop=="number"?t.paddingTop:o,s=typeof t.paddingBottom=="number"?t.paddingBottom:o,l=typeof t.paddingLeft=="number"?t.paddingLeft:o,c=typeof t.paddingRight=="number"?t.paddingRight:o,u=t.overlay&&t.overlay.length>0,A=typeof t.width=="number"&&typeof t.height=="number";let d,h,m,C;if(u){const x=t.overlay.map(ke=>({selector:ke,port:this.getSubcircuit().selectOne(ke,{type:"port"})})).filter(({port:ke})=>ke!=null).map(({port:ke})=>({position:ke._getGlobalSchematicPositionAfterLayout()}));if(x.length===0)return;const Q=x.map(ke=>ke.position.x),P=x.map(ke=>ke.position.y),O=Math.min(...Q),z=Math.max(...Q),Y=Math.min(...P),V=Math.max(...P),Z=z-O,J=V-Y,se=Z===0?i:0,ae=J===0?i:0,ue=l+se/2,ve=c+se/2,xe=a+ae/2,fe=s+ae/2,Ee=O-ue,Ie=z+ve,Qe=Y-fe,Me=V+xe;d=Ie-Ee,h=Me-Qe,m=Ee+(t.schX??0),C=Qe+(t.schY??0)}else if(A){d=t.width,h=t.height;const _=typeof t.schX=="number"?t.schX:0,x=typeof t.schY=="number"?t.schY:0;m=_-d/2,C=x-h/2}else return;e.schematic_box.insert({height:h,width:d,x:m,y:C,is_dashed:t.strokeStyle==="dashed",schematic_component_id:""})}};new Proxy({},{get:(r,e)=>{const t=(...n)=>(n[0],new Proxy({},{get:(i,o)=>`.${e} > .${o}`}));return new Proxy(t,{get:(n,i)=>e==="net"?`net.${i}`:e==="subcircuit"?new Proxy({},{get:(o,a)=>new Proxy({},{get:(s,l)=>`subcircuit.${i} > .${a} > .${l}`})}):`.${e} > .${i}`,apply:(n,i,o)=>new Proxy({},{get:(a,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}`})}})})}}),eLe(Xke),eLe({Bug:ILe});const CLe=r=>`hsl(${LB.indexOf(r)*137.5%360}, 70%, 50%)`,SKt=({phaseTimings:r})=>{if(!r)return null;const e=Object.values(r).reduce((t,n)=>t+n,0);return dt.jsxs("div",{className:"rf-space-y-2 rf-w-full rf-px-4",children:[dt.jsx("div",{className:"rf-relative rf-h-8 rf-flex rf-rounded-sm",children:LB.map(t=>{const n=r[t]||0,i=n/e*100;return dt.jsx("div",{className:"rf-group/bar rf-relative rf-overflow-visible",style:{width:`${i}%`,backgroundColor:CLe(t)},children:dt.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)})}),dt.jsxs("div",{className:"rf-text-xs rf-text-gray-500",children:["Total: ",e.toFixed(2),"ms"]})]})},QKt=({renderLog:r})=>{const[e,t]=yt.useState("chronological");if(!r)return dt.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((o,a)=>LB.indexOf(o[0])-LB.indexOf(a[0])):n.sort((o,a)=>a[1]-o[1]);const i=n.reduce((o,[a,s])=>o+s,0);return dt.jsxs("div",{className:"rf-bg-white",children:[dt.jsxs("div",{className:"rf-flex rf-justify-between rf-items-center",children:[dt.jsx("div",{children:"Render Logs"}),dt.jsxs("div",{className:"rf-mb-4 rf-pr-2 rf-flex rf-text-xs rf-items-center",children:[dt.jsx("div",{className:"rf-mr-2",children:"Sort by:"}),dt.jsxs("select",{value:e,onChange:o=>t(o.target.value),className:"rf-px-2 rf-py-1 rf-border rf-rounded rf-text-xs",children:[dt.jsx("option",{value:"chronological",children:"Phase Order"}),dt.jsx("option",{value:"longest",children:"Duration"})]})]})]}),dt.jsx(SKt,{phaseTimings:r.phaseTimings}),dt.jsxs("table",{className:"rf-w-full rf-text-xs",children:[dt.jsx("thead",{children:dt.jsxs("tr",{children:[dt.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase Order"}),dt.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase"}),dt.jsx("th",{className:"rf-text-left rf-p-2",children:"Duration (ms)"})]})}),dt.jsx("tbody",{children:n.map(([o,a])=>dt.jsxs("tr",{children:[dt.jsx("td",{className:"rf-p-2",children:LB.indexOf(o)}),dt.jsx("td",{className:"rf-p-2",children:o}),dt.jsx("td",{className:"rf-p-2",children:dt.jsx("div",{className:"rf-w-8",children:dt.jsx("div",{className:"rf-h-2 rf-rounded-sm",style:{backgroundColor:CLe(o),width:`${a/i*100}%`}})})}),dt.jsx("td",{className:"rf-p-2",children:dt.jsxs("div",{className:"rf-flex w-full",children:[dt.jsxs("span",{className:"rf-flex-grow",children:[a,"ms"]}),dt.jsxs("span",{className:"rf-text-gray-500 rf-pr-2",children:[(a/i*100).toFixed(1),"%"]})]})})]},o))})]})]})},wKt="0.0.528",MKt=["assembly","bom","circuit_json","errors","render_log"],DKt=({code:r,onRunClicked:e=void 0,errorMessage:t,circuitJson:n,autoroutingGraphics:i,showRightHeaderContent:o=!0,showCodeTab:a=!1,codeTabContent:s,showJsonTab:l=!0,showRenderLogTab:c=!0,onActiveTabChange:u,renderLog:A,showImportAndFormatButtons:d=!0,className:h,headerClassName:m,leftHeaderContent:C,readOnly:E,isStreaming:_,autoroutingLog:x,onReportAutoroutingLog:Q,isRunningCode:P,hasCodeChangedSinceLastRun:O,onEditEvent:z,editEvents:Y,defaultActiveTab:V,autoRotate3dViewerDisabled:Z,showSchematicDebugGrid:J=!1,showToggleFullScreen:se=!0,defaultToFullScreen:ae=!1})=>{var ke;LHt();const ue=yt.useMemo(()=>n?n.filter(Ue=>Ue&&"error_type"in Ue||Ue.type.includes("error")):null,[n]),[ve,xe]=yt.useState(V??"pcb"),[fe,Ee]=yt.useState(ae),Ie=yt.useCallback(Ue=>{xe(Ue),u==null||u(Ue)},[u]),Qe=()=>{Ee(!fe)};yt.useEffect(()=>{t&&Ie("errors")},[t]),yt.useEffect(()=>{(ve==="code"||ve==="errors")&&n&&!t&&Ie(V??"pcb")},[n]);const Me=yt.useCallback(Ue=>{window.TSCIRCUIT_3D_OBJECT_REF=Ue===null?void 0:Ue},[]);return dt.jsx("div",{className:Zv("flex flex-col relative rf-overflow-x-hidden",h),children:dt.jsx("div",{className:Zv("rf-md:sticky rf-md:top-2",fe&&"rf-fixed rf-top-0 rf-left-0 rf-w-full rf-bg-white"),children:dt.jsxs(wOe,{value:ve,onValueChange:Ie,className:"rf-flex-grow rf-flex rf-flex-col",children:[dt.jsxs("div",{className:Zv("rf-flex rf-items-center rf-gap-2 rf-p-2 rf-pb-0",m),children:[C,C&&dt.jsx("div",{className:"rf-flex-grow"}),!C&&P&&dt.jsx(HNe,{className:"rf-w-4 rf-h-4 rf-animate-spin"}),!C&&dt.jsx("div",{className:"rf-flex-grow"}),A&&A.progress!==1&&dt.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[A.lastRenderEvent&&dt.jsx("div",{className:"rf-text-xs rf-text-gray-500",children:((ke=A.lastRenderEvent)==null?void 0:ke.phase)??""}),dt.jsx("div",{className:"rf-w-4 rf-h-4 rf-bg-blue-500 rf-opacity-50 rf-rounded-full rf-text-white",children:dt.jsx(HNe,{className:"rf-w-4 rf-h-4 rf-animate-spin"})}),dt.jsxs("div",{className:"rf-text-xs rf-font-bold rf-text-gray-700 rf-tabular-nums",children:[((A.progress??0)*100).toFixed(1),"%"]})]}),o&&dt.jsxs(yce,{children:[a&&dt.jsx(y9,{value:"code",children:"Code"}),dt.jsxs(y9,{value:"pcb",className:"rf-whitespace-nowrap",children:[n&&dt.jsx("span",{className:Zv("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",O?"rf-bg-gray-500":"rf-bg-blue-500")}),"PCB"]}),dt.jsxs(y9,{value:"schematic",className:"rf-whitespace-nowrap",children:[n&&dt.jsx("span",{className:Zv("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",O?"rf-bg-gray-500":"rf-bg-blue-500")}),"Schematic"]}),dt.jsxs(y9,{value:"cad",children:[n&&dt.jsx("span",{className:Zv("inline-flex items-center justify-center w-2 h-2 mr-1 text-xs font-bold text-white rounded-full",O?"rf-bg-gray-500":"rf-bg-blue-500")}),"3D"]}),!["pcb","cad","schematic"].includes(ve)&&dt.jsx(y9,{value:ve,children:mce(ve)}),dt.jsxs($4e,{children:[dt.jsx(ePe,{asChild:!0,children:dt.jsxs("div",{className:"rf-whitespace-nowrap rf-p-2 rf-mr-1 rf-cursor-pointer rf-relative",children:[dt.jsx(Q4t,{className:"rf-w-4 rf-h-4"}),(ue&&ue.length>0||t)&&dt.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"})]})}),dt.jsxs(Kie,{className:"rf-*:text-xs",children:[MKt.map(Ue=>dt.jsxs($L,{onSelect:()=>Ie(Ue),children:[ve!==Ue&&dt.jsx(zNe,{className:"rf-w-3 rf-h-3 rf-opacity-30"}),ve===Ue&&dt.jsx(GNe,{className:"rf-w-3 rf-h-3"}),dt.jsx("div",{className:"rf-pr-2",children:mce(Ue)}),Ue==="errors"&&(ue&&ue.length>0||t)&&dt.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:ue==null?void 0:ue.length})]},Ue)),dt.jsx($L,{disabled:!0,className:"rf-opacity-60 rf-cursor-default rf-select-none",children:dt.jsxs("div",{className:"rf-pr-2 rf-text-xs rf-text-gray-500",children:["@tscircuit/runframe@",wKt.split(".").map((Ue,it)=>it===2?parseInt(Ue)+1:Ue).join(".")]})})]})]})]}),se&&dt.jsx(q2,{onClick:Qe,variant:"ghost",children:fe?dt.jsx(D4t,{size:16}):dt.jsx(w4t,{size:16})})]}),a&&dt.jsx(Ib,{value:"code",className:"rf-flex-grow rf-overflow-hidden",children:dt.jsx("div",{className:"rf-h-full",children:s})}),dt.jsx(Ib,{value:"pcb",children:dt.jsx("div",{className:Zv("rf-overflow-hidden",fe?"rf-h-[calc(100vh-52px)]":"rf-h-[620px]"),children:dt.jsx(lD,{fallbackRender:({error:Ue})=>dt.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:dt.jsxs("div",{className:"rf-p-4",children:[dt.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading PCB viewer"}),dt.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ue==null?void 0:Ue.message)||"An unknown error occurred"})]})}),children:n?dt.jsx(FHt,{focusOnHover:!1,circuitJson:n,debugGraphics:i,containerClassName:Zv("rf-h-full rf-w-full",fe?"rf-min-h-[calc(100vh-240px)]":"rf-min-h-[620px]"),onEditEventsChanged:Ue=>{z&&Ue.forEach(it=>z(it))}}):dt.jsx(Jw,{onRunClicked:e})})})}),dt.jsx(Ib,{value:"assembly",children:dt.jsx("div",{className:Zv("rf-overflow-auto",fe?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:dt.jsx(lD,{fallback:dt.jsx("div",{children:"Error loading Assembly"}),children:n?dt.jsx(oLt,{circuitJson:n,containerStyle:{height:"100%"},editingEnabled:!0,debugGrid:!0}):dt.jsx(Jw,{onRunClicked:e})})})}),dt.jsx(Ib,{value:"schematic",children:dt.jsx("div",{className:Zv("rf-overflow-auto rf-bg-white",fe?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:dt.jsx(lD,{fallbackRender:({error:Ue})=>dt.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:dt.jsxs("div",{className:"rf-p-4",children:[dt.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Schematic"}),dt.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ue==null?void 0:Ue.message)||"An unknown error occurred"})]})}),children:n?dt.jsx(nLt,{circuitJson:n,containerStyle:{height:"100%"},editingEnabled:!0,onEditEvent:Ue=>{z==null||z(Ue)},debugGrid:J,colorOverrides:{schematic:{background:"transparent"}}}):dt.jsx(Jw,{onRunClicked:e})})})}),dt.jsx(Ib,{value:"cad",children:dt.jsx("div",{className:Zv("rf-overflow-auto",fe?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:dt.jsx(lD,{FallbackComponent:h4t,children:n?dt.jsx(d4t,{ref:Me,circuitJson:n,autoRotateDisabled:Z}):dt.jsx(Jw,{onRunClicked:e})})})}),dt.jsx(Ib,{value:"bom",children:dt.jsx("div",{className:Zv("rf-overflow-auto",fe?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:dt.jsx(lD,{fallbackRender:({error:Ue})=>dt.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:dt.jsxs("div",{className:"rf-p-4",children:[dt.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Bill of Materials"}),dt.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ue==null?void 0:Ue.message)||"An unknown error occurred"})]})}),children:n?dt.jsx(uLt,{circuitJson:n}):dt.jsx(Jw,{onRunClicked:e})})})}),dt.jsx(Ib,{value:"circuit_json",children:dt.jsx("div",{className:Zv("rf-overflow-auto",fe?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:dt.jsx(lD,{fallback:dt.jsx("div",{children:"Error loading JSON viewer"}),children:n?dt.jsx(lLt,{elements:n}):dt.jsx(Jw,{onRunClicked:e})})})}),dt.jsx(Ib,{value:"errors",children:dt.jsx("div",{className:Zv("rf-overflow-auto",fe?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:t||ue&&ue.length>0?dt.jsx(QFt,{code:r,circuitJsonErrors:ue,errorMessage:t,autoroutingLog:x,onReportAutoroutingLog:Q}):dt.jsx(Jw,{onRunClicked:e})})}),c&&dt.jsx(Ib,{value:"render_log",children:dt.jsx(QKt,{renderLog:A})})]})})})};kle.createRoot(document.getElementById("root")).render(dt.jsx(DKt,{defaultActiveTab:"cad",autoRotate3dViewerDisabled:!0,showRightHeaderContent:!1,circuitJson:window.CIRCUIT_JSON||{},...window.CIRCUIT_JSON_PREVIEW_PROPS||{}}));const RKt=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}))});
13468
+ searched component ${c.getString()}, which has ports: ${c.children.filter(u=>u.componentName==="Port").map(u=>`${u.getString()}(${u.getNameAndAliases().join(",")})`).join(" & ")}`):this.renderError(`Could not find port for selector "${a}"`)}return o.some(a=>!a.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:o,ports:o.map(({port:a})=>a)}}_findConnectedNets(){const e=this.getTracePathNetSelectors().map(n=>({selector:n,net:this.getSubcircuit().selectOne(n,{type:"net"})})),t=e.filter(n=>!n.net);return t.length>0&&this.renderError(`Could not find net for selector "${t[0].selector}" inside ${this}`),{netsWithSelectors:e,nets:e.map(n=>n.net)}}_getAllTracesConnectedToSameNet(){const e=this.getSubcircuit().selectAll("trace"),t=this._findConnectedNets().nets,n=this._findConnectedPorts().ports??[];return e.filter(i=>{if(i===this)return!1;const o=i._findConnectedNets().nets,a=i._findConnectedPorts().ports??[];return o.some(s=>t.includes(s))||a.some(s=>n.includes(s))})}_isExplicitlyConnectedToPort(e){const{allPortsFound:t,portsWithSelectors:n}=this._findConnectedPorts();return t?n.map(o=>o.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){aLe(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();return!e||!t?null:[...t].sort((o,a)=>(o.pcb_port_id||"").localeCompare(a.pcb_port_id||"")).map(o=>o.pcb_port_id).join(",")}doInitialSourceTraceRender(){var A;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n){this.renderError("Trace has no parent");return}const{allPortsFound:i,portsWithSelectors:o}=this._findConnectedPorts();if(!i)return;this._traceConnectionHash=this._computeTraceConnectionHash();const s=e.source_trace.list().find(d=>d.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&d.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(s){this.source_trace_id=s.source_trace_id;return}const l=this._findConnectedNets().nets,c=UVt({ports:o,nets:l}),u=e.source_trace.insert({connected_source_port_ids:o.map(d=>d.port.source_port_id),connected_source_net_ids:l.map(d=>d.source_net_id),subcircuit_id:(A=this.getSubcircuit())==null?void 0:A.subcircuit_id,max_length:RVt(o.map(d=>d.port),{db:e})??t.maxLength,display_name:c,min_trace_thickness:t.thickness});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(e,t){const{db:n}=this.root;kVt(e,{db:n})&&n.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:t.map(o=>o.pcb_port_id)})}doInitialPcbTraceRender(){var V,Z,J,se;if((V=this.root)!=null&&V.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this,i=this.getSubcircuit();if(!n)throw new Error("Trace has no parent");if(i._parsedProps.routingDisabled)return;const o=(Z=i._parsedProps.pcbRouteCache)==null?void 0:Z.pcbTraces;if(o){const ae=e.pcb_trace.insert({route:o.flatMap(ue=>ue.route),source_trace_id:this.source_trace_id,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((J=this.getGroup())==null?void 0:J.pcb_group_id)??void 0});this.pcb_trace_id=ae.pcb_trace_id;return}if(!i._shouldUseTraceByTraceRouting())return;const{allPortsFound:a,ports:s}=this._findConnectedPorts();if(!a)return;const l=[];for(const ae of s)ae._hasMatchedPcbPrimitive()||l.push(ae);if(l.length>0){e.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: ${l.map(ae=>ae.getString()).join(", ")}`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(ae=>ae.pcb_port_id).filter(Boolean)});return}const c=this._findConnectedNets().netsWithSelectors;if(s.length===0&&c.length===2){this.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(s.length===1&&c.length===1){const ae=s[0],ve=c[0].net.getAllConnectedPorts().filter(fe=>fe!==ae);if(ve.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}const xe=bVt(ae,ve);s.push(xe)}else if(s.length>1&&c.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 u=s.flatMap(ae=>ae.matchedComponents.filter(ue=>ue.componentName==="TraceHint")),A=(this._parsedProps.pcbRouteHints??[]).concat(u.flatMap(ae=>ae.getPcbRouteHints()));if(s.length>2){this.renderError(`Trace has more than two ports (${s.map(ae=>ae.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(this.getSubcircuit().selectAll("trace").filter(ae=>ae.renderPhaseStates.PcbTraceRender.initialized).some(ae=>ae._portsRoutedOnPcb.length===s.length&&ae._portsRoutedOnPcb.every(ue=>s.includes(ue))))return;let m=[];A.length===0?m=[o6(s[0]),o6(s[1])]:m=[o6(s[0]),...A,o6(s[1])];const C=n6(m),E=WB(this.root.db.toArray()),[_,x]=QVt(()=>P9(this.root.db.toArray()));if(x){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: ${x.message}`,source_trace_id:this.source_trace_id,center:{x:0,y:0},pcb_port_ids:s.map(ae=>ae.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[]});return}for(const ae of _)if(ae.connectedTo.length>0){const ve=E.getNetConnectedToId(ae.connectedTo[0]);ve&&ae.connectedTo.push(ve)}let Q=[];if(C.length===0)Q=m;else{const ae=C[0].layer_path;Q=m.map((ue,ve)=>ue.via?{...ue,via_to_layer:ae[ve]}:{...ue,layers:[ae[ve]]})}Q[0].pcb_port_id=s[0].pcb_port_id,Q[Q.length-1].pcb_port_id=s[1].pcb_port_id;const P=[];for(const[ae,ue]of iLe(Q)){const ve="via_to_layer"in ae?ae.via_to_layer:null,xe=2,fe="layers"in ae&&ae.layers.length===1?ae.layers[0]:ve??"top",Ee="layers"in ue&&ue.layers.length===1?ue.layers[0]:ve??"top",Ie="pcb_port_id"in ae?ae.pcb_port_id:null,Qe="pcb_port_id"in ue?ue.pcb_port_id:null,Me=this.getSubcircuit()._parsedProps.minTraceWidth??.16,ke=new T9({OBSTACLE_MARGIN:Me*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(Ie&&Qe),connMap:E,input:{obstacles:_,minTraceWidth:Me,connections:[{name:this.source_trace_id,pointsToConnect:[{...ae,layer:fe,pcb_port_id:Ie},{...ue,layer:Ee,pcb_port_id:Qe}]}],layerCount:2,bounds:{minX:Math.min(ae.x,ue.x)-xe,maxX:Math.max(ae.x,ue.x)+xe,minY:Math.min(ae.y,ue.y)-xe,maxY:Math.max(ae.y,ue.y)+xe}}});let Ue=null;try{Ue=ke.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:(ae.x+ue.x)/2,y:(ae.y+ue.y)/2},pcb_port_ids:s.map(Et=>Et.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:s.map(Et=>Et.pcb_component_id)})}if(!Ue)return;if(Ue.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:(ae.x+ue.x)/2,y:(ae.y+ue.y)/2},pcb_port_ids:s.map(ht=>ht.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:s.map(ht=>ht.pcb_component_id)});return}const[it]=Ue;ve&&(it.route=it.route.map(ht=>(ht.route_type==="wire"&&!ht.layer&&(ht.layer=ve),ht))),Ie&&it.route[0].route_type==="wire"&&(it.route[0].start_pcb_port_id=Ie);const nt=it.route[it.route.length-1];Qe&&nt.route_type==="wire"&&(nt.end_pcb_port_id=Qe),P.push(it.route)}const O=xVt(P),z=wVt(O),Y=e.pcb_trace.insert({route:O,source_trace_id:this.source_trace_id,subcircuit_id:(se=this.getSubcircuit())==null?void 0:se.subcircuit_id,trace_length:z});this._portsRoutedOnPcb=s,this.pcb_trace_id=Y.pcb_trace_id;for(const ae of O)ae.route_type==="via"&&e.pcb_via.insert({pcb_trace_id:Y.pcb_trace_id,x:ae.x,y:ae.y,hole_diameter:.3,outer_diameter:.6,layers:[ae.from_layer,ae.to_layer],from_layer:ae.from_layer,to_layer:ae.to_layer});this._insertErrorIfTraceIsOutsideBoard(O,s)}_doInitialSchematicTraceRenderWithDisplayLabel(){var P,O,z,Y;if((P=this.root)!=null&&P.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)throw new Error("Trace has no parent");const{allPortsFound:i,portsWithSelectors:o}=this._findConnectedPorts();if(!i)return;const a=o.map(({port:V})=>({port:V,position:V._getGlobalSchematicPositionAfterLayout(),schematic_port_id:V.schematic_port_id,facingDirection:V.facingDirection}));if(a.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let s,l;const c=a[0].position,u=a[0].port;if("path"in this.props){if(this.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[s,l]=this.props.path}else{if(!("from"in this.props&&"to"in this.props))throw new Error("Missing 'from' or 'to' properties in props.");s=this.props.from,l=this.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${s}).`);const A=a[1].position,d=a[1].port;if(!d.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${l}).`);const h=e.schematic_net_label.list().find(V=>V.source_net_id===u.source_port_id),m=e.schematic_net_label.list().find(V=>V.source_net_id===d.source_port_id),[C,E]=o.map(({port:V})=>V),x=((O=C.parent)==null?void 0:O.config.shouldRenderAsSchematicBox)?`${(z=C==null?void 0:C.parent)==null?void 0:z.props.name}_${C==null?void 0:C.props.name}`:`${(Y=E==null?void 0:E.parent)==null?void 0:Y.props.name}_${E==null?void 0:E.props.name}`,Q=this.props.schDisplayLabel??x;if(h&&h.text!==Q&&(h.text=`${Q} / ${h.text}`),m&&(m==null?void 0:m.text)!==Q&&(m.text=`${Q} / ${m.text}`),Q!=null&&Q.toLocaleLowerCase().includes("gnd")||Q!=null&&Q.toLocaleLowerCase().includes("ground")){!h&&!m?(r6({port:u,anchorPos:c,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e}),r6({port:d,anchorPos:A,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e})):h?m||r6({port:d,anchorPos:A,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e}):r6({port:u,anchorPos:c,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e});return}m||e.schematic_net_label.insert({text:this.props.schDisplayLabel??x,source_net_id:d.source_port_id,anchor_position:A,center:A,anchor_side:lse(d.facingDirection)??"bottom"}),h||e.schematic_net_label.insert({text:this.props.schDisplayLabel??x,source_net_id:u.source_port_id,anchor_position:c,center:c,anchor_side:lse(u.facingDirection)??"bottom"})}_isSymbolToChipConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const o=n.parent.config.shouldRenderAsSchematicBox,a=i.parent.config.shouldRenderAsSchematicBox;return o&&!a||!o&&a}_isSymbolToSymbolConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const o=!n.parent.config.shouldRenderAsSchematicBox,a=!i.parent.config.shouldRenderAsSchematicBox;return o&&a}_isChipToChipConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const o=n.parent.config.shouldRenderAsSchematicBox,a=i.parent.config.shouldRenderAsSchematicBox;return o&&a}doInitialSchematicTraceRender(){var fe,Ee,Ie;if((fe=this.root)!=null&&fe.schematicDisabled||((Ee=this.getGroup())==null?void 0:Ee._getSchematicLayoutMode())==="match-adapt")return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)throw new Error("Trace has no parent");const{allPortsFound:i,portsWithSelectors:o}=this._findConnectedPorts(),{netsWithSelectors:a}=this._findConnectedNets();if(!i)return;const l=o.map(Qe=>Qe.port.schematic_port_id).sort().join(","),c=(Ie=this.root)==null?void 0:Ie._getBoard();if(c!=null&&c._connectedSchematicPortPairs&&c._connectedSchematicPortPairs.has(l))return;if(this.props.schDisplayLabel&&("from"in this.props&&"to"in this.props||"path"in this.props)){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const u={name:this.source_trace_id,pointsToConnect:[]},A=PVt(this),d=o.map(({port:Qe})=>({port:Qe,position:Qe._getGlobalSchematicPositionAfterLayout(),schematic_port_id:Qe.schematic_port_id??void 0,facingDirection:Qe.facingDirection}));if(d.length===1&&a.length===1){const Qe=a[0].net,{port:Me,position:ke}=d[0];e.schematic_net_label.insert({text:Qe._parsedProps.name,source_net_id:Qe.source_net_id,anchor_position:ke,center:ke,anchor_side:lse(Me.facingDirection)??"bottom"});return}if(d.length<2)return;u.pointsToConnect=d.map(({position:Qe})=>({...Qe,layer:"top"}));const m=_Vt(A),C=2,E={minTraceWidth:.1,obstacles:A,connections:[u],bounds:{minX:m.minX-C,maxX:m.maxX+C,minY:m.minY-C,maxY:m.maxY+C},layerCount:1};let _=T9,x=!1;this.getSubcircuit().props._schDirectLineRoutingEnabled&&(_=fLe,x=!0);let P=new _({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(P.length===0){if(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection()){this._doInitialSchematicTraceRenderWithDisplayLabel();return}P=new fLe({input:E}).solveAndMapToTraces(),x=!0}const[{route:O}]=P;let z=[];for(let Qe=0;Qe<O.length-1;Qe++)z.push({from:O[Qe],to:O[Qe+1]});const Y=this.source_trace_id;let V=[];if(!x){FVt({edges:z,db:e,source_trace_id:Y});const Qe=i6({db:e,source_trace_id:Y,differentNetOnly:!0}).flatMap(Me=>Me.edges);z=gLe({edges:z,otherEdges:Qe}),V=mLe({edges:z,db:e,source_trace_id:this.source_trace_id})}const Z=z[z.length-1],J=d[d.length-1],se=pLe(Z);z.push(...cse({lastEdge:Z,lastEdgePort:J,lastDominantDirection:se}));const ae=z[0],ue=d[0],ve=pLe(ae);if(z.unshift(...cse({firstEdge:ae,firstEdgePort:ue,firstDominantDirection:ve})),!this.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(this.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&SVt(V,z)>=5&&(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection())){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const xe=e.schematic_trace.insert({source_trace_id:this.source_trace_id,edges:z,junctions:V});this.schematic_trace_id=xe.schematic_trace_id,c!=null&&c._connectedSchematicPortPairs&&c._connectedSchematicPortPairs.add(l)}},LVt=Rm("tscircuit:core"),GVt=In({x:xC,y:xC,z:xC}),N1=class extends $v{constructor(e){super(e);Le(this,"reactSubtrees",[]);Le(this,"_impliedFootprint");Le(this,"isPrimitiveContainer",!0);Le(this,"_asyncSupplierPartNumbers");Le(this,"pcb_missing_footprint_error_id");Le(this,"_hasStartedFootprintUrlLoad",!1);this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames}initPorts(e={}){var a,s,l,c,u,A,d,h,m,C;if((a=this.root)!=null&&a.schematicDisabled)return;const{config:t}=this,n=[],i=this._getSchematicPortArrangement();if(i&&!this._parsedProps.pinLabels){for(const x in i){const Q=i[x].pins;if(Array.isArray(Q))for(const P of Q){const O=tT(P,this._parsedProps.pinLabels);n.push(new r2({pinNumber:O,aliases:((s=e.additionalAliases)==null?void 0:s[`pin${O}`])??[]},{originDescription:`schPortArrangement:${x}`}))}}const E=["left","right","top","bottom"];let _=1;for(const x of E){const Q=i[`${x}Size`];for(let P=0;P<Q;P++)n.push(new r2({pinNumber:_++,aliases:((l=e.additionalAliases)==null?void 0:l[`pin${_}`])??[]},{originDescription:`schPortArrangement:${x}`}))}}const o=this._parsedProps.pinLabels;if(o)for(let[E,_]of Object.entries(o)){E=E.replace("pin","");let x=n.find(O=>O._parsedProps.pinNumber===Number(E));const Q=Array.isArray(_)?_[0]:_,P=Array.isArray(_)?_.slice(1):[];x?(x.externallyAddedAliases.push(Q,...P),x.props.name=Q):(x=new r2({pinNumber:parseInt(E),name:Q,aliases:[...P,...((c=e.additionalAliases)==null?void 0:c[`pin${parseInt(E)}`])??[]]},{originDescription:`pinLabels:pin${E}`}),n.push(x))}if(t.schematicSymbolName){const E=l0[this._getSchematicSymbolNameOrThrow()];if(!E)return;for(const _ of E.ports){const x=ALe(_.labels);if(!x)continue;const Q=n.find(P=>P._parsedProps.pinNumber===Number(x));if(Q)Q.schematicSymbolPortDef=_;else{const P=nT(_.labels.concat(((u=e.additionalAliases)==null?void 0:u[`pin${x}`])??[]));P&&(P.originDescription=`schematicSymbol:labels[0]:${_.labels[0]}`,P.schematicSymbolPortDef=_,n.push(P))}}this.addAll(n)}if(!this._getSchematicPortArrangement()){const E=this.getPortsFromFootprint(e);for(const _ of E)n.some(x=>x.isMatchingAnyOf(_.getNameAndAliases()))||n.push(_)}for(let E=1;E<=(e.pinCount??this._getPinCount());E++){if(!i||n.find(x=>x._parsedProps.pinNumber===E))continue;let _=[...((A=i.leftSide)==null?void 0:A.pins)??[],...((d=i.rightSide)==null?void 0:d.pins)??[],...((h=i.topSide)==null?void 0:h.pins)??[],...((m=i.bottomSide)==null?void 0:m.pins)??[]].map(x=>tT(x,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(x=>x in i)&&(_=Array.from({length:this._getPinCount()},(x,Q)=>Q+1)),_.includes(E)&&n.push(new r2({pinNumber:E,aliases:((C=e.additionalAliases)==null?void 0:C[`pin${E}`])??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${E}`}))}n.length>0&&this.addAll(n)}_getImpliedFootprintString(){return null}_isFootprintUrl(e){return e.startsWith("http://")||e.startsWith("https://")}_addChildrenFromStringFootprint(){var o;const{name:e,pcbRotation:t,pinLabels:n}=this.props;let{footprint:i}=this.props;if(i??(i=(o=this._getImpliedFootprintString)==null?void 0:o.call(this)),!!i&&typeof i=="string"){if(this._isFootprintUrl(i))return;const a=S9.string(i).soup(),s=uLe({componentName:e,componentRotation:t,footprint:i,pinLabels:n},a);this.addAll(s)}}get portMap(){return new Proxy({},{get:(e,t)=>{const n=this.children.find(i=>i.componentName==="Port"&&i.isMatchingNameOrAlias(t));if(!n)throw new Error(`There was an issue finding the port "${t.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return n}})}getInstanceForReactElement(e){for(const t of this.reactSubtrees)if(t.element===e)return t.component;return null}doInitialSourceRender(){const e=this.config.sourceFtype;if(!e)return;const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:e,name:n.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialSchematicComponentRender(){var i,o,a;if((i=this.root)!=null&&i.schematicDisabled)return;const{db:e}=this.root,{schematicSymbolName:t}=this.config;t?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();const n=(o=this.getSubcircuit())==null?void 0:o._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&n){if(!this.schematic_component_id)return;const s=AR.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:(a=this.getSubcircuit())==null?void 0:a.subcircuit_id});e.schematic_manual_edit_conflict_warning.insert(s)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];const e=[];for(const t of this.internallyConnectedPinNames){const n=[];for(const i of t)n.push(this.portMap[i]);e.push(n)}return e}_doInitialSchematicComponentRenderWithSymbol(){var a;if((a=this.root)!=null&&a.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getSchematicSymbolNameOrThrow(),i=l0[n],o=this._getGlobalSchematicPositionBeforeLayout();if(i){const s=e.schematic_component.insert({center:o,size:i.size,source_component_id:this.source_component_id,symbol_name:n,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=s.schematic_component_id}}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){var A;if((A=this.root)!=null&&A.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getSchematicBoxDimensions(),i={};if(Array.isArray(t.pinLabels))t.pinLabels.forEach((d,h)=>{i[String(h+1)]=d});else for(const[d,h]of Object.entries(t.pinLabels??{}))i[d]=Array.isArray(h)?h[0]:h;const o=this._getGlobalSchematicPositionBeforeLayout(),a=this._getSchematicPortArrangement(),s=e.schematic_component.insert({center:o,rotation:t.schRotation??0,size:n.getSize(),port_arrangement:lVt(a),pin_spacing:t.schPinSpacing??.2,pin_styles:sVt(t.schPinStyle,t.pinLabels),port_labels:i,source_component_id:this.source_component_id}),l=(a==null?void 0:a.topSide)!==void 0||(a==null?void 0:a.bottomSide)!==void 0,c=n==null?void 0:n.getSize().width,u=n==null?void 0:n.getSize().height;e.schematic_text.insert({text:t.manufacturerPartNumber??"",schematic_component_id:s.schematic_component_id,anchor:"left",rotation:0,position:{x:l?o.x+(c??0)/2+.1:o.x-(c??0)/2,y:l?o.y+(u??0)/2+.35:o.y-(u??0)/2-.13},color:"#006464",font_size:.18}),e.schematic_text.insert({text:t.name??"",schematic_component_id:s.schematic_component_id,anchor:"left",rotation:0,position:{x:l?o.x+(c??0)/2+.1:o.x-(c??0)/2,y:l?o.y+(u??0)/2+.55:o.y+(u??0)/2+.13},color:"#006464",font_size:.18}),this.schematic_component_id=s.schematic_component_id}doInitialPcbComponentRender(){var a;if((a=this.root)!=null&&a.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getSubcircuit(),i=e.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:n.subcircuit_id??void 0});if(!t.footprint&&!this.isGroup){const s=e.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=s.pcb_missing_footprint_error_id}this.pcb_component_id=i.pcb_component_id;const o=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&o){const s=hR.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:n.subcircuit_id??void 0});e.pcb_manual_edit_conflict_warning.insert(s)}}doInitialPcbComponentSizeCalculation(){var o;if((o=this.root)!=null&&o.pcbDisabled||!this.pcb_component_id)return;const{db:e}=this.root,{_parsedProps:t}=this,n=sse(this.children);if(n.width===0||n.height===0)return;const i={x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2};e.pcb_component.update(this.pcb_component_id,{center:i,width:n.width,height:n.height})}_renderReactSubtree(e){return{element:e,component:aVt(e)}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){}doInitialPcbFootprintStringRender(){var o;let{footprint:e}=this.props;if(e??(e=(o=this._getImpliedFootprintString)==null?void 0:o.call(this)),!e)return;const{name:t,pcbRotation:n,pinLabels:i}=this.props;if(typeof e=="string"&&this._isFootprintUrl(e)){if(this._hasStartedFootprintUrlLoad)return;this._hasStartedFootprintUrlLoad=!0;const a=e;this._queueAsyncEffect("load-footprint-url",async()=>{const l=await(await fetch(a)).json(),c=uLe({componentName:t,componentRotation:n,footprint:a,pinLabels:i},l);this.addAll(c),this._markDirty("InitializePortsFromChildren")});return}if(yt.isValidElement(e)){if(this.reactSubtrees.some(s=>s.element===e))return;const a=this._renderReactSubtree(e);this.reactSubtrees.push(a),this.add(a.component);return}!yt.isValidElement(e)&&e.componentName==="Footprint"&&this.add(e)}_hasExistingPortExactly(e){return this.children.filter(n=>n.componentName==="Port").some(n=>{const i=e.getNameAndAliases(),o=n.getNameAndAliases();return i.length===o.length&&i.every(a=>o.includes(a))})}add(e){let t;if(yt.isValidElement(e)){const n=this._renderReactSubtree(e);this.reactSubtrees.push(n),t=n.component}else t=e;if(t.componentName==="Port"){if(this._hasExistingPortExactly(t))return;const i=this.children.filter(o=>o.componentName==="Port").find(o=>o.isMatchingAnyOf(t.getNameAndAliases()));i&&LVt(`Similar ports added. Port 1: ${i}, Port 2: ${t}`)}super.add(t)}getPortsFromFootprint(e){let{footprint:t}=this.props;if((!t||yt.isValidElement(t))&&(t=this.children.find(i=>i.componentName==="Footprint")),typeof t=="string"){if(this._isFootprintUrl(t))return[];const i=S9.string(t).soup(),o=[];for(const a of i)if("port_hints"in a&&a.port_hints){const s=nT(a.port_hints,e);if(!s)continue;s.originDescription=`footprint:string:${t}:port_hints[0]:${a.port_hints[0]}`,o.push(s)}return o}if(!yt.isValidElement(t)&&t&&t.componentName==="Footprint"){const i=t;let o=1;const a=[];for(const s of i.children){if(!s.props.portHints)continue;let l=s.props.portHints;l.some(A=>A.startsWith("pin"))||(l=[...l,`pin${o}`]),o++;const u=nT(l);u&&(u.originDescription=`footprint:${t}`,a.push(u))}return a}const n=[];if(!t){for(const i of this.children)if(i.props.portHints&&i.isPcbPrimitive){const o=nT(i.props.portHints);o&&n.push(o)}}return n}getPortsFromSchematicSymbol(){var i;if((i=this.root)!=null&&i.schematicDisabled)return[];const{config:e}=this;if(!e.schematicSymbolName)return[];const t=l0[e.schematicSymbolName];if(!t)return[];const n=[];for(const o of t.ports){const a=nT(o.labels);a&&(a.schematicSymbolPortDef=o,n.push(a))}return n}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){const{_parsedProps:e}=this,t=[];if(e.connections)for(const[n,i]of Object.entries(e.connections)){const o=Array.isArray(i)?i:[i];for(const a of o)t.push(a)}return t}_createNetsFromProps(e){aLe(this,e)}_getPcbCircuitJsonBounds(){const{db:e}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();const t=e.pcb_component.get(this.pcb_component_id);return{center:{x:t.center.x,y:t.center.y},bounds:{left:t.center.x-t.width/2,top:t.center.y-t.height/2,right:t.center.x+t.width/2,bottom:t.center.y+t.height/2},width:t.width,height:t.height}}_getPinCountFromSchematicPortArrangement(){const e=this._getSchematicPortArrangement();if(!e)return 0;if(!dLe(e))return(e.leftSize??e.leftPinCount??0)+(e.rightSize??e.rightPinCount??0)+(e.topSize??e.topPinCount??0)+(e.bottomSize??e.bottomPinCount??0);const{leftSide:n,rightSide:i,topSide:o,bottomSide:a}=e;return Math.max(...(n==null?void 0:n.pins)??[],...(i==null?void 0:i.pins)??[],...(o==null?void 0:o.pins)??[],...(a==null?void 0:a.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:e}=this,t=this._getPinCount(),n=e.schPinSpacing??.2;return vVt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:n,numericSchPinStyle:EVt(e.schPinStyle,e.pinLabels),pinCount:t,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:e.pinLabels})}doInitialCadModelRender(){var c;const{db:e}=this.root,{boardThickness:t=0}=((c=this.root)==null?void 0:c._getBoard())??{},n=this._parsedProps.cadModel;if(!this.pcb_component_id||!n&&!this.props.footprint||n===null)return;const i=this._getPcbCircuitJsonBounds(),o=e.pcb_component.get(this.pcb_component_id);if(typeof n=="string")throw new Error("String cadModel not yet implemented");const a=GVt.parse({x:0,y:0,z:typeof(n==null?void 0:n.rotationOffset)=="number"?n.rotationOffset:0,...typeof(n==null?void 0:n.rotationOffset)=="object"?n.rotationOffset??{}:{}}),s=m2.parse({x:0,y:0,z:0,...typeof(n==null?void 0:n.positionOffset)=="object"?n.positionOffset:{}}),l=this.props.layer==="bottom"?"bottom":"top";e.cad_component.insert({position:{x:i.center.x+s.x,y:i.center.y+s.y,z:(l==="bottom"?-t/2:t/2)+s.z},rotation:{x:a.x,y:(l==="top"?0:180)+a.y,z:l==="bottom"?-(((o==null?void 0:o.rotation)??0)+a.z)+180:((o==null?void 0:o.rotation)??0)+a.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(n??{})?this._addCachebustToModelUrl(n.stlUrl):void 0,model_obj_url:"objUrl"in(n??{})?this._addCachebustToModelUrl(n.objUrl):void 0,model_jscad:"jscad"in(n??{})?n.jscad:void 0,footprinter_string:typeof this.props.footprint=="string"&&!n?this.props.footprint:void 0})}_addCachebustToModelUrl(e){var n;if(!e||!e.includes("modelcdn.tscircuit.com"))return e;const t=((n=this.root)==null?void 0:n.getClientOrigin())??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(t)}`}_getPartsEngineCacheKey(e,t){return JSON.stringify({ftype:e.ftype,name:e.name,manufacturer_part_number:e.manufacturer_part_number,footprinterString:t})}async _getSupplierPartNumbers(e,t,n){var l,c;if(this.props.doNotPlace)return{};const i=(c=(l=this.root)==null?void 0:l.platform)==null?void 0:c.localCacheEngine,o=this._getPartsEngineCacheKey(t,n);if(i){const u=await i.getItem(o);if(u)try{return JSON.parse(u)}catch{}}const a=await Promise.resolve(e.findPart({sourceComponent:t,footprinterString:n})),s=a==="Not found"?{}:a;if(i)try{await i.setItem(o,JSON.stringify(s))}catch{}return s}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;const e=this.getInheritedProperty("partsEngine");if(!e)return;const{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(!n||n.supplier_part_numbers)return;let i;this.props.footprint&&typeof this.props.footprint=="string"&&(i=this.props.footprint);const o=this._getSupplierPartNumbers(e,n,i);if(!(o instanceof Promise)){t.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:e}=this.root,t=e.source_component.get(this.source_component_id);if(t&&!t.supplier_part_numbers&&this._asyncSupplierPartNumbers){e.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){const{_parsedProps:e}=this;if(e.connections)for(const[t,n]of Object.entries(e.connections)){const i=Array.isArray(n)?n:[n];for(const o of i)this.add(new i9({from:`${this.getSubcircuitSelector()} > port.${t}`,to:o}))}}},OVt=class{constructor(r,e={}){Le(this,"input");Le(this,"isRouting",!1);Le(this,"solver");Le(this,"eventHandlers",{complete:[],error:[],progress:[]});Le(this,"cycleCount",0);Le(this,"stepDelay");Le(this,"timeoutId");this.input=r;const{capacityDepth:t,targetMinCapacity:n,stepDelay:i=0}=e;this.solver=new UY(r,{capacityDepth:t,targetMinCapacity:n,cacheProvider:null}),this.stepDelay=i}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){var r;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 e=Date.now(),t=this.solver.iterations;for(;Date.now()-e<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();const n=(this.solver.iterations-t)/(Date.now()-e)*1e3;this.cycleCount++;const i=((r=this.solver)==null?void 0:r.preview())||void 0,o=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,progress:o,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(e){this.emitEvent({type:"error",error:e instanceof Error?e:new Error(String(e))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(r,e){r==="complete"?this.eventHandlers.complete.push(e):r==="error"?this.eventHandlers.error.push(e):r==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(r){if(r.type==="complete")for(const e of this.eventHandlers.complete)e(r);else if(r.type==="error")for(const e of this.eventHandlers.error)e(r);else if(r.type==="progress")for(const e of this.eventHandlers.progress)e(r)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new Error(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},yLe=class extends $v{constructor(){super(...arguments);Le(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:y8e}}doInitialPortMatching(){const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)return;if(n.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!n)throw new Error("TraceHint has no parent");if(!t.for){this.renderError(`TraceHint has no for property (${this})`);return}const i=n.selectOne(t.for,{type:"port"});i||this.renderError(`${this} could not find port for selector "${t.for}"`),this.matchedPort=i,i.registerMatch(this)}getPcbRouteHints(){const{_parsedProps:e}=this,t=e.offset?[e.offset]:e.offsets;if(!t)return[];const n=this._computePcbGlobalTransformBeforeLayout();return t.map(i=>({...ei(n,i),via:i.via,to_layer:i.to_layer,trace_width:i.trace_width}))}doInitialPcbTraceHintRender(){var n,i,o;if((n=this.root)!=null&&n.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;e.pcb_trace_hint.insert({pcb_component_id:(i=this.matchedPort)==null?void 0:i.pcb_component_id,pcb_port_id:(o=this.matchedPort)==null?void 0:o.pcb_port_id,route:this.getPcbRouteHints()})}},zVt=(r,e)=>{const t=r.source_group.list(),n=[],i=o=>{const a=t.filter(s=>s.parent_subcircuit_id===o);for(const s of a)s.subcircuit_id&&(n.push(s.subcircuit_id),i(s.subcircuit_id))};return i(e),n},vLe=({db:r,circuitJson:e,subcircuit_id:t,minTraceWidth:n=.1})=>{if(!r&&e&&(r=q1(e)),!r)throw new Error("db or circuitJson is required");const i=r.pcb_trace_hint.list(),o=t?new Set([t]):null;if(t){const C=zVt(r,t);for(const E of C)o.add(E)}const a=(e??r.toArray()).filter(C=>!t||"subcircuit_id"in C&&o.has(C.subcircuit_id)),s=r.pcb_board.list()[0];r=q1(a);const l=WB(a),c=P9([...r.pcb_component.list(),...r.pcb_smtpad.list(),...r.pcb_plated_hole.list(),...r.pcb_hole.list(),...r.pcb_via.list()].filter(C=>!t||(o==null?void 0:o.has(C.subcircuit_id))),l);for(const C of c){const E=C.connectedTo.flatMap(_=>l.getIdsConnectedToNet(_));C.connectedTo.push(...E)}const u=c.flatMap(C=>[{x:C.center.x-C.width/2,y:C.center.y-C.height/2},{x:C.center.x+C.width/2,y:C.center.y+C.height/2}]);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(C=>C.x))-1,maxX:Math.max(...u.map(C=>C.x))+1,minY:Math.min(...u.map(C=>C.y))-1,maxY:Math.max(...u.map(C=>C.y))+1};const d=r.source_trace.list().map(C=>{var Y,V,Z;const E=C.connected_source_port_ids.map(J=>{const se=r.source_port.get(J),ae=r.pcb_port.getWhere({source_port_id:J});return{...se,...ae}});if(E.length<2)return null;const[_,x]=E,Q=((Y=_.layers)==null?void 0:Y[0])??"top",P=((V=x.layers)==null?void 0:V[0])??"top",O=i.filter(J=>J.pcb_port_id===_.pcb_port_id||J.pcb_port_id===x.pcb_port_id),z=[];for(const J of O){const se=r.pcb_port.get(J.pcb_port_id),ae=((Z=se==null?void 0:se.layers)==null?void 0:Z[0])??"top";for(const ue of J.route)z.push({x:ue.x,y:ue.y,layer:ae})}return{name:C.source_trace_id??l.getNetConnectedToId(C.source_trace_id)??"",source_trace_id:C.source_trace_id,pointsToConnect:[{x:_.x,y:_.y,layer:Q},...z,{x:x.x,y:x.y,layer:P}]}}).filter(C=>C!==null),h=r.source_net.list().filter(C=>!t||(o==null?void 0:o.has(C.subcircuit_id))),m=[];for(const C of h){const E=r.source_trace.list().filter(_=>{var x;return(x=_.connected_source_net_ids)==null?void 0:x.includes(C.source_net_id)});m.push({name:C.source_net_id??l.getNetConnectedToId(C.source_net_id),pointsToConnect:E.flatMap(_=>r.pcb_port.list().filter(Q=>_.connected_source_port_ids.includes(Q.source_port_id)).map(Q=>{var P;return{x:Q.x,y:Q.y,layer:((P=Q.layers)==null?void 0:P[0])??"top",pcb_port_id:Q.pcb_port_id}}))})}return{simpleRouteJson:{bounds:A,obstacles:c,connections:[...d,...m],layerCount:2,minTraceWidth:n},connMap:l}};function use(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 o=e.source_port.getWhere({source_component_id:i.source_component_id,pin_number:n});return{subcircuit_connectivity_map_key:(o==null?void 0:o.subcircuit_connectivity_map_key)??null,source_port_id:o.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 HVt({path:r,db:e,layoutConnMap:t}){let n=use(r.to,e)??use(r.from,e);if(!n){const o=t.getNetConnectedToId(iS(r.to));n=t.getIdsConnectedToNet(o).map(s=>Jae(s)).map(s=>use(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 o of i)if(o.connected_source_port_ids.includes(n.source_port_id))return o.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 YVt(r){const{db:e}=r.root;let t=structuredClone(e.toArray());t=ZYt(t);const n=WYt(t),i=new jYt({inputNetlist:n});let o=null;try{i.solve(),o=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:a,junctions:s,netLabels:l,paths:c}=o,u=new xQ({});for(const A of c)u.addConnections([[iS(A.from),iS(A.to)]]);for(const A of s)for(const d of c)for(const h of d.points)Math.abs(h.x-A.x)<.001&&Math.abs(h.y-A.y)<.001&&u.addConnections([[iS(d.from),iS(A)],[iS(d.to),iS(A)]]);for(const A of a){const d=e.source_component.list().find(_=>_.name===A.boxId);if(!d)continue;const h=e.schematic_component.getWhere({source_component_id:d.source_component_id});if(!h)continue;const m={x:A.centerX-h.center.x+.1,y:A.centerY-h.center.y-.1};e.schematic_component.update(h.schematic_component_id,{center:{x:h.center.x+m.x,y:h.center.y+m.y}});const C=e.schematic_port.list({schematic_component_id:h.schematic_component_id});for(const _ of C)e.schematic_port.update(_.schematic_port_id,{center:{x:_.center.x+m.x,y:_.center.y+m.y}});const E=e.schematic_text.list({schematic_component_id:h.schematic_component_id});for(const _ of E)e.schematic_text.update(_.schematic_text_id,{position:{x:_.position.x+m.x,y:_.position.y+m.y}})}for(const A of l){const d=e.source_net.list().find(h=>h.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=HVt({path:A,db:xB(t),layoutConnMap:u});let h=[];for(let E=0;E<A.points.length-1;E++)h.push({from:{x:A.points[E].x,y:A.points[E].y},to:{x:A.points[E+1].x,y:A.points[E+1].y}});const m=i6({db:e,source_trace_id:d,differentNetOnly:!0}).flatMap(E=>E.edges);m.length>0&&(h=gLe({edges:h,otherEdges:m}));const C=mLe({edges:h,db:e,source_trace_id:d});e.schematic_trace.insert({source_trace_id:d,edges:h,junctions:C})}}function VVt(r){if(!r.isSubcircuit)return;const{db:e}=r.root,t=r.selectAll("trace"),n=new xQ({});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 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_port_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_port.update(s,{subcircuit_connectivity_map_key:c})}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_net_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_net.update(s,{subcircuit_connectivity_map_key:c})}}function KVt(r){var x;const{db:e}=r.root,t=r._parsedProps,n=r.children.filter(Q=>Q.schematic_component_id);if(n.length===0)return;let i=0,o=0;for(const Q of n){const P=e.schematic_component.get(Q.schematic_component_id);P!=null&&P.size&&(i=Math.max(i,P.size.width),o=Math.max(o,P.size.height))}i===0&&n.length>0&&(i=1),o===0&&n.length>0&&(o=1);let a=t.gridCols,s,l=t.gridGap;(x=t.schLayout)!=null&&x.grid&&(a=t.schLayout.grid.cols??a,s=t.schLayout.grid.rows,l=t.schLayout.grid.gap??l);let c,u;a!==void 0&&s!==void 0?(c=a,u=s):a!==void 0?(c=a,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 h=c*i+Math.max(0,c-1)*A,m=u*o+Math.max(0,u-1)*d,C=r._getGlobalSchematicPositionBeforeLayout(),E=C.x-h/2+i/2,_=C.y+m/2-o/2;for(let Q=0;Q<n.length;Q++){const P=n[Q];if(!P.schematic_component_id)continue;const O=Math.floor(Q/c),z=Q%c;if(O>=u||z>=c){console.warn(`Schematic grid layout: Child ${P.getString()} at index ${Q} (row ${O}, col ${z}) exceeds specified grid dimensions (${u}x${c}). Skipping placement.`);continue}const Y=E+z*(i+A),V=_-O*(o+d),Z=e.schematic_component.get(P.schematic_component_id);if(Z){const J=Z.center,se={x:Y,y:V};e.schematic_component.update(P.schematic_component_id,{center:se});const ae=se.x-J.x,ue=se.y-J.y,ve=e.schematic_port.list({schematic_component_id:P.schematic_component_id});for(const fe of ve)e.schematic_port.update(fe.schematic_port_id,{center:{x:fe.center.x+ae,y:fe.center.y+ue}});const xe=e.schematic_text.list({schematic_component_id:P.schematic_component_id});for(const fe of xe)e.schematic_text.update(fe.schematic_text_id,{position:{x:fe.position.x+ae,y:fe.position.y+ue}})}}r.schematic_group_id&&e.schematic_group.update(r.schematic_group_id,{width:h,height:m,center:C})}var Ase=class extends N1{constructor(){super(...arguments);Le(this,"pcb_group_id",null);Le(this,"schematic_group_id",null);Le(this,"subcircuit_id",null);Le(this,"_hasStartedAsyncAutorouting",!1);Le(this,"_asyncAutoroutingResult",null)}get config(){return{zodProps:NPe,componentName:"Group"}}doInitialSourceRender(){const{db:e}=this.root,t=e.source_group.insert({name:this._parsedProps.name,is_subcircuit:this.isSubcircuit});this.subcircuit_id=`subcircuit_${t.source_group_id}`,this.source_group_id=t.source_group_id,e.source_group.update(t.source_group_id,{subcircuit_id:this.subcircuit_id});for(const n of this.children)e.source_component.update(n.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){var n,i,o;const{db:e}=this.root;if(!this.isSubcircuit)return;const t=(o=(i=(n=this.parent)==null?void 0:n.getSubcircuit)==null?void 0:i.call(n))==null?void 0:o.subcircuit_id;t&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:t})}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.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=n.pcb_group_id;for(const o of this.children)e.pcb_component.update(o.pcb_component_id,{pcb_group_id:n.pcb_group_id})}doInitialPcbPrimitiveRender(){var n;if((n=this.root)!=null&&n.pcbDisabled)return;const{db:e}=this.root,t=sse(this.children);this.pcb_group_id&&e.pcb_group.update(this.pcb_group_id,{width:t.width,height:t.height,center:{x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2}})}doInitialCreateTraceHintsFromProps(){var o;const{_parsedProps:e}=this,{db:t}=this.root,n=e;if(!this.isSubcircuit)return;const i=(o=n.layout)==null?void 0:o.manual_trace_hints;if(i)for(const a of i)this.add(new yLe({for:a.pcb_port_selector,offsets:a.offsets}))}doInitialSourceAddConnectivityMapKey(){VVt(this)}_areChildSubcircuitsRouted(){const e=this.selectAll("group").filter(t=>t.isSubcircuit);for(const t of e)if(t._shouldRouteAsync()&&!t._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){const e=this._getAutorouterConfig();return e.groupMode==="sequential-trace"?!1:!!(e.local&&e.groupMode==="subcircuit"||!e.local)}_hasTracesToRoute(){const e=Rm("tscircuit:core:_hasTracesToRoute"),t=this.selectAll("trace");return e(`[${this.getString()}] has ${t.length} traces to route`),t.length>0}async _runEffectMakeHttpAutoroutingRequest(){var c,u,A,d;const{db:e}=this.root,t=Rm("tscircuit:core:_runEffectMakeHttpAutoroutingRequest");this._parsedProps;const n=this._getAutorouterConfig(),i=n.serverUrl,o=n.serverMode,a=(h,m)=>{var C;return t("fetching",h),m.headers&&(m.headers["Tscircuit-Core-Version"]=(C=this.root)==null?void 0:C.getCoreVersion()),fetch(h,m)},s=this.root.db.toArray().filter(h=>h.type.startsWith("source_")||h.type.startsWith("pcb_"));if(o==="solve-endpoint"){if(((c=this.props.autorouter)==null?void 0:c.inputFormat)==="simplified"){const{autorouting_result:m}=await a(`${i}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:vLe({db:e,minTraceWidth:((u=this.props.autorouter)==null?void 0:u.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(C=>C.json());this._asyncAutoroutingResult=m,this._markDirty("PcbTraceRender");return}const{autorouting_result:h}=await a(`${i}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:s,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(m=>m.json());this._asyncAutoroutingResult=h,this._markDirty("PcbTraceRender");return}const{autorouting_job:l}=await a(`${i}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:s,provider:"freerouting",autostart:!0,display_name:(A=this.root)==null?void 0:A.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:n.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());for(;;){const{autorouting_job:h}=await a(`${i}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(m=>m.json());if(h.is_finished){const{autorouting_job_output:m}=await a(`${i}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(C=>C.json());this._asyncAutoroutingResult={output_pcb_traces:m.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(h.has_error)throw e.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,message:((d=h.error)==null?void 0:d.message)??JSON.stringify(h.error)}),new Error(`Autorouting job failed: ${JSON.stringify(h.error)}`);await new Promise(m=>setTimeout(m,100))}}async _runLocalAutorouting(){var s,l,c,u,A;const{db:e}=this.root;this._parsedProps;const t=Rm("tscircuit:core:_runLocalAutorouting");t(`[${this.getString()}] starting local autorouting`);const n=this._getAutorouterConfig(),{simpleRouteJson:i}=vLe({db:e,minTraceWidth:((s=this.props.autorouter)==null?void 0:s.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id});(l=this.root)==null||l.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:i});let o;n.algorithmFn?o=await n.algorithmFn(i):o=new OVt(i,{capacityDepth:(c=this.props.autorouter)==null?void 0:c.capacityDepth,targetMinCapacity:(u=this.props.autorouter)==null?void 0:u.targetMinCapacity});const a=new Promise((d,h)=>{o.on("complete",m=>{t(`[${this.getString()}] local autorouting complete`),d(m.traces)}),o.on("error",m=>{t(`[${this.getString()}] local autorouting error: ${m.error.message}`),h(m.error)})});o.on("progress",d=>{var h;(h=this.root)==null||h.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...d})}),o.start();try{const d=await a;this._asyncAutoroutingResult={output_pcb_traces:d},this._markDirty("PcbTraceRender")}catch(d){const{db:h}=this.root;throw h.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,message:d instanceof Error?d.message:String(d)}),(A=this.root)==null||A.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:d instanceof Error?d.message:String(d)},simpleRouteJson:i}),d}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 t;const e=Rm("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!((t=this.root)!=null&&t.pcbDisabled)&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){e(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}e(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}updatePcbTraceRender(){var n;const e=Rm("tscircuit:core:updatePcbTraceRender");if(e(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(e(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;const{db:t}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){e(`[${this.getString()}] updating PCB traces from simple route json (${(n=this._asyncAutoroutingResult.output_simple_route_json.traces)==null?void 0:n.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){e(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){const{db:e}=this.root,{traces:t}=this._asyncAutoroutingResult.output_simple_route_json;if(t)for(const n of t)e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:n.route})}_updatePcbTraceRenderFromPcbTraces(){const{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;const{db:t}=this.root;for(const n of e)if(n.type==="pcb_trace"){if(n.subcircuit_id=this.subcircuit_id,n.connection_name){const i=n.connection_name;n.source_trace_id=i}t.pcb_trace.insert(n)}for(const n of e)if(n.type!=="pcb_via"&&n.type==="pcb_trace")for(const i of n.route)i.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:n.pcb_trace_id,x:i.x,y:i.y,hole_diameter:.3,outer_diameter:.6,layers:[i.from_layer,i.to_layer],from_layer:i.from_layer,to_layer:i.to_layer})}doInitialSchematicComponentRender(){var i;if((i=this.root)!=null&&i.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.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=n.schematic_group_id;for(const o of this.children)o.schematic_component_id&&e.schematic_component.update(o.schematic_component_id,{schematic_group_id:n.schematic_group_id})}_getSchematicLayoutMode(){var t,n,i;const e=this._parsedProps;return(t=e.schLayout)!=null&&t.matchAdapt?"match-adapt":(n=e.schLayout)!=null&&n.flex?"flex":(i=e.schLayout)!=null&&i.grid?"grid":e.matchAdapt?"match-adapt":e.flex?"flex":e.grid?"grid":"none"}doInitialSchematicLayout(){this._parsedProps;const e=this._getSchematicLayoutMode();e==="match-adapt"&&this._doInitialSchematicLayoutMatchAdapt(),e==="grid"&&this._doInitialSchematicLayoutGrid()}_doInitialSchematicLayoutMatchAdapt(){YVt(this)}_doInitialSchematicLayoutGrid(){KVt(this)}_determineSideFromPosition(e,t){if(!e.center||!t.center)return"left";const n=e.center.x-t.center.x,i=e.center.y-t.center.y;return Math.abs(n)>Math.abs(i)?n>0?"right":"left":i>0?"bottom":"top"}_calculateSchematicBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let t=1/0,n=-1/0,i=1/0,o=-1/0;for(const s of e)t=Math.min(t,s.centerX),n=Math.max(n,s.centerX),i=Math.min(i,s.centerY),o=Math.max(o,s.centerY);const a=2;return{minX:t-a,maxX:n+a,minY:i-a,maxY:o+a}}_getAutorouterConfig(){const e={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0},t=this._parsedProps.autorouter??this.getInheritedProperty("autorouter");return typeof t=="object"?{local:!(t.serverUrl||t.serverMode||t.serverCacheEnabled),...e,...t}:t==="auto-local"?{local:!0,groupMode:"subcircuit"}:t==="sequential-trace"?{local:!0,groupMode:"sequential-trace"}:t==="subcircuit"?{local:!0,groupMode:"subcircuit"}:t==="auto-cloud"?{local:!1,groupMode:"subcircuit",serverUrl:e.serverUrl,serverMode:e.serverMode,serverCacheEnabled:!0}:{local:!0,groupMode:"subcircuit"}}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){var t;if((t=this.root)!=null&&t.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:e}=this.root;if(this.isSubcircuit){const n=new Map;for(const i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){const o=n.get(i._parsedProps.name)||[];o.push(i),n.set(i._parsedProps.name,o)}for(const[i,o]of n.entries())o.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" 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(a=>a.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}},jVt=class extends Ase{constructor(){super(...arguments);Le(this,"pcb_board_id",null);Le(this,"_drcChecksComplete",!1);Le(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:Aoe}}get boardThickness(){const{_parsedProps:e}=this;return 1.4}get allLayers(){return["top","bottom","inner1","inner2"]}doInitialPcbBoardAutoSize(){var h;if((h=this.root)!=null&&h.pcbDisabled||!this.pcb_board_id)return;const{db:e}=this.root,{_parsedProps:t}=this;if(t.width&&t.height)return;let n=1/0,i=1/0,o=-1/0,a=-1/0;const s=e.pcb_component.list();let l=!1;for(const m of s){const{width:C,height:E,center:_}=m;C===0||E===0||(l=!0,n=Math.min(n,_.x-C/2),i=Math.min(i,_.y-E/2),o=Math.max(o,_.x+C/2),a=Math.max(a,_.y+E/2))}const c=2,u=l?o-n+c*2:0,A=l?a-i+c*2:0,d={x:l?(n+o)/2+(t.outlineOffsetX??0):t.outlineOffsetX??0,y:l?(i+a)/2+(t.outlineOffsetY??0):t.outlineOffsetY??0};e.pcb_board.update(this.pcb_board_id,{width:u,height:A,center:d})}doInitialPcbComponentRender(){var a,s;if((a=this.root)!=null&&a.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;let n=t.width??0,i=t.height??0;if(t.outline){const l=t.outline.map(m=>m.x),c=t.outline.map(m=>m.y),u=Math.min(...l),A=Math.max(...l),d=Math.min(...c),h=Math.max(...c);n=A-u,i=h-d}const o=e.pcb_board.insert({center:{x:(t.pcbX??0)+(t.outlineOffsetX??0),y:(t.pcbY??0)+(t.outlineOffsetY??0)},thickness:this.boardThickness,num_layers:this.allLayers.length,width:n,height:i,outline:(s=t.outline)==null?void 0:s.map(l=>({x:l.x+(t.outlineOffsetX??0),y:l.y+(t.outlineOffsetY??0)})),material:t.material});this.pcb_board_id=o.pcb_board_id}removePcbComponentRender(){const{db:e}=this.root;this.pcb_board_id&&(e.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return a0()}doInitialPcbDesignRuleChecks(){var e;(e=this.root)!=null&&e.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){var n;if((n=this.root)!=null&&n.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:e}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;const t=zY(e.toArray());for(const i of t)e.pcb_trace_error.insert(i)}_emitRenderLifecycleEvent(e,t){var n;super._emitRenderLifecycleEvent(e,t),t==="start"&&((n=this.root)==null||n.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e}))}},JVt=new Proxy({},{get:(r,e)=>e}),o9=JVt,WVt=class extends N1{get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:OPe,sourceFtype:o9.simple_capacitor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){const r=`${x1(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${r}/${x1(this._parsedProps.maxVoltageRating)}V`:r}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new i9({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new i9({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_capacitor",name:e.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,capacitance:e.capacitance,max_voltage_rating:e.maxVoltageRating,max_decoupling_trace_length:e.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!e.polarized});this.source_component_id=t.source_component_id}},ILe=class extends N1{constructor(){super(...arguments);Le(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:doe,shouldRenderAsSchematicBox:!0}}doInitialSchematicComponentRender(){const{_parsedProps:e}=this;(e==null?void 0:e.noSchematicRepresentation)!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_chip",name:t.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=n.pcb_component_id}doInitialCreateTracesFromProps(){const{_parsedProps:e}=this;if(e.externallyConnectedPins)for(const[t,n]of e.externallyConnectedPins)this.add(new i9({from:`${this.getSubcircuitSelector()} > port.${t}`,to:`${this.getSubcircuitSelector()} > port.${n}`}));this._createTracesFromConnectionsProp()}},ZVt=class extends N1{constructor(){super(...arguments);Le(this,"pos",this.portMap.pin1);Le(this,"anode",this.portMap.pin1);Le(this,"neg",this.portMap.pin2);Le(this,"cathode",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"diode",componentName:"Diode",zodProps:n8e,sourceFtype:"simple_diode"}}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({ftype:"simple_diode",name:t.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},qVt=class extends N1{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:NLt,sourceFtype:o9.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`${x1(t)}A / ${x1(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:o9.simple_fuse,current_rating_amps:t,voltage_rating_volts:n,display_current_rating:`${x1(t)}A`,display_voltage_rating:`${x1(n)}V`});this.source_component_id=i.source_component_id}},XVt=class extends N1{constructor(){super(...arguments);Le(this,"schematicDimensions",null)}get config(){let e="";if(this.props.pinCount&&(e+=`solderjumper${this.props.pinCount||2}`),Array.isArray(this.props.internallyConnectedPins)&&this.props.internallyConnectedPins.length>0){const t=Array.from(new Set(this.props.internallyConnectedPins.flat())).sort().join("");e+=`_bridged${t}`}return{schematicSymbolName:e,componentName:"Jumper",zodProps:TPe,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){const e=super._getSchematicPortArrangement();if(e)return e;const t=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),n=this._parsedProps.schDirection??"right";return{leftSize:n==="left"?t:0,rightSize:n==="right"?t:0}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_chip",name:t.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=n.pcb_component_id}doInitialPcbTraceRender(){const{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),n={};for(let a=0;a<t.length;a++){const s=t[a],l=e.source_port.get(s.source_port_id);let c="";if(typeof(l==null?void 0:l.pin_number)=="number")c=l.pin_number.toString();else if(Array.isArray(l==null?void 0:l.port_hints)){let u=l.port_hints.find(A=>/^(pin)?\d+$/.test(A));u&&(/^pin\d+$/.test(u)?c=u.replace(/^pin/,""):c=u)}n[c]=s.pcb_port_id}const i=e.pcb_trace.list(),o=a=>{if(a&&typeof a=="string"&&a.startsWith("{PIN")){const s=a.replace("{PIN","").replace("}","");return n[s]||a}return a};for(const a of i)if(a.route)for(const s of a.route)s.route_type==="wire"&&(s.start_pcb_port_id=o(s.start_pcb_port_id),s.end_pcb_port_id=o(s.end_pcb_port_id))}},$Vt=class extends N1{constructor(){super(...arguments);Le(this,"pos",this.portMap.pin1);Le(this,"anode",this.portMap.pin1);Le(this,"neg",this.portMap.pin2);Le(this,"cathode",this.portMap.pin2)}get config(){return{componentName:"Led",schematicSymbolName:this.props.symbolName??"led",zodProps:r8e,sourceFtype:"simple_led"}}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({ftype:"simple_led",name:t.name,wave_length:t.wavelength,color:t.color,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},eKt=class extends N1{constructor(){super(...arguments);Le(this,"pos",this.portMap.pin1);Le(this,"positive",this.portMap.pin1);Le(this,"neg",this.portMap.pin2);Le(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:c8e,sourceFtype:"simple_power_source"}}initPorts(){this.add(new r2({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new r2({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_power_source",name:t.name,voltage:t.voltage,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},tKt=class extends N1{get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:FPe,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${x1(this._parsedProps.resistance)}Ω`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new i9({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new i9({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_resistor",name:e.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,resistance:e.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}},nKt=["leftedge","rightedge","topedge","bottomedge","center"],rKt=class extends $v{get config(){return{componentName:"Constraint",zodProps:zPe}}constructor(r){if(super(r),("xdist"in r||"ydist"in r)&&!("edgeToEdge"in r)&&!("centerToCenter"in r))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in r&&r.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){const r=[],e=this.getPrimitiveContainer();function t(n){const i=n.split(" ").pop(),o=nKt.includes(i)?i:void 0,a=o?n.replace(` ${o}`,""):n,s=e.selectOne(a,{pcbPrimitive:!0});s&&r.push({selector:n,component:s,componentSelector:a,edge:o})}for(const n of["left","right","top","bottom"])n in this._parsedProps&&t(this._parsedProps[n]);if("for"in this._parsedProps)for(const n of this._parsedProps.for)t(n);return{componentsWithSelectors:r}}},iKt=class extends $v{constructor(){super(...arguments);Le(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:a8e}}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,t=this.getSubcircuit(),{_parsedProps:n}=this,i=n.layer??"top";if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenPath. Must be "top" or "bottom".`);const o=this._computePcbGlobalTransformBeforeLayout(),a=e.pcb_fabrication_note_path.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,color:n.color,route:n.route.map(c=>{const u=ei(o,{x:c.x,y:c.y});return{...c,x:u.x,y:u.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:(t==null?void 0:t.subcircuit_id)??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},oKt=class extends $v{get config(){return{componentName:"FabricationNoteText",zodProps:o8e}}doInitialPcbPrimitiveRender(){var i,o;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:r}=this.root,{_parsedProps:e}=this,t=this.getPrimitiveContainer(),n=this.getSubcircuit();r.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:e.pcbX??0,y:e.pcbY??0},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:e.text??"",pcb_component_id:t.pcb_component_id,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0,pcb_group_id:((o=this.getGroup())==null?void 0:o.pcb_group_id)??void 0})}},aKt=class extends Ase{constructor(r){super({...r,subcircuit:!0})}},sKt=class extends $v{constructor(){super(...arguments);Le(this,"source_net_alias_id")}get config(){return{componentName:"NetAlias",zodProps:qPe}}doInitialSchematicComponentRender(){var o;if((o=this.root)!=null&&o.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n={x:t.schX??0,y:t.schY??0},i=e.schematic_net_label.insert({text:t.net,source_net_id:t.net,anchor_position:n,center:n,anchor_side:"bottom"});this.source_net_alias_id=i.source_net_id}},lKt=class extends $v{constructor(){super(...arguments);Le(this,"pcb_silkscreen_circle_id",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:g8e}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenCircle. Must be "top" or "bottom".`);this._computePcbGlobalTransformBeforeLayout();const o=this.getSubcircuit(),a=e.pcb_silkscreen_circle.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,center:{x:t.pcbX??0,y:t.pcbY??0},radius:t.radius,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((c=this.getGroup())==null?void 0:c.pcb_group_id)??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_circle_id=a.pcb_silkscreen_circle_id}getPcbSize(){const{_parsedProps:e}=this,t=e.radius*2;return{width:t,height:t}}},cKt=class extends $v{constructor(){super(...arguments);Le(this,"pcb_silkscreen_rect_id",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:p8e}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenRect. Must be "top" or "bottom".`);const o=this.getSubcircuit(),a=e.pcb_silkscreen_rect.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,center:{x:t.pcbX??0,y:t.pcbY??0},width:t.width,height:t.height,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((c=this==null?void 0:this.getGroup())==null?void 0:c.pcb_group_id)??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){const{_parsedProps:e}=this;return{width:e.width,height:e.height}}},uKt=class extends $v{constructor(){super(...arguments);Le(this,"pcb_silkscreen_line_id",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:h8e}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenLine. Must be "top" or "bottom".`);const o=this.getSubcircuit(),a=e.pcb_silkscreen_line.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,stroke_width:t.strokeWidth??.1,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((c=o==null?void 0:o.getGroup())==null?void 0:c.pcb_group_id)??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){const{_parsedProps:e}=this,t=Math.abs(e.x2-e.x1),n=Math.abs(e.y2-e.y1);return{width:t,height:n}}},AKt=class extends $v{constructor(){super(...arguments);Le(this,"pcb_via_id",null);Le(this,"matchedPort",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Via",zodProps:s8e}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){const{_parsedProps:e}=this;return{width:e.outerDiameter,height:e.outerDiameter}}_getPcbCircuitJsonBounds(){const{db:e}=this.root,t=e.pcb_via.get(this.pcb_via_id),n=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-n.width/2,top:t.y-n.height/2,right:t.x+n.width/2,bottom:t.y+n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(e){const{db:t}=this.root;t.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}doInitialPcbPrimitiveRender(){var a,s;if((a=this.root)!=null&&a.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getGlobalPcbPositionBeforeLayout(),i=this.getSubcircuit(),o=e.pcb_via.insert({x:n.x,y:n.y,hole_diameter:t.holeDiameter,outer_diameter:t.outerDiameter,layers:["bottom","top"],from_layer:t.fromLayer||"bottom",to_layer:t.toLayer||"top",subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((s=this.getGroup())==null?void 0:s.pcb_group_id)??void 0});this.pcb_via_id=o.pcb_via_id}},dKt=class extends $v{constructor(){super(...arguments);Le(this,"pcb_cutout_id",null);Le(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:HPe}}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getSubcircuit(),i=((l=this.getGroup())==null?void 0:l.pcb_group_id)??void 0,o=this._getGlobalPcbPositionBeforeLayout();let a;if(t.shape==="rect"){const c={shape:"rect",center:o,width:t.width,height:t.height,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0,pcb_group_id:i};a=e.pcb_cutout.insert(c)}else if(t.shape==="circle"){const c={shape:"circle",center:o,radius:t.radius,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0,pcb_group_id:i};a=e.pcb_cutout.insert(c)}else if(t.shape==="polygon"){const c=this._computePcbGlobalTransformBeforeLayout(),A={shape:"polygon",points:t.points.map(d=>ei(c,d)),subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0,pcb_group_id:i};a=e.pcb_cutout.insert(A)}a&&(this.pcb_cutout_id=a.pcb_cutout_id)}getPcbSize(){const{_parsedProps:e}=this;if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="polygon"){if(e.points.length===0)return{width:0,height:0};let t=1/0,n=-1/0,i=1/0,o=-1/0;for(const a of e.points)t=Math.min(t,a.x),n=Math.max(n,a.x),i=Math.min(i,a.y),o=Math.max(o,a.y);return{width:n-t,height:o-i}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();const{db:e}=this.root,t=e.pcb_cutout.get(this.pcb_cutout_id);if(!t)return super._getPcbCircuitJsonBounds();if(t.shape==="rect")return{center:t.center,bounds:{left:t.center.x-t.width/2,top:t.center.y+t.height/2,right:t.center.x+t.width/2,bottom:t.center.y-t.height/2},width:t.width,height:t.height};if(t.shape==="circle")return{center:t.center,bounds:{left:t.center.x-t.radius,top:t.center.y+t.radius,right:t.center.x+t.radius,bottom:t.center.y-t.radius},width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){if(t.points.length===0)return super._getPcbCircuitJsonBounds();let n=1/0,i=-1/0,o=1/0,a=-1/0;for(const s of t.points)n=Math.min(n,s.x),i=Math.max(i,s.x),o=Math.min(o,s.y),a=Math.max(a,s.y);return{center:{x:(n+i)/2,y:(o+a)/2},bounds:{left:n,top:a,right:i,bottom:o},width:i-n,height:a-o}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(e){if(!this.pcb_cutout_id)return;const{db:t}=this.root,n=t.pcb_cutout.get(this.pcb_cutout_id);if(n){if(n.shape==="rect"||n.shape==="circle")t.pcb_cutout.update(this.pcb_cutout_id,{...n,center:e});else if(n.shape==="polygon"){const i=this._getPcbCircuitJsonBounds().center,o=e.x-i.x,a=e.y-i.y,s=n.points.map(l=>({x:l.x+o,y:l.y+a}));t.pcb_cutout.update(this.pcb_cutout_id,{...n,points:s})}}}},fKt=class extends N1{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:WPe,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=t.source_component_id}},hKt=class extends N1{get config(){return{componentName:"PinHeader",zodProps:ZPe,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){var i;const r=this._parsedProps.pinCount??((i=this._parsedProps.pinLabels)==null?void 0:i.length)??0,e=this._parsedProps.holeDiameter,t=this._parsedProps.platedDiameter,n=this._parsedProps.pitch;return r>0&&n?!e&&!t?`pinrow${r}_p${n}`:`pinrow${r}_p${n}_id${e}_od${t}`:null}initPorts(){var e,t;const r=this._parsedProps.pinCount??((e=this._parsedProps.pinLabels)==null?void 0:e.length)??1;for(let n=1;n<=r;n++)this.add(new r2({name:`pin${n}`,pinNumber:n,aliases:[(t=this._parsedProps.pinLabels)==null?void 0:t[n-1]].filter(Boolean)}))}_getSchematicPortArrangement(){var n,i,o,a;const r=this._parsedProps.pinCount??1,e=this._parsedProps.facingDirection??"right",t=this._parsedProps.schPinArrangement;return e==="left"?{leftSide:{direction:((n=t==null?void 0:t.leftSide)==null?void 0:n.direction)??"top-to-bottom",pins:((i=t==null?void 0:t.leftSide)==null?void 0:i.pins)??Array.from({length:r},(s,l)=>`pin${l+1}`)}}:{rightSide:{direction:((o=t==null?void 0:t.rightSide)==null?void 0:o.direction)??"top-to-bottom",pins:((a=t==null?void 0:t.rightSide)==null?void 0:a.pins)??Array.from({length:r},(s,l)=>`pin${l+1}`)}}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_pin_header",name:e.name,supplier_part_numbers:e.supplierPartNumbers,pin_count:e.pinCount,gender:e.gender,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}};function pKt(r){switch(r){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var gKt=class extends N1{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??pKt(this.props.pinVariant),zodProps:GPe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"no_ground",n=r.source_component.insert({ftype:"simple_resonator",name:e.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:t,are_pins_interchangeable:t==="no_ground"||t==="ground_pin"});this.source_component_id=n.source_component_id}},mKt=class extends N1{get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:t8e,sourceFtype:o9.simple_inductor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:o9.simple_inductor,inductance:e.inductance,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}};function yKt(r){switch(r){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var vKt=class extends N1{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??yKt(this.props.pinVariant),zodProps:kPe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"two_pin",n=r.source_component.insert({ftype:"simple_potentiometer",name:e.name,max_resistance:e.maxResistance,pin_variant:t,are_pins_interchangeable:t==="two_pin"});this.source_component_id=n.source_component_id}},IKt=class extends N1{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:XPe,sourceFtype:o9.simple_push_button}}get defaultInternallyConnectedPinNames(){return[["pin1","pin4"],["pin2","pin3"]]}initPorts(){super.initPorts({pinCount:4,additionalAliases:{pin1:["side1"],pin3:["side2"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:o9.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}},CKt=class extends N1{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:LPe,sourceFtype:"simple_crystal"}}initPorts(){const r=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:r})}_getSchematicSymbolDisplayValue(){return`${x1(this._parsedProps.frequency)}Hz`}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:"simple_crystal",frequency:e.frequency,load_capacitance:e.loadCapacitance,pin_variant:e.pinVariant||"two_pin",are_pins_interchangeable:(e.pinVariant||"two_pin")==="two_pin"});this.source_component_id=t.source_component_id}},EKt=class extends N1{constructor(){super(...arguments);Le(this,"emitter",this.portMap.pin1);Le(this,"collector",this.portMap.pin2);Le(this,"base",this.portMap.pin3)}get config(){return{componentName:"Transistor",schematicSymbolName:this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor",zodProps:$Pe,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){const e=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:e})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_transistor",name:t.name,transistor_type:t.type});this.source_component_id=n.source_component_id}},_Kt=class extends N1{get config(){const r=this.props.mosfetMode==="depletion"?"d":"e";return{componentName:"Mosfet",schematicSymbolName:`${this.props.channelType}_channel_${r}_mosfet_transistor`,zodProps:e8e,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_mosfet",name:e.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=t.source_component_id}},xKt=class extends N1{_getSwitchType(){const{spst:r,spdt:e,dpst:t,dpdt:n,type:i}=this._parsedProps??{};return n?"dpdt":r?"spst":e?"spdt":t?"dpst":i??"spst"}get config(){const r=this._getSwitchType(),{isNormallyClosed:e}=this._parsedProps??{};return{componentName:"Switch",schematicSymbolName:{spst:e?"spst_normally_closed_switch":"spst_switch",spdt:e?"spdt_normally_closed_switch":"spdt_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"}[r]??"spst_switch",zodProps:i8e,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_switch",name:e.name,switch_type:e.type,is_normally_closed:e.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=t.source_component_id}},BKt=class extends $v{constructor(){super(...arguments);Le(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:A8e}}doInitialSchematicPrimitiveRender(){var n;if((n=this.root)!=null&&n.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;e.schematic_text.insert({anchor:t.anchor??"center",text:t.text,font_size:t.fontSize,color:t.color||"#000000",position:{x:t.schX,y:t.schY},rotation:t.schRotation??0})}},bKt=class extends $v{constructor(){super(...arguments);Le(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:u8e,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){var E;if((E=this.root)!=null&&E.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=u8e.safeParse(t);if(!n.success)throw console.error("Validation failed:",n.error.format()),n.error;const i=.6,o=typeof t.padding=="number"?t.padding:0,a=typeof t.paddingTop=="number"?t.paddingTop:o,s=typeof t.paddingBottom=="number"?t.paddingBottom:o,l=typeof t.paddingLeft=="number"?t.paddingLeft:o,c=typeof t.paddingRight=="number"?t.paddingRight:o,u=t.overlay&&t.overlay.length>0,A=typeof t.width=="number"&&typeof t.height=="number";let d,h,m,C;if(u){const x=t.overlay.map(ke=>({selector:ke,port:this.getSubcircuit().selectOne(ke,{type:"port"})})).filter(({port:ke})=>ke!=null).map(({port:ke})=>({position:ke._getGlobalSchematicPositionAfterLayout()}));if(x.length===0)return;const Q=x.map(ke=>ke.position.x),P=x.map(ke=>ke.position.y),O=Math.min(...Q),z=Math.max(...Q),Y=Math.min(...P),V=Math.max(...P),Z=z-O,J=V-Y,se=Z===0?i:0,ae=J===0?i:0,ue=l+se/2,ve=c+se/2,xe=a+ae/2,fe=s+ae/2,Ee=O-ue,Ie=z+ve,Qe=Y-fe,Me=V+xe;d=Ie-Ee,h=Me-Qe,m=Ee+(t.schX??0),C=Qe+(t.schY??0)}else if(A){d=t.width,h=t.height;const _=typeof t.schX=="number"?t.schX:0,x=typeof t.schY=="number"?t.schY:0;m=_-d/2,C=x-h/2}else return;e.schematic_box.insert({height:h,width:d,x:m,y:C,is_dashed:t.strokeStyle==="dashed",schematic_component_id:""})}};new Proxy({},{get:(r,e)=>{const t=(...n)=>(n[0],new Proxy({},{get:(i,o)=>`.${e} > .${o}`}));return new Proxy(t,{get:(n,i)=>e==="net"?`net.${i}`:e==="subcircuit"?new Proxy({},{get:(o,a)=>new Proxy({},{get:(s,l)=>`subcircuit.${i} > .${a} > .${l}`})}):`.${e} > .${i}`,apply:(n,i,o)=>new Proxy({},{get:(a,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}`})}})})}}),eLe(Xke),eLe({Bug:ILe});const CLe=r=>`hsl(${LB.indexOf(r)*137.5%360}, 70%, 50%)`,SKt=({phaseTimings:r})=>{if(!r)return null;const e=Object.values(r).reduce((t,n)=>t+n,0);return dt.jsxs("div",{className:"rf-space-y-2 rf-w-full rf-px-4",children:[dt.jsx("div",{className:"rf-relative rf-h-8 rf-flex rf-rounded-sm",children:LB.map(t=>{const n=r[t]||0,i=n/e*100;return dt.jsx("div",{className:"rf-group/bar rf-relative rf-overflow-visible",style:{width:`${i}%`,backgroundColor:CLe(t)},children:dt.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)})}),dt.jsxs("div",{className:"rf-text-xs rf-text-gray-500",children:["Total: ",e.toFixed(2),"ms"]})]})},QKt=({renderLog:r})=>{const[e,t]=yt.useState("chronological");if(!r)return dt.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((o,a)=>LB.indexOf(o[0])-LB.indexOf(a[0])):n.sort((o,a)=>a[1]-o[1]);const i=n.reduce((o,[a,s])=>o+s,0);return dt.jsxs("div",{className:"rf-bg-white",children:[dt.jsxs("div",{className:"rf-flex rf-justify-between rf-items-center",children:[dt.jsx("div",{children:"Render Logs"}),dt.jsxs("div",{className:"rf-mb-4 rf-pr-2 rf-flex rf-text-xs rf-items-center",children:[dt.jsx("div",{className:"rf-mr-2",children:"Sort by:"}),dt.jsxs("select",{value:e,onChange:o=>t(o.target.value),className:"rf-px-2 rf-py-1 rf-border rf-rounded rf-text-xs",children:[dt.jsx("option",{value:"chronological",children:"Phase Order"}),dt.jsx("option",{value:"longest",children:"Duration"})]})]})]}),dt.jsx(SKt,{phaseTimings:r.phaseTimings}),dt.jsxs("table",{className:"rf-w-full rf-text-xs",children:[dt.jsx("thead",{children:dt.jsxs("tr",{children:[dt.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase Order"}),dt.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase"}),dt.jsx("th",{className:"rf-text-left rf-p-2",children:"Duration (ms)"})]})}),dt.jsx("tbody",{children:n.map(([o,a])=>dt.jsxs("tr",{children:[dt.jsx("td",{className:"rf-p-2",children:LB.indexOf(o)}),dt.jsx("td",{className:"rf-p-2",children:o}),dt.jsx("td",{className:"rf-p-2",children:dt.jsx("div",{className:"rf-w-8",children:dt.jsx("div",{className:"rf-h-2 rf-rounded-sm",style:{backgroundColor:CLe(o),width:`${a/i*100}%`}})})}),dt.jsx("td",{className:"rf-p-2",children:dt.jsxs("div",{className:"rf-flex w-full",children:[dt.jsxs("span",{className:"rf-flex-grow",children:[a,"ms"]}),dt.jsxs("span",{className:"rf-text-gray-500 rf-pr-2",children:[(a/i*100).toFixed(1),"%"]})]})})]},o))})]})]})},wKt="0.0.529",MKt=["assembly","bom","circuit_json","errors","render_log"],DKt=({code:r,onRunClicked:e=void 0,errorMessage:t,circuitJson:n,autoroutingGraphics:i,showRightHeaderContent:o=!0,showCodeTab:a=!1,codeTabContent:s,showJsonTab:l=!0,showRenderLogTab:c=!0,onActiveTabChange:u,renderLog:A,showImportAndFormatButtons:d=!0,className:h,headerClassName:m,leftHeaderContent:C,readOnly:E,isStreaming:_,autoroutingLog:x,onReportAutoroutingLog:Q,isRunningCode:P,hasCodeChangedSinceLastRun:O,onEditEvent:z,editEvents:Y,defaultActiveTab:V,autoRotate3dViewerDisabled:Z,showSchematicDebugGrid:J=!1,showToggleFullScreen:se=!0,defaultToFullScreen:ae=!1})=>{var ke;LHt();const ue=yt.useMemo(()=>n?n.filter(Ue=>Ue&&"error_type"in Ue||Ue.type.includes("error")):null,[n]),[ve,xe]=yt.useState(V??"pcb"),[fe,Ee]=yt.useState(ae),Ie=yt.useCallback(Ue=>{xe(Ue),u==null||u(Ue)},[u]),Qe=()=>{Ee(!fe)};yt.useEffect(()=>{t&&Ie("errors")},[t]),yt.useEffect(()=>{(ve==="code"||ve==="errors")&&n&&!t&&Ie(V??"pcb")},[n]);const Me=yt.useCallback(Ue=>{window.TSCIRCUIT_3D_OBJECT_REF=Ue===null?void 0:Ue},[]);return dt.jsx("div",{className:Zv("flex flex-col relative rf-overflow-x-hidden",h),children:dt.jsx("div",{className:Zv("rf-md:sticky rf-md:top-2",fe&&"rf-fixed rf-top-0 rf-left-0 rf-w-full rf-bg-white"),children:dt.jsxs(wOe,{value:ve,onValueChange:Ie,className:"rf-flex-grow rf-flex rf-flex-col",children:[dt.jsxs("div",{className:Zv("rf-flex rf-items-center rf-gap-2 rf-p-2 rf-pb-0",m),children:[C,C&&dt.jsx("div",{className:"rf-flex-grow"}),!C&&P&&dt.jsx(HNe,{className:"rf-w-4 rf-h-4 rf-animate-spin"}),!C&&dt.jsx("div",{className:"rf-flex-grow"}),A&&A.progress!==1&&dt.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[A.lastRenderEvent&&dt.jsx("div",{className:"rf-text-xs rf-text-gray-500",children:((ke=A.lastRenderEvent)==null?void 0:ke.phase)??""}),dt.jsx("div",{className:"rf-w-4 rf-h-4 rf-bg-blue-500 rf-opacity-50 rf-rounded-full rf-text-white",children:dt.jsx(HNe,{className:"rf-w-4 rf-h-4 rf-animate-spin"})}),dt.jsxs("div",{className:"rf-text-xs rf-font-bold rf-text-gray-700 rf-tabular-nums",children:[((A.progress??0)*100).toFixed(1),"%"]})]}),o&&dt.jsxs(yce,{children:[a&&dt.jsx(y9,{value:"code",children:"Code"}),dt.jsxs(y9,{value:"pcb",className:"rf-whitespace-nowrap",children:[n&&dt.jsx("span",{className:Zv("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",O?"rf-bg-gray-500":"rf-bg-blue-500")}),"PCB"]}),dt.jsxs(y9,{value:"schematic",className:"rf-whitespace-nowrap",children:[n&&dt.jsx("span",{className:Zv("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",O?"rf-bg-gray-500":"rf-bg-blue-500")}),"Schematic"]}),dt.jsxs(y9,{value:"cad",children:[n&&dt.jsx("span",{className:Zv("inline-flex items-center justify-center w-2 h-2 mr-1 text-xs font-bold text-white rounded-full",O?"rf-bg-gray-500":"rf-bg-blue-500")}),"3D"]}),!["pcb","cad","schematic"].includes(ve)&&dt.jsx(y9,{value:ve,children:mce(ve)}),dt.jsxs($4e,{children:[dt.jsx(ePe,{asChild:!0,children:dt.jsxs("div",{className:"rf-whitespace-nowrap rf-p-2 rf-mr-1 rf-cursor-pointer rf-relative",children:[dt.jsx(Q4t,{className:"rf-w-4 rf-h-4"}),(ue&&ue.length>0||t)&&dt.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"})]})}),dt.jsxs(Kie,{className:"rf-*:text-xs",children:[MKt.map(Ue=>dt.jsxs($L,{onSelect:()=>Ie(Ue),children:[ve!==Ue&&dt.jsx(zNe,{className:"rf-w-3 rf-h-3 rf-opacity-30"}),ve===Ue&&dt.jsx(GNe,{className:"rf-w-3 rf-h-3"}),dt.jsx("div",{className:"rf-pr-2",children:mce(Ue)}),Ue==="errors"&&(ue&&ue.length>0||t)&&dt.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:ue==null?void 0:ue.length})]},Ue)),dt.jsx($L,{disabled:!0,className:"rf-opacity-60 rf-cursor-default rf-select-none",children:dt.jsxs("div",{className:"rf-pr-2 rf-text-xs rf-text-gray-500",children:["@tscircuit/runframe@",wKt.split(".").map((Ue,it)=>it===2?parseInt(Ue)+1:Ue).join(".")]})})]})]})]}),se&&dt.jsx(q2,{onClick:Qe,variant:"ghost",children:fe?dt.jsx(D4t,{size:16}):dt.jsx(w4t,{size:16})})]}),a&&dt.jsx(Ib,{value:"code",className:"rf-flex-grow rf-overflow-hidden",children:dt.jsx("div",{className:"rf-h-full",children:s})}),dt.jsx(Ib,{value:"pcb",children:dt.jsx("div",{className:Zv("rf-overflow-hidden",fe?"rf-h-[calc(100vh-52px)]":"rf-h-[620px]"),children:dt.jsx(lD,{fallbackRender:({error:Ue})=>dt.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:dt.jsxs("div",{className:"rf-p-4",children:[dt.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading PCB viewer"}),dt.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ue==null?void 0:Ue.message)||"An unknown error occurred"})]})}),children:n?dt.jsx(FHt,{focusOnHover:!1,circuitJson:n,debugGraphics:i,containerClassName:Zv("rf-h-full rf-w-full",fe?"rf-min-h-[calc(100vh-240px)]":"rf-min-h-[620px]"),onEditEventsChanged:Ue=>{z&&Ue.forEach(it=>z(it))}}):dt.jsx(Jw,{onRunClicked:e})})})}),dt.jsx(Ib,{value:"assembly",children:dt.jsx("div",{className:Zv("rf-overflow-auto",fe?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:dt.jsx(lD,{fallback:dt.jsx("div",{children:"Error loading Assembly"}),children:n?dt.jsx(oLt,{circuitJson:n,containerStyle:{height:"100%"},editingEnabled:!0,debugGrid:!0}):dt.jsx(Jw,{onRunClicked:e})})})}),dt.jsx(Ib,{value:"schematic",children:dt.jsx("div",{className:Zv("rf-overflow-auto rf-bg-white",fe?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:dt.jsx(lD,{fallbackRender:({error:Ue})=>dt.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:dt.jsxs("div",{className:"rf-p-4",children:[dt.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Schematic"}),dt.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ue==null?void 0:Ue.message)||"An unknown error occurred"})]})}),children:n?dt.jsx(nLt,{circuitJson:n,containerStyle:{height:"100%"},editingEnabled:!0,onEditEvent:Ue=>{z==null||z(Ue)},debugGrid:J}):dt.jsx(Jw,{onRunClicked:e})})})}),dt.jsx(Ib,{value:"cad",children:dt.jsx("div",{className:Zv("rf-overflow-auto",fe?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:dt.jsx(lD,{FallbackComponent:h4t,children:n?dt.jsx(d4t,{ref:Me,circuitJson:n,autoRotateDisabled:Z}):dt.jsx(Jw,{onRunClicked:e})})})}),dt.jsx(Ib,{value:"bom",children:dt.jsx("div",{className:Zv("rf-overflow-auto",fe?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:dt.jsx(lD,{fallbackRender:({error:Ue})=>dt.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:dt.jsxs("div",{className:"rf-p-4",children:[dt.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Bill of Materials"}),dt.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ue==null?void 0:Ue.message)||"An unknown error occurred"})]})}),children:n?dt.jsx(uLt,{circuitJson:n}):dt.jsx(Jw,{onRunClicked:e})})})}),dt.jsx(Ib,{value:"circuit_json",children:dt.jsx("div",{className:Zv("rf-overflow-auto",fe?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:dt.jsx(lD,{fallback:dt.jsx("div",{children:"Error loading JSON viewer"}),children:n?dt.jsx(lLt,{elements:n}):dt.jsx(Jw,{onRunClicked:e})})})}),dt.jsx(Ib,{value:"errors",children:dt.jsx("div",{className:Zv("rf-overflow-auto",fe?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:t||ue&&ue.length>0?dt.jsx(QFt,{code:r,circuitJsonErrors:ue,errorMessage:t,autoroutingLog:x,onReportAutoroutingLog:Q}):dt.jsx(Jw,{onRunClicked:e})})}),c&&dt.jsx(Ib,{value:"render_log",children:dt.jsx(QKt,{renderLog:A})})]})})})};kle.createRoot(document.getElementById("root")).render(dt.jsx(DKt,{defaultActiveTab:"cad",autoRotate3dViewerDisabled:!0,showRightHeaderContent:!1,circuitJson:window.CIRCUIT_JSON||{},...window.CIRCUIT_JSON_PREVIEW_PROPS||{}}));const RKt=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}))});