@tscircuit/eval 0.0.388 → 0.0.389

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.
@@ -158,7 +158,7 @@ svg { font-family: 'Inter', 'Helvetica Neue', Arial, sans-serif; }
158
158
  fieldset[disabled]:not(fieldset[disabled] legend:first-of-type *)
159
159
  )`,enabled:":not(:disabled)",checked:":is(:is(input[type=radio], input[type=checkbox])[checked], option:selected)",required:":is(input, select, textarea)[required]",optional:":is(input, select, textarea):not([required])",selected:"option:is([selected], select:not([multiple]):not(:has(> option[selected])) > :first-of-type)",checkbox:"[type=checkbox]",file:"[type=file]",password:"[type=password]",radio:"[type=radio]",reset:"[type=reset]",image:"[type=image]",submit:"[type=submit]",parent:":not(:empty)",header:":is(h1, h2, h3, h4, h5, h6)",button:":is(button, input[type=button])",input:":is(input, textarea, select, button)",text:"input:is(:not([type!='']), [type=text])"};var ro=Yt(vl(),1);var C5={};function k5(e,t){return e===ro.default.falseFunc?ro.default.falseFunc:n=>t.isTag(n)&&e(n)}function N5(e,t){let n=t.getSiblings(e);if(n.length<=1)return[];let i=n.indexOf(e);return i<0||i===n.length-1?[]:n.slice(i+1).filter(t.isTag)}function E5(e){return{xmlMode:!!e.xmlMode,lowerCaseAttributeNames:!!e.lowerCaseAttributeNames,lowerCaseTags:!!e.lowerCaseTags,quirksMode:!!e.quirksMode,cacheResults:!!e.cacheResults,pseudos:e.pseudos,adapter:e.adapter,equals:e.equals}}var M5=(e,t,n,i,r)=>{let o=r(t,E5(n),i);return o===ro.default.trueFunc?e:o===ro.default.falseFunc?ro.default.falseFunc:s=>o(s)&&e(s)},lg={is:M5,matches:M5,where:M5,not(e,t,n,i,r){let o=r(t,E5(n),i);return o===ro.default.falseFunc?e:o===ro.default.trueFunc?ro.default.falseFunc:s=>!o(s)&&e(s)},has(e,t,n,i,r){let{adapter:o}=n,s=E5(n);s.relativeSelector=!0;let a=t.some(u=>u.some(Bd))?[C5]:void 0,c=r(t,s,a);if(c===ro.default.falseFunc)return ro.default.falseFunc;let l=k5(c,o);if(a&&c!==ro.default.trueFunc){let{shouldTestNextSiblings:u=!1}=c;return h=>{if(!e(h))return!1;a[0]=h;let d=o.getChildren(h),_=u?[...d,...N5(h,o)]:d;return o.existsOne(l,_)}}return u=>e(u)&&o.existsOne(l,o.getChildren(u))}};function lL(e,t,n,i,r){var o;let{name:s,data:a}=t;if(Array.isArray(a)){if(!(s in lg))throw new Error(`Unknown pseudo-class :${s}(${a})`);return lg[s](e,a,n,i,r)}let c=(o=n.pseudos)===null||o===void 0?void 0:o[s],l=typeof c=="string"?c:I5[s];if(typeof l=="string"){if(a!=null)throw new Error(`Pseudo ${s} doesn't have any arguments`);let u=$d(l);return lg.is(e,u,n,i,r)}if(typeof c=="function")return T5(c,s,a,1),u=>c(u,a)&&e(u);if(s in Yd)return Yd[s](e,a,n,i);if(s in cg){let u=cg[s];return T5(u,s,a,2),h=>u(h,n,a)&&e(h)}throw new Error(`Unknown pseudo-class :${s}`)}function A5(e,t){let n=t.getParent(e);return n&&t.isTag(n)?n:null}function uL(e,t,n,i,r){let{adapter:o,equals:s}=n;switch(t.type){case oe.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case oe.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case oe.Attribute:{if(t.namespace!=null)throw new Error("Namespaced attributes are not yet supported by css-select");return(!n.xmlMode||n.lowerCaseAttributeNames)&&(t.name=t.name.toLowerCase()),oL[t.action](e,t,n)}case oe.Pseudo:return lL(e,t,n,i,r);case oe.Tag:{if(t.namespace!=null)throw new Error("Namespaced tag names are not yet supported by css-select");let{name:a}=t;return(!n.xmlMode||n.lowerCaseTags)&&(a=a.toLowerCase()),function(l){return o.getName(l)===a&&e(l)}}case oe.Descendant:{if(n.cacheResults===!1||typeof WeakSet>"u")return function(l){let u=l;for(;u=A5(u,o);)if(e(u))return!0;return!1};let a=new WeakSet;return function(l){let u=l;for(;u=A5(u,o);)if(!a.has(u)){if(o.isTag(u)&&e(u))return!0;a.add(u)}return!1}}case"_flexibleDescendant":return function(c){let l=c;do if(e(l))return!0;while(l=A5(l,o));return!1};case oe.Parent:return function(c){return o.getChildren(c).some(l=>o.isTag(l)&&e(l))};case oe.Child:return function(c){let l=o.getParent(c);return l!=null&&o.isTag(l)&&e(l)};case oe.Sibling:return function(c){let l=o.getSiblings(c);for(let u=0;u<l.length;u++){let h=l[u];if(s(c,h))break;if(o.isTag(h)&&e(h))return!0}return!1};case oe.Adjacent:return o.prevElementSibling?function(c){let l=o.prevElementSibling(c);return l!=null&&e(l)}:function(c){let l=o.getSiblings(c),u;for(let h=0;h<l.length;h++){let d=l[h];if(s(c,d))break;o.isTag(d)&&(u=d)}return!!u&&e(u)};case oe.Universal:{if(t.namespace!=null&&t.namespace!=="*")throw new Error("Namespaced universal selectors are not yet supported by css-select");return e}}}function pL(e,t,n){let i=ug(e,t,n);return k5(i,t.adapter)}function ug(e,t,n){let i=typeof e=="string"?$d(e):e;return pg(i,t,n)}function hL(e){return e.type===oe.Pseudo&&(e.name==="scope"||Array.isArray(e.data)&&e.data.some(t=>t.some(hL)))}var tmt={type:oe.Descendant},emt={type:"_flexibleDescendant"},nmt={type:oe.Pseudo,name:"scope",data:null};function imt(e,{adapter:t},n){let i=!!n?.every(r=>{let o=t.isTag(r)&&t.getParent(r);return r===C5||o&&t.isTag(o)});for(let r of e){if(!(r.length>0&&Bd(r[0])&&r[0].type!==oe.Descendant))if(i&&!r.some(hL))r.unshift(tmt);else continue;r.unshift(nmt)}}function pg(e,t,n){var i;e.forEach(w5),n=(i=t.context)!==null&&i!==void 0?i:n;let r=Array.isArray(n),o=n&&(Array.isArray(n)?n:[n]);if(t.relativeSelector!==!1)imt(e,t,o);else if(e.some(c=>c.length>0&&Bd(c[0])))throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");let s=!1,a=e.map(c=>{if(c.length>=2){let[l,u]=c;l.type!==oe.Pseudo||l.name!=="scope"||(r&&u.type===oe.Descendant?c[1]=emt:(u.type===oe.Adjacent||u.type===oe.Sibling)&&(s=!0))}return rmt(c,t,o)}).reduce(omt,Ds.default.falseFunc);return a.shouldTestNextSiblings=s,a}function rmt(e,t,n){var i;return e.reduce((r,o)=>r===Ds.default.falseFunc?Ds.default.falseFunc:uL(r,o,t,n,pg),(i=t.rootFunc)!==null&&i!==void 0?i:Ds.default.trueFunc)}function omt(e,t){return t===Ds.default.falseFunc||e===Ds.default.trueFunc?e:e===Ds.default.falseFunc||t===Ds.default.trueFunc?t:function(i){return e(i)||t(i)}}var dL=(e,t)=>e===t,smt={adapter:sg,equals:dL};function fL(e){var t,n,i,r;let o=e??smt;return(t=o.adapter)!==null&&t!==void 0||(o.adapter=sg),(n=o.equals)!==null&&n!==void 0||(o.equals=(r=(i=o.adapter)===null||i===void 0?void 0:i.equals)!==null&&r!==void 0?r:dL),o}function O5(e){return function(n,i,r){let o=fL(i);return e(n,o,r)}}var j7t=O5(pL),Y7t=O5(ug),X7t=O5(pg);function mL(e){return function(n,i,r){let o=fL(r);typeof n!="function"&&(n=ug(n,o,i));let s=amt(i,o.adapter,n.shouldTestNextSiblings);return e(n,s,o)}}function amt(e,t,n=!1){return n&&(e=cmt(e,t)),Array.isArray(e)?t.removeSubsets(e):t.getChildren(e)}function cmt(e,t){let n=Array.isArray(e)?e.slice(0):[e],i=n.length;for(let r=0;r<i;r++){let o=N5(n[r],t);n.push(...o)}return n}var L5=mL((e,t,n)=>e===R5.default.falseFunc||!t||t.length===0?[]:n.adapter.findAll(e,t)),hg=mL((e,t,n)=>e===R5.default.falseFunc||!t||t.length===0?null:n.adapter.findOne(e,t));W();vt();W();var GL=Yt(Mn(),1);vt();var WL=Yt(Mn(),1),KL=Yt(Mn(),1);vt();Ho();Y5();var X5=(e,t={})=>{let n=e._internal_store;if(!n){n={counts:{}},e._internal_store=n;for(let r of e){let o=r.type,s=r[`${o}_id`];if(!s)continue;let a=Number.parseInt(s.split("_").pop());Number.isNaN(a)||(n.counts[o]=Math.max(n.counts[o]??0,a))}}return new Proxy({},{get:(r,o)=>o==="toArray"?()=>e:{get:s=>e.find(a=>a.type===o&&a[`${o}_id`]===s),getUsing:s=>{let a=Object.keys(s);if(a.length!==1)throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");let c=a[0],l=c.replace("_id",""),u=e.find(h=>h.type===l&&h[c]===s[c]);return u?e.find(h=>h.type===o&&h[`${o}_id`]===u[`${o}_id`]):null},getWhere:s=>{let a=Object.keys(s);return e.find(c=>c.type===o&&a.every(l=>c[l]===s[l]))},list:s=>{let a=s?Object.keys(s):[];return e.filter(c=>c.type===o&&a.every(l=>c[l]===s[l]))},insert:s=>{var l;(l=n.counts)[o]??(l[o]=-1),n.counts[o]++;let a=n.counts[o],c={type:o,[`${o}_id`]:`${o}_${a}`,...s};return t.validateInserts&&(fl[o]??dl).parse(c),e.push(c),c},delete:s=>{let a=e.find(c=>c[`${o}_id`]===s);a&&e.splice(e.indexOf(a),1)},update:(s,a)=>{let c=e.find(l=>l.type===o&&l[`${o}_id`]===s);if(c)return Object.assign(c,a),c},select:s=>{if(o==="source_component")return e.find(a=>a.type==="source_component"&&a.name===s.replace(/\./g,""));if(o==="pcb_port"||o==="source_port"||o==="schematic_port"){let[a,c]=s.replace(/\./g,"").split(/[\s\>]+/),l=e.find(h=>h.type==="source_component"&&h.name===a);if(!l)return null;let u=e.find(h=>h.type==="source_port"&&h.source_component_id===l.source_component_id&&(h.name===c||(h.port_hints??[]).includes(c)));if(!u)return null;if(o==="source_port")return u;if(o==="pcb_port")return e.find(h=>h.type==="pcb_port"&&h.source_port_id===u.source_port_id);if(o==="schematic_port")return e.find(h=>h.type==="schematic_port"&&h.source_port_id===u.source_port_id)}}}})};X5.unparsed=X5;var Io=X5;var Gzt=Yt(kL(),1);yi();function $s(e){let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,maxX:e.center.x+t,minY:e.center.y-n,maxY:e.center.y+n}}function Mo(e,t){let n=$s(e),i=$s(t),r=Math.max(n.minX-i.maxX,i.minX-n.maxX,0),o=Math.max(n.minY-i.maxY,i.minY-n.maxY,0),s={x:0,y:0},a={x:0,y:0};return r===0&&o===0?{distance:0,pointA:e.center,pointB:t.center}:(s.x=Rn(e.center.x,i.minX,i.maxX),s.y=Rn(e.center.y,i.minY,i.maxY),a.x=Rn(t.center.x,n.minX,n.maxX),a.y=Rn(t.center.y,n.minY,n.maxY),{distance:Math.hypot(s.x-a.x,s.y-a.y),pointA:s,pointB:a})}function Rn(e,t,n){return Math.max(t,Math.min(n,e))}function Ud(e,t){let n=Number.POSITIVE_INFINITY,i={x:0,y:0},r={x:0,y:0};for(let o of e)for(let s of t){let{distance:a,pointA:c,pointB:l}=Mo(o,s);a<n&&(n=a,i=c,r=l)}return{pointA:i,pointB:r,distance:n}}yi();yi();var FL="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var DL=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=FL[n[e]&63];return t};yi();var Cl=(e,t)=>Math.abs(e.x-t.x)+Math.abs(e.y-t.y),$L=(e,t)=>{let n=t.x-e.x,i=t.y-e.y;return Math.abs(n)>Math.abs(i)?{dx:Math.sign(n),dy:0}:{dx:0,dy:Math.sign(i)}},VL=(e,t,n)=>Math.abs(e.x-t.x)*Math.abs(n.dx)+Math.abs(e.y-t.y)*Math.abs(n.dy),HL=(e,t=.1)=>`${Math.round(e.x/t)},${Math.round(e.y/t)}`,BL=(e,t)=>Math.abs(e-t)<1e-4,UL=(e,t,{viaDiameter:n=.5}={})=>{let i=[];for(let r=0;r<e.length-1;r++){let[o,s]=[e[r],e[r+1]],a=r-1>=0?e[r-1]:null,c=BL(o.y,s.y),l=BL(o.x,s.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${t}, start: (${o.x}, ${o.y}), end: (${s.x}, ${s.y})`);let u={type:"rect",layers:[o.layer],center:{x:(o.x+s.x)/2,y:(o.y+s.y)/2},width:c?Math.abs(o.x-s.x):.1,height:l?Math.abs(o.y-s.y):.1,connectedTo:[t]};if(i.push(u),a&&a.layer===o.layer&&o.layer!==s.layer){let h={type:"rect",layers:[o.layer,s.layer],center:{x:o.x,y:o.y},connectedTo:[t],width:n,height:n};i.push(h)}}return i},qL=class{constructor(e){T(this,"obstacles");T(this,"GRID_STEP",.1);this.obstacles=e.map(t=>({...t,left:t.center.x-t.width/2,right:t.center.x+t.width/2,top:t.center.y+t.height/2,bottom:t.center.y-t.height/2}))}getObstacleAt(e,t,n){n??(n=this.GRID_STEP);for(let i of this.obstacles){let r=i.width/2+n,o=i.height/2+n;if(e>=i.center.x-r&&e<=i.center.x+r&&t>=i.center.y-o&&t<=i.center.y+o)return i}return null}isObstacleAt(e,t,n){return this.getObstacleAt(e,t,n)!==null}getDirectionDistancesToNearestObstacle(e,t){let{GRID_STEP:n}=this,i={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let r of this.obstacles)if(r.type==="rect"){let o=r.center.x-r.width/2-n,s=r.center.x+r.width/2+n,a=r.center.y+r.height/2+n,c=r.center.y-r.height/2-n;t>=c&&t<=a&&e>o&&(i.left=Math.min(i.left,e-s)),t>=c&&t<=a&&e<s&&(i.right=Math.min(i.right,o-e)),e>=o&&e<=s&&t<a&&(i.top=Math.min(i.top,c-t)),e>=o&&e<=s&&t>c&&(i.bottom=Math.min(i.bottom,t-a))}return i}getOrthoDirectionCollisionInfo(e,t,{margin:n=0}={}){let{x:i,y:r}=e,{dx:o,dy:s}=t,a=1/0,c=null;for(let l of this.obstacles){let u=l.left-n,h=l.right+n,d=l.top+n,_=l.bottom-n,y=null;o===1&&s===0?r>_&&r<d&&i<l.left&&(y=l.left-i):o===-1&&s===0?r>_&&r<d&&i>l.right&&(y=i-l.right):o===0&&s===1?i>u&&i<h&&r<l.bottom&&(y=l.bottom-r):o===0&&s===-1&&i>u&&i<h&&r>l.top&&(y=r-l.top),y!==null&&y<a&&(a=y,c=l)}return{dx:o,dy:s,wallDistance:a,obstacle:c}}getObstaclesOverlappingRegion(e){let t=[];for(let n of this.obstacles){let{left:i,right:r,top:o,bottom:s}=n;i<=e.maxX&&r>=e.minX&&o<=e.maxY&&s>=e.minY&&t.push(n)}return t}};function fmt(e){if(e.length<4)return e;let t=[{...e[0]}],n=e[0].layer;for(let i=1;i<e.length;i++){let r={start:e[i-1],end:e[i]},o=e[i].route_type==="via"||e[i-1].route_type==="via";if(e[i].layer!==n||o){t.push({...e[i]}),n=e[i].layer;continue}let s=!1,a=null,c=-1;for(let u=0;u<t.length-1;u++){let h={start:t[u],end:t[u+1]};if(h.start.layer===r.start.layer&&h.start.layer===r.start.layer){let d=mmt(h,r);if(d){s=!0,a={...d,layer:n},c=u;break}}}s&&a&&(t.splice(c+1),t.push(a));let l=t[t.length-1];(l.x!==e[i].x||l.y!==e[i].y)&&t.push(e[i])}return t}function mmt(e,t){if(e.start.x===e.end.x&&t.start.x===t.end.x||e.start.y===e.end.y&&t.start.y===t.end.y)return null;let n;if(e.start.x===e.end.x){let i=e.start.x,r=t.start.y;n={...e.start,x:i,y:r}}else{let i=t.start.x,r=e.start.y;n={...e.start,x:i,y:r}}return jL(n,e)&&jL(n,t)?n:null}function jL(e,t){return e.x>=Math.min(t.start.x,t.end.x)&&e.x<=Math.max(t.start.x,t.end.x)&&e.y>=Math.min(t.start.y,t.end.y)&&e.y<=Math.max(t.start.y,t.end.y)}function _mt(e){let t=[e[0]];for(let n=1;n<e.length-1;n++){let[i,r,o]=[e[n-1],e[n],e[n+1]];t.push(r),!(r.route_type!=="wire"||i.route_type!=="wire"||o.route_type!=="wire")&&i.layer===r.layer&&r.layer!==o.layer&&t.push({route_type:"via",from_layer:r.layer,to_layer:o.layer,x:r.x,y:r.y})}return t.push(e[e.length-1]),t}var Vzt=(0,WL.default)("autorouter:shortenPathWithShortcuts");function ymt(e,t){if(e.length<=2)return e;let n=[e[0]];for(let i=1;i<e.length;i++){let r={start:n[n.length-1],end:e[i]},o=-1,s=r.start.x===r.end.x,a=r.start.y===r.end.y;for(let c=i+1;c<e.length;c++){if(c<=o)continue;let l={start:e[c],end:e[c+1]};if(!l.end)continue;let u=l.start.x===l.end.x,h=l.start.y===l.end.y,d=s&&u,_=a&&h;if(_&&d||!(d||_))continue;let g=!1,x=Math.min(r.start.x,r.end.x),w=Math.max(r.start.x,r.end.x),S=Math.min(l.start.x,l.end.x),E=Math.max(l.start.x,l.end.x),M=Math.min(r.start.y,r.end.y),k=Math.max(r.start.y,r.end.y),I=Math.min(l.start.y,l.end.y),N=Math.max(l.start.y,l.end.y);if(_?g=x<=E&&w>=S:d&&(g=M<=N&&k>=I),!g)continue;let C=[],A=n[n.length-1],O=e[c+2];if(!O)continue;_&&S<w&&O.x===S&&C.push({x:S,y:r.start.y,layer:r.start.layer}),_&&E>x&&O.x===E&&C.push({x:E,y:r.start.y,layer:r.start.layer}),d&&I<k&&O.y===I&&C.push({x:r.start.x,y:I,layer:r.start.layer}),d&&N>M&&O.y===N&&C.push({x:r.start.x,y:N,layer:r.start.layer});let B=null;for(let D of C)if(!(t(A,D)||t(O,D))){B=D;break}if(B){n.push(B),i=c+1,o=c+1;break}}o===-1&&n.push(e[i])}return n[n.length-1]!==e[e.length-1]&&n.push(e[e.length-1]),n}var El=(0,GL.default)("autorouting-dataset:astar"),ZL=class{constructor(e){T(this,"openSet",[]);T(this,"closedSet",new Set);T(this,"debug",!1);T(this,"debugSolutions");T(this,"debugMessage",null);T(this,"debugTraceCount",0);T(this,"input");T(this,"obstacles");T(this,"allObstacles");T(this,"startNode");T(this,"goalPoint");T(this,"GRID_STEP");T(this,"OBSTACLE_MARGIN");T(this,"MAX_ITERATIONS");T(this,"isRemovePathLoopsEnabled");T(this,"isShortenPathWithShortcutsEnabled");T(this,"GREEDY_MULTIPLIER",1.1);T(this,"iterations",-1);this.input=e.input,this.allObstacles=e.input.obstacles,this.startNode=e.startNode,this.goalPoint=e.goalPoint?{l:0,...e.goalPoint}:void 0,this.GRID_STEP=e.GRID_STEP??.1,this.OBSTACLE_MARGIN=e.OBSTACLE_MARGIN??.15,this.MAX_ITERATIONS=e.MAX_ITERATIONS??100,this.debug=e.debug??El.enabled,this.isRemovePathLoopsEnabled=e.isRemovePathLoopsEnabled??!1,this.isShortenPathWithShortcutsEnabled=e.isShortenPathWithShortcutsEnabled??!1,this.debug&&(El.enabled=!0),El.enabled&&(this.debugSolutions={},this.debugMessage="")}getNeighbors(e){return[]}isSameNode(e,t){return Cl(e,t)<this.GRID_STEP}computeG(e,t){return e.g+Cl(e,t)}computeH(e){return Cl(e,this.goalPoint)}getNodeName(e){return HL(e,this.GRID_STEP)}solveOneStep(){this.iterations+=1;let{openSet:e,closedSet:t,GRID_STEP:n,goalPoint:i}=this;e.sort((a,c)=>a.f-c.f);let r=e.shift();if(this.computeH(r)<=n*2)return{solved:!0,current:r,newNeighbors:[]};this.closedSet.add(this.getNodeName(r));let s=[];for(let a of this.getNeighbors(r)){if(t.has(this.getNodeName(a)))continue;let c=this.computeG(r,a),l=this.openSet.find(u=>this.isSameNode(u,a));if(!l||c<l.g){let u=this.computeH(a),h=c+u*this.GREEDY_MULTIPLIER,d={...a,g:c,h:u,f:h,obstacleHit:a.obstacleHit??void 0,manDistFromParent:Cl(r,a),nodesInPath:r.nodesInPath+1,parent:r,enterMarginCost:a.enterMarginCost,travelMarginCostFactor:a.travelMarginCostFactor};e.push(d),s.push(d)}}return El.enabled&&(e.sort((a,c)=>a.f-c.f),this.drawDebugSolution({current:r,newNeighbors:s})),{solved:!1,current:r,newNeighbors:s}}getStartNode(e){return{x:e.pointsToConnect[0].x,y:e.pointsToConnect[0].y,manDistFromParent:0,f:0,g:0,h:0,nodesInPath:0,parent:null}}layerToIndex(e){return 0}indexToLayer(e){return"top"}preprocessConnectionBeforeSolving(e){return e}solveConnection(e){if(e.pointsToConnect.length>2)throw new Error("GeneralizedAstarAutorouter doesn't currently support 2+ points in a connection");e=this.preprocessConnectionBeforeSolving(e);let{pointsToConnect:t}=e;for(this.iterations=0,this.closedSet=new Set,this.startNode=this.getStartNode(e),this.goalPoint={...t[t.length-1],l:this.layerToIndex(t[t.length-1].layer)},this.openSet=[this.startNode];this.iterations<this.MAX_ITERATIONS;){let{solved:n,current:i}=this.solveOneStep();if(n){let r=[],o=i;for(;o;){let s=o.l;r.unshift({x:o.x,y:o.y,layer:s!==void 0?this.indexToLayer(s):t[0].layer}),o=o.parent}return El.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations
160
160
  `),this.isRemovePathLoopsEnabled&&(r=fmt(r)),this.isShortenPathWithShortcutsEnabled&&(r=ymt(r,(s,a)=>{if(s.x===a.x&&s.y===a.y)return!1;let c=this.obstacles.getOrthoDirectionCollisionInfo({x:s.x,y:s.y,l:this.layerToIndex(s.layer)??0},{dx:Math.sign(a.x-s.x),dy:Math.sign(a.y-s.y),dl:0},{margin:.05}),l=Math.sqrt((s.x-a.x)**2+(s.y-a.y)**2);return c.wallDistance<l})),{solved:!0,route:r,connectionName:e.name}}if(this.openSet.length===0)break}return El.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations (failed)
161
- `),{solved:!1,connectionName:e.name}}createObstacleList({dominantLayer:e,connection:t,obstaclesFromTraces:n}){return new qL(this.allObstacles.filter(i=>!i.connectedTo.includes(t.name)).filter(i=>i.layers.includes(e)).concat(n??[]))}postprocessConnectionSolveResult(e,t){return t}solve(){let e=[],t=[];this.debugTraceCount=0;for(let n of this.input.connections){let i=n.pointsToConnect[0].layer??"top";this.debugTraceCount+=1,this.obstacles=this.createObstacleList({dominantLayer:i,connection:n,obstaclesFromTraces:t});let r=this.solveConnection(n);r=this.postprocessConnectionSolveResult(n,r),e.push(r),El.enabled&&this.drawDebugTraceObstacles(t),r.solved&&t.push(...UL(r.route.map(o=>({x:o.x,y:o.y,layer:o.layer??i})),n.name))}return e}solveAndMapToTraces(){return this.solve().flatMap(t=>t.solved?[{type:"pcb_trace",pcb_trace_id:`pcb_trace_for_${t.connectionName}`,route:_mt(t.route.map(n=>({route_type:"wire",x:n.x,y:n.y,width:this.input.minTraceWidth,layer:n.layer})))}]:[])}getDebugGroup(){let e=`t${this.debugTraceCount}_iter[${this.iterations-1}]`;return this.iterations<30||this.iterations<100&&this.iterations%10===0||this.iterations<1e3&&this.iterations%100===0||!this.debugSolutions?e:null}drawDebugTraceObstacles(e){let{debugTraceCount:t,debugSolutions:n}=this;for(let i in n)i.startsWith(`t${t}_`)&&n[i].push(...e.map((r,o)=>({type:"pcb_smtpad",pcb_component_id:"",layer:r.layers[0],width:r.width,shape:"rect",x:r.center.x,y:r.center.y,pcb_smtpad_id:`trace_obstacle_${o}`,height:r.height})))}drawDebugSolution({current:e,newNeighbors:t}){let n=this.getDebugGroup();if(!n)return;let{openSet:i,debugTraceCount:r,debugSolutions:o}=this;o[n]??(o[n]=[]);let s=o[n];s.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${e.x}_${e.y}`,font:"tscircuit2024",font_size:.25,text:"X"+(e.l!==void 0?e.l:""),pcb_component_id:"",layer:"top",anchor_position:{x:e.x,y:e.y},anchor_alignment:"center"});for(let a=0;a<i.length;a++){let c=i[a];s.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${c.x}_${c.y}`,layer:"top",route:[[0,.05],[.05,0],[0,-.05],[-.05,0],[0,.05]].map(([l,u])=>({x:c.x+l,y:c.y+u})),stroke_width:.01}),s.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${c.x}_${c.y}`,font:"tscircuit2024",font_size:.03,text:a.toString(),pcb_component_id:"",layer:"top",anchor_position:{x:c.x,y:c.y},anchor_alignment:"center"})}if(e.parent){let a=[],c=e;for(;c;)a.unshift(c),c=c.parent;s.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${e.x}_${e.y}`,layer:"top",route:a,stroke_width:.01})}}},gmt=(0,KL.default)("autorouting-dataset:infinite-grid-ijump-astar:get-distance-to-overcome-obstacle");function q5({node:e,travelDir:t,wallDir:n,obstacle:i,obstacles:r,obstaclesInRow:o=0,OBSTACLE_MARGIN:s=.15,SHOULD_DETECT_CONJOINED_OBSTACLES:a=!1,MAX_CONJOINED_OBSTACLES:c=20}){let l;if(t.dx===0?t.dy>0?l=i.center.y+i.height/2-e.y:l=e.y-(i.center.y-i.height/2):t.dx>0?l=i.center.x+i.width/2-e.x:l=e.x-(i.center.x-i.width/2),l+=s,a&&o<c){let u=r.getObstacleAt(e.x+t.dx*l+n.dx*(n.wallDistance+.001),e.y+t.dy*l+n.dy*(n.wallDistance+.001));if(u===i)return l;if(u&&u.type==="rect"){let h=t.dy===0,d=h?i.height:i.width;if((h?u.height:u.width)>d)return gmt("next obstacle on path is bigger, not trying to overcome it"),l;let y=q5({node:{x:e.x+t.dx*l,y:e.y+t.dy*l},travelDir:t,wallDir:n,obstacle:u,obstacles:r,obstaclesInRow:o+1,SHOULD_DETECT_CONJOINED_OBSTACLES:a,MAX_CONJOINED_OBSTACLES:c,OBSTACLE_MARGIN:s});l+=y}}return l}var bmt=class extends ZL{constructor(){super(...arguments);T(this,"MAX_ITERATIONS",200)}getNeighbors(t){let n=this.obstacles,i=this.goalPoint,r;t.parent?r=$L(t.parent,t):r=$L(t,i);let o=[{dx:0,dy:1},{dx:1,dy:0},{dx:0,dy:-1},{dx:-1,dy:0}].filter(a=>a.dx===r.dx*-1&&a.dy===r.dy*-1?!1:!(a.dx===r.dx&&a.dy===r.dy&&t.parent?.obstacleHit)).map(a=>n.getOrthoDirectionCollisionInfo(t,a,{margin:this.OBSTACLE_MARGIN})).filter(a=>a.wallDistance>=this.OBSTACLE_MARGIN),s=[];for(let a of o){let c=null;t?.obstacleHit&&(c=q5({node:t,travelDir:a,wallDir:{...r,wallDistance:this.OBSTACLE_MARGIN},obstacle:t.obstacleHit,obstacles:n,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let l=VL(t,i,a),u=(a.dx===0||Math.sign(i.x-t.x)===a.dx)&&(a.dy===0||Math.sign(i.y-t.y)===a.dy);l<a.wallDistance&&l>0&&u?s.push({...a,travelDistance:l}):c!==null&&c<a.wallDistance?s.push({...a,travelDistance:c}):a.wallDistance!==1/0&&s.push({...a,travelDistance:a.wallDistance-this.OBSTACLE_MARGIN})}return s.filter(a=>!n.isObstacleAt(t.x+a.dx*a.travelDistance,t.y+a.dy*a.travelDistance)).map(a=>({x:t.x+a.dx*a.travelDistance,y:t.y+a.dy*a.travelDistance,obstacleHit:a.obstacle}))}};function xmt(e,t=4){let{center:n,width:i,height:r,rotation:o}=e,s=[],a=o*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(o%360+360)%360;if(r<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*c,x=-y*l,w=d*1.1,S=Math.abs(r*c)+Math.abs(d*l);s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}else{let d=r/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*l,x=y*c,w=Math.abs(i*c)+Math.abs(d*l),S=d*1.1;s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}return s}var gg=["top","inner1","inner2","bottom"],JL=(e,t)=>{let n=r=>t?r.concat(r.map(o=>t?.getNetConnectedToId(o)).filter(Boolean)):r,i=[];for(let r of e)if(r.type==="pcb_smtpad"){if(r.shape==="circle")i.push({type:"oval",layers:[r.layer],center:{x:r.x,y:r.y},width:r.radius*2,height:r.radius*2,connectedTo:n([r.pcb_smtpad_id])});else if(r.shape==="rect")i.push({type:"rect",layers:[r.layer],center:{x:r.x,y:r.y},width:r.width,height:r.height,connectedTo:n([r.pcb_smtpad_id])});else if(r.shape==="rotated_rect"){let o={center:{x:r.x,y:r.y},width:r.width,height:r.height,rotation:r.ccw_rotation},s=xmt(o);for(let a of s)i.push({type:"rect",layers:[r.layer],center:a.center,width:a.width,height:a.height,connectedTo:n([r.pcb_smtpad_id])})}}else if(r.type==="pcb_keepout")r.shape==="circle"?i.push({type:"oval",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.radius*2,height:r.radius*2,connectedTo:[]}):r.shape==="rect"&&i.push({type:"rect",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.type==="pcb_hole")r.hole_shape==="oval"?i.push({type:"oval",center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="square"?i.push({type:"rect",layers:gg,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]}):(r.hole_shape==="round"||r.hole_shape==="circle")&&i.push({type:"rect",layers:gg,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]});else if(r.type==="pcb_plated_hole")r.shape==="circle"?i.push({type:"oval",layers:gg,center:{x:r.x,y:r.y},width:r.outer_diameter,height:r.outer_diameter,connectedTo:n([r.pcb_plated_hole_id])}):(r.shape==="oval"||r.shape==="pill")&&i.push({type:"oval",layers:gg,center:{x:r.x,y:r.y},width:r.outer_width,height:r.outer_height,connectedTo:n([r.pcb_plated_hole_id])});else if(r.type==="pcb_trace"){let o=UL(r.route.map(s=>({x:s.x,y:s.y,layer:"layer"in s?s.layer:s.from_layer})),r.source_trace_id);i.push(...o)}else r.type==="pcb_via"&&i.push({type:"rect",layers:r.layers,center:{x:r.x,y:r.y},connectedTo:[],width:r.outer_diameter,height:r.outer_diameter});return i};function YL(e){let{pcbConnMap:t,goalElementId:n}=e;if(!n.startsWith("pcb_port_"))throw new Error(`Currently alternative goal boxes must have a goal id with prefix "pcb_port_" (got ${n})`);let i=t.getAllTracesConnectedToPort(n);return JL(i).map(r=>({...r,connectedTo:[n]}))}var QL=e=>{let{connection:t,pcbConnMap:n}=e;if(t.pointsToConnect.length!==2)throw new Error(`Connection must have exactly 2 points for alternative goal boxes (got ${t.pointsToConnect.length})`);let[i,r]=t.pointsToConnect;if(!i.pcb_port_id||!r.pcb_port_id)throw new Error(`Connection points must have pcb_port_id for alternative goal box calculation (got ${i.pcb_port_id} and ${r.pcb_port_id})`);let o=YL({goalElementId:i.pcb_port_id,pcbConnMap:n}).concat([{center:i,width:.01,height:.01,connectedTo:[i.pcb_port_id],layers:[i.layer],type:"rect"}]),s=YL({goalElementId:r.pcb_port_id,pcbConnMap:n}).concat([{center:r,width:.01,height:.01,connectedTo:[r.pcb_port_id],layers:[r.layer],type:"rect"}]);if(o.length<=1&&s.length<=1)return{...t,startPoint:i,endPoint:r,goalBoxes:[]};let a=Ud(o,s),c,l,u;return o.length>=s.length?(c={...r,...a.pointB},l={...i,...a.pointA},u=o):(c={...i,...a.pointA},l={...r,...a.pointB},u=s),{startPoint:c,endPoint:l,goalBoxes:u,name:t.name,pointsToConnect:[c,l]}},vmt=(e,t={})=>{let n={minTraceWidth:.1};n.layerCount=t.layerCount??1,n.obstacles=JL(e,t.connMap),n.connections=[];for(let r of e)if(r.type==="source_trace"){let o={name:r.source_trace_id,pointsToConnect:r.connected_source_port_ids.map(s=>{let a=Io(e).pcb_port.getWhere({source_port_id:s});if(!a)throw new Error(`Could not find pcb_port for source_port_id "${s}"`);return{x:a.x,y:a.y,layer:a.layers?.[0]??"top",pcb_port_id:a.pcb_port_id}})};if(t.optimizeWithGoalBoxes){let s=new yg(e);o=QL({connection:o,pcbConnMap:s})}n.connections.push(o),wmt(n.obstacles,o.pointsToConnect,o.name)}let i={minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0};for(let r of n.obstacles)i.minX=Math.min(i.minX,r.center.x-r.width/2),i.maxX=Math.max(i.maxX,r.center.x+r.width/2),i.minY=Math.min(i.minY,r.center.y-r.height/2),i.maxY=Math.max(i.maxY,r.center.y+r.height/2);for(let r of n.connections)for(let o of r.pointsToConnect)i.minX=Math.min(i.minX,o.x),i.maxX=Math.max(i.maxX,o.x),i.minY=Math.min(i.minY,o.y),i.maxY=Math.max(i.maxY,o.y);return n.bounds=i,n},wmt=(e,t,n)=>{for(let i of t)for(let r of e)Smt(i,r)&&r.connectedTo.push(n)};function Smt(e,t){let n=t.width/2,i=t.height/2;if(t.type==="rect")return e.x>=t.center.x-n&&e.x<=t.center.x+n&&e.y>=t.center.y-i&&e.y<=t.center.y+i;if(t.type==="oval"){let r=(e.x-t.center.x)/n,o=(e.y-t.center.y)/i;return r*r+o*o<=1}return!1}function XL(e,t){let n=t.x>e.x?1:t.x<e.x?-1:0,i=t.y>e.y?1:t.y<e.y?-1:0,r=t.l>e.l?1:t.l<e.l?-1:0;return{dx:n,dy:i,dl:r}}var W5={1:["top"],2:["top","bottom"],4:["top","inner1","inner2","bottom"]},Pmt=e=>W5[e];function tz(e,t){let i=W5[e].indexOf(t);if(i===-1)throw new Error(`Invalid layer for getLayerIndex (for layerCount === ${e}): "${t}"`);return i}function Tmt(e,t){let i=W5[e][t];if(!i)throw new Error(`Invalid index for indexToLayer (for layerCount === ${e}): "${t}"`);return i}var Imt=class extends qL{constructor(t,n){super([]);T(this,"obstacles");T(this,"GRID_STEP",.1);T(this,"layerCount");this.layerCount=t;let i=Pmt(t);this.obstacles=n.flatMap(r=>r.layers.filter(o=>i.includes(o)).map(o=>({...r,left:r.center.x-r.width/2,right:r.center.x+r.width/2,top:r.center.y+r.height/2,bottom:r.center.y-r.height/2,l:tz(t,o)})))}getObstacleAt(t,n,i,r){r??(r=this.GRID_STEP);for(let o of this.obstacles){if(o.l!==i)continue;let s=o.width/2+r,a=o.height/2+r;if(t>=o.center.x-s&&t<=o.center.x+s&&n>=o.center.y-a&&n<=o.center.y+a)return o}return null}isObstacleAt(t,n,i,r){return this.getObstacleAt(t,n,i,r)!==null}getDirectionDistancesToNearestObstacle3d(t,n,i){let{GRID_STEP:r}=this,o={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let s of this.obstacles)if(s.l===i&&s.type==="rect"){let a=s.center.x-s.width/2-r,c=s.center.x+s.width/2+r,l=s.center.y+s.height/2+r,u=s.center.y-s.height/2-r;n>=u&&n<=l&&t>a&&(o.left=Math.min(o.left,t-c)),n>=u&&n<=l&&t<c&&(o.right=Math.min(o.right,a-t)),t>=a&&t<=c&&n<l&&(o.top=Math.min(o.top,u-n)),t>=a&&t<=c&&n>u&&(o.bottom=Math.min(o.bottom,n-l))}return o}getOrthoDirectionCollisionInfo(t,n,{margin:i=0}={}){let{x:r,y:o,l:s}=t,{dx:a,dy:c,dl:l}=n,u=1/0,h=null;if(l!==0){let d=s+l;return this.isObstacleAt(r,o,d,i)?(u=1,h=this.getObstacleAt(r,o,d,i)):u=1,{dx:a,dy:c,dl:l,wallDistance:u,obstacle:h}}else{for(let d of this.obstacles){if(d.l!==s)continue;let _=d.left-i,y=d.right+i,g=d.top+i,x=d.bottom-i,w=null;a===1&&c===0?o>x&&o<g&&r<d.left&&(w=d.left-r):a===-1&&c===0?o>x&&o<g&&r>d.right&&(w=r-d.right):a===0&&c===1?r>_&&r<y&&o<d.bottom&&(w=d.bottom-o):a===0&&c===-1&&r>_&&r<y&&o>d.top&&(w=o-d.top),w!==null&&w<u&&(u=w,h=d)}return{dx:a,dy:c,dl:0,wallDistance:u,obstacle:h}}}getObstaclesOverlappingRegion(t){let n=[];for(let i of this.obstacles){if(i.l!==t.l)continue;let{left:r,right:o,top:s,bottom:a}=i;r<=t.maxX&&o>=t.minX&&s>=t.minY&&a<=t.maxY&&n.push(i)}return n}},bg=class extends ZL{constructor(t){super(t);T(this,"MAX_ITERATIONS",500);T(this,"VIA_COST",4);T(this,"VIA_DIAMETER",.5);T(this,"allowLayerChange",!0);T(this,"layerCount");T(this,"obstacles");T(this,"optimizeWithGoalBoxes");T(this,"connMap");T(this,"pcbConnMap");T(this,"GOAL_RUSH_FACTOR",1.1);T(this,"defaultGoalViaMargin",.5);T(this,"marginsWithCosts");this.layerCount=t.input.layerCount??2,this.MAX_ITERATIONS=t.MAX_ITERATIONS??this.MAX_ITERATIONS,this.VIA_COST=t.VIA_COST??this.VIA_COST,this.connMap=t.connMap,this.pcbConnMap=t.pcbConnMap??new yg,this.optimizeWithGoalBoxes=t.optimizeWithGoalBoxes??!1,this.obstacles=null,this.marginsWithCosts=t.marginsWithCosts??[{margin:1,enterCost:0,travelCostFactor:1},{margin:this.OBSTACLE_MARGIN,enterCost:10,travelCostFactor:2}]}get largestMargin(){return this.marginsWithCosts[0].margin}preprocessConnectionBeforeSolving(t){return this.optimizeWithGoalBoxes?QL({connection:t,pcbConnMap:this.pcbConnMap}):t}postprocessConnectionSolveResult(t,n){if(!n.solved)return n;if(this.optimizeWithGoalBoxes){let i=n.route.map(r=>({x:r.x,y:r.y,route_type:"wire",layer:r.layer,width:this.input.minTraceWidth}));i[0].start_pcb_port_id=t.pointsToConnect[0].pcb_port_id,i[i.length-1].end_pcb_port_id=t.pointsToConnect[1].pcb_port_id,this.pcbConnMap.addTrace({type:"pcb_trace",pcb_trace_id:`postprocess_trace_${DL(8)}`,route:i})}return n}createObstacleList({dominantLayer:t,connection:n,obstaclesFromTraces:i}){let r=this.connMap?this.connMap.getNetConnectedToId(n.name):n.name;if(!r)throw new Error(`The connection.name "${n.name}" wasn't present in the full connectivity map`);return new Imt(this.layerCount,this.allObstacles.filter(o=>!o.connectedTo.includes(r)).concat(i??[]))}computeG(t,n){let i=t.g+Cl(t,n)*(t.travelMarginCostFactor??1)+(n.enterMarginCost??0);return(n.l??t.l!==-1??-1)&&(i+=this.VIA_COST),i}computeH(t){let n=Math.abs(t.x-this.goalPoint.x),i=Math.abs(t.y-this.goalPoint.y),r=Math.abs(t.l-this.goalPoint.l);return(n+i)**this.GOAL_RUSH_FACTOR+r*this.VIA_COST}getStartNode(t){return{...super.getStartNode(t),l:this.layerToIndex(t.pointsToConnect[0].layer)}}layerToIndex(t){return tz(this.layerCount,t)}indexToLayer(t){return Tmt(this.layerCount,t)}getNodeName(t){return`${HL(t,this.GRID_STEP)}-${t.l??0}`}hasSpaceForVia(t,n){return t.every(i=>this.obstacles.getObstaclesOverlappingRegion({minX:n.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:n.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:n.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:n.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:i}).length===0)}getNeighborsSurroundingGoal(t){let n=this.obstacles,i=this.goalPoint,r=[],o=[{dx:1,dy:0,dl:0},{dx:-1,dy:0,dl:0},{dx:0,dy:1,dl:0},{dx:0,dy:-1,dl:0}],s=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin;for(let a of o){let c={x:t.x+a.dx*s,y:t.y+a.dy*s,l:t.l+a.dl,obstacleHit:null};this.hasSpaceForVia([t.l,i.l],c)&&r.push(c)}return r}getNeighbors(t){let n=this.obstacles,i=this.goalPoint,r=Cl(t,i);if(r<=this.OBSTACLE_MARGIN)return this.getNeighborsSurroundingGoal(t);let o;t.parent?o=XL(t.parent,t):o=XL(t,i);let s=[{dx:0,dy:1,dl:0},{dx:1,dy:0,dl:0},{dx:0,dy:-1,dl:0},{dx:-1,dy:0,dl:0}],a=r>this.VIA_DIAMETER+this.OBSTACLE_MARGIN,c=Cl(t,this.startNode)>this.VIA_DIAMETER+this.OBSTACLE_MARGIN;this.allowLayerChange&&a&&c&&(t.l<this.layerCount-1&&s.push({dx:0,dy:0,dl:1}),t.l>0&&s.push({dx:0,dy:0,dl:-1}));let l=s.filter(h=>h.dx===o.dx*-1&&h.dy===o.dy*-1&&h.dl===o.dl*-1?!1:!(h.dx===o.dx&&h.dy===o.dy&&h.dl===o.dl&&t.parent?.obstacleHit)).map(h=>n.getOrthoDirectionCollisionInfo(t,h,{margin:this.OBSTACLE_MARGIN})).filter(h=>!(h.wallDistance<this.OBSTACLE_MARGIN)),u=[];for(let h of l){let d=h.dx===0&&h.dy===0&&h.dl===1,_=h.dx===0&&h.dy===0&&h.dl===-1;if((d||_)&&![t.l,t.l+h.dl].every(S=>n.getObstaclesOverlappingRegion({minX:t.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:t.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:t.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:t.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:S}).length===0))continue;if(d){t.l<this.layerCount-1&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}if(_){t.l>0&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}let y=null;t?.obstacleHit&&(y=q5({node:t,travelDir:h,wallDir:{...o,wallDistance:this.OBSTACLE_MARGIN},obstacle:t.obstacleHit,obstacles:n,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let g=VL(t,i,h),x=(h.dx===0||Math.sign(i.x-t.x)===h.dx)&&(h.dy===0||Math.sign(i.y-t.y)===h.dy);if(g<h.wallDistance&&g>0&&x){let w=t.l===i.l,S=0;!w&&Math.abs(g-r)<this.GRID_STEP&&(S=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin),u.push({...h,travelDistance:g-S,enterMarginCost:0,travelMarginCostFactor:1})}else if(y!==null&&y<h.wallDistance){for(let{margin:w,enterCost:S,travelCostFactor:E}of this.marginsWithCosts)y-this.OBSTACLE_MARGIN+w*2<h.wallDistance&&u.push({...h,travelDistance:y-this.OBSTACLE_MARGIN+w,enterMarginCost:S,travelMarginCostFactor:E});if(h.wallDistance===1/0)u.push({...h,travelDistance:g,enterMarginCost:0,travelMarginCostFactor:1});else if(h.wallDistance>this.largestMargin)for(let{margin:w,enterCost:S,travelCostFactor:E}of this.marginsWithCosts)h.wallDistance>this.largestMargin+w&&u.push({...h,travelDistance:h.wallDistance-w,enterMarginCost:S,travelMarginCostFactor:E})}else if(h.wallDistance!==1/0)for(let{margin:w,enterCost:S,travelCostFactor:E}of this.marginsWithCosts)h.wallDistance>w&&u.push({...h,travelDistance:h.wallDistance-w,enterMarginCost:S,travelMarginCostFactor:E})}return u.map(h=>({x:t.x+h.dx*h.travelDistance,y:t.y+h.dy*h.travelDistance,l:t.l+h.dl,obstacleHit:h.obstacle,travelMarginCostFactor:h.travelMarginCostFactor,enterMarginCost:h.enterMarginCost}))}};function ez(e){let t=vmt(e),n=new bmt({input:t});return{solution:n.solveAndMapToTraces(),debugSolutions:n.debugSolutions,debugMessage:n.debugMessage}}W();W();vt();W();W();vt();vt();W();W();W();W();W();vt();W();W();W();vt();W();W();vt();W();W();W();W();W();W();W();W();W();W();vt();W();vt();W();vt();W();vt();vt();W();vt();W();W();vt();W();W();vt();W();vt();W();vt();W();vt();W();vt();W();vt();W();vt();W();W();W();W();W();W();W();W();vt();W();vt();W();W();vt();W();vt();W();W();W();vt();W();vt();vt();W();W();W();vt();W();W();W();W();vt();W();vt();W();vt();W();vt();W();vt();W();vt();W();vt();W();W();vt();W();vt();W();vt();W();W();vt();vt();W();W();vt();vt();W();W();vt();W();vt();W();vt();W();vt();W();vt();W();vt();W();W();vt();W();vt();W();vt();W();vt();W();vt();W();vt();W();vt();vt();W();vt();W();vt();W();W();vt();W();vt();W();vt();W();vt();W();vt();W();W();vt();var It=e=>{};It("extra props b");It("missing props b");It(!0);It("property a has mismatched types");var Mmt=p.enum(["up","down","left","right"]),cFt=p.enum(["top-to-bottom","left-to-right","bottom-to-top","right-to-left"]);It(!0);It(!0);var Go=p.array(p.string().or(p.number()));It(!0);var wg=p.object({x:V,y:V,z:V}),Emt=p.object({x:p.union([p.number(),p.string()]),y:p.union([p.number(),p.string()]),z:p.union([p.number(),p.string()])}),Ga=p.object({rotationOffset:p.number().or(Emt).optional(),positionOffset:wg.optional(),size:wg.optional(),modelUnitToMmScale:V.optional()});It(!0);var Cmt=Ga.extend({stlUrl:p.string()}),kmt=Ga.extend({objUrl:p.string(),mtlUrl:p.string().optional()}),Nmt=Ga.extend({gltfUrl:p.string()}),Amt=Ga.extend({glbUrl:p.string()}),Rmt=Ga.extend({stepUrl:p.string()}),Omt=Ga.extend({wrlUrl:p.string()}),Lmt=Ga.extend({jscad:p.record(p.any())}),lz=p.union([p.null(),p.string(),p.custom(e=>e&&typeof e=="object"&&"type"in e&&"props"in e),Cmt,kmt,Nmt,Amt,Rmt,Omt,Lmt]);It(!0);var zmt=p.custom(e=>!0),Fmt=p.custom(e=>!0),$e=p.object({pcbX:V.optional(),pcbY:V.optional(),pcbRotation:ze.optional(),pcbPositionAnchor:p.string().optional(),layer:ye.optional(),pcbMarginTop:V.optional(),pcbMarginRight:V.optional(),pcbMarginBottom:V.optional(),pcbMarginLeft:V.optional(),pcbMarginX:V.optional(),pcbMarginY:V.optional(),pcbRelative:p.boolean().optional(),relative:p.boolean().optional()});It(!0);var Sg=p.object({pcbX:V.optional(),pcbY:V.optional(),pcbRotation:ze.optional(),pcbPositionAnchor:p.string().optional(),pcbMarginTop:V.optional(),pcbMarginRight:V.optional(),pcbMarginBottom:V.optional(),pcbMarginLeft:V.optional(),pcbMarginX:V.optional(),pcbMarginY:V.optional(),schMarginTop:V.optional(),schMarginRight:V.optional(),schMarginBottom:V.optional(),schMarginLeft:V.optional(),schMarginX:V.optional(),schMarginY:V.optional(),schX:V.optional(),schY:V.optional(),schRotation:ze.optional(),layer:ye.optional(),footprint:zmt.optional(),symbol:Fmt.optional(),relative:p.boolean().optional(),schRelative:p.boolean().optional(),pcbRelative:p.boolean().optional()});It(!0);var Dmt=p.object({supplierPartNumbers:p.record(pp,p.array(p.string())).optional()});It(!0);var $mt=p.object({providesPower:p.boolean().optional(),requiresPower:p.boolean().optional(),providesGround:p.boolean().optional(),requiresGround:p.boolean().optional(),providesVoltage:p.union([p.string(),p.number()]).optional(),requiresVoltage:p.union([p.string(),p.number()]).optional(),doNotConnect:p.boolean().optional(),includeInBoardPinout:p.boolean().optional(),highlightColor:p.string().optional()});It(!0);var Fn=Sg.merge(Dmt).extend({key:p.any().optional(),name:p.string(),cadModel:lz.optional(),children:p.any().optional(),symbolName:p.string().optional(),doNotPlace:p.boolean().optional(),obstructsWithinBounds:p.boolean().optional().describe("Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath"),pinAttributes:p.record(p.string(),$mt).optional()});It(!0);var K5=["pin1","left","pin2","right"],Pg=["pin1","left","anode","pos","pin2","right","cathode","neg"],bFt=V.or(p.enum(["2x","3x","4x"])),Ua=p.enum(["vertical","horizontal","pos_top","pos_bottom","pos_left","pos_right","neg_top","neg_bottom","neg_left","neg_right"]).describe("horizontal means pins go 1->2 rightward and vertical means pins go 1->2 downward (generally, positive on top)");It(!0);var xg=p.object({pins:p.array(p.union([p.number(),p.string()])),direction:p.union([p.literal("top-to-bottom"),p.literal("left-to-right"),p.literal("bottom-to-top"),p.literal("right-to-left")])}),Wd=p.object({leftSize:p.number().optional().describe("@deprecated, use leftPinCount"),topSize:p.number().optional().describe("@deprecated, use topPinCount"),rightSize:p.number().optional().describe("@deprecated, use rightPinCount"),bottomSize:p.number().optional().describe("@deprecated, use bottomPinCount"),leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftSide:xg.optional(),rightSide:xg.optional(),topSide:xg.optional(),bottomSide:xg.optional()}),J5=Wd;It(!0);var Zd=p.record(p.object({marginLeft:V.optional(),marginRight:V.optional(),marginTop:V.optional(),marginBottom:V.optional(),leftMargin:V.optional(),rightMargin:V.optional(),topMargin:V.optional(),bottomMargin:V.optional()}));It(!0);var oo=p.string().regex(/^[A-Za-z0-9_]+$/),Kd=p.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),Bs=p.object({x:V,y:V}),Jd=p.object({edit_event_id:p.string(),in_progress:p.boolean().optional(),created_at:p.number()});It(!0);var Bmt=Jd.extend({pcb_edit_event_type:p.literal("edit_component_location").describe("deprecated"),edit_event_type:p.literal("edit_pcb_component_location"),pcb_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});It(!0);var jmt=Jd.extend({pcb_edit_event_type:p.literal("edit_trace_hint").describe("deprecated"),edit_event_type:p.literal("edit_pcb_trace_hint").optional(),pcb_port_id:p.string(),pcb_trace_hint_id:p.string().optional(),route:p.array(p.object({x:p.number(),y:p.number(),via:p.boolean().optional()}))});It(!0);var Ymt=Jd.extend({edit_event_type:p.literal("edit_schematic_component_location"),schematic_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});It(!0);var zFt=Jd.extend({edit_event_type:p.literal("edit_pcb_group_location"),pcb_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});It(!0);var DFt=Jd.extend({edit_event_type:p.literal("edit_schematic_group_location"),schematic_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});It(!0);var BFt=p.union([Bmt,jmt,Ymt]);It(!0);var Xmt=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Zt});It(!0);var Vmt=p.object({pcb_port_selector:p.string(),offsets:p.array(Ni)});It(!0);var Hmt=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Zt});It(!0);var Gmt=p.object({pcb_placements:p.array(Xmt).optional(),manual_trace_hints:p.array(Vmt).optional(),schematic_placements:p.array(Hmt).optional()});It(!0);var Qd=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),kl=e=>p.record(p.enum(e),Qd),qd=p.object({layoutMode:p.enum(["grid","flex","match-adapt","relative","none"]).optional(),position:p.enum(["absolute","relative"]).optional(),grid:p.boolean().optional(),gridCols:p.number().or(p.string()).optional(),gridRows:p.number().or(p.string()).optional(),gridTemplateRows:p.string().optional(),gridTemplateColumns:p.string().optional(),gridTemplate:p.string().optional(),gridGap:p.number().or(p.string()).optional(),gridRowGap:p.number().or(p.string()).optional(),gridColumnGap:p.number().or(p.string()).optional(),flex:p.boolean().or(p.string()).optional(),flexDirection:p.enum(["row","column"]).optional(),alignItems:p.enum(["start","center","end","stretch"]).optional(),justifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),flexRow:p.boolean().optional(),flexColumn:p.boolean().optional(),gap:p.number().or(p.string()).optional(),pack:p.boolean().optional().describe("Pack the contents of this group using a packing strategy"),packOrderStrategy:p.enum(["largest_to_smallest","first_to_last","highest_to_lowest_pin_count"]).optional(),packPlacementStrategy:p.enum(["shortest_connection_along_outline"]).optional(),padding:$.optional(),paddingLeft:$.optional(),paddingRight:$.optional(),paddingTop:$.optional(),paddingBottom:$.optional(),paddingX:$.optional(),paddingY:$.optional(),width:$.optional(),height:$.optional(),matchAdapt:p.boolean().optional(),matchAdaptTemplate:p.any().optional()});It(!0);var nz=p.object({strokeWidth:$.optional(),dashed:p.boolean().optional(),solid:p.boolean().optional()}),Umt=p.custom(e=>typeof e=="string"),qmt=p.object({serverUrl:p.string().optional(),inputFormat:p.enum(["simplified","circuit-json"]).optional(),serverMode:p.enum(["job","solve-endpoint"]).optional(),serverCacheEnabled:p.boolean().optional(),cache:p.custom(e=>!0).optional(),traceClearance:$.optional(),groupMode:p.enum(["sequential_trace","subcircuit","sequential-trace"]).optional(),algorithmFn:p.custom(e=>typeof e=="function"||e===void 0).optional(),preset:p.enum(["sequential_trace","subcircuit","auto","auto_local","auto_cloud","freerouting","sequential-trace","auto-local","auto-cloud"]).optional(),local:p.boolean().optional()}),Wmt=p.union([p.literal("sequential_trace"),p.literal("subcircuit"),p.literal("auto"),p.literal("auto_local"),p.literal("auto_cloud"),p.literal("freerouting"),p.literal("sequential-trace"),p.literal("auto-local"),p.literal("auto-cloud")]),Zmt=p.string(),uz=p.union([qmt,Wmt,Zmt]),pz=Sg.extend({name:p.string().optional(),children:p.any().optional(),schTitle:p.string().optional(),key:p.any().optional(),showAsSchematicBox:p.boolean().optional(),connections:p.record(p.string(),Qd.optional()).optional(),schPinArrangement:J5.optional(),schPinSpacing:$.optional(),schPinStyle:Zd.optional(),...qd.shape,grid:qd.shape.grid.describe("@deprecated use pcbGrid"),flex:qd.shape.flex.describe("@deprecated use pcbFlex"),pcbGrid:p.boolean().optional(),pcbGridCols:p.number().or(p.string()).optional(),pcbGridRows:p.number().or(p.string()).optional(),pcbGridTemplateRows:p.string().optional(),pcbGridTemplateColumns:p.string().optional(),pcbGridTemplate:p.string().optional(),pcbGridGap:p.number().or(p.string()).optional(),pcbGridRowGap:p.number().or(p.string()).optional(),pcbGridColumnGap:p.number().or(p.string()).optional(),pcbFlex:p.boolean().or(p.string()).optional(),pcbFlexGap:p.number().or(p.string()).optional(),pcbFlexDirection:p.enum(["row","column"]).optional(),pcbAlignItems:p.enum(["start","center","end","stretch"]).optional(),pcbJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),pcbFlexRow:p.boolean().optional(),pcbFlexColumn:p.boolean().optional(),pcbGap:p.number().or(p.string()).optional(),pcbPack:p.boolean().optional(),pcbPackGap:p.number().or(p.string()).optional(),schGrid:p.boolean().optional(),schGridCols:p.number().or(p.string()).optional(),schGridRows:p.number().or(p.string()).optional(),schGridTemplateRows:p.string().optional(),schGridTemplateColumns:p.string().optional(),schGridTemplate:p.string().optional(),schGridGap:p.number().or(p.string()).optional(),schGridRowGap:p.number().or(p.string()).optional(),schGridColumnGap:p.number().or(p.string()).optional(),schFlex:p.boolean().or(p.string()).optional(),schFlexGap:p.number().or(p.string()).optional(),schFlexDirection:p.enum(["row","column"]).optional(),schAlignItems:p.enum(["start","center","end","stretch"]).optional(),schJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),schFlexRow:p.boolean().optional(),schFlexColumn:p.boolean().optional(),schGap:p.number().or(p.string()).optional(),schPack:p.boolean().optional(),schMatchAdapt:p.boolean().optional(),pcbWidth:$.optional(),pcbHeight:$.optional(),schWidth:$.optional(),schHeight:$.optional(),pcbLayout:qd.optional(),schLayout:qd.optional(),cellBorder:nz.nullable().optional(),border:nz.nullable().optional(),schPadding:$.optional(),schPaddingLeft:$.optional(),schPaddingRight:$.optional(),schPaddingTop:$.optional(),schPaddingBottom:$.optional(),pcbPadding:$.optional(),pcbPaddingLeft:$.optional(),pcbPaddingRight:$.optional(),pcbPaddingTop:$.optional(),pcbPaddingBottom:$.optional(),pcbPositionAnchor:Umt.optional()}),hz=p.custom(e=>"findPart"in e),Q5=pz.extend({manualEdits:Gmt.optional(),schAutoLayoutEnabled:p.boolean().optional(),schTraceAutoLabelEnabled:p.boolean().optional(),schMaxTraceDistance:V.optional(),routingDisabled:p.boolean().optional(),defaultTraceWidth:$.optional(),minTraceWidth:$.optional(),partsEngine:hz.optional(),pcbRouteCache:p.custom(e=>!0).optional(),autorouter:uz.optional(),square:p.boolean().optional(),emptyArea:p.string().optional(),filledArea:p.string().optional(),width:V.optional(),height:V.optional(),outline:p.array(Bs).optional(),outlineOffsetX:V.optional(),outlineOffsetY:V.optional()}),Kmt=Q5.extend({subcircuit:p.literal(!0)}),dz=p.discriminatedUnion("subcircuit",[pz.extend({subcircuit:p.literal(!1).optional()}),Kmt]);It(!0);It(!0);It(!0);It(!0);var Ap=p.custom(e=>typeof e=="string"),t4=Q5.omit({connections:!0}).extend({material:p.enum(["fr4","fr1"]).default("fr4"),layers:p.union([p.literal(2),p.literal(4)]).default(2),borderRadius:V.optional(),thickness:V.optional(),boardAnchorPosition:Bs.optional(),boardAnchorAlignment:Kd.optional(),title:p.string().optional(),solderMaskColor:Ap.optional(),topSolderMaskColor:Ap.optional(),bottomSolderMaskColor:Ap.optional(),silkscreenColor:Ap.optional(),topSilkscreenColor:Ap.optional(),bottomSilkscreenColor:Ap.optional()});It(!0);var ZFt=Q5.extend({padding:V.optional(),paddingLeft:V.optional(),paddingRight:V.optional(),paddingTop:V.optional(),paddingBottom:V.optional()});It(!0);var Jmt=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),Qmt=p.custom().pipe(p.record(p.string(),Jmt)),t1t=p.record(oo,oo.or(p.array(oo).readonly()).or(p.array(oo)));It(!0);var e1t=p.object({manufacturerPartNumber:p.string().optional(),supplierPartNumber:p.record(pp,p.array(p.string())).optional()}),Rp=Fn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:t1t.optional(),showPinAliases:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),externallyConnectedPins:p.array(p.array(p.string())).optional(),schPinArrangement:Wd.optional(),schPortArrangement:Wd.optional(),pinCompatibleVariants:p.array(e1t).optional(),schPinStyle:Zd.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional(),noSchematicRepresentation:p.boolean().optional(),connections:Qmt.optional()});It(!0);var fz=Rp;It(!0);var e4=Fn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(oo),oo.or(p.array(oo))).optional(),schPinStyle:Zd.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional(),schDirection:p.enum(["left","right"]).optional(),schPinArrangement:J5.optional(),schPortArrangement:Wd.optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),pinCount:p.union([p.literal(2),p.literal(3)]).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),connections:p.custom().pipe(p.record(p.string(),Qd)).optional()});It(!0);var mz=e4.extend({bridgedPins:p.array(p.array(p.string())).optional(),bridged:p.boolean().optional()});It(!0);var rDt=Fn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(oo),oo.or(p.array(oo))).optional(),schPinStyle:Zd.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional(),schDirection:p.enum(["left","right"]).optional(),schPortArrangement:Wd.optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),standard:p.enum(["usb_c","m2"]).optional()});It(!0);var _z=Fn.extend({currentRating:p.union([p.number(),p.string()]),voltageRating:p.union([p.number(),p.string()]).optional(),schShowRatings:p.boolean().optional(),schOrientation:Ua.optional(),connections:p.record(p.string(),p.union([p.string(),p.array(p.string()).readonly(),p.array(p.string())])).optional()}),vg=p.custom().transform(e=>{if(e!==void 0)return V.parse(e)}),yz=p.discriminatedUnion("shape",[$e.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circle"),holeDiameter:V,outerDiameter:V,portHints:Go.optional()}),$e.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("oval"),outerWidth:V,outerHeight:V,holeWidth:vg,holeHeight:vg,innerWidth:V.optional().describe("DEPRECATED use holeWidth"),innerHeight:V.optional().describe("DEPRECATED use holeHeight"),portHints:Go.optional()}),$e.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill"),rectPad:p.boolean().optional(),outerWidth:V,outerHeight:V,holeWidth:vg,holeHeight:vg,innerWidth:V.optional().describe("DEPRECATED use holeWidth"),innerHeight:V.optional().describe("DEPRECATED use holeHeight"),portHints:Go.optional(),holeOffsetX:V.optional(),holeOffsetY:V.optional()}),$e.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circular_hole_with_rect_pad"),holeDiameter:V,rectPadWidth:V,rectPadHeight:V,rectBorderRadius:V.optional(),holeShape:p.literal("circle").optional(),padShape:p.literal("rect").optional(),portHints:Go.optional(),holeOffsetX:V.optional(),holeOffsetY:V.optional()}),$e.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill_hole_with_rect_pad"),holeShape:p.literal("pill"),padShape:p.literal("rect"),holeWidth:V,holeHeight:V,rectPadWidth:V,rectPadHeight:V,portHints:Go.optional(),holeOffsetX:V.optional(),holeOffsetY:V.optional()})]).refine(e=>("innerWidth"in e&&e.innerWidth!==void 0&&(e.holeWidth??(e.holeWidth=e.innerWidth)),"innerHeight"in e&&e.innerHeight!==void 0&&(e.holeHeight??(e.holeHeight=e.innerHeight)),e));It(!0);var n1t=["pin1","pin2","pos","neg"],gz=Fn.extend({resistance:Da,pullupFor:p.string().optional(),pullupTo:p.string().optional(),pulldownFor:p.string().optional(),pulldownTo:p.string().optional(),schOrientation:Ua.optional(),connections:kl(n1t).optional()}),bz=K5;It(!0);var xz=Fn.extend({maxResistance:Da,pinVariant:p.enum(["two_pin","three_pin"]).optional()});It(!0);var i1t=K5,vz=Fn.extend({frequency:fr,loadCapacitance:ks,manufacturerPartNumber:p.string().optional(),mpn:p.string().optional(),pinVariant:p.enum(["two_pin","four_pin"]).optional(),schOrientation:Ua.optional(),connections:kl(i1t).optional()});It(!0);var wz=Fn.extend({frequency:fr,loadCapacitance:ks,pinVariant:p.enum(["no_ground","ground_pin","two_ground_pins"]).optional()});It(!0);var gDt=t4.extend({leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftPins:p.array(p.string()).optional(),rightPins:p.array(p.string()).optional(),topPins:p.array(p.string()).optional(),bottomPins:p.array(p.string()).optional(),pinPitch:V.optional(),innerHoles:p.boolean().optional()});It(!0);var r1t=["pin1","pin2","pos","neg","anode","cathode"],Sz=Fn.extend({capacitance:ks,maxVoltageRating:oi.optional(),schShowRatings:p.boolean().optional().default(!1),polarized:p.boolean().optional().default(!1),decouplingFor:p.string().optional(),decouplingTo:p.string().optional(),bypassFor:p.string().optional(),bypassTo:p.string().optional(),maxDecouplingTraceLength:p.number().optional(),schOrientation:Ua.optional(),connections:kl(r1t).optional()}),Pz=Pg;It(!0);var wDt=p.object({name:p.string(),connectsTo:p.string().or(p.array(p.string())).optional(),highlightColor:p.string().optional()});It(!0);var PDt=p.object({name:p.string().optional(),pcbOnly:p.boolean().optional(),schOnly:p.boolean().optional()});It(!0);var o1t=p.object({pcb:p.literal(!0).optional(),xDist:V,left:p.string(),right:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});It(!0);var s1t=p.object({pcb:p.literal(!0).optional(),yDist:V,top:p.string(),bottom:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});It(!0);var a1t=p.object({pcb:p.literal(!0).optional(),sameY:p.literal(!0).optional(),for:p.array(p.string())});It(!0);var c1t=p.object({pcb:p.literal(!0).optional(),sameX:p.literal(!0).optional(),for:p.array(p.string())});It(!0);var Tz=p.union([o1t,s1t,a1t,c1t]);It(!0);var l1t=$e.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:V,height:V});It(!0);var u1t=$e.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:V});It(!0);var p1t=$e.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Bs)});It(!0);var Iz=p.discriminatedUnion("shape",[l1t,u1t,p1t]),h1t=$e.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:V,height:V,rectBorderRadius:V.optional(),portHints:Go.optional(),coveredWithSolderMask:p.boolean().optional()});It(!0);var d1t=$e.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rotated_rect"),width:V,height:V,ccwRotation:p.number(),portHints:Go.optional(),coveredWithSolderMask:p.boolean().optional()});It(!0);var f1t=$e.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:V,portHints:Go.optional(),coveredWithSolderMask:p.boolean().optional()});It(!0);var m1t=$e.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("pill"),width:V,height:V,radius:V,portHints:Go.optional(),coveredWithSolderMask:p.boolean().optional()});It(!0);var _1t=$e.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Bs),portHints:Go.optional(),coveredWithSolderMask:p.boolean().optional()});It(!0);var Mz=p.discriminatedUnion("shape",[f1t,h1t,d1t,m1t,_1t]);It(!0);var y1t=$e.omit({pcbRotation:!0}).extend({shape:p.literal("rect"),width:V,height:V});It(!0);var g1t=$e.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:V});It(!0);var CDt=p.union([g1t,y1t]);It(!0);var b1t=$e.extend({name:p.string().optional(),shape:p.literal("circle").optional(),diameter:V.optional(),radius:V.optional()}).transform(e=>({...e,diameter:e.diameter??2*e.radius,radius:e.radius??e.diameter/2})),x1t=$e.extend({name:p.string().optional(),shape:p.literal("pill"),width:V,height:V}),Ez=p.union([b1t,x1t]);It(!0);var Z5=p.union([p.string(),p.custom(e=>!!e.getPortSelector)]),iz=p.object({key:p.string().optional(),thickness:V.optional(),schematicRouteHints:p.array(Bs).optional(),pcbRouteHints:p.array(Ni).optional(),pcbPathRelativeTo:p.string().optional(),pcbPath:p.array(Bs).optional(),schDisplayLabel:p.string().optional(),schStroke:p.string().optional(),highlightColor:p.string().optional(),maxLength:V.optional()}),Cz=p.union([iz.extend({path:p.array(Z5)}),iz.extend({from:Z5,to:Z5})]),kz=p.object({originalLayer:ye.default("top").optional()});It(!0);var Nz=p.object({originalFacingDirection:p.enum(["up","down","left","right"]).default("right").optional()});It(!0);var v1t=p.number().or(p.string().endsWith("mAh")).transform(e=>{if(typeof e=="string"){let t=e.replace("mAh",""),n=Number.parseFloat(t);if(Number.isNaN(n))throw new Error("Invalid capacity");return n}return e}).describe("Battery capacity in mAh"),Az=Fn.extend({capacity:v1t.optional(),voltage:oi.optional(),standard:p.enum(["AA","AAA","9V","CR2032","18650","C"]).optional(),schOrientation:Ua.optional()});It(!0);var w1t=p.enum(["vertical","horizontal"]).describe("vertical means pins go 1->2 downward and horizontal means pins go 1->2 rightward");It(!0);var Rz=Fn.extend({pinCount:p.number(),pitch:V.optional(),schFacingDirection:p.enum(["up","down","left","right"]).optional(),gender:p.enum(["male","female","unpopulated"]).optional().default("male"),showSilkscreenPinLabels:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),doubleRow:p.boolean().optional(),rightAngle:p.boolean().optional(),pcbOrientation:w1t.optional(),holeDiameter:V.optional(),platedDiameter:V.optional(),pinLabels:p.record(p.string(),oo).or(p.array(oo)).optional(),connections:p.custom().pipe(p.record(p.string(),Qd)).optional(),facingDirection:p.enum(["left","right"]).optional(),schPinArrangement:J5.optional(),schPinStyle:Zd.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional()});It(!0);var XDt=p.object({net:p.string().optional(),connection:p.string().optional(),schX:V.optional(),schY:V.optional(),schRotation:ze.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});It(!0);var Oz=p.object({net:p.string().optional(),connection:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),schX:V.optional(),schY:V.optional(),schRotation:ze.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});It(!0);var Lz=Rp.extend({});It(!0);It(!0);var zz=p.object({simulationType:p.literal("spice_transient_analysis").default("spice_transient_analysis"),duration:Rr.optional(),timePerStep:Rr.optional()});It(!0);var S1t=["pin1","pin2","pin3","emitter","collector","base","gate","source","drain"],Fz=Fn.extend({type:p.enum(["npn","pnp","bjt","jfet","mosfet","igbt"]),connections:kl(S1t).optional()});It(!0);var Dz=Fn.extend({channelType:p.enum(["n","p"]),mosfetMode:p.enum(["enhancement","depletion"])});It(!0);var P1t=K5,$z=Fn.extend({inductance:K1,maxCurrentRating:p.union([p.string(),p.number()]).optional(),schOrientation:Ua.optional(),connections:kl(P1t).optional()});It(!0);var T1t=p.enum(["anode","cathode","pin1","pin2","pos","neg"]),I1t=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),M1t=p.record(T1t,I1t),E1t=p.enum(["standard","schottky","zener","avalanche","photo","tvs"]),Bz=Fn.extend({connections:M1t.optional(),variant:E1t.optional().default("standard"),standard:p.boolean().optional(),schottky:p.boolean().optional(),zener:p.boolean().optional(),avalanche:p.boolean().optional(),photo:p.boolean().optional(),tvs:p.boolean().optional(),schOrientation:Ua.optional()}).superRefine((e,t)=>{if([e.standard,e.schottky,e.zener,e.avalanche,e.photo,e.tvs].filter(Boolean).length>1)return t.addIssue({code:p.ZodIssueCode.custom,message:"Exactly one diode variant must be enabled",path:[]}),p.INVALID}).transform(e=>{let t={...e,standard:!1,schottky:!1,zener:!1,avalanche:!1,photo:!1,tvs:!1};if(e.standard)t.standard=!0;else if(e.schottky)t.schottky=!0;else if(e.zener)t.zener=!0;else if(e.photo)t.photo=!0;else if(e.tvs)t.tvs=!0;else switch(e.variant){case"standard":t.standard=!0;break;case"schottky":t.schottky=!0;break;case"zener":t.zener=!0;break;case"avalanche":t.avalanche=!0;break;case"photo":t.photo=!0;break;case"tvs":t.tvs=!0;break;default:t.standard=!0}return t}),jz=Pg;It(!0);var Yz=Fn.extend({color:p.string().optional(),wavelength:p.string().optional(),schDisplayValue:p.string().optional(),schOrientation:Ua.optional(),connections:kl(Pg).optional(),laser:p.boolean().optional()}),Xz=Pg,Vz=Fn.extend({type:p.enum(["spst","spdt","dpst","dpdt"]).optional(),isNormallyClosed:p.boolean().optional().default(!1),spst:p.boolean().optional(),spdt:p.boolean().optional(),dpst:p.boolean().optional(),dpdt:p.boolean().optional(),connections:p.custom().pipe(p.record(p.string(),Qd)).optional()}).transform(e=>{let t={...e};switch(t.dpdt?t.type="dpdt":t.spst?t.type="spst":t.spdt?t.type="spdt":t.dpst&&(t.type="dpst"),t.type){case"spdt":t.spdt=!0;break;case"spst":t.spst=!0;break;case"dpst":t.dpst=!0;break;case"dpdt":t.dpdt=!0;break}return t});It(!0);var Hz=$e.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:$.optional(),color:p.string().optional()});It(!0);var Gz=$e.omit({pcbRotation:!0}).extend({width:V,height:V,strokeWidth:V.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),Uz=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:p.array(Ni),strokeWidth:$.optional(),color:p.string().optional()}),rz=p.union([p.string(),Bs]),qz=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({from:rz,to:rz,text:p.string().optional(),offset:V.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:$.optional(),color:p.string().optional(),arrowSize:V.optional()});It(!0);var p$t=p.object({layer:p.string().optional(),thickness:V.optional(),route:p.array(Ni)}),Wz=Sg.extend({name:p.string().optional(),fromLayer:ye,toLayer:ye,holeDiameter:V,outerDiameter:V,connectsTo:p.string().or(p.array(p.string())).optional()});It(!0);var Zz=Fn.extend({footprintVariant:p.enum(["pad","through_hole"]).optional(),padShape:p.enum(["rect","circle"]).optional().default("circle"),padDiameter:V.optional(),holeDiameter:V.optional(),width:V.optional(),height:V.optional()}).refine(e=>e.footprintVariant!=="through_hole"||e.holeDiameter!==void 0,{message:"holeDiameter is required for through_hole testpoints"});It(!0);var Kz=$e.omit({pcbRotation:!0,layer:!0}).extend({connection:p.string()});It(!0);var Jz=p.union([$e.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:V}),$e.extend({shape:p.literal("rect"),width:V,height:V})]),v$t=$e.omit({pcbRotation:!0}).extend({width:V,height:V,strokeWidth:V.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),P$t=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({outline:p.array(Bs),strokeWidth:$.optional(),isClosed:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),Qz=p.object({name:p.string().optional(),layer:ye,connectsTo:p.string(),padMargin:V.optional(),traceMargin:V.optional()});It(!0);var tF=p.object({originalLayer:ye.default("top").optional(),children:p.any().optional()});It(!0);var C1t=p.object({pcbX:V.optional(),pcbY:V.optional(),pcbZ:V.optional()}),k1t=Ga.extend({modelUrl:p.string(),stepUrl:p.string().optional()}),N1t=k1t.merge(C1t);It(!0);var eF=p.union([p.null(),p.string(),N1t]),nF=Fn.extend({voltage:oi}),A1t=["pin1","pin2","pos","neg"],R1t=p.union([p.string(),p.number()]).transform(e=>typeof e=="string"?e.endsWith("%")?parseFloat(e.slice(0,-1))/100:parseFloat(e):e).pipe(p.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),R$t=Fn.extend({voltage:oi.optional(),frequency:fr.optional(),peakToPeakVoltage:oi.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:ze.optional(),dutyCycle:R1t.optional(),connections:kl(A1t).optional()});It(!0);var iF=Fn.omit({name:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string()))});It(!0);var rF=p.object({center:Zt,radius:V,startAngleDegrees:ze,endAngleDegrees:ze,direction:p.enum(["clockwise","counterclockwise"]).default("counterclockwise"),strokeWidth:V.optional(),color:p.string().optional().default("#000000"),isDashed:p.boolean().optional().default(!1)}),oF=p.object({schX:V.optional(),schY:V.optional(),width:V.optional(),height:V.optional(),overlay:p.array(p.string()).optional(),padding:V.optional(),paddingLeft:V.optional(),paddingRight:V.optional(),paddingTop:V.optional(),paddingBottom:V.optional(),title:p.string().optional(),titleAlignment:Kd.default("top_left"),titleColor:p.string().optional(),titleFontSize:V.optional(),titleInside:p.boolean().default(!1),strokeStyle:p.enum(["solid","dashed"]).default("solid")}).refine(e=>e.width!==void 0&&e.height!==void 0||Array.isArray(e.overlay)&&e.overlay.length>0,{message:"Must provide either both `width` and `height`, or a non-empty `overlay` array."}).refine(e=>!(e.width!==void 0&&e.height!==void 0&&Array.isArray(e.overlay)&&e.overlay.length>0),{message:"Cannot provide both `width`/`height` and `overlay` at the same time."}),sF=p.object({center:Zt,radius:V,strokeWidth:V.optional(),color:p.string().optional().default("#000000"),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),aF=p.object({schX:V.optional(),schY:V.optional(),width:V,height:V,rotation:ze.default(0),strokeWidth:V.optional(),color:p.string().optional().default("#000000"),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),cF=p.object({x1:V,y1:V,x2:V,y2:V,strokeWidth:V.optional(),color:p.string().optional().default("#000000"),isDashed:p.boolean().optional().default(!1)}),O1t=p.enum(["center","left","right","top","bottom"]),lF=p.object({schX:V.optional(),schY:V.optional(),text:p.string(),fontSize:p.number().default(1),anchor:p.union([O1t.describe("legacy"),Kd]).default("center"),color:p.string().default("#000000"),schRotation:ze.default(0)}),Z$t=p.object({points:p.array(Zt),isFilled:p.boolean().optional().default(!1),fillColor:p.enum(["red","blue"]).optional()}),uF=p.object({schX:V.optional(),schY:V.optional(),children:p.any().optional(),cellPadding:V.optional(),borderWidth:V.optional(),anchor:Kd.optional(),fontSize:V.optional()});It(!0);var pF=p.object({children:p.any().optional(),height:V.optional()});It(!0);var hF=p.object({children:p.string().optional(),horizontalAlign:p.enum(["left","center","right"]).optional(),verticalAlign:p.enum(["top","middle","bottom"]).optional(),fontSize:V.optional(),rowSpan:p.number().optional(),colSpan:p.number().optional(),width:V.optional(),text:p.string().optional()});It(!0);var dF=$e.extend({text:p.string(),anchorAlignment:Kd.default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:$.optional(),isKnockout:p.boolean().optional(),knockoutPadding:$.optional(),knockoutPaddingLeft:$.optional(),knockoutPaddingRight:$.optional(),knockoutPaddingTop:$.optional(),knockoutPaddingBottom:$.optional(),layers:p.array(ye).optional()}),fF=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:p.array(Ni),strokeWidth:$.optional()}),mF=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({strokeWidth:V,x1:V,y1:V,x2:V,y2:V}),_F=$e.omit({pcbRotation:!0}).extend({filled:p.boolean().default(!0).optional(),stroke:p.enum(["dashed","solid","none"]).optional(),strokeWidth:V.optional(),width:V,height:V}),yF=$e.omit({pcbRotation:!0}).extend({isFilled:p.boolean().optional(),isOutline:p.boolean().optional(),strokeWidth:V.optional(),radius:V}),oz=p.object({x:V,y:V,via:p.boolean().optional(),toLayer:ye.optional()}),gF=p.object({for:p.string().optional().describe("Selector for the port you're targeting, not required if you're inside a trace"),order:p.number().optional(),offset:Ni.or(oz).optional(),offsets:p.array(Ni).or(p.array(oz)).optional(),traceWidth:p.number().optional()}),mBt=Sg.extend({name:p.string(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),direction:Mmt,connectsTo:p.string().or(p.array(p.string())).optional()}),gBt=$e.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:$.optional(),color:p.string().optional()});It(!0);var bF=$e.omit({pcbRotation:!0}).extend({width:V,height:V,strokeWidth:V.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()});It(!0);var xF=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:p.array(Ni),strokeWidth:$.optional(),color:p.string().optional()});It(!0);var vF=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({x1:V,y1:V,x2:V,y2:V,strokeWidth:V.optional(),color:p.string().optional(),isDashed:p.boolean().optional()});It(!0);var sz=p.union([p.string(),Bs]),wF=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({from:sz,to:sz,text:p.string().optional(),offset:V.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:$.optional(),color:p.string().optional(),arrowSize:V.optional()});It(!0);var SF=p.array(p.any()).describe("Circuit JSON"),PF=p.object({footprintCircuitJson:p.array(p.any()),cadModel:lz.optional()}),az=p.function().args(p.string()).returns(p.promise(PF)).describe("A function that takes a path and returns Circuit JSON"),L1t=p.object({loadFromUrl:p.function().args(p.string()).returns(p.promise(PF)).describe("A function that takes a footprint file URL and returns Circuit JSON")}),z1t=p.object({engineVersionString:p.string().optional(),simulationResultCircuitJson:SF}),F1t=p.object({simulate:p.function().args(p.string()).returns(p.promise(z1t)).describe("A function that takes a SPICE string and returns a simulation result")}),cz=p.object({run:p.function().args().returns(p.promise(p.unknown())).describe("Run the autorouter"),getOutputSimpleRouteJson:p.function().args().returns(p.promise(p.any())).describe("Get the resulting SimpleRouteJson")}),D1t=p.object({createAutorouter:p.function().args(p.any(),p.any().optional()).returns(p.union([cz,p.promise(cz)])).describe("Create an autorouter instance")}),$1t=p.object({partsEngine:hz.optional(),autorouter:uz.optional(),autorouterMap:p.record(p.string(),D1t).optional(),registryApiUrl:p.string().optional(),cloudAutorouterUrl:p.string().optional(),projectName:p.string().optional(),projectBaseUrl:p.string().optional(),version:p.string().optional(),url:p.string().optional(),printBoardInformationToSilkscreen:p.boolean().optional(),localCacheEngine:p.any().optional(),pcbDisabled:p.boolean().optional(),schematicDisabled:p.boolean().optional(),partsEngineDisabled:p.boolean().optional(),spiceEngineMap:p.record(p.string(),F1t).optional(),footprintLibraryMap:p.record(p.string(),p.union([az,p.record(p.string(),p.union([SF,az]))])).optional(),footprintFileParserMap:p.record(p.string(),L1t).optional(),simSwitchFrequency:fr.optional(),simCloseAt:Rr.optional(),simOpenAt:Rr.optional(),simStartClosed:p.boolean().optional(),simStartOpen:p.boolean().optional()});It(!0);var B1t=$1t,CBt=B1t.pick({projectName:!0,projectBaseUrl:!0,version:!0,url:!0,printBoardInformationToSilkscreen:!0});It(!0);W();vt();Ls();W();var ea=Yt(vo(),1);Ls();W();function qa(){return new n4}var n4=class e{constructor(){T(this,"index",{});T(this,"array",[])}size(){return this.array.length}empty(){return this.array.length===0}itemAt(t){return this.array[t]}contains(t){return this.index[t.id()]!==void 0}find(t){let n=this.index[t.id()];return n===void 0?void 0:this.array[n]}setDefault(t,n){let i=this.index[t.id()];if(i===void 0){let r=new Tg(t,n());return this.index[t.id()]=this.array.length,this.array.push(r),r}else return this.array[i]}insert(t,n){let i=new Tg(t,n),r=this.index[t.id()];return r===void 0?(this.index[t.id()]=this.array.length,this.array.push(i)):this.array[r]=i,i}erase(t){let n=this.index[t.id()];if(n===void 0)return;this.index[t.id()]=void 0;let i=this.array[n],r=this.array.pop();return i!==r&&(this.array[n]=r,this.index[r.first.id()]=n),i}copy(){let t=new e;for(let n=0;n<this.array.length;n++){let i=this.array[n].copy();t.array[n]=i,t.index[i.first.id()]=n}return t}},Tg=class e{constructor(t,n){T(this,"first");T(this,"second");this.first=t,this.second=n}copy(){return new e(this.first,this.second)}};var js=class{constructor(t=""){T(this,"_name");T(this,"_value",0);T(this,"_context",null);T(this,"_id",j1t++);this._name=t}id(){return this._id}name(){return this._name}setName(t){this._name=t}context(){return this._context}setContext(t){this._context=t}value(){return this._value}setValue(t){this._value=t}plus(t){return new En(this,t)}minus(t){return new En(this,typeof t=="number"?-t:[-1,t])}multiply(t){return new En([t,this])}divide(t){return new En([1/t,this])}toJSON(){return{name:this._name,value:this._value}}toString(){return this._context+"["+this._name+":"+this._value+"]"}},j1t=0;var En=class e{constructor(){T(this,"_terms");T(this,"_constant");let t=Y1t(arguments);this._terms=t.terms,this._constant=t.constant}terms(){return this._terms}constant(){return this._constant}value(){let t=this._constant;for(let n=0,i=this._terms.size();n<i;n++){let r=this._terms.itemAt(n);t+=r.first.value()*r.second}return t}plus(t){return new e(this,t)}minus(t){return new e(this,typeof t=="number"?-t:[-1,t])}multiply(t){return new e([t,this])}divide(t){return new e([1/t,this])}isConstant(){return this._terms.size()==0}toString(){let t=this._terms.array.map(function(n){return n.second+"*"+n.first.toString()}).join(" + ");return!this.isConstant()&&this._constant!==0&&(t+=" + "),t+=this._constant,t}};function Y1t(e){let t=0,n=()=>0,i=qa();for(let r=0,o=e.length;r<o;++r){let s=e[r];if(typeof s=="number")t+=s;else if(s instanceof js)i.setDefault(s,n).second+=1;else if(s instanceof En){t+=s.constant();let a=s.terms();for(let c=0,l=a.size();c<l;c++){let u=a.itemAt(c);i.setDefault(u.first,n).second+=u.second}}else if(s instanceof Array){if(s.length!==2)throw new Error("array must have length 2");let a=s[0],c=s[1];if(typeof a!="number")throw new Error("array item 0 must be a number");if(c instanceof js)i.setDefault(c,n).second+=a;else if(c instanceof En){t+=c.constant()*a;let l=c.terms();for(let u=0,h=l.size();u<h;u++){let d=l.itemAt(u);i.setDefault(d.first,n).second+=d.second*a}}else throw new Error("array item 1 must be a variable or expression")}else throw new Error("invalid Expression argument: "+s)}return{terms:i,constant:t}}var Eo=class Eo{static create(t,n,i,r=1){let o=0;return o+=Math.max(0,Math.min(1e3,t*r))*1e6,o+=Math.max(0,Math.min(1e3,n*r))*1e3,o+=Math.max(0,Math.min(1e3,i*r)),o}static clip(t){return Math.max(0,Math.min(Eo.required,t))}};T(Eo,"required",Eo.create(1e3,1e3,1e3)),T(Eo,"strong",Eo.create(1,0,0)),T(Eo,"medium",Eo.create(0,1,0)),T(Eo,"weak",Eo.create(0,0,1));var wn=Eo;var Yn;(function(e){e[e.Le=0]="Le",e[e.Ge=1]="Ge",e[e.Eq=2]="Eq"})(Yn||(Yn={}));var ai=class{constructor(t,n,i,r=wn.required){T(this,"_expression");T(this,"_operator");T(this,"_strength");T(this,"_id",X1t++);this._operator=n,this._strength=wn.clip(r),i===void 0&&t instanceof En?this._expression=t:this._expression=t.minus(i)}id(){return this._id}expression(){return this._expression}op(){return this._operator}strength(){return this._strength}toString(){return this._expression.toString()+" "+["<=",">=","="][this._operator]+" 0 ("+this._strength.toString()+")"}},X1t=0;var Op=class{constructor(){T(this,"maxIterations",1e3);T(this,"_cnMap",V1t());T(this,"_rowMap",H1t());T(this,"_varMap",G1t());T(this,"_editMap",U1t());T(this,"_infeasibleRows",[]);T(this,"_objective",new Eg);T(this,"_artificial",null);T(this,"_idTick",0)}createConstraint(t,n,i,r=wn.required){let o=new ai(t,n,i,r);return this.addConstraint(o),o}addConstraint(t){if(this._cnMap.find(t)!==void 0)throw new Error("duplicate constraint");let i=this._createRow(t),r=i.row,o=i.tag,s=this._chooseSubject(r,o);if(s.type()===He.Invalid&&r.allDummies())if(Ig(r.constant()))s=o.marker;else throw new Error("unsatisfiable constraint");if(s.type()===He.Invalid){if(!this._addWithArtificialVariable(r))throw new Error("unsatisfiable constraint")}else r.solveFor(s),this._substitute(s,r),this._rowMap.insert(s,r);this._cnMap.insert(t,o),this._optimize(this._objective)}removeConstraint(t){let n=this._cnMap.erase(t);if(n===void 0)throw new Error("unknown constraint");this._removeConstraintEffects(t,n.second);let i=n.second.marker,r=this._rowMap.erase(i);if(r===void 0){let o=this._getMarkerLeavingSymbol(i);if(o.type()===He.Invalid)throw new Error("failed to find leaving row");r=this._rowMap.erase(o),r.second.solveForEx(o,i),this._substitute(i,r.second)}this._optimize(this._objective)}hasConstraint(t){return this._cnMap.contains(t)}getConstraints(){return this._cnMap.array.map(({first:t})=>t)}addEditVariable(t,n){if(this._editMap.find(t)!==void 0)throw new Error("duplicate edit variable");if(n=wn.clip(n),n===wn.required)throw new Error("bad required strength");let r=new En(t),o=new ai(r,Yn.Eq,void 0,n);this.addConstraint(o);let a={tag:this._cnMap.find(o).second,constraint:o,constant:0};this._editMap.insert(t,a)}removeEditVariable(t){let n=this._editMap.erase(t);if(n===void 0)throw new Error("unknown edit variable");this.removeConstraint(n.second.constraint)}hasEditVariable(t){return this._editMap.contains(t)}suggestValue(t,n){let i=this._editMap.find(t);if(i===void 0)throw new Error("unknown edit variable");let r=this._rowMap,o=i.second,s=n-o.constant;o.constant=n;let a=o.tag.marker,c=r.find(a);if(c!==void 0){c.second.add(-s)<0&&this._infeasibleRows.push(a),this._dualOptimize();return}let l=o.tag.other;if(c=r.find(l),c!==void 0){c.second.add(s)<0&&this._infeasibleRows.push(l),this._dualOptimize();return}for(let u=0,h=r.size();u<h;++u){let d=r.itemAt(u),_=d.second,y=_.coefficientFor(a);y!==0&&_.add(s*y)<0&&d.first.type()!==He.External&&this._infeasibleRows.push(d.first)}this._dualOptimize()}updateVariables(){let t=this._varMap,n=this._rowMap;for(let i=0,r=t.size();i<r;++i){let o=t.itemAt(i),s=n.find(o.second);s!==void 0?o.first.setValue(s.second.constant()):o.first.setValue(0)}}_getVarSymbol(t){let n=()=>this._makeSymbol(He.External);return this._varMap.setDefault(t,n).second}_createRow(t){let n=t.expression(),i=new Eg(n.constant()),r=n.terms();for(let c=0,l=r.size();c<l;++c){let u=r.itemAt(c);if(!Ig(u.second)){let h=this._getVarSymbol(u.first),d=this._rowMap.find(h);d!==void 0?i.insertRow(d.second,u.second):i.insertSymbol(h,u.second)}}let o=this._objective,s=t.strength(),a={marker:Wa,other:Wa};switch(t.op()){case Yn.Le:case Yn.Ge:{let c=t.op()===Yn.Le?1:-1,l=this._makeSymbol(He.Slack);if(a.marker=l,i.insertSymbol(l,c),s<wn.required){let u=this._makeSymbol(He.Error);a.other=u,i.insertSymbol(u,-c),o.insertSymbol(u,s)}break}case Yn.Eq:{if(s<wn.required){let c=this._makeSymbol(He.Error),l=this._makeSymbol(He.Error);a.marker=c,a.other=l,i.insertSymbol(c,-1),i.insertSymbol(l,1),o.insertSymbol(c,s),o.insertSymbol(l,s)}else{let c=this._makeSymbol(He.Dummy);a.marker=c,i.insertSymbol(c)}break}}return i.constant()<0&&i.reverseSign(),{row:i,tag:a}}_chooseSubject(t,n){let i=t.cells();for(let o=0,s=i.size();o<s;++o){let a=i.itemAt(o);if(a.first.type()===He.External)return a.first}let r=n.marker.type();return(r===He.Slack||r===He.Error)&&t.coefficientFor(n.marker)<0?n.marker:(r=n.other.type(),(r===He.Slack||r===He.Error)&&t.coefficientFor(n.other)<0?n.other:Wa)}_addWithArtificialVariable(t){let n=this._makeSymbol(He.Slack);this._rowMap.insert(n,t.copy()),this._artificial=t.copy(),this._optimize(this._artificial);let i=Ig(this._artificial.constant());this._artificial=null;let r=this._rowMap.erase(n);if(r!==void 0){let s=r.second;if(s.isConstant())return i;let a=this._anyPivotableSymbol(s);if(a.type()===He.Invalid)return!1;s.solveForEx(n,a),this._substitute(a,s),this._rowMap.insert(a,s)}let o=this._rowMap;for(let s=0,a=o.size();s<a;++s)o.itemAt(s).second.removeSymbol(n);return this._objective.removeSymbol(n),i}_substitute(t,n){let i=this._rowMap;for(let r=0,o=i.size();r<o;++r){let s=i.itemAt(r);s.second.substitute(t,n),s.second.constant()<0&&s.first.type()!==He.External&&this._infeasibleRows.push(s.first)}this._objective.substitute(t,n),this._artificial&&this._artificial.substitute(t,n)}_optimize(t){let n=0;for(;n<this.maxIterations;){let i=this._getEnteringSymbol(t);if(i.type()===He.Invalid)return;let r=this._getLeavingSymbol(i);if(r.type()===He.Invalid)throw new Error("the objective is unbounded");let o=this._rowMap.erase(r).second;o.solveForEx(r,i),this._substitute(i,o),this._rowMap.insert(i,o),n++}throw new Error("solver iterations exceeded")}_dualOptimize(){let t=this._rowMap,n=this._infeasibleRows;for(;n.length!==0;){let i=n.pop(),r=t.find(i);if(r!==void 0&&r.second.constant()<0){let o=this._getDualEnteringSymbol(r.second);if(o.type()===He.Invalid)throw new Error("dual optimize failed");let s=r.second;t.erase(i),s.solveForEx(i,o),this._substitute(o,s),t.insert(o,s)}}}_getEnteringSymbol(t){let n=t.cells();for(let i=0,r=n.size();i<r;++i){let o=n.itemAt(i),s=o.first;if(o.second<0&&s.type()!==He.Dummy)return s}return Wa}_getDualEnteringSymbol(t){let n=Number.MAX_VALUE,i=Wa,r=t.cells();for(let o=0,s=r.size();o<s;++o){let a=r.itemAt(o),c=a.first,l=a.second;if(l>0&&c.type()!==He.Dummy){let h=this._objective.coefficientFor(c)/l;h<n&&(n=h,i=c)}}return i}_getLeavingSymbol(t){let n=Number.MAX_VALUE,i=Wa,r=this._rowMap;for(let o=0,s=r.size();o<s;++o){let a=r.itemAt(o),c=a.first;if(c.type()!==He.External){let l=a.second,u=l.coefficientFor(t);if(u<0){let h=-l.constant()/u;h<n&&(n=h,i=c)}}}return i}_getMarkerLeavingSymbol(t){let n=Number.MAX_VALUE,i=n,r=n,o=Wa,s=o,a=o,c=o,l=this._rowMap;for(let u=0,h=l.size();u<h;++u){let d=l.itemAt(u),_=d.second,y=_.coefficientFor(t);if(y===0)continue;let g=d.first;if(g.type()===He.External)c=g;else if(y<0){let x=-_.constant()/y;x<i&&(i=x,s=g)}else{let x=_.constant()/y;x<r&&(r=x,a=g)}}return s!==o?s:a!==o?a:c}_removeConstraintEffects(t,n){n.marker.type()===He.Error&&this._removeMarkerEffects(n.marker,t.strength()),n.other.type()===He.Error&&this._removeMarkerEffects(n.other,t.strength())}_removeMarkerEffects(t,n){let i=this._rowMap.find(t);i!==void 0?this._objective.insertRow(i.second,-n):this._objective.insertSymbol(t,-n)}_anyPivotableSymbol(t){let n=t.cells();for(let i=0,r=n.size();i<r;++i){let o=n.itemAt(i),s=o.first.type();if(s===He.Slack||s===He.Error)return o.first}return Wa}_makeSymbol(t){return new Mg(t,this._idTick++)}};function Ig(e){let t=1e-8;return e<0?-e<t:e<t}function V1t(){return qa()}function H1t(){return qa()}function G1t(){return qa()}function U1t(){return qa()}var He;(function(e){e[e.Invalid=0]="Invalid",e[e.External=1]="External",e[e.Slack=2]="Slack",e[e.Error=3]="Error",e[e.Dummy=4]="Dummy"})(He||(He={}));var Mg=class{constructor(t,n){T(this,"_id");T(this,"_type");this._id=n,this._type=t}id(){return this._id}type(){return this._type}},Wa=new Mg(He.Invalid,-1),Eg=class e{constructor(t=0){T(this,"_cellMap",qa());T(this,"_constant");this._constant=t}cells(){return this._cellMap}constant(){return this._constant}isConstant(){return this._cellMap.empty()}allDummies(){let t=this._cellMap;for(let n=0,i=t.size();n<i;++n)if(t.itemAt(n).first.type()!==He.Dummy)return!1;return!0}copy(){let t=new e(this._constant);return t._cellMap=this._cellMap.copy(),t}add(t){return this._constant+=t}insertSymbol(t,n=1){let i=this._cellMap.setDefault(t,()=>0);Ig(i.second+=n)&&this._cellMap.erase(t)}insertRow(t,n=1){this._constant+=t._constant*n;let i=t._cellMap;for(let r=0,o=i.size();r<o;++r){let s=i.itemAt(r);this.insertSymbol(s.first,s.second*n)}}removeSymbol(t){this._cellMap.erase(t)}reverseSign(){this._constant=-this._constant;let t=this._cellMap;for(let n=0,i=t.size();n<i;++n){let r=t.itemAt(n);r.second=-r.second}}solveFor(t){let n=this._cellMap,r=-1/n.erase(t).second;this._constant*=r;for(let o=0,s=n.size();o<s;++o)n.itemAt(o).second*=r}solveForEx(t,n){this.insertSymbol(t,-1),this.solveFor(n)}coefficientFor(t){let n=this._cellMap.find(t);return n!==void 0?n.second:0}substitute(t,n){let i=this._cellMap.erase(t);i!==void 0&&this.insertRow(n,i.second)}};var sV=Yt(Mn(),1);W();vt();yi();var i4={};Ju(i4,{boundsAreaOverlap:()=>LF,boundsDistance:()=>zF,clamp:()=>Rn,computeDistanceBetweenBoxes:()=>Mo,distSq:()=>NF,distance:()=>Oi,doBoundsOverlap:()=>Ka,doSegmentsIntersect:()=>Gi,doesLineIntersectLine:()=>Za,doesSegmentIntersectRect:()=>MF,findNearestPointsBetweenBoxSets:()=>Ud,getBoundingBox:()=>$s,getSegmentIntersection:()=>IF,getUnitVectorFromDirection:()=>Ng,getUnitVectorFromPointAToB:()=>kg,grid:()=>FF,midpoint:()=>kF,onSegment:()=>zp,orientation:()=>Lp,pointToBoundsDistance:()=>CF,pointToBoxDistance:()=>EF,pointToSegmentClosestPoint:()=>OF,pointToSegmentDistance:()=>ci,range:()=>AF,segmentToBoundsMinDistance:()=>tf,segmentToBoxMinDistance:()=>RF,segmentToCircleMinDistance:()=>Cg,segmentToSegmentMinDistance:()=>Fp});function Za([e,t],[n,i],{lineThickness:r=0}={}){return r===0?Gi(e,t,n,i):q1t(e,t,n,i)<=r}function Gi(e,t,n,i){let r=Lp(e,t,n),o=Lp(e,t,i),s=Lp(n,i,e),a=Lp(n,i,t);return!!(r!==o&&s!==a||r===0&&zp(e,n,t)||o===0&&zp(e,i,t)||s===0&&zp(n,e,i)||a===0&&zp(n,t,i))}function Lp(e,t,n){let i=(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y);return i===0?0:i>0?1:2}function zp(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function q1t(e,t,n,i){if(e.x===t.x&&e.y===t.y)return ci(e,n,i);if(n.x===i.x&&n.y===i.y)return ci(n,e,t);if(Gi(e,t,n,i))return 0;let r=[ci(e,n,i),ci(t,n,i),ci(n,e,t),ci(i,e,t)];return Math.min(...r)}function ci(e,t,n){let i=(n.x-t.x)**2+(n.y-t.y)**2;if(i===0)return Oi(e,t);let r=((e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y))/i;r=Math.max(0,Math.min(1,r));let o={x:t.x+r*(n.x-t.x),y:t.y+r*(n.y-t.y)};return Oi(e,o)}function Oi(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}function IF(e,t,n,i){let r=t.x-e.x,o=t.y-e.y,s=i.x-n.x,a=i.y-n.y,c=e.x-n.x,l=e.y-n.y,u=r*a-o*s;if(Math.abs(u)<1e-10)return null;let h=(l*s-c*a)/u,d=(r*l-o*c)/u,_=1e-9;if(h>=-_&&h<=1+_&&d>=-_&&d<=1+_){let y=e.x+h*r,g=e.y+h*o;return{x:y,y:g}}return null}function MF(e,t,n){let i=c=>c.x>=n.minX&&c.x<=n.maxX&&c.y>=n.minY&&c.y<=n.maxY;if(i(e)||i(t))return!0;let r={x:n.minX,y:n.minY},o={x:n.maxX,y:n.minY},s={x:n.minX,y:n.maxY},a={x:n.maxX,y:n.maxY};return Gi(e,t,r,o)||Gi(e,t,o,a)||Gi(e,t,a,s)||Gi(e,t,s,r)}function EF(e,t){let n=t.width/2,i=t.height/2,r=t.center.x-n,o=t.center.x+n,s=t.center.y-i,a=t.center.y+i;if(e.x>=r&&e.x<=o&&e.y>=s&&e.y<=a)return 0;let c=Rn(e.x,r,o),l=Rn(e.y,s,a);return Oi(e,{x:c,y:l})}function CF(e,t){if(e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)return 0;let n=Rn(e.x,t.minX,t.maxX),i=Rn(e.y,t.minY,t.maxY);return Oi(e,{x:n,y:i})}function kF(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function NF(e,t){let n=e.x-t.x,i=e.y-t.y;return n*n+i*i}function AF(e,t,n=1){if(n===0)throw new Error("step cannot be 0");let i,r;t===void 0?(i=0,r=e):(i=e,r=t);let o=[];if(n>0)for(let s=i;s<r;s+=n)o.push(s);else for(let s=i;s>r;s+=n)o.push(s);return o}function Fp(e,t,n,i){if(e.x===t.x&&e.y===t.y)return ci(e,n,i);if(n.x===i.x&&n.y===i.y)return ci(n,e,t);if(Gi(e,t,n,i))return 0;let r=[ci(e,n,i),ci(t,n,i),ci(n,e,t),ci(i,e,t)];return Math.min(...r)}function tf(e,t,n){let i={x:n.minX,y:n.minY},r={x:n.maxX,y:n.minY},o={x:n.minX,y:n.maxY},s={x:n.maxX,y:n.maxY};if(Gi(e,t,i,r)||Gi(e,t,r,s)||Gi(e,t,s,o)||Gi(e,t,o,i)||e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY&&t.x>=n.minX&&t.x<=n.maxX&&t.y>=n.minY&&t.y<=n.maxY)return 0;let a=[ci(i,e,t),ci(r,e,t),ci(o,e,t),ci(s,e,t)];if(e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY||t.x>=n.minX&&t.x<=n.maxX&&t.y>=n.minY&&t.y<=n.maxY)return 0;if(e.x<n.minX||e.x>n.maxX||e.y<n.minY||e.y>n.maxY){let c=Rn(e.x,n.minX,n.maxX),l=Rn(e.y,n.minY,n.maxY);a.push(Oi(e,{x:c,y:l}))}if(t.x<n.minX||t.x>n.maxX||t.y<n.minY||t.y>n.maxY){let c=Rn(t.x,n.minX,n.maxX),l=Rn(t.y,n.minY,n.maxY);a.push(Oi(t,{x:c,y:l}))}return Math.min(...a)}function RF(e,t,n){let i=n.width/2,r=n.height/2,o={minX:n.center.x-i,maxX:n.center.x+i,minY:n.center.y-r,maxY:n.center.y+r};return tf(e,t,o)}function Cg(e,t,n){let i={x:n.x,y:n.y};if(e.x===t.x&&e.y===t.y)return Math.max(0,Oi(e,i)-n.radius);let r={x:t.x-e.x,y:t.y-e.y},o={x:i.x-e.x,y:i.y-e.y},s=r.x*r.x+r.y*r.y,a=Math.max(0,Math.min(1,(r.x*o.x+r.y*o.y)/s)),c={x:e.x+a*r.x,y:e.y+a*r.y},l=Oi(c,i);return Math.max(0,l-n.radius)}function OF(e,t,n){let i=n.x-t.x,r=n.y-t.y,o=i*i+r*r;if(o===0)return{x:t.x,y:t.y};let s=((e.x-t.x)*i+(e.y-t.y)*r)/o;return s=Math.max(0,Math.min(1,s)),{x:t.x+s*i,y:t.y+s*r}}var LF=(e,t)=>{let n=Math.max(0,Math.min(e.maxX,t.maxX)-Math.max(e.minX,t.minX)),i=Math.max(0,Math.min(e.maxY,t.maxY)-Math.max(e.minY,t.minY));return n*i};var zF=(e,t)=>{let n=e.maxX<t.minX?t.minX-e.maxX:t.maxX<e.minX?e.minX-t.maxX:0,i=e.maxY<t.minY?t.minY-e.maxY:t.maxY<e.minY?e.minY-t.maxY:0;return Math.sqrt(n*n+i*i)};var Ka=(e,t)=>!(e.maxX<t.minX||t.maxX<e.minX||e.maxY<t.minY||t.maxY<e.minY);var kg=(e,t)=>{let n={x:t.x-e.x,y:t.y-e.y},i=Math.sqrt(n.x**2+n.y**2);return{x:n.x/i,y:n.y/i}},Ng=e=>{switch(e){case"up":return{x:0,y:1};case"down":return{x:0,y:-1};case"left":return{x:-1,y:0};case"right":return{x:1,y:0}}};function FF({rows:e,cols:t,xSpacing:n,ySpacing:i,width:r,height:o,offsetX:s=0,offsetY:a=0,yDirection:c="cartesian",centered:l=!0}){let u=n??1,h=i??1,d=r??t*u,_=o??e*h,y=l?-d/2:0,g=l?-_/2:0,x=r?r/t:u,w=o?o/e:h,S=[];for(let E=0;E<e;E++)for(let M=0;M<t;M++){let k=E*t+M,I=s+y+M*x+x/2,N=a+E*w+w/2,C=c==="cartesian"?a+g+(e-1-E)*w+w/2:a+g+E*w+w/2;S.push({index:k,center:{x:I,y:C},topLeft:{x:I-x/2,y:C+w/2},bottomRight:{x:I+x/2,y:C-w/2},row:E,col:M})}return S}vt();ef();var DF={name:"@tscircuit/capacity-autorouter",main:"./dist/index.js",version:"0.0.132",type:"module",files:["dist"],scripts:{start:"cosmos",build:"tsup ./lib/index.ts --minify terser --external @tscircuit/core --external circuit-to-svg --format esm --dts --sourcemap",bench:"bun test tests/spatial-index-bench.test.ts",format:"biome format --write .","format:check":"biome format .","vercel-build":"cosmos-export","repomix:lib":"repomix --ignore 'testing/**,**/TwoRouteHighDensitySolver/**,**/RouteStitchingSolver/**,solvers/CapacitySegmentPointOptimizer/CapacitySegmentPointOptimizer.ts' lib","bug-report":"bun run scripts/download-bug-report.ts","bug-report-with-test":"bun run scripts/create-bug-report-test.ts"},devDependencies:{"@biomejs/biome":"^1.9.4","@radix-ui/react-icons":"^1.3.2","@radix-ui/react-menubar":"^1.1.14","@react-hook/resize-observer":"^2.0.2","@resvg/resvg-js":"^2.6.2","@tscircuit/checks":"^0.0.75","@tscircuit/circuit-json-util":"^0.0.46","@tscircuit/core":"^0.0.337","@tscircuit/math-utils":"^0.0.27","@types/bun":"^1.2.23","@types/fast-json-stable-stringify":"^2.1.2","@types/object-hash":"^3.0.6","@types/rbush":"^4.0.0","@types/react":"^19.0.8","@types/react-dom":"^19.0.3","@vercel/node":"^5.1.7","@vitejs/plugin-react":"^4.3.4","circuit-json-to-connectivity-map":"^0.0.19","circuit-to-svg":"^0.0.220",clsx:"^2.1.1",flatbush:"^4.4.0","graphics-debug":"^0.0.44","looks-same":"9",rbush:"^4.0.1",react:"18","react-cosmos":"^6.2.3","react-cosmos-plugin-vite":"^6.2.0","react-dom":"18","react-konva":"18",recharts:"^2.15.1","tailwind-merge":"^3.2.0",terser:"^5.43.1",tsup:"^8.3.6",typescript:"^5.9.3","use-mouse-matrix-transform":"^1.3.0",vite:"^6.0.11","vite-tsconfig-paths":"^5.1.4"},dependencies:{"fast-json-stable-stringify":"^2.1.0","object-hash":"^3.0.0"}};vt();yi();Ce();var $I=Yt(vo(),1);vt();var YD=Yt(Lg(),1),ZD=Yt(Lg(),1),JD=Yt(Lg(),1);var Wg=(...e)=>{let t={points:[],lines:[],circles:[],rects:[]};return e.forEach((n,i)=>{n&&(n.lines&&(t.lines=[...t.lines||[],...n.lines.map(r=>({...r,step:i}))]),n.points&&(t.points=[...t.points||[],...n.points.map(r=>({...r,step:i}))]),n.circles&&(t.circles=[...t.circles||[],...n.circles.map(r=>({...r,step:i}))]),n.rects&&(t.rects=[...t.rects||[],...n.rects.map(r=>({...r,step:i}))]))}),t},dn=class{constructor(){T(this,"MAX_ITERATIONS",1e3);T(this,"solved",!1);T(this,"failed",!1);T(this,"iterations",0);T(this,"progress",0);T(this,"error",null);T(this,"activeSubSolver");T(this,"failedSubSolvers");T(this,"timeToSolve");T(this,"stats",{});T(this,"cacheHit");T(this,"cacheKey");T(this,"cacheToSolveSpaceTransform")}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e){throw this.error=`${this.constructor.name} error: ${e}`,console.error(this.error),this.failed=!0,e}!this.solved&&this.iterations>this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,console.error(this.error),this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}solve(){let e=Date.now();for(;!this.solved&&!this.failed;)this.step();let t=Date.now();this.timeToSolve=t-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function JF(e){let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,maxX:e.center.x+t,minY:e.center.y-n,maxY:e.center.y+n}}function tc(e,t,n){return Math.max(t,Math.min(n,e))}function gi(e,t,n,i){let r=zg(e,t,n),o=zg(e,t,i),s=zg(n,i,e),a=zg(n,i,t);return r!==o&&s!==a||!(r!==0||!Fg(e,n,t))||!(o!==0||!Fg(e,i,t))||!(s!==0||!Fg(n,e,i))||!(a!==0||!Fg(n,t,i))}function zg(e,t,n){let i=(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y);return i===0?0:i>0?1:2}function Fg(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function Ui(e,t,n){let i=(n.x-t.x)**2+(n.y-t.y)**2;if(i===0)return Gt(e,t);let r=((e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y))/i;return r=Math.max(0,Math.min(1,r)),Gt(e,{x:t.x+r*(n.x-t.x),y:t.y+r*(n.y-t.y)})}function Gt(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}function ED(e,t,n,i){let r=t.x-e.x,o=t.y-e.y,s=i.x-n.x,a=i.y-n.y,c=e.x-n.x,l=e.y-n.y,u=r*a-o*s;if(Math.abs(u)<1e-10)return null;let h=(l*s-c*a)/u,d=(r*l-o*c)/u,_=1e-9;return h>=-1e-9&&h<=1+_&&d>=-1e-9&&d<=1+_?{x:e.x+h*r,y:e.y+h*o}:null}function QF(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}var CD=e=>{if("minX"in e)return e;let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,minY:e.center.y-n,maxX:e.center.x+t,maxY:e.center.y+n}},k4=e=>[{x:e.minX,y:e.minY},{x:e.maxX,y:e.minY},{x:e.maxX,y:e.maxY},{x:e.minX,y:e.maxY}],kD=e=>{let t=[];for(let n=0;n<e.length;n++){let i=e[n],r=e[(n+1)%e.length];t.push([i,r])}return t},a_t=(e,t,n)=>{let i=(e.y-t.y)*(n.x-t.x)-(e.x-t.x)*(n.y-t.y);if(Math.abs(i)>1e-9)return!1;let r=(e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y);return r<0?!1:!(r>(n.x-t.x)**2+(n.y-t.y)**2)},ND=(e,t)=>{if(t.length<3)return!1;let n=kD(t);for(let[r,o]of n)if(a_t(e,r,o))return!0;let i=!1;for(let r=0,o=t.length-1;r<t.length;o=r++){let s=t[r].x,a=t[r].y,c=t[o].x,l=t[o].y;a>e.y!=l>e.y&&e.x<(c-s)*(e.y-a)/(l-a)+s&&(i=!i)}return i},AD=(e,t)=>{let n=k4(e),i=[[n[0],n[1]],[n[1],n[2]],[n[2],n[3]],[n[3],n[0]]],r=kD(t);for(let[o,s]of r)for(let[a,c]of i)if(gi(o,s,a,c))return!0;return!1},g4=(e,t)=>((n,i)=>!(i.length<3)&&(!!i.some(r=>((o,s)=>o.x>=s.minX&&o.x<=s.maxX&&o.y>=s.minY&&o.y<=s.maxY)(r,n))||!!k4(n).some(r=>ND(r,i))||AD(n,i)))(CD(e),t),RD=(e,t)=>((n,i)=>!(i.length<3)&&!!k4(n).every(r=>ND(r,i))&&!AD(n,i))(CD(e),t);function b4(e,t,n,i){if(e.x===t.x&&e.y===t.y)return Ui(e,n,i);if(n.x===i.x&&n.y===i.y)return Ui(n,e,t);if(gi(e,t,n,i))return 0;let r=[Ui(e,n,i),Ui(t,n,i),Ui(n,e,t),Ui(i,e,t)];return Math.min(...r)}function OD(e,t,n){let i=n.width/2,r=n.height/2;return(function(o,s,a){let c={x:a.minX,y:a.minY},l={x:a.maxX,y:a.minY},u={x:a.minX,y:a.maxY},h={x:a.maxX,y:a.maxY};if(gi(o,s,c,l)||gi(o,s,l,h)||gi(o,s,h,u)||gi(o,s,u,c)||o.x>=a.minX&&o.x<=a.maxX&&o.y>=a.minY&&o.y<=a.maxY&&s.x>=a.minX&&s.x<=a.maxX&&s.y>=a.minY&&s.y<=a.maxY)return 0;let d=[Ui(c,o,s),Ui(l,o,s),Ui(u,o,s),Ui(h,o,s)];if(o.x>=a.minX&&o.x<=a.maxX&&o.y>=a.minY&&o.y<=a.maxY||s.x>=a.minX&&s.x<=a.maxX&&s.y>=a.minY&&s.y<=a.maxY)return 0;if(o.x<a.minX||o.x>a.maxX||o.y<a.minY||o.y>a.maxY){let _=tc(o.x,a.minX,a.maxX),y=tc(o.y,a.minY,a.maxY);d.push(Gt(o,{x:_,y}))}if(s.x<a.minX||s.x>a.maxX||s.y<a.minY||s.y>a.maxY){let _=tc(s.x,a.minX,a.maxX),y=tc(s.y,a.minY,a.maxY);d.push(Gt(s,{x:_,y}))}return Math.min(...d)})(e,t,{minX:n.center.x-i,maxX:n.center.x+i,minY:n.center.y-r,maxY:n.center.y+r})}function Vp(e,t,n){let i=n.x-t.x,r=n.y-t.y,o=i*i+r*r;if(o===0)return{x:t.x,y:t.y};let s=((e.x-t.x)*i+(e.y-t.y)*r)/o;return s=Math.max(0,Math.min(1,s)),{x:t.x+s*i,y:t.y+s*r}}function br(){return br=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},br.apply(null,arguments)}function Jg(e,t){return(Jg=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n})(e,t)}function LD(e){return(LD=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)})(e)}function zD(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(zD=function(){return!!e})()}function x4(e){var t=typeof Map=="function"?new Map:void 0;return x4=function(n){if(n===null||!(function(r){try{return Function.toString.call(r).indexOf("[native code]")!==-1}catch{return typeof r=="function"}})(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(t!==void 0){if(t.has(n))return t.get(n);t.set(n,i)}function i(){return(function(r,o,s){if(zD())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,o);var c=new(r.bind.apply(r,a));return s&&Jg(c,s.prototype),c})(n,arguments,LD(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),Jg(i,n)},x4(e)}var gr=(function(e){var t,n;function i(r){var o;if(1)o=e.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+r+" for more information.")||this;else for(var s,a,c;c<s;c++);return(function(l){if(l===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return l})(o)}return n=e,(t=i).prototype=Object.create(n.prototype),t.prototype.constructor=t,Jg(t,n),i})(x4(Error));function tD(e,t){return e.substr(-t.length)===t}var c_t=/^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;function eD(e){return typeof e!="string"?e:e.match(c_t)?parseFloat(e):e}var nD=function(e){return function(t,n){n===void 0&&(n="16px");var i=t,r=n;if(typeof t=="string"){if(!tD(t,"px"))throw new gr(69,e,t);i=eD(t)}if(typeof n=="string"){if(!tD(n,"px"))throw new gr(70,e,n);r=eD(n)}if(typeof i=="string")throw new gr(71,t,e);if(typeof r=="string")throw new gr(72,n,e);return""+i/r+e}};nD("em"),nD("rem");function a4(e){return Math.round(255*e)}function l_t(e,t,n){return a4(e)+","+a4(t)+","+a4(n)}function pf(e,t,n,i){if(i===void 0&&(i=l_t),t===0)return i(n,n,n);var r=(e%360+360)%360/60,o=(1-Math.abs(2*n-1))*t,s=o*(1-Math.abs(r%2-1)),a=0,c=0,l=0;r>=0&&r<1?(a=o,c=s):r>=1&&r<2?(a=s,c=o):r>=2&&r<3?(c=o,l=s):r>=3&&r<4?(c=s,l=o):r>=4&&r<5?(a=s,l=o):r>=5&&r<6&&(a=o,l=s);var u=n-o/2;return i(a+u,c+u,l+u)}var iD={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},u_t=/^#[a-fA-F0-9]{6}$/,p_t=/^#[a-fA-F0-9]{8}$/,h_t=/^#[a-fA-F0-9]{3}$/,d_t=/^#[a-fA-F0-9]{4}$/,c4=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,f_t=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,m_t=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,__t=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function Hp(e){if(typeof e!="string")throw new gr(3);var t=(function(d){if(typeof d!="string")return d;var _=d.toLowerCase();return iD[_]?"#"+iD[_]:d})(e);if(t.match(u_t))return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16)};if(t.match(p_t)){var n=parseFloat((parseInt(""+t[7]+t[8],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16),alpha:n}}if(t.match(h_t))return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16)};if(t.match(d_t)){var i=parseFloat((parseInt(""+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16),alpha:i}}var r=c4.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var o=f_t.exec(t.substring(0,50));if(o)return{red:parseInt(""+o[1],10),green:parseInt(""+o[2],10),blue:parseInt(""+o[3],10),alpha:parseFloat(""+o[4])>1?parseFloat(""+o[4])/100:parseFloat(""+o[4])};var s=m_t.exec(t);if(s){var a="rgb("+pf(parseInt(""+s[1],10),parseInt(""+s[2],10)/100,parseInt(""+s[3],10)/100)+")",c=c4.exec(a);if(!c)throw new gr(4,t,a);return{red:parseInt(""+c[1],10),green:parseInt(""+c[2],10),blue:parseInt(""+c[3],10)}}var l=__t.exec(t.substring(0,50));if(l){var u="rgb("+pf(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",h=c4.exec(u);if(!h)throw new gr(4,t,u);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+l[4])>1?parseFloat(""+l[4])/100:parseFloat(""+l[4])}}throw new gr(5)}function ec(e){return(function(t){var n,i=t.red/255,r=t.green/255,o=t.blue/255,s=Math.max(i,r,o),a=Math.min(i,r,o),c=(s+a)/2;if(s===a)return t.alpha!==void 0?{hue:0,saturation:0,lightness:c,alpha:t.alpha}:{hue:0,saturation:0,lightness:c};var l=s-a,u=c>.5?l/(2-s-a):l/(s+a);switch(s){case i:n=(r-o)/l+(r<o?6:0);break;case r:n=(o-i)/l+2;break;default:n=(i-r)/l+4}return n*=60,t.alpha!==void 0?{hue:n,saturation:u,lightness:c,alpha:t.alpha}:{hue:n,saturation:u,lightness:c}})(Hp(e))}var v4=function(e){return e.length===7&&e[1]===e[2]&&e[3]===e[4]&&e[5]===e[6]?"#"+e[1]+e[3]+e[5]:e};function Rl(e){var t=e.toString(16);return t.length===1?"0"+t:t}function l4(e){return Rl(Math.round(255*e))}function y_t(e,t,n){return v4("#"+l4(e)+l4(t)+l4(n))}function Dg(e,t,n){return pf(e,t,n,y_t)}function w4(e,t,n){if(typeof e=="number"&&typeof t=="number"&&typeof n=="number")return v4("#"+Rl(e)+Rl(t)+Rl(n));if(typeof e=="object"&&t===void 0&&n===void 0)return v4("#"+Rl(e.red)+Rl(e.green)+Rl(e.blue));throw new gr(6)}function rb(e,t,n,i){if(typeof e=="string"&&typeof t=="number"){var r=Hp(e);return"rgba("+r.red+","+r.green+","+r.blue+","+t+")"}if(typeof e=="number"&&typeof t=="number"&&typeof n=="number"&&typeof i=="number")return i>=1?w4(e,t,n):"rgba("+e+","+t+","+n+","+i+")";if(typeof e=="object"&&t===void 0&&n===void 0&&i===void 0)return e.alpha>=1?w4(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new gr(7)}function nc(e){if(typeof e!="object")throw new gr(8);if((function(t){return typeof t.red=="number"&&typeof t.green=="number"&&typeof t.blue=="number"&&typeof t.alpha=="number"})(e))return rb(e);if((function(t){return typeof t.red=="number"&&typeof t.green=="number"&&typeof t.blue=="number"&&(typeof t.alpha!="number"||t.alpha===void 0)})(e))return w4(e);if((function(t){return typeof t.hue=="number"&&typeof t.saturation=="number"&&typeof t.lightness=="number"&&typeof t.alpha=="number"})(e))return(function(t,n,i,r){if(typeof t=="number"&&typeof n=="number"&&typeof i=="number"&&typeof r=="number")return r>=1?Dg(t,n,i):"rgba("+pf(t,n,i)+","+r+")";if(typeof t=="object"&&n===void 0&&i===void 0&&r===void 0)return t.alpha>=1?Dg(t.hue,t.saturation,t.lightness):"rgba("+pf(t.hue,t.saturation,t.lightness)+","+t.alpha+")";throw new gr(2)})(e);if((function(t){return typeof t.hue=="number"&&typeof t.saturation=="number"&&typeof t.lightness=="number"&&(typeof t.alpha!="number"||t.alpha===void 0)})(e))return(function(t,n,i){if(typeof t=="number"&&typeof n=="number"&&typeof i=="number")return Dg(t,n,i);if(typeof t=="object"&&n===void 0&&i===void 0)return Dg(t.hue,t.saturation,t.lightness);throw new gr(1)})(e);throw new gr(8)}function FD(e,t,n){return function(){var i=n.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):FD(e,t,i)}}function Lr(e){return FD(e,e.length,[])}Lr(function(e,t){if(t==="transparent")return t;var n=ec(t);return nc(br({},n,{hue:n.hue+parseFloat(e)}))});function Up(e,t,n){return Math.max(e,Math.min(t,n))}Lr(function(e,t){if(t==="transparent")return t;var n=ec(t);return nc(br({},n,{lightness:Up(0,1,n.lightness-parseFloat(e))}))});Lr(function(e,t){if(t==="transparent")return t;var n=ec(t);return nc(br({},n,{saturation:Up(0,1,n.saturation-parseFloat(e))}))});Lr(function(e,t){if(t==="transparent")return t;var n=ec(t);return nc(br({},n,{lightness:Up(0,1,n.lightness+parseFloat(e))}))});var DD=Lr(function(e,t,n){if(t==="transparent")return n;if(n==="transparent")return t;if(e===0)return n;var i=Hp(t),r=br({},i,{alpha:typeof i.alpha=="number"?i.alpha:1}),o=Hp(n),s=br({},o,{alpha:typeof o.alpha=="number"?o.alpha:1}),a=r.alpha-s.alpha,c=2*parseFloat(e)-1,l=((c*a===-1?c:c+a)/(1+c*a)+1)/2,u=1-l;return rb({red:Math.floor(r.red*l+s.red*u),green:Math.floor(r.green*l+s.green*u),blue:Math.floor(r.blue*l+s.blue*u),alpha:r.alpha*parseFloat(e)+s.alpha*(1-parseFloat(e))})});Lr(function(e,t){if(t==="transparent")return t;var n=Hp(t);return rb(br({},n,{alpha:Up(0,1,(100*(typeof n.alpha=="number"?n.alpha:1)+100*parseFloat(e))/100)}))});Lr(function(e,t){if(t==="transparent")return t;var n=ec(t);return nc(br({},n,{saturation:Up(0,1,n.saturation+parseFloat(e))}))});Lr(function(e,t){return t==="transparent"?t:nc(br({},ec(t),{hue:parseFloat(e)}))});Lr(function(e,t){return t==="transparent"?t:nc(br({},ec(t),{lightness:parseFloat(e)}))});Lr(function(e,t){return t==="transparent"?t:nc(br({},ec(t),{saturation:parseFloat(e)}))});Lr(function(e,t){return t==="transparent"?t:DD(parseFloat(e),"rgb(0, 0, 0)",t)});Lr(function(e,t){return t==="transparent"?t:DD(parseFloat(e),"rgb(255, 255, 255)",t)});var g_t=Lr(function(e,t){if(t==="transparent")return t;var n=Hp(t);return rb(br({},n,{alpha:Up(0,1,+(100*(typeof n.alpha=="number"?n.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))}),rD=["blue","orange","purple","cyan","magenta","yellowgreen","darkgoldenrod","deeppink"],S4=(e,t)=>{let n={};for(let i=0;i<e.connections.length;i++){let r=e.connections[i],o=t?.getNetConnectedToId(r.name);o&&!n[o]&&(n[o]=`hsl(${300*i/e.connections.length}, 100%, 50%)`),n[r.name]=(o?n[o]:null)??`hsl(${340*i/e.connections.length}, 100%, 50%)`}return n},Xn=(e,t)=>{try{return g_t(t,e)}catch(n){return console.error(n),e}},Ll=(e,t)=>e==="top"?0:e==="bottom"?t-1:parseInt(e.slice(5)),qo=(e,t=1)=>{let n=(("width"in e?e.width:e)/.5/2)**1.1*t;return e.availableZ?.length===1&&n>1?1:n},b_t=(e,t=.5,n=16)=>{let i=0,r=e;for(;i<n&&!(qo({width:r})<=t);)r/=2,i++;return Math.max(1,i)};function $D(e,t,n=0,i=e.length-1,r=x_t){for(;i>n;){if(i-n>600){let c=i-n+1,l=t-n+1,u=Math.log(c),h=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*h*(c-h)/c)*(l-c/2<0?-1:1);$D(e,t,Math.max(n,Math.floor(t-l*h/c+d)),Math.min(i,Math.floor(t+(c-l)*h/c+d)),r)}let o=e[t],s=n,a=i;for(rf(e,n,t),r(e[i],o)>0&&rf(e,n,i);s<a;){for(rf(e,s,a),s++,a--;r(e[s],o)<0;)s++;for(;r(e[a],o)>0;)a--}r(e[n],o)===0?rf(e,n,a):(a++,rf(e,a,i)),a<=t&&(n=a+1),t<=a&&(i=a-1)}}function rf(e,t,n){let i=e[t];e[t]=e[n],e[n]=i}function x_t(e,t){return e<t?-1:e>t?1:0}var v_t=class{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data,n=[];if(!Bg(e,t))return n;let i=this.toBBox,r=[];for(;t;){for(let o=0;o<t.children.length;o++){let s=t.children[o],a=t.leaf?i(s):s;Bg(e,a)&&(t.leaf?n.push(s):p4(e,a)?this._all(s,n):r.push(s))}t=r.pop()}return n}collides(e){let t=this.data;if(!Bg(e,t))return!1;let n=[];for(;t;){for(let i=0;i<t.children.length;i++){let r=t.children[i],o=t.leaf?this.toBBox(r):r;if(Bg(e,o)){if(t.leaf||p4(e,o))return!0;n.push(r)}}t=n.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let n=0;n<e.length;n++)this.insert(e[n]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){let n=this.data;this.data=t,t=n}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=Yp([]),this}remove(e,t){if(!e)return this;let n=this.data,i=this.toBBox(e),r=[],o=[],s,a,c;for(;n||r.length;){if(n||(n=r.pop(),a=r[r.length-1],s=o.pop(),c=!0),n.leaf){let l=w_t(e,n.children,t);if(l!==-1)return n.children.splice(l,1),r.push(n),this._condense(r),this}c||n.leaf||!p4(n,i)?a?(s++,n=a.children[s],c=!1):n=null:(r.push(n),o.push(s),s=0,a=n,n=n.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){let n=[];for(;e;)e.leaf?t.push(...e.children):n.push(...e.children),e=n.pop();return t}_build(e,t,n,i){let r=n-t+1,o,s=this._maxEntries;if(r<=s)return o=Yp(e.slice(t,n+1)),jp(o,this.toBBox),o;i||(i=Math.ceil(Math.log(r)/Math.log(s)),s=Math.ceil(r/Math.pow(s,i-1))),o=Yp([]),o.leaf=!1,o.height=i;let a=Math.ceil(r/s),c=a*Math.ceil(Math.sqrt(s));oD(e,t,n,c,this.compareMinX);for(let l=t;l<=n;l+=c){let u=Math.min(l+c-1,n);oD(e,l,u,a,this.compareMinY);for(let h=l;h<=u;h+=a){let d=Math.min(h+a-1,u);o.children.push(this._build(e,h,d,i-1))}}return jp(o,this.toBBox),o}_chooseSubtree(e,t,n,i){for(;i.push(t),!t.leaf&&i.length-1!==n;){let r,o=1/0,s=1/0;for(let a=0;a<t.children.length;a++){let c=t.children[a],l=u4(c),u=T_t(e,c)-l;u<s?(s=u,o=l<o?l:o,r=c):u===s&&l<o&&(o=l,r=c)}t=r||t.children[0]}return t}_insert(e,t,n){let i=n?e:this.toBBox(e),r=[],o=this._chooseSubtree(i,this.data,t,r);for(o.children.push(e),sf(o,i);t>=0&&r[t].children.length>this._maxEntries;)this._split(r,t),t--;this._adjustParentBBoxes(i,r,t)}_split(e,t){let n=e[t],i=n.children.length,r=this._minEntries;this._chooseSplitAxis(n,r,i);let o=this._chooseSplitIndex(n,r,i),s=Yp(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,jp(n,this.toBBox),jp(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)}_splitRoot(e,t){this.data=Yp([e,t]),this.data.height=e.height+1,this.data.leaf=!1,jp(this.data,this.toBBox)}_chooseSplitIndex(e,t,n){let i,r=1/0,o=1/0;for(let s=t;s<=n-t;s++){let a=of(e,0,s,this.toBBox),c=of(e,s,n,this.toBBox),l=I_t(a,c),u=u4(a)+u4(c);l<r?(r=l,i=s,o=u<o?u:o):l===r&&u<o&&(o=u,i=s)}return i||n-t}_chooseSplitAxis(e,t,n){let i=e.leaf?this.compareMinX:S_t,r=e.leaf?this.compareMinY:P_t;this._allDistMargin(e,t,n,i)<this._allDistMargin(e,t,n,r)&&e.children.sort(i)}_allDistMargin(e,t,n,i){e.children.sort(i);let r=this.toBBox,o=of(e,0,t,r),s=of(e,n-t,n,r),a=$g(o)+$g(s);for(let c=t;c<n-t;c++){let l=e.children[c];sf(o,e.leaf?r(l):l),a+=$g(o)}for(let c=n-t-1;c>=t;c--){let l=e.children[c];sf(s,e.leaf?r(l):l),a+=$g(s)}return a}_adjustParentBBoxes(e,t,n){for(let i=n;i>=0;i--)sf(t[i],e)}_condense(e){for(let t,n=e.length-1;n>=0;n--)e[n].children.length===0?n>0?(t=e[n-1].children,t.splice(t.indexOf(e[n]),1)):this.clear():jp(e[n],this.toBBox)}};function w_t(e,t,n){if(!n)return t.indexOf(e);for(let i=0;i<t.length;i++)if(n(e,t[i]))return i;return-1}function jp(e,t){of(e,0,e.children.length,t,e)}function of(e,t,n,i,r){r||(r=Yp(null)),r.minX=1/0,r.minY=1/0,r.maxX=-1/0,r.maxY=-1/0;for(let o=t;o<n;o++){let s=e.children[o];sf(r,e.leaf?i(s):s)}return r}function sf(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function S_t(e,t){return e.minX-t.minX}function P_t(e,t){return e.minY-t.minY}function u4(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function $g(e){return e.maxX-e.minX+(e.maxY-e.minY)}function T_t(e,t){return(Math.max(t.maxX,e.maxX)-Math.min(t.minX,e.minX))*(Math.max(t.maxY,e.maxY)-Math.min(t.minY,e.minY))}function I_t(e,t){let n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),r=Math.min(e.maxX,t.maxX),o=Math.min(e.maxY,t.maxY);return Math.max(0,r-n)*Math.max(0,o-i)}function p4(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function Bg(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function Yp(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function oD(e,t,n,i,r){let o=[t,n];for(;o.length;){if((n=o.pop())-(t=o.pop())<=i)continue;let s=t+Math.ceil((n-t)/i/2)*i;$D(e,s,t,n,r),o.push(t,s,s,n)}}var sD=class{constructor(e=9){T(this,"tree");this.tree=new v_t(e)}insert(e,t,n,i,r){this.tree.insert({minX:t,minY:n,maxX:i,maxY:r,data:e})}bulkLoad(e){let t=e.map(({item:n,minX:i,minY:r,maxX:o,maxY:s})=>({minX:i,minY:r,maxX:o,maxY:s,data:n}));this.tree.load(t)}search(e,t,n,i){return this.tree.search({minX:e,minY:t,maxX:n,maxY:i}).map(r=>r.data)}clear(){this.tree.clear()}},M_t=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(e,t){let n=this.length++;for(;n>0;){let i=n-1>>1,r=this.values[i];if(t>=r)break;this.ids[n]=this.ids[i],this.values[n]=r,n=i}this.ids[n]=e,this.values[n]=t}pop(){if(this.length===0)return;let e=this.ids,t=this.values,n=e[0],i=--this.length;if(i>0){let r=e[i],o=t[i],s=0,a=i>>1;for(;s<a;){let c=1+(s<<1),l=c+1,u=c+(+(l<i)&+(t[l]<t[c]));if(t[u]>=o)break;e[s]=e[u],t[s]=t[u],s=u}e[s]=r,t[s]=o}return n}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){this.ids.length=this.values.length=this.length}},aD=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],cD=class BD{static from(t,n=0){if(n%8!=0)throw new Error("byteOffset must be 8-byte aligned.");if(!t||t.byteLength===void 0||t.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[i,r]=new Uint8Array(t,n+0,2);if(i!==251)throw new Error("Data does not appear to be in a Flatbush format.");let o=r>>4;if(o!==3)throw new Error(`Got v${o} data when expected v3.`);let s=aD[15&r];if(!s)throw new Error("Unrecognized array type.");let[a]=new Uint16Array(t,n+2,1),[c]=new Uint32Array(t,n+4,1);return new BD(c,a,s,void 0,t,n)}constructor(t,n=16,i=Float64Array,r=ArrayBuffer,o,s=0){if(t===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(t)||t<=0)throw new Error(`Unexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+n,2),65535),this.byteOffset=s;let a=t,c=a;this._levelBounds=[4*a];do a=Math.ceil(a/this.nodeSize),c+=a,this._levelBounds.push(4*c);while(a!==1);this.ArrayType=i,this.IndexArrayType=c<16384?Uint16Array:Uint32Array;let l=aD.indexOf(i),u=4*c*i.BYTES_PER_ELEMENT;if(l<0)throw new Error(`Unexpected typed array class: ${i}.`);if(o)this.data=o,this._boxes=new i(o,s+8,4*c),this._indices=new this.IndexArrayType(o,s+8+u,c),this._pos=4*c,this.minX=this._boxes[this._pos-4],this.minY=this._boxes[this._pos-3],this.maxX=this._boxes[this._pos-2],this.maxY=this._boxes[this._pos-1];else{let h=this.data=new r(8+u+c*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new i(h,8,4*c),this._indices=new this.IndexArrayType(h,8+u,c),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(h,0,2).set([251,48+l]),new Uint16Array(h,2,1)[0]=n,new Uint32Array(h,4,1)[0]=t}this._queue=new M_t}add(t,n,i=t,r=n){let o=this._pos>>2,s=this._boxes;return this._indices[o]=o,s[this._pos++]=t,s[this._pos++]=n,s[this._pos++]=i,s[this._pos++]=r,t<this.minX&&(this.minX=t),n<this.minY&&(this.minY=n),i>this.maxX&&(this.maxX=i),r>this.maxY&&(this.maxY=r),o}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let t=this._boxes;if(this.numItems<=this.nodeSize)return t[this._pos++]=this.minX,t[this._pos++]=this.minY,t[this._pos++]=this.maxX,void(t[this._pos++]=this.maxY);let n=this.maxX-this.minX||1,i=this.maxY-this.minY||1,r=new Uint32Array(this.numItems);for(let o=0,s=0;o<this.numItems;o++){let a=t[s++],c=t[s++],l=t[s++],u=t[s++],h=Math.floor(65535*((a+l)/2-this.minX)/n),d=Math.floor(65535*((c+u)/2-this.minY)/i);r[o]=C_t(h,d)}P4(r,t,this._indices,0,this.numItems-1,this.nodeSize);for(let o=0,s=0;o<this._levelBounds.length-1;o++){let a=this._levelBounds[o];for(;s<a;){let c=s,l=t[s++],u=t[s++],h=t[s++],d=t[s++];for(let _=1;_<this.nodeSize&&s<a;_++)l=Math.min(l,t[s++]),u=Math.min(u,t[s++]),h=Math.max(h,t[s++]),d=Math.max(d,t[s++]);this._indices[this._pos>>2]=c,t[this._pos++]=l,t[this._pos++]=u,t[this._pos++]=h,t[this._pos++]=d}}}search(t,n,i,r,o){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=[],c=[];for(;s!==void 0;){let l=Math.min(s+4*this.nodeSize,lD(s,this._levelBounds));for(let u=s;u<l;u+=4){let h=this._boxes[u];if(i<h)continue;let d=this._boxes[u+1];if(r<d)continue;let _=this._boxes[u+2];if(t>_)continue;let y=this._boxes[u+3];if(n>y)continue;let g=0|this._indices[u>>2];s>=4*this.numItems?a.push(g):(o===void 0||o(g,h,d,_,y))&&c.push(g)}s=a.pop()}return c}neighbors(t,n,i=1/0,r=1/0,o){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=this._queue,c=[],l=r*r;t:for(;s!==void 0;){let u=Math.min(s+4*this.nodeSize,lD(s,this._levelBounds));for(let h=s;h<u;h+=4){let d=0|this._indices[h>>2],_=this._boxes[h],y=this._boxes[h+1],g=this._boxes[h+2],x=this._boxes[h+3],w=t<_?_-t:t>g?t-g:0,S=n<y?y-n:n>x?n-x:0,E=w*w+S*S;E>l||(s>=4*this.numItems?a.push(d<<1,E):(o===void 0||o(d))&&a.push(1+(d<<1),E))}for(;a.length&&1&a.peek();)if(a.peekValue()>l||(c.push(a.pop()>>1),c.length===i))break t;s=a.length?a.pop()>>1:void 0}return a.clear(),c}};function lD(e,t){let n=0,i=t.length-1;for(;n<i;){let r=n+i>>1;t[r]>e?i=r:n=r+1}return t[n]}function P4(e,t,n,i,r,o){if(Math.floor(i/o)>=Math.floor(r/o))return;let s=e[i],a=e[i+r>>1],c=e[r],l=c,u=Math.max(s,a);c>u?l=u:u===s?l=Math.max(a,c):u===a&&(l=Math.max(s,c));let h=i-1,d=r+1;for(;;){do h++;while(e[h]<l);do d--;while(e[d]>l);if(h>=d)break;E_t(e,t,n,h,d)}P4(e,t,n,i,d,o),P4(e,t,n,d+1,r,o)}function E_t(e,t,n,i,r){let o=e[i];e[i]=e[r],e[r]=o;let s=4*i,a=4*r,c=t[s],l=t[s+1],u=t[s+2],h=t[s+3];t[s]=t[a],t[s+1]=t[a+1],t[s+2]=t[a+2],t[s+3]=t[a+3],t[a]=c,t[a+1]=l,t[a+2]=u,t[a+3]=h;let d=n[i];n[i]=n[r],n[r]=d}function C_t(e,t){let n=e^t,i=65535^n,r=65535^(e|t),o=e&(65535^t),s=n|i>>1,a=n>>1^n,c=r>>1^i&o>>1^r,l=n&r>>1^o>>1^o;n=s,i=a,r=c,o=l,s=n&n>>2^i&i>>2,a=n&i>>2^i&(n^i)>>2,c^=n&r>>2^i&o>>2,l^=i&r>>2^(n^i)&o>>2,n=s,i=a,r=c,o=l,s=n&n>>4^i&i>>4,a=n&i>>4^i&(n^i)>>4,c^=n&r>>4^i&o>>4,l^=i&r>>4^(n^i)&o>>4,n=s,i=a,r=c,o=l,c^=n&r>>8^i&o>>8,l^=i&r>>8^(n^i)&o>>8,n=c^c>>1,i=l^l>>1;let u=e^t,h=i|65535^(u|n);return u=16711935&(u|u<<8),u=252645135&(u|u<<4),u=858993459&(u|u<<2),u=1431655765&(u|u<<1),h=16711935&(h|h<<8),h=252645135&(h|h<<4),h=858993459&(h|h<<2),h=1431655765&(h|h<<1),(h<<1|u)>>>0}var k_t=class{constructor(e){T(this,"index");T(this,"items",[]);T(this,"currentIndex",0);T(this,"capacity");this.capacity=Math.max(1,e),this.index=new cD(this.capacity)}insert(e,t,n,i,r){if(this.currentIndex>=this.index.numItems)throw new Error("Exceeded initial capacity");this.items[this.currentIndex]=e,this.index.add(t,n,i,r),this.currentIndex++}finish(){this.index.finish()}search(e,t,n,i){return this.index.search(e,t,n,i).map(r=>this.items[r]||null).filter(Boolean)}clear(){this.items=[],this.currentIndex=0,this.index=new cD(this.capacity)}},jD=class{constructor(e="native",t=[]){T(this,"idx");T(this,"storage",[]);e==="flatbush"?t.length===0?(this.idx=new sD,e="rbush"):this.idx=new k_t(t.length):this.idx=e==="rbush"?new sD:new class{constructor(){T(this,"shi",new N_t(t))}insert(n){}search(n,i,r,o){let s=(n+r)/2,a=(i+o)/2,c=r-n,l=o-i;return this.shi.getNodesInArea(s,a,c,l)}clear(){}},t.forEach(n=>this.insert(n)),e==="flatbush"&&t.length>0&&this.idx.finish?.()}insert(e){this.storage.push(e),this.idx.insert(e,e.center.x-e.width/2,e.center.y-e.height/2,e.center.x+e.width/2,e.center.y+e.height/2)}search(e){return this.idx.search(e.minX,e.minY,e.maxX,e.maxY)}searchArea(e,t,n,i){return this.search({minX:e-n/2,minY:t-i/2,maxX:e+n/2,maxY:t+i/2})}},N_t=class{constructor(e){T(this,"buckets");T(this,"CELL_SIZE",.4);this.obstacles=e,this.buckets=new Map;for(let t=0;t<e.length;t++){let n=e[t],i=n.center.x-n.width/2,r=n.center.y-n.height/2,o=n.center.x+n.width/2,s=n.center.y+n.height/2;for(let a=i;a<=o;a+=this.CELL_SIZE)for(let c=r;c<=s;c+=this.CELL_SIZE){let l=this.getBucketKey(a,c),u=this.buckets.get(l);u?u.push([n,t]):this.buckets.set(l,[[n,t]])}}}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getNodesInArea(e,t,n,i){let r=[],o=new Set,s=t-i/2,a=e+n/2,c=t+i/2;for(let l=e-n/2;l<=a;l+=this.CELL_SIZE)for(let u=s;u<=c;u+=this.CELL_SIZE){let h=this.getBucketKey(l,u),d=this.buckets.get(h)||[];for(let _ of d)o.has(_[1])||(o.add(_[1]),r.push(_[0]))}return r}},A_t=class{constructor(e){T(this,"buckets");T(this,"CELL_SIZE",5);this.targets=e,this.buckets=new Map;for(let t=0;t<e.length;t++){let n=e[t],i=Math.floor(n.bounds.minX/this.CELL_SIZE)*this.CELL_SIZE,r=Math.floor(n.bounds.minY/this.CELL_SIZE)*this.CELL_SIZE,o=n.bounds.maxX,s=n.bounds.maxY;for(let a=i;a<=o;a+=this.CELL_SIZE)for(let c=r;c<=s;c+=this.CELL_SIZE){let l=this.getBucketKey(a,c),u=this.buckets.get(l);u?u.push([n,t]):this.buckets.set(l,[[n,t]])}}}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getTargetsInArea(e,t,n,i){let r=[],o=new Set,s=Math.floor((e-n/2)/this.CELL_SIZE)*this.CELL_SIZE,a=Math.floor((t-i/2)/this.CELL_SIZE)*this.CELL_SIZE,c=e+n/2,l=t+i/2;for(let u=s;u<=c;u+=this.CELL_SIZE)for(let h=a;h<=l;h+=this.CELL_SIZE){let d=this.getBucketKey(u,h),_=this.buckets.get(d)||[];for(let y of _)o.has(y[1])||(o.add(y[1]),r.push(y[0]))}return r}},R_t=class extends dn{constructor(t,n={}){super();T(this,"unfinishedNodes");T(this,"finishedNodes");T(this,"nodeToXYOverlappingObstaclesMap");T(this,"layerCount");T(this,"outlinePolygon");T(this,"MAX_DEPTH",4);T(this,"targets");T(this,"targetTree");T(this,"obstacleTree");T(this,"_nextNodeCounter",0);this.srj=t,this.opts=n,this.MAX_DEPTH=n?.capacityDepth??this.MAX_DEPTH,this.MAX_ITERATIONS=1e5,this.layerCount=t.layerCount??2,this.outlinePolygon=t.outline&&t.outline.length>=3?t.outline:void 0;for(let s of t.obstacles)if(!s.zLayers){let a=[];for(let c of s.layers)a.push(Ll(c,t.layerCount));s.zLayers=a}let i={x:(t.bounds.minX+t.bounds.maxX)/2,y:(t.bounds.minY+t.bounds.maxY)/2},r={width:t.bounds.maxX-t.bounds.minX,height:t.bounds.maxY-t.bounds.minY},o=Math.max(r.width,r.height);this.unfinishedNodes=[{capacityMeshNodeId:this.getNextNodeId(),center:i,width:o,height:o,layer:"top",availableZ:Array.from({length:this.layerCount},(s,a)=>a),_depth:0,_containsTarget:!0,_containsObstacle:!0,_completelyInsideObstacle:!1}],this.finishedNodes=[],this.nodeToXYOverlappingObstaclesMap=new Map,this.obstacleTree=new jD("flatbush",this.srj.obstacles),this.targets=this.computeTargets(),this.targetTree=new A_t(this.targets)}computeTargets(){let t=[];for(let n of this.srj.connections)for(let i of n.pointsToConnect){let r=this.obstacleTree.searchArea(i.x,i.y,.01,.01).filter(a=>a.zLayers.some(c=>c===Ll(i.layer,this.layerCount))),o={minX:i.x-.005,minY:i.y-.005,maxX:i.x+.005,maxY:i.y+.005};r.length>0&&(o={minX:Math.min(...r.map(a=>a.center.x-a.width/2)),minY:Math.min(...r.map(a=>a.center.y-a.height/2)),maxX:Math.max(...r.map(a=>a.center.x+a.width/2)),maxY:Math.max(...r.map(a=>a.center.y+a.height/2))});let s={...i,connectionName:n.name,availableZ:[Ll(i.layer,this.layerCount)],bounds:o};t.push(s)}return t}getNodeBounds(t){let n=t.width/2,i=t.height/2;return{minX:t.center.x-n,maxX:t.center.x+n,minY:t.center.y-i,maxY:t.center.y+i}}getNodeRect(t){return{center:{x:t.center.x,y:t.center.y},width:t.width,height:t.height}}getNextNodeId(){return"cn"+this._nextNodeCounter++}getCapacityFromDepth(t){return(this.MAX_DEPTH-t+1)**2}getTargetIfNodeContainsTarget(t){let n=t.width>4*this.targetTree.CELL_SIZE?this.targets:this.targetTree.getTargetsInArea(t.center.x,t.center.y,t.width,t.height);for(let i of n)if(i.bounds.minX<=t.center.x+t.width/2&&i.bounds.maxX>=t.center.x-t.width/2&&i.bounds.minY<=t.center.y+t.height/2&&i.bounds.maxY>=t.center.y-t.height/2&&i.availableZ.some(r=>t.availableZ.includes(r)))return i;return null}getXYOverlappingObstacles(t){let n=this.nodeToXYOverlappingObstaclesMap.get(t.capacityMeshNodeId);if(n)return n;let i=[],r=this.getNodeBounds(t),o=r.minX,s=r.maxX,a=r.minY,c=r.maxY,l=t._parent?this.getXYOverlappingObstacles(t._parent):this.srj.obstacles;for(let u of l){let h=u.center.x-u.width/2,d=u.center.x+u.width/2,_=u.center.y-u.height/2,y=u.center.y+u.height/2;(s>=h&&o<=d&&c>=_&&a<=y||o>=h&&s<=d&&a>=_&&c<=y||h>=o&&d<=s&&_>=a&&y<=c)&&i.push(u)}return this.nodeToXYOverlappingObstaclesMap.set(t.capacityMeshNodeId,i),i}getXYZOverlappingObstacles(t){let n=this.getXYOverlappingObstacles(t),i=[];for(let r of n)t.availableZ.some(o=>r.zLayers.includes(o))&&i.push(r);return i}doesNodeOverlapObstacle(t){if(this.getXYZOverlappingObstacles(t).length>0)return!0;let n=this.getNodeBounds(t);if(this.outlinePolygon){let i=this.getNodeRect(t);if(!RD(i,this.outlinePolygon))return!0}return n.minX<this.srj.bounds.minX||n.maxX>this.srj.bounds.maxX||n.minY<this.srj.bounds.minY||n.maxY>this.srj.bounds.maxY}isNodeCompletelyInsideObstacle(t){let n=this.getXYZOverlappingObstacles(t),i=this.getNodeBounds(t);if(this.outlinePolygon){let r=this.getNodeRect(t);if(!g4(r,this.outlinePolygon))return!0}for(let r of n){let o=r.center.x-r.width/2,s=r.center.x+r.width/2,a=r.center.y-r.height/2,c=r.center.y+r.height/2;if(i.minX>=o&&i.maxX<=s&&i.minY>=a&&i.maxY<=c)return!0}return!1}getChildNodes(t){if(t._depth===this.MAX_DEPTH)return[];let n=[],i={width:t.width/2,height:t.height/2},r=[{x:t.center.x-i.width/2,y:t.center.y-i.height/2},{x:t.center.x+i.width/2,y:t.center.y-i.height/2},{x:t.center.x-i.width/2,y:t.center.y+i.height/2},{x:t.center.x+i.width/2,y:t.center.y+i.height/2}];for(let o of r){let s={capacityMeshNodeId:this.getNextNodeId(),center:o,width:i.width,height:i.height,layer:t.layer,availableZ:t.availableZ,_depth:(t._depth??0)+1,_parent:t};s._containsObstacle=this.doesNodeOverlapObstacle(s);let a=this.getTargetIfNodeContainsTarget(s);a&&(s._targetConnectionName=a.connectionName,s.availableZ=a.availableZ,s._containsTarget=!0),s._containsObstacle&&(s._completelyInsideObstacle=this.isNodeCompletelyInsideObstacle(s)),s._completelyInsideObstacle&&!s._containsTarget||n.push(s)}return n}shouldNodeBeXYSubdivided(t){return!(t._depth>=this.MAX_DEPTH)&&(!!t._containsTarget||!(!t._containsObstacle||t._completelyInsideObstacle))}_step(){let t=this.unfinishedNodes.pop();if(!t)return void(this.solved=!0);let n=this.getChildNodes(t),i=[],r=[];for(let o of n){let s=this.shouldNodeBeXYSubdivided(o);s?r.push(o):s||o._containsObstacle?!s&&o._containsTarget&&i.push(o):i.push(o)}this.unfinishedNodes.push(...r),this.finishedNodes.push(...i)}visualize(){let t={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Capacity Mesh Visualization"};if(this.outlinePolygon&&this.outlinePolygon.length>=2){let i=this.outlinePolygon.map(r=>({x:r.x,y:r.y}));i.push({...i[0]}),t.lines.push({points:i,strokeColor:"rgba(0, 136, 255, 0.95)",label:"outline"});for(let r of this.outlinePolygon)t.points.push({x:r.x,y:r.y,color:"rgba(0, 136, 255, 0.95)"})}for(let i of this.srj.obstacles)t.rects.push({center:i.center,width:i.width,height:i.height,fill:i.zLayers?.length===1&&i.zLayers?.includes(1)?"rgba(0,0,255,0.3)":"rgba(255,0,0,0.3)",stroke:"red",label:["obstacle",`z: ${i.zLayers.join(",")}`].join(`
161
+ `),{solved:!1,connectionName:e.name}}createObstacleList({dominantLayer:e,connection:t,obstaclesFromTraces:n}){return new qL(this.allObstacles.filter(i=>!i.connectedTo.includes(t.name)).filter(i=>i.layers.includes(e)).concat(n??[]))}postprocessConnectionSolveResult(e,t){return t}solve(){let e=[],t=[];this.debugTraceCount=0;for(let n of this.input.connections){let i=n.pointsToConnect[0].layer??"top";this.debugTraceCount+=1,this.obstacles=this.createObstacleList({dominantLayer:i,connection:n,obstaclesFromTraces:t});let r=this.solveConnection(n);r=this.postprocessConnectionSolveResult(n,r),e.push(r),El.enabled&&this.drawDebugTraceObstacles(t),r.solved&&t.push(...UL(r.route.map(o=>({x:o.x,y:o.y,layer:o.layer??i})),n.name))}return e}solveAndMapToTraces(){return this.solve().flatMap(t=>t.solved?[{type:"pcb_trace",pcb_trace_id:`pcb_trace_for_${t.connectionName}`,route:_mt(t.route.map(n=>({route_type:"wire",x:n.x,y:n.y,width:this.input.minTraceWidth,layer:n.layer})))}]:[])}getDebugGroup(){let e=`t${this.debugTraceCount}_iter[${this.iterations-1}]`;return this.iterations<30||this.iterations<100&&this.iterations%10===0||this.iterations<1e3&&this.iterations%100===0||!this.debugSolutions?e:null}drawDebugTraceObstacles(e){let{debugTraceCount:t,debugSolutions:n}=this;for(let i in n)i.startsWith(`t${t}_`)&&n[i].push(...e.map((r,o)=>({type:"pcb_smtpad",pcb_component_id:"",layer:r.layers[0],width:r.width,shape:"rect",x:r.center.x,y:r.center.y,pcb_smtpad_id:`trace_obstacle_${o}`,height:r.height})))}drawDebugSolution({current:e,newNeighbors:t}){let n=this.getDebugGroup();if(!n)return;let{openSet:i,debugTraceCount:r,debugSolutions:o}=this;o[n]??(o[n]=[]);let s=o[n];s.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${e.x}_${e.y}`,font:"tscircuit2024",font_size:.25,text:"X"+(e.l!==void 0?e.l:""),pcb_component_id:"",layer:"top",anchor_position:{x:e.x,y:e.y},anchor_alignment:"center"});for(let a=0;a<i.length;a++){let c=i[a];s.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${c.x}_${c.y}`,layer:"top",route:[[0,.05],[.05,0],[0,-.05],[-.05,0],[0,.05]].map(([l,u])=>({x:c.x+l,y:c.y+u})),stroke_width:.01}),s.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${c.x}_${c.y}`,font:"tscircuit2024",font_size:.03,text:a.toString(),pcb_component_id:"",layer:"top",anchor_position:{x:c.x,y:c.y},anchor_alignment:"center"})}if(e.parent){let a=[],c=e;for(;c;)a.unshift(c),c=c.parent;s.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${e.x}_${e.y}`,layer:"top",route:a,stroke_width:.01})}}},gmt=(0,KL.default)("autorouting-dataset:infinite-grid-ijump-astar:get-distance-to-overcome-obstacle");function q5({node:e,travelDir:t,wallDir:n,obstacle:i,obstacles:r,obstaclesInRow:o=0,OBSTACLE_MARGIN:s=.15,SHOULD_DETECT_CONJOINED_OBSTACLES:a=!1,MAX_CONJOINED_OBSTACLES:c=20}){let l;if(t.dx===0?t.dy>0?l=i.center.y+i.height/2-e.y:l=e.y-(i.center.y-i.height/2):t.dx>0?l=i.center.x+i.width/2-e.x:l=e.x-(i.center.x-i.width/2),l+=s,a&&o<c){let u=r.getObstacleAt(e.x+t.dx*l+n.dx*(n.wallDistance+.001),e.y+t.dy*l+n.dy*(n.wallDistance+.001));if(u===i)return l;if(u&&u.type==="rect"){let h=t.dy===0,d=h?i.height:i.width;if((h?u.height:u.width)>d)return gmt("next obstacle on path is bigger, not trying to overcome it"),l;let y=q5({node:{x:e.x+t.dx*l,y:e.y+t.dy*l},travelDir:t,wallDir:n,obstacle:u,obstacles:r,obstaclesInRow:o+1,SHOULD_DETECT_CONJOINED_OBSTACLES:a,MAX_CONJOINED_OBSTACLES:c,OBSTACLE_MARGIN:s});l+=y}}return l}var bmt=class extends ZL{constructor(){super(...arguments);T(this,"MAX_ITERATIONS",200)}getNeighbors(t){let n=this.obstacles,i=this.goalPoint,r;t.parent?r=$L(t.parent,t):r=$L(t,i);let o=[{dx:0,dy:1},{dx:1,dy:0},{dx:0,dy:-1},{dx:-1,dy:0}].filter(a=>a.dx===r.dx*-1&&a.dy===r.dy*-1?!1:!(a.dx===r.dx&&a.dy===r.dy&&t.parent?.obstacleHit)).map(a=>n.getOrthoDirectionCollisionInfo(t,a,{margin:this.OBSTACLE_MARGIN})).filter(a=>a.wallDistance>=this.OBSTACLE_MARGIN),s=[];for(let a of o){let c=null;t?.obstacleHit&&(c=q5({node:t,travelDir:a,wallDir:{...r,wallDistance:this.OBSTACLE_MARGIN},obstacle:t.obstacleHit,obstacles:n,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let l=VL(t,i,a),u=(a.dx===0||Math.sign(i.x-t.x)===a.dx)&&(a.dy===0||Math.sign(i.y-t.y)===a.dy);l<a.wallDistance&&l>0&&u?s.push({...a,travelDistance:l}):c!==null&&c<a.wallDistance?s.push({...a,travelDistance:c}):a.wallDistance!==1/0&&s.push({...a,travelDistance:a.wallDistance-this.OBSTACLE_MARGIN})}return s.filter(a=>!n.isObstacleAt(t.x+a.dx*a.travelDistance,t.y+a.dy*a.travelDistance)).map(a=>({x:t.x+a.dx*a.travelDistance,y:t.y+a.dy*a.travelDistance,obstacleHit:a.obstacle}))}};function xmt(e,t=4){let{center:n,width:i,height:r,rotation:o}=e,s=[],a=o*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(o%360+360)%360;if(r<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*c,x=-y*l,w=d*1.1,S=Math.abs(r*c)+Math.abs(d*l);s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}else{let d=r/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*l,x=y*c,w=Math.abs(i*c)+Math.abs(d*l),S=d*1.1;s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}return s}var gg=["top","inner1","inner2","bottom"],JL=(e,t)=>{let n=r=>t?r.concat(r.map(o=>t?.getNetConnectedToId(o)).filter(Boolean)):r,i=[];for(let r of e)if(r.type==="pcb_smtpad"){if(r.shape==="circle")i.push({type:"oval",layers:[r.layer],center:{x:r.x,y:r.y},width:r.radius*2,height:r.radius*2,connectedTo:n([r.pcb_smtpad_id])});else if(r.shape==="rect")i.push({type:"rect",layers:[r.layer],center:{x:r.x,y:r.y},width:r.width,height:r.height,connectedTo:n([r.pcb_smtpad_id])});else if(r.shape==="rotated_rect"){let o={center:{x:r.x,y:r.y},width:r.width,height:r.height,rotation:r.ccw_rotation},s=xmt(o);for(let a of s)i.push({type:"rect",layers:[r.layer],center:a.center,width:a.width,height:a.height,connectedTo:n([r.pcb_smtpad_id])})}}else if(r.type==="pcb_keepout")r.shape==="circle"?i.push({type:"oval",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.radius*2,height:r.radius*2,connectedTo:[]}):r.shape==="rect"&&i.push({type:"rect",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.type==="pcb_hole")r.hole_shape==="oval"?i.push({type:"oval",center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="square"?i.push({type:"rect",layers:gg,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]}):(r.hole_shape==="round"||r.hole_shape==="circle")&&i.push({type:"rect",layers:gg,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]});else if(r.type==="pcb_plated_hole")r.shape==="circle"?i.push({type:"oval",layers:gg,center:{x:r.x,y:r.y},width:r.outer_diameter,height:r.outer_diameter,connectedTo:n([r.pcb_plated_hole_id])}):(r.shape==="oval"||r.shape==="pill")&&i.push({type:"oval",layers:gg,center:{x:r.x,y:r.y},width:r.outer_width,height:r.outer_height,connectedTo:n([r.pcb_plated_hole_id])});else if(r.type==="pcb_trace"){let o=UL(r.route.map(s=>({x:s.x,y:s.y,layer:"layer"in s?s.layer:s.from_layer})),r.source_trace_id);i.push(...o)}else r.type==="pcb_via"&&i.push({type:"rect",layers:r.layers,center:{x:r.x,y:r.y},connectedTo:[],width:r.outer_diameter,height:r.outer_diameter});return i};function YL(e){let{pcbConnMap:t,goalElementId:n}=e;if(!n.startsWith("pcb_port_"))throw new Error(`Currently alternative goal boxes must have a goal id with prefix "pcb_port_" (got ${n})`);let i=t.getAllTracesConnectedToPort(n);return JL(i).map(r=>({...r,connectedTo:[n]}))}var QL=e=>{let{connection:t,pcbConnMap:n}=e;if(t.pointsToConnect.length!==2)throw new Error(`Connection must have exactly 2 points for alternative goal boxes (got ${t.pointsToConnect.length})`);let[i,r]=t.pointsToConnect;if(!i.pcb_port_id||!r.pcb_port_id)throw new Error(`Connection points must have pcb_port_id for alternative goal box calculation (got ${i.pcb_port_id} and ${r.pcb_port_id})`);let o=YL({goalElementId:i.pcb_port_id,pcbConnMap:n}).concat([{center:i,width:.01,height:.01,connectedTo:[i.pcb_port_id],layers:[i.layer],type:"rect"}]),s=YL({goalElementId:r.pcb_port_id,pcbConnMap:n}).concat([{center:r,width:.01,height:.01,connectedTo:[r.pcb_port_id],layers:[r.layer],type:"rect"}]);if(o.length<=1&&s.length<=1)return{...t,startPoint:i,endPoint:r,goalBoxes:[]};let a=Ud(o,s),c,l,u;return o.length>=s.length?(c={...r,...a.pointB},l={...i,...a.pointA},u=o):(c={...i,...a.pointA},l={...r,...a.pointB},u=s),{startPoint:c,endPoint:l,goalBoxes:u,name:t.name,pointsToConnect:[c,l]}},vmt=(e,t={})=>{let n={minTraceWidth:.1};n.layerCount=t.layerCount??1,n.obstacles=JL(e,t.connMap),n.connections=[];for(let r of e)if(r.type==="source_trace"){let o={name:r.source_trace_id,pointsToConnect:r.connected_source_port_ids.map(s=>{let a=Io(e).pcb_port.getWhere({source_port_id:s});if(!a)throw new Error(`Could not find pcb_port for source_port_id "${s}"`);return{x:a.x,y:a.y,layer:a.layers?.[0]??"top",pcb_port_id:a.pcb_port_id}})};if(t.optimizeWithGoalBoxes){let s=new yg(e);o=QL({connection:o,pcbConnMap:s})}n.connections.push(o),wmt(n.obstacles,o.pointsToConnect,o.name)}let i={minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0};for(let r of n.obstacles)i.minX=Math.min(i.minX,r.center.x-r.width/2),i.maxX=Math.max(i.maxX,r.center.x+r.width/2),i.minY=Math.min(i.minY,r.center.y-r.height/2),i.maxY=Math.max(i.maxY,r.center.y+r.height/2);for(let r of n.connections)for(let o of r.pointsToConnect)i.minX=Math.min(i.minX,o.x),i.maxX=Math.max(i.maxX,o.x),i.minY=Math.min(i.minY,o.y),i.maxY=Math.max(i.maxY,o.y);return n.bounds=i,n},wmt=(e,t,n)=>{for(let i of t)for(let r of e)Smt(i,r)&&r.connectedTo.push(n)};function Smt(e,t){let n=t.width/2,i=t.height/2;if(t.type==="rect")return e.x>=t.center.x-n&&e.x<=t.center.x+n&&e.y>=t.center.y-i&&e.y<=t.center.y+i;if(t.type==="oval"){let r=(e.x-t.center.x)/n,o=(e.y-t.center.y)/i;return r*r+o*o<=1}return!1}function XL(e,t){let n=t.x>e.x?1:t.x<e.x?-1:0,i=t.y>e.y?1:t.y<e.y?-1:0,r=t.l>e.l?1:t.l<e.l?-1:0;return{dx:n,dy:i,dl:r}}var W5={1:["top"],2:["top","bottom"],4:["top","inner1","inner2","bottom"]},Pmt=e=>W5[e];function tz(e,t){let i=W5[e].indexOf(t);if(i===-1)throw new Error(`Invalid layer for getLayerIndex (for layerCount === ${e}): "${t}"`);return i}function Tmt(e,t){let i=W5[e][t];if(!i)throw new Error(`Invalid index for indexToLayer (for layerCount === ${e}): "${t}"`);return i}var Imt=class extends qL{constructor(t,n){super([]);T(this,"obstacles");T(this,"GRID_STEP",.1);T(this,"layerCount");this.layerCount=t;let i=Pmt(t);this.obstacles=n.flatMap(r=>r.layers.filter(o=>i.includes(o)).map(o=>({...r,left:r.center.x-r.width/2,right:r.center.x+r.width/2,top:r.center.y+r.height/2,bottom:r.center.y-r.height/2,l:tz(t,o)})))}getObstacleAt(t,n,i,r){r??(r=this.GRID_STEP);for(let o of this.obstacles){if(o.l!==i)continue;let s=o.width/2+r,a=o.height/2+r;if(t>=o.center.x-s&&t<=o.center.x+s&&n>=o.center.y-a&&n<=o.center.y+a)return o}return null}isObstacleAt(t,n,i,r){return this.getObstacleAt(t,n,i,r)!==null}getDirectionDistancesToNearestObstacle3d(t,n,i){let{GRID_STEP:r}=this,o={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let s of this.obstacles)if(s.l===i&&s.type==="rect"){let a=s.center.x-s.width/2-r,c=s.center.x+s.width/2+r,l=s.center.y+s.height/2+r,u=s.center.y-s.height/2-r;n>=u&&n<=l&&t>a&&(o.left=Math.min(o.left,t-c)),n>=u&&n<=l&&t<c&&(o.right=Math.min(o.right,a-t)),t>=a&&t<=c&&n<l&&(o.top=Math.min(o.top,u-n)),t>=a&&t<=c&&n>u&&(o.bottom=Math.min(o.bottom,n-l))}return o}getOrthoDirectionCollisionInfo(t,n,{margin:i=0}={}){let{x:r,y:o,l:s}=t,{dx:a,dy:c,dl:l}=n,u=1/0,h=null;if(l!==0){let d=s+l;return this.isObstacleAt(r,o,d,i)?(u=1,h=this.getObstacleAt(r,o,d,i)):u=1,{dx:a,dy:c,dl:l,wallDistance:u,obstacle:h}}else{for(let d of this.obstacles){if(d.l!==s)continue;let _=d.left-i,y=d.right+i,g=d.top+i,x=d.bottom-i,w=null;a===1&&c===0?o>x&&o<g&&r<d.left&&(w=d.left-r):a===-1&&c===0?o>x&&o<g&&r>d.right&&(w=r-d.right):a===0&&c===1?r>_&&r<y&&o<d.bottom&&(w=d.bottom-o):a===0&&c===-1&&r>_&&r<y&&o>d.top&&(w=o-d.top),w!==null&&w<u&&(u=w,h=d)}return{dx:a,dy:c,dl:0,wallDistance:u,obstacle:h}}}getObstaclesOverlappingRegion(t){let n=[];for(let i of this.obstacles){if(i.l!==t.l)continue;let{left:r,right:o,top:s,bottom:a}=i;r<=t.maxX&&o>=t.minX&&s>=t.minY&&a<=t.maxY&&n.push(i)}return n}},bg=class extends ZL{constructor(t){super(t);T(this,"MAX_ITERATIONS",500);T(this,"VIA_COST",4);T(this,"VIA_DIAMETER",.5);T(this,"allowLayerChange",!0);T(this,"layerCount");T(this,"obstacles");T(this,"optimizeWithGoalBoxes");T(this,"connMap");T(this,"pcbConnMap");T(this,"GOAL_RUSH_FACTOR",1.1);T(this,"defaultGoalViaMargin",.5);T(this,"marginsWithCosts");this.layerCount=t.input.layerCount??2,this.MAX_ITERATIONS=t.MAX_ITERATIONS??this.MAX_ITERATIONS,this.VIA_COST=t.VIA_COST??this.VIA_COST,this.connMap=t.connMap,this.pcbConnMap=t.pcbConnMap??new yg,this.optimizeWithGoalBoxes=t.optimizeWithGoalBoxes??!1,this.obstacles=null,this.marginsWithCosts=t.marginsWithCosts??[{margin:1,enterCost:0,travelCostFactor:1},{margin:this.OBSTACLE_MARGIN,enterCost:10,travelCostFactor:2}]}get largestMargin(){return this.marginsWithCosts[0].margin}preprocessConnectionBeforeSolving(t){return this.optimizeWithGoalBoxes?QL({connection:t,pcbConnMap:this.pcbConnMap}):t}postprocessConnectionSolveResult(t,n){if(!n.solved)return n;if(this.optimizeWithGoalBoxes){let i=n.route.map(r=>({x:r.x,y:r.y,route_type:"wire",layer:r.layer,width:this.input.minTraceWidth}));i[0].start_pcb_port_id=t.pointsToConnect[0].pcb_port_id,i[i.length-1].end_pcb_port_id=t.pointsToConnect[1].pcb_port_id,this.pcbConnMap.addTrace({type:"pcb_trace",pcb_trace_id:`postprocess_trace_${DL(8)}`,route:i})}return n}createObstacleList({dominantLayer:t,connection:n,obstaclesFromTraces:i}){let r=this.connMap?this.connMap.getNetConnectedToId(n.name):n.name;if(!r)throw new Error(`The connection.name "${n.name}" wasn't present in the full connectivity map`);return new Imt(this.layerCount,this.allObstacles.filter(o=>!o.connectedTo.includes(r)).concat(i??[]))}computeG(t,n){let i=t.g+Cl(t,n)*(t.travelMarginCostFactor??1)+(n.enterMarginCost??0);return(n.l??t.l!==-1??-1)&&(i+=this.VIA_COST),i}computeH(t){let n=Math.abs(t.x-this.goalPoint.x),i=Math.abs(t.y-this.goalPoint.y),r=Math.abs(t.l-this.goalPoint.l);return(n+i)**this.GOAL_RUSH_FACTOR+r*this.VIA_COST}getStartNode(t){return{...super.getStartNode(t),l:this.layerToIndex(t.pointsToConnect[0].layer)}}layerToIndex(t){return tz(this.layerCount,t)}indexToLayer(t){return Tmt(this.layerCount,t)}getNodeName(t){return`${HL(t,this.GRID_STEP)}-${t.l??0}`}hasSpaceForVia(t,n){return t.every(i=>this.obstacles.getObstaclesOverlappingRegion({minX:n.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:n.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:n.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:n.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:i}).length===0)}getNeighborsSurroundingGoal(t){let n=this.obstacles,i=this.goalPoint,r=[],o=[{dx:1,dy:0,dl:0},{dx:-1,dy:0,dl:0},{dx:0,dy:1,dl:0},{dx:0,dy:-1,dl:0}],s=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin;for(let a of o){let c={x:t.x+a.dx*s,y:t.y+a.dy*s,l:t.l+a.dl,obstacleHit:null};this.hasSpaceForVia([t.l,i.l],c)&&r.push(c)}return r}getNeighbors(t){let n=this.obstacles,i=this.goalPoint,r=Cl(t,i);if(r<=this.OBSTACLE_MARGIN)return this.getNeighborsSurroundingGoal(t);let o;t.parent?o=XL(t.parent,t):o=XL(t,i);let s=[{dx:0,dy:1,dl:0},{dx:1,dy:0,dl:0},{dx:0,dy:-1,dl:0},{dx:-1,dy:0,dl:0}],a=r>this.VIA_DIAMETER+this.OBSTACLE_MARGIN,c=Cl(t,this.startNode)>this.VIA_DIAMETER+this.OBSTACLE_MARGIN;this.allowLayerChange&&a&&c&&(t.l<this.layerCount-1&&s.push({dx:0,dy:0,dl:1}),t.l>0&&s.push({dx:0,dy:0,dl:-1}));let l=s.filter(h=>h.dx===o.dx*-1&&h.dy===o.dy*-1&&h.dl===o.dl*-1?!1:!(h.dx===o.dx&&h.dy===o.dy&&h.dl===o.dl&&t.parent?.obstacleHit)).map(h=>n.getOrthoDirectionCollisionInfo(t,h,{margin:this.OBSTACLE_MARGIN})).filter(h=>!(h.wallDistance<this.OBSTACLE_MARGIN)),u=[];for(let h of l){let d=h.dx===0&&h.dy===0&&h.dl===1,_=h.dx===0&&h.dy===0&&h.dl===-1;if((d||_)&&![t.l,t.l+h.dl].every(S=>n.getObstaclesOverlappingRegion({minX:t.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:t.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:t.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:t.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:S}).length===0))continue;if(d){t.l<this.layerCount-1&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}if(_){t.l>0&&u.push({...h,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}let y=null;t?.obstacleHit&&(y=q5({node:t,travelDir:h,wallDir:{...o,wallDistance:this.OBSTACLE_MARGIN},obstacle:t.obstacleHit,obstacles:n,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let g=VL(t,i,h),x=(h.dx===0||Math.sign(i.x-t.x)===h.dx)&&(h.dy===0||Math.sign(i.y-t.y)===h.dy);if(g<h.wallDistance&&g>0&&x){let w=t.l===i.l,S=0;!w&&Math.abs(g-r)<this.GRID_STEP&&(S=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin),u.push({...h,travelDistance:g-S,enterMarginCost:0,travelMarginCostFactor:1})}else if(y!==null&&y<h.wallDistance){for(let{margin:w,enterCost:S,travelCostFactor:E}of this.marginsWithCosts)y-this.OBSTACLE_MARGIN+w*2<h.wallDistance&&u.push({...h,travelDistance:y-this.OBSTACLE_MARGIN+w,enterMarginCost:S,travelMarginCostFactor:E});if(h.wallDistance===1/0)u.push({...h,travelDistance:g,enterMarginCost:0,travelMarginCostFactor:1});else if(h.wallDistance>this.largestMargin)for(let{margin:w,enterCost:S,travelCostFactor:E}of this.marginsWithCosts)h.wallDistance>this.largestMargin+w&&u.push({...h,travelDistance:h.wallDistance-w,enterMarginCost:S,travelMarginCostFactor:E})}else if(h.wallDistance!==1/0)for(let{margin:w,enterCost:S,travelCostFactor:E}of this.marginsWithCosts)h.wallDistance>w&&u.push({...h,travelDistance:h.wallDistance-w,enterMarginCost:S,travelMarginCostFactor:E})}return u.map(h=>({x:t.x+h.dx*h.travelDistance,y:t.y+h.dy*h.travelDistance,l:t.l+h.dl,obstacleHit:h.obstacle,travelMarginCostFactor:h.travelMarginCostFactor,enterMarginCost:h.enterMarginCost}))}};function ez(e){let t=vmt(e),n=new bmt({input:t});return{solution:n.solveAndMapToTraces(),debugSolutions:n.debugSolutions,debugMessage:n.debugMessage}}W();W();vt();W();W();vt();vt();W();W();W();W();W();vt();W();W();W();vt();W();W();vt();W();W();W();W();W();W();W();W();W();W();vt();W();vt();W();vt();W();vt();vt();W();vt();W();W();vt();W();W();vt();W();vt();W();vt();W();vt();W();vt();W();vt();W();vt();W();W();W();W();W();W();W();W();vt();W();vt();W();W();vt();W();vt();W();W();W();vt();W();vt();vt();W();W();W();vt();W();W();W();W();vt();W();vt();W();vt();W();vt();W();vt();W();vt();W();vt();W();W();vt();W();vt();W();vt();W();W();vt();vt();W();W();vt();vt();W();W();vt();W();vt();W();vt();W();vt();W();vt();W();vt();W();W();vt();W();vt();W();vt();W();vt();W();vt();W();vt();W();vt();vt();W();vt();W();vt();W();W();vt();W();vt();W();vt();W();vt();W();vt();W();W();vt();var It=e=>{};It("extra props b");It("missing props b");It(!0);It("property a has mismatched types");var Mmt=p.enum(["up","down","left","right"]),cFt=p.enum(["top-to-bottom","left-to-right","bottom-to-top","right-to-left"]);It(!0);It(!0);var Go=p.array(p.string().or(p.number()));It(!0);var wg=p.object({x:V,y:V,z:V}),Emt=p.object({x:p.union([p.number(),p.string()]),y:p.union([p.number(),p.string()]),z:p.union([p.number(),p.string()])}),Ga=p.object({rotationOffset:p.number().or(Emt).optional(),positionOffset:wg.optional(),size:wg.optional(),modelUnitToMmScale:V.optional()});It(!0);var Cmt=Ga.extend({stlUrl:p.string()}),kmt=Ga.extend({objUrl:p.string(),mtlUrl:p.string().optional()}),Nmt=Ga.extend({gltfUrl:p.string()}),Amt=Ga.extend({glbUrl:p.string()}),Rmt=Ga.extend({stepUrl:p.string()}),Omt=Ga.extend({wrlUrl:p.string()}),Lmt=Ga.extend({jscad:p.record(p.any())}),lz=p.union([p.null(),p.string(),p.custom(e=>e&&typeof e=="object"&&"type"in e&&"props"in e),Cmt,kmt,Nmt,Amt,Rmt,Omt,Lmt]);It(!0);var zmt=p.custom(e=>!0),Fmt=p.custom(e=>!0),$e=p.object({pcbX:V.optional(),pcbY:V.optional(),pcbRotation:ze.optional(),pcbPositionAnchor:p.string().optional(),layer:ye.optional(),pcbMarginTop:V.optional(),pcbMarginRight:V.optional(),pcbMarginBottom:V.optional(),pcbMarginLeft:V.optional(),pcbMarginX:V.optional(),pcbMarginY:V.optional(),pcbRelative:p.boolean().optional(),relative:p.boolean().optional()});It(!0);var Sg=p.object({pcbX:V.optional(),pcbY:V.optional(),pcbRotation:ze.optional(),pcbPositionAnchor:p.string().optional(),pcbMarginTop:V.optional(),pcbMarginRight:V.optional(),pcbMarginBottom:V.optional(),pcbMarginLeft:V.optional(),pcbMarginX:V.optional(),pcbMarginY:V.optional(),schMarginTop:V.optional(),schMarginRight:V.optional(),schMarginBottom:V.optional(),schMarginLeft:V.optional(),schMarginX:V.optional(),schMarginY:V.optional(),schX:V.optional(),schY:V.optional(),schRotation:ze.optional(),layer:ye.optional(),footprint:zmt.optional(),symbol:Fmt.optional(),relative:p.boolean().optional(),schRelative:p.boolean().optional(),pcbRelative:p.boolean().optional()});It(!0);var Dmt=p.object({supplierPartNumbers:p.record(pp,p.array(p.string())).optional()});It(!0);var $mt=p.object({providesPower:p.boolean().optional(),requiresPower:p.boolean().optional(),providesGround:p.boolean().optional(),requiresGround:p.boolean().optional(),providesVoltage:p.union([p.string(),p.number()]).optional(),requiresVoltage:p.union([p.string(),p.number()]).optional(),doNotConnect:p.boolean().optional(),includeInBoardPinout:p.boolean().optional(),highlightColor:p.string().optional()});It(!0);var Fn=Sg.merge(Dmt).extend({key:p.any().optional(),name:p.string(),cadModel:lz.optional(),children:p.any().optional(),symbolName:p.string().optional(),doNotPlace:p.boolean().optional(),obstructsWithinBounds:p.boolean().optional().describe("Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath"),pinAttributes:p.record(p.string(),$mt).optional()});It(!0);var K5=["pin1","left","pin2","right"],Pg=["pin1","left","anode","pos","pin2","right","cathode","neg"],bFt=V.or(p.enum(["2x","3x","4x"])),Ua=p.enum(["vertical","horizontal","pos_top","pos_bottom","pos_left","pos_right","neg_top","neg_bottom","neg_left","neg_right"]).describe("horizontal means pins go 1->2 rightward and vertical means pins go 1->2 downward (generally, positive on top)");It(!0);var xg=p.object({pins:p.array(p.union([p.number(),p.string()])),direction:p.union([p.literal("top-to-bottom"),p.literal("left-to-right"),p.literal("bottom-to-top"),p.literal("right-to-left")])}),Wd=p.object({leftSize:p.number().optional().describe("@deprecated, use leftPinCount"),topSize:p.number().optional().describe("@deprecated, use topPinCount"),rightSize:p.number().optional().describe("@deprecated, use rightPinCount"),bottomSize:p.number().optional().describe("@deprecated, use bottomPinCount"),leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftSide:xg.optional(),rightSide:xg.optional(),topSide:xg.optional(),bottomSide:xg.optional()}),J5=Wd;It(!0);var Zd=p.record(p.object({marginLeft:V.optional(),marginRight:V.optional(),marginTop:V.optional(),marginBottom:V.optional(),leftMargin:V.optional(),rightMargin:V.optional(),topMargin:V.optional(),bottomMargin:V.optional()}));It(!0);var oo=p.string().regex(/^[A-Za-z0-9_]+$/),Kd=p.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),Bs=p.object({x:V,y:V}),Jd=p.object({edit_event_id:p.string(),in_progress:p.boolean().optional(),created_at:p.number()});It(!0);var Bmt=Jd.extend({pcb_edit_event_type:p.literal("edit_component_location").describe("deprecated"),edit_event_type:p.literal("edit_pcb_component_location"),pcb_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});It(!0);var jmt=Jd.extend({pcb_edit_event_type:p.literal("edit_trace_hint").describe("deprecated"),edit_event_type:p.literal("edit_pcb_trace_hint").optional(),pcb_port_id:p.string(),pcb_trace_hint_id:p.string().optional(),route:p.array(p.object({x:p.number(),y:p.number(),via:p.boolean().optional()}))});It(!0);var Ymt=Jd.extend({edit_event_type:p.literal("edit_schematic_component_location"),schematic_component_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});It(!0);var zFt=Jd.extend({edit_event_type:p.literal("edit_pcb_group_location"),pcb_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});It(!0);var DFt=Jd.extend({edit_event_type:p.literal("edit_schematic_group_location"),schematic_group_id:p.string(),original_center:p.object({x:p.number(),y:p.number()}),new_center:p.object({x:p.number(),y:p.number()})});It(!0);var BFt=p.union([Bmt,jmt,Ymt]);It(!0);var Xmt=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Zt});It(!0);var Vmt=p.object({pcb_port_selector:p.string(),offsets:p.array(Ni)});It(!0);var Hmt=p.object({selector:p.string(),relative_to:p.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Zt});It(!0);var Gmt=p.object({pcb_placements:p.array(Xmt).optional(),manual_trace_hints:p.array(Vmt).optional(),schematic_placements:p.array(Hmt).optional()});It(!0);var Qd=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),kl=e=>p.record(p.enum(e),Qd),qd=p.object({layoutMode:p.enum(["grid","flex","match-adapt","relative","none"]).optional(),position:p.enum(["absolute","relative"]).optional(),grid:p.boolean().optional(),gridCols:p.number().or(p.string()).optional(),gridRows:p.number().or(p.string()).optional(),gridTemplateRows:p.string().optional(),gridTemplateColumns:p.string().optional(),gridTemplate:p.string().optional(),gridGap:p.number().or(p.string()).optional(),gridRowGap:p.number().or(p.string()).optional(),gridColumnGap:p.number().or(p.string()).optional(),flex:p.boolean().or(p.string()).optional(),flexDirection:p.enum(["row","column"]).optional(),alignItems:p.enum(["start","center","end","stretch"]).optional(),justifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),flexRow:p.boolean().optional(),flexColumn:p.boolean().optional(),gap:p.number().or(p.string()).optional(),pack:p.boolean().optional().describe("Pack the contents of this group using a packing strategy"),packOrderStrategy:p.enum(["largest_to_smallest","first_to_last","highest_to_lowest_pin_count"]).optional(),packPlacementStrategy:p.enum(["shortest_connection_along_outline"]).optional(),padding:$.optional(),paddingLeft:$.optional(),paddingRight:$.optional(),paddingTop:$.optional(),paddingBottom:$.optional(),paddingX:$.optional(),paddingY:$.optional(),width:$.optional(),height:$.optional(),matchAdapt:p.boolean().optional(),matchAdaptTemplate:p.any().optional()});It(!0);var nz=p.object({strokeWidth:$.optional(),dashed:p.boolean().optional(),solid:p.boolean().optional()}),Umt=p.custom(e=>typeof e=="string"),qmt=p.object({serverUrl:p.string().optional(),inputFormat:p.enum(["simplified","circuit-json"]).optional(),serverMode:p.enum(["job","solve-endpoint"]).optional(),serverCacheEnabled:p.boolean().optional(),cache:p.custom(e=>!0).optional(),traceClearance:$.optional(),groupMode:p.enum(["sequential_trace","subcircuit","sequential-trace"]).optional(),algorithmFn:p.custom(e=>typeof e=="function"||e===void 0).optional(),preset:p.enum(["sequential_trace","subcircuit","auto","auto_local","auto_cloud","freerouting","sequential-trace","auto-local","auto-cloud"]).optional(),local:p.boolean().optional()}),Wmt=p.union([p.literal("sequential_trace"),p.literal("subcircuit"),p.literal("auto"),p.literal("auto_local"),p.literal("auto_cloud"),p.literal("freerouting"),p.literal("sequential-trace"),p.literal("auto-local"),p.literal("auto-cloud")]),Zmt=p.string(),uz=p.union([qmt,Wmt,Zmt]),pz=Sg.extend({name:p.string().optional(),children:p.any().optional(),schTitle:p.string().optional(),key:p.any().optional(),showAsSchematicBox:p.boolean().optional(),connections:p.record(p.string(),Qd.optional()).optional(),schPinArrangement:J5.optional(),schPinSpacing:$.optional(),schPinStyle:Zd.optional(),...qd.shape,grid:qd.shape.grid.describe("@deprecated use pcbGrid"),flex:qd.shape.flex.describe("@deprecated use pcbFlex"),pcbGrid:p.boolean().optional(),pcbGridCols:p.number().or(p.string()).optional(),pcbGridRows:p.number().or(p.string()).optional(),pcbGridTemplateRows:p.string().optional(),pcbGridTemplateColumns:p.string().optional(),pcbGridTemplate:p.string().optional(),pcbGridGap:p.number().or(p.string()).optional(),pcbGridRowGap:p.number().or(p.string()).optional(),pcbGridColumnGap:p.number().or(p.string()).optional(),pcbFlex:p.boolean().or(p.string()).optional(),pcbFlexGap:p.number().or(p.string()).optional(),pcbFlexDirection:p.enum(["row","column"]).optional(),pcbAlignItems:p.enum(["start","center","end","stretch"]).optional(),pcbJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),pcbFlexRow:p.boolean().optional(),pcbFlexColumn:p.boolean().optional(),pcbGap:p.number().or(p.string()).optional(),pcbPack:p.boolean().optional(),pcbPackGap:p.number().or(p.string()).optional(),schGrid:p.boolean().optional(),schGridCols:p.number().or(p.string()).optional(),schGridRows:p.number().or(p.string()).optional(),schGridTemplateRows:p.string().optional(),schGridTemplateColumns:p.string().optional(),schGridTemplate:p.string().optional(),schGridGap:p.number().or(p.string()).optional(),schGridRowGap:p.number().or(p.string()).optional(),schGridColumnGap:p.number().or(p.string()).optional(),schFlex:p.boolean().or(p.string()).optional(),schFlexGap:p.number().or(p.string()).optional(),schFlexDirection:p.enum(["row","column"]).optional(),schAlignItems:p.enum(["start","center","end","stretch"]).optional(),schJustifyContent:p.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),schFlexRow:p.boolean().optional(),schFlexColumn:p.boolean().optional(),schGap:p.number().or(p.string()).optional(),schPack:p.boolean().optional(),schMatchAdapt:p.boolean().optional(),pcbWidth:$.optional(),pcbHeight:$.optional(),schWidth:$.optional(),schHeight:$.optional(),pcbLayout:qd.optional(),schLayout:qd.optional(),cellBorder:nz.nullable().optional(),border:nz.nullable().optional(),schPadding:$.optional(),schPaddingLeft:$.optional(),schPaddingRight:$.optional(),schPaddingTop:$.optional(),schPaddingBottom:$.optional(),pcbPadding:$.optional(),pcbPaddingLeft:$.optional(),pcbPaddingRight:$.optional(),pcbPaddingTop:$.optional(),pcbPaddingBottom:$.optional(),pcbPositionAnchor:Umt.optional()}),hz=p.custom(e=>"findPart"in e),Q5=pz.extend({manualEdits:Gmt.optional(),schAutoLayoutEnabled:p.boolean().optional(),schTraceAutoLabelEnabled:p.boolean().optional(),schMaxTraceDistance:V.optional(),routingDisabled:p.boolean().optional(),defaultTraceWidth:$.optional(),minTraceWidth:$.optional(),partsEngine:hz.optional(),pcbRouteCache:p.custom(e=>!0).optional(),autorouter:uz.optional(),square:p.boolean().optional(),emptyArea:p.string().optional(),filledArea:p.string().optional(),width:V.optional(),height:V.optional(),outline:p.array(Bs).optional(),outlineOffsetX:V.optional(),outlineOffsetY:V.optional()}),Kmt=Q5.extend({subcircuit:p.literal(!0)}),dz=p.discriminatedUnion("subcircuit",[pz.extend({subcircuit:p.literal(!1).optional()}),Kmt]);It(!0);It(!0);It(!0);It(!0);var Ap=p.custom(e=>typeof e=="string"),t4=Q5.omit({connections:!0}).extend({material:p.enum(["fr4","fr1"]).default("fr4"),layers:p.union([p.literal(2),p.literal(4)]).default(2),borderRadius:V.optional(),thickness:V.optional(),boardAnchorPosition:Bs.optional(),boardAnchorAlignment:Kd.optional(),title:p.string().optional(),solderMaskColor:Ap.optional(),topSolderMaskColor:Ap.optional(),bottomSolderMaskColor:Ap.optional(),silkscreenColor:Ap.optional(),topSilkscreenColor:Ap.optional(),bottomSilkscreenColor:Ap.optional()});It(!0);var ZFt=Q5.extend({padding:V.optional(),paddingLeft:V.optional(),paddingRight:V.optional(),paddingTop:V.optional(),paddingBottom:V.optional()});It(!0);var Jmt=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),Qmt=p.custom().pipe(p.record(p.string(),Jmt)),t1t=p.record(oo,oo.or(p.array(oo).readonly()).or(p.array(oo)));It(!0);var e1t=p.object({manufacturerPartNumber:p.string().optional(),supplierPartNumber:p.record(pp,p.array(p.string())).optional()}),Rp=Fn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:t1t.optional(),showPinAliases:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),externallyConnectedPins:p.array(p.array(p.string())).optional(),schPinArrangement:Wd.optional(),schPortArrangement:Wd.optional(),pinCompatibleVariants:p.array(e1t).optional(),schPinStyle:Zd.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional(),noSchematicRepresentation:p.boolean().optional(),connections:Qmt.optional()});It(!0);var fz=Rp;It(!0);var e4=Fn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(oo),oo.or(p.array(oo))).optional(),schPinStyle:Zd.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional(),schDirection:p.enum(["left","right"]).optional(),schPinArrangement:J5.optional(),schPortArrangement:Wd.optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),pinCount:p.union([p.literal(2),p.literal(3)]).optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),connections:p.custom().pipe(p.record(p.string(),Qd)).optional()});It(!0);var mz=e4.extend({bridgedPins:p.array(p.array(p.string())).optional(),bridged:p.boolean().optional()});It(!0);var rDt=Fn.extend({manufacturerPartNumber:p.string().optional(),pinLabels:p.record(p.number().or(oo),oo.or(p.array(oo))).optional(),schPinStyle:Zd.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional(),schDirection:p.enum(["left","right"]).optional(),schPortArrangement:Wd.optional(),internallyConnectedPins:p.array(p.array(p.union([p.string(),p.number()]))).optional(),standard:p.enum(["usb_c","m2"]).optional()});It(!0);var _z=Fn.extend({currentRating:p.union([p.number(),p.string()]),voltageRating:p.union([p.number(),p.string()]).optional(),schShowRatings:p.boolean().optional(),schOrientation:Ua.optional(),connections:p.record(p.string(),p.union([p.string(),p.array(p.string()).readonly(),p.array(p.string())])).optional()}),vg=p.custom().transform(e=>{if(e!==void 0)return V.parse(e)}),yz=p.discriminatedUnion("shape",[$e.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circle"),holeDiameter:V,outerDiameter:V,portHints:Go.optional()}),$e.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("oval"),outerWidth:V,outerHeight:V,holeWidth:vg,holeHeight:vg,innerWidth:V.optional().describe("DEPRECATED use holeWidth"),innerHeight:V.optional().describe("DEPRECATED use holeHeight"),portHints:Go.optional()}),$e.omit({layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill"),rectPad:p.boolean().optional(),outerWidth:V,outerHeight:V,holeWidth:vg,holeHeight:vg,innerWidth:V.optional().describe("DEPRECATED use holeWidth"),innerHeight:V.optional().describe("DEPRECATED use holeHeight"),portHints:Go.optional(),holeOffsetX:V.optional(),holeOffsetY:V.optional()}),$e.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("circular_hole_with_rect_pad"),holeDiameter:V,rectPadWidth:V,rectPadHeight:V,rectBorderRadius:V.optional(),holeShape:p.literal("circle").optional(),padShape:p.literal("rect").optional(),portHints:Go.optional(),holeOffsetX:V.optional(),holeOffsetY:V.optional()}),$e.omit({pcbRotation:!0,layer:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),shape:p.literal("pill_hole_with_rect_pad"),holeShape:p.literal("pill"),padShape:p.literal("rect"),holeWidth:V,holeHeight:V,rectPadWidth:V,rectPadHeight:V,portHints:Go.optional(),holeOffsetX:V.optional(),holeOffsetY:V.optional()})]).refine(e=>("innerWidth"in e&&e.innerWidth!==void 0&&(e.holeWidth??(e.holeWidth=e.innerWidth)),"innerHeight"in e&&e.innerHeight!==void 0&&(e.holeHeight??(e.holeHeight=e.innerHeight)),e));It(!0);var n1t=["pin1","pin2","pos","neg"],gz=Fn.extend({resistance:Da,pullupFor:p.string().optional(),pullupTo:p.string().optional(),pulldownFor:p.string().optional(),pulldownTo:p.string().optional(),schOrientation:Ua.optional(),connections:kl(n1t).optional()}),bz=K5;It(!0);var xz=Fn.extend({maxResistance:Da,pinVariant:p.enum(["two_pin","three_pin"]).optional()});It(!0);var i1t=K5,vz=Fn.extend({frequency:fr,loadCapacitance:ks,manufacturerPartNumber:p.string().optional(),mpn:p.string().optional(),pinVariant:p.enum(["two_pin","four_pin"]).optional(),schOrientation:Ua.optional(),connections:kl(i1t).optional()});It(!0);var wz=Fn.extend({frequency:fr,loadCapacitance:ks,pinVariant:p.enum(["no_ground","ground_pin","two_ground_pins"]).optional()});It(!0);var gDt=t4.extend({leftPinCount:p.number().optional(),rightPinCount:p.number().optional(),topPinCount:p.number().optional(),bottomPinCount:p.number().optional(),leftPins:p.array(p.string()).optional(),rightPins:p.array(p.string()).optional(),topPins:p.array(p.string()).optional(),bottomPins:p.array(p.string()).optional(),pinPitch:V.optional(),innerHoles:p.boolean().optional()});It(!0);var r1t=["pin1","pin2","pos","neg","anode","cathode"],Sz=Fn.extend({capacitance:ks,maxVoltageRating:oi.optional(),schShowRatings:p.boolean().optional().default(!1),polarized:p.boolean().optional().default(!1),decouplingFor:p.string().optional(),decouplingTo:p.string().optional(),bypassFor:p.string().optional(),bypassTo:p.string().optional(),maxDecouplingTraceLength:p.number().optional(),schOrientation:Ua.optional(),connections:kl(r1t).optional()}),Pz=Pg;It(!0);var wDt=p.object({name:p.string(),connectsTo:p.string().or(p.array(p.string())).optional(),highlightColor:p.string().optional()});It(!0);var PDt=p.object({name:p.string().optional(),pcbOnly:p.boolean().optional(),schOnly:p.boolean().optional()});It(!0);var o1t=p.object({pcb:p.literal(!0).optional(),xDist:V,left:p.string(),right:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});It(!0);var s1t=p.object({pcb:p.literal(!0).optional(),yDist:V,top:p.string(),bottom:p.string(),edgeToEdge:p.literal(!0).optional(),centerToCenter:p.literal(!0).optional()});It(!0);var a1t=p.object({pcb:p.literal(!0).optional(),sameY:p.literal(!0).optional(),for:p.array(p.string())});It(!0);var c1t=p.object({pcb:p.literal(!0).optional(),sameX:p.literal(!0).optional(),for:p.array(p.string())});It(!0);var Tz=p.union([o1t,s1t,a1t,c1t]);It(!0);var l1t=$e.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:V,height:V});It(!0);var u1t=$e.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:V});It(!0);var p1t=$e.omit({layer:!0,pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Bs)});It(!0);var Iz=p.discriminatedUnion("shape",[l1t,u1t,p1t]),h1t=$e.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rect"),width:V,height:V,rectBorderRadius:V.optional(),portHints:Go.optional(),coveredWithSolderMask:p.boolean().optional()});It(!0);var d1t=$e.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("rotated_rect"),width:V,height:V,ccwRotation:p.number(),portHints:Go.optional(),coveredWithSolderMask:p.boolean().optional()});It(!0);var f1t=$e.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("circle"),radius:V,portHints:Go.optional(),coveredWithSolderMask:p.boolean().optional()});It(!0);var m1t=$e.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("pill"),width:V,height:V,radius:V,portHints:Go.optional(),coveredWithSolderMask:p.boolean().optional()});It(!0);var _1t=$e.omit({pcbRotation:!0}).extend({name:p.string().optional(),shape:p.literal("polygon"),points:p.array(Bs),portHints:Go.optional(),coveredWithSolderMask:p.boolean().optional()});It(!0);var Mz=p.discriminatedUnion("shape",[f1t,h1t,d1t,m1t,_1t]);It(!0);var y1t=$e.omit({pcbRotation:!0}).extend({shape:p.literal("rect"),width:V,height:V});It(!0);var g1t=$e.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:V});It(!0);var CDt=p.union([g1t,y1t]);It(!0);var b1t=$e.extend({name:p.string().optional(),shape:p.literal("circle").optional(),diameter:V.optional(),radius:V.optional()}).transform(e=>({...e,diameter:e.diameter??2*e.radius,radius:e.radius??e.diameter/2})),x1t=$e.extend({name:p.string().optional(),shape:p.literal("pill"),width:V,height:V}),Ez=p.union([b1t,x1t]);It(!0);var Z5=p.union([p.string(),p.custom(e=>!!e.getPortSelector)]),iz=p.object({key:p.string().optional(),thickness:V.optional(),schematicRouteHints:p.array(Bs).optional(),pcbRouteHints:p.array(Ni).optional(),pcbPathRelativeTo:p.string().optional(),pcbPath:p.array(Bs).optional(),schDisplayLabel:p.string().optional(),schStroke:p.string().optional(),highlightColor:p.string().optional(),maxLength:V.optional()}),Cz=p.union([iz.extend({path:p.array(Z5)}),iz.extend({from:Z5,to:Z5})]),kz=p.object({originalLayer:ye.default("top").optional()});It(!0);var Nz=p.object({originalFacingDirection:p.enum(["up","down","left","right"]).default("right").optional()});It(!0);var v1t=p.number().or(p.string().endsWith("mAh")).transform(e=>{if(typeof e=="string"){let t=e.replace("mAh",""),n=Number.parseFloat(t);if(Number.isNaN(n))throw new Error("Invalid capacity");return n}return e}).describe("Battery capacity in mAh"),Az=Fn.extend({capacity:v1t.optional(),voltage:oi.optional(),standard:p.enum(["AA","AAA","9V","CR2032","18650","C"]).optional(),schOrientation:Ua.optional()});It(!0);var w1t=p.enum(["vertical","horizontal"]).describe("vertical means pins go 1->2 downward and horizontal means pins go 1->2 rightward");It(!0);var Rz=Fn.extend({pinCount:p.number(),pitch:V.optional(),schFacingDirection:p.enum(["up","down","left","right"]).optional(),gender:p.enum(["male","female","unpopulated"]).optional().default("male"),showSilkscreenPinLabels:p.boolean().optional(),pcbPinLabels:p.record(p.string(),p.string()).optional(),doubleRow:p.boolean().optional(),rightAngle:p.boolean().optional(),pcbOrientation:w1t.optional(),holeDiameter:V.optional(),platedDiameter:V.optional(),pinLabels:p.record(p.string(),oo).or(p.array(oo)).optional(),connections:p.custom().pipe(p.record(p.string(),Qd)).optional(),facingDirection:p.enum(["left","right"]).optional(),schPinArrangement:J5.optional(),schPinStyle:Zd.optional(),schPinSpacing:V.optional(),schWidth:V.optional(),schHeight:V.optional()});It(!0);var XDt=p.object({net:p.string().optional(),connection:p.string().optional(),schX:V.optional(),schY:V.optional(),schRotation:ze.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});It(!0);var Oz=p.object({net:p.string().optional(),connection:p.string().optional(),connectsTo:p.string().or(p.array(p.string())).optional(),schX:V.optional(),schY:V.optional(),schRotation:ze.optional(),anchorSide:p.enum(["left","top","right","bottom"]).optional()});It(!0);var Lz=Rp.extend({});It(!0);It(!0);var zz=p.object({simulationType:p.literal("spice_transient_analysis").default("spice_transient_analysis"),duration:Rr.optional(),timePerStep:Rr.optional()});It(!0);var S1t=["pin1","pin2","pin3","emitter","collector","base","gate","source","drain"],Fz=Fn.extend({type:p.enum(["npn","pnp","bjt","jfet","mosfet","igbt"]),connections:kl(S1t).optional()});It(!0);var Dz=Fn.extend({channelType:p.enum(["n","p"]),mosfetMode:p.enum(["enhancement","depletion"])});It(!0);var P1t=K5,$z=Fn.extend({inductance:K1,maxCurrentRating:p.union([p.string(),p.number()]).optional(),schOrientation:Ua.optional(),connections:kl(P1t).optional()});It(!0);var T1t=p.enum(["anode","cathode","pin1","pin2","pos","neg"]),I1t=p.string().or(p.array(p.string()).readonly()).or(p.array(p.string())),M1t=p.record(T1t,I1t),E1t=p.enum(["standard","schottky","zener","avalanche","photo","tvs"]),Bz=Fn.extend({connections:M1t.optional(),variant:E1t.optional().default("standard"),standard:p.boolean().optional(),schottky:p.boolean().optional(),zener:p.boolean().optional(),avalanche:p.boolean().optional(),photo:p.boolean().optional(),tvs:p.boolean().optional(),schOrientation:Ua.optional()}).superRefine((e,t)=>{if([e.standard,e.schottky,e.zener,e.avalanche,e.photo,e.tvs].filter(Boolean).length>1)return t.addIssue({code:p.ZodIssueCode.custom,message:"Exactly one diode variant must be enabled",path:[]}),p.INVALID}).transform(e=>{let t={...e,standard:!1,schottky:!1,zener:!1,avalanche:!1,photo:!1,tvs:!1};if(e.standard)t.standard=!0;else if(e.schottky)t.schottky=!0;else if(e.zener)t.zener=!0;else if(e.photo)t.photo=!0;else if(e.tvs)t.tvs=!0;else switch(e.variant){case"standard":t.standard=!0;break;case"schottky":t.schottky=!0;break;case"zener":t.zener=!0;break;case"avalanche":t.avalanche=!0;break;case"photo":t.photo=!0;break;case"tvs":t.tvs=!0;break;default:t.standard=!0}return t}),jz=Pg;It(!0);var Yz=Fn.extend({color:p.string().optional(),wavelength:p.string().optional(),schDisplayValue:p.string().optional(),schOrientation:Ua.optional(),connections:kl(Pg).optional(),laser:p.boolean().optional()}),Xz=Pg,Vz=Fn.extend({type:p.enum(["spst","spdt","dpst","dpdt"]).optional(),isNormallyClosed:p.boolean().optional().default(!1),spst:p.boolean().optional(),spdt:p.boolean().optional(),dpst:p.boolean().optional(),dpdt:p.boolean().optional(),connections:p.custom().pipe(p.record(p.string(),Qd)).optional()}).transform(e=>{let t={...e};switch(t.dpdt?t.type="dpdt":t.spst?t.type="spst":t.spdt?t.type="spdt":t.dpst&&(t.type="dpst"),t.type){case"spdt":t.spdt=!0;break;case"spst":t.spst=!0;break;case"dpst":t.dpst=!0;break;case"dpdt":t.dpdt=!0;break}return t});It(!0);var Hz=$e.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:$.optional(),color:p.string().optional()});It(!0);var Gz=$e.omit({pcbRotation:!0}).extend({width:V,height:V,strokeWidth:V.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),Uz=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:p.array(Ni),strokeWidth:$.optional(),color:p.string().optional()}),rz=p.union([p.string(),Bs]),qz=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({from:rz,to:rz,text:p.string().optional(),offset:V.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:$.optional(),color:p.string().optional(),arrowSize:V.optional()});It(!0);var p$t=p.object({layer:p.string().optional(),thickness:V.optional(),route:p.array(Ni)}),Wz=Sg.extend({name:p.string().optional(),fromLayer:ye,toLayer:ye,holeDiameter:V,outerDiameter:V,connectsTo:p.string().or(p.array(p.string())).optional()});It(!0);var Zz=Fn.extend({footprintVariant:p.enum(["pad","through_hole"]).optional(),padShape:p.enum(["rect","circle"]).optional().default("circle"),padDiameter:V.optional(),holeDiameter:V.optional(),width:V.optional(),height:V.optional()}).refine(e=>e.footprintVariant!=="through_hole"||e.holeDiameter!==void 0,{message:"holeDiameter is required for through_hole testpoints"});It(!0);var Kz=$e.omit({pcbRotation:!0,layer:!0}).extend({connection:p.string()});It(!0);var Jz=p.union([$e.omit({pcbRotation:!0}).extend({shape:p.literal("circle"),radius:V}),$e.extend({shape:p.literal("rect"),width:V,height:V})]),v$t=$e.omit({pcbRotation:!0}).extend({width:V,height:V,strokeWidth:V.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),P$t=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({outline:p.array(Bs),strokeWidth:$.optional(),isClosed:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()}),Qz=p.object({name:p.string().optional(),layer:ye,connectsTo:p.string(),padMargin:V.optional(),traceMargin:V.optional()});It(!0);var tF=p.object({originalLayer:ye.default("top").optional(),children:p.any().optional()});It(!0);var C1t=p.object({pcbX:V.optional(),pcbY:V.optional(),pcbZ:V.optional()}),k1t=Ga.extend({modelUrl:p.string(),stepUrl:p.string().optional()}),N1t=k1t.merge(C1t);It(!0);var eF=p.union([p.null(),p.string(),N1t]),nF=Fn.extend({voltage:oi}),A1t=["pin1","pin2","pos","neg"],R1t=p.union([p.string(),p.number()]).transform(e=>typeof e=="string"?e.endsWith("%")?parseFloat(e.slice(0,-1))/100:parseFloat(e):e).pipe(p.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),R$t=Fn.extend({voltage:oi.optional(),frequency:fr.optional(),peakToPeakVoltage:oi.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:ze.optional(),dutyCycle:R1t.optional(),connections:kl(A1t).optional()});It(!0);var iF=Fn.omit({name:!0}).extend({name:p.string().optional(),connectsTo:p.string().or(p.array(p.string()))});It(!0);var rF=p.object({center:Zt,radius:V,startAngleDegrees:ze,endAngleDegrees:ze,direction:p.enum(["clockwise","counterclockwise"]).default("counterclockwise"),strokeWidth:V.optional(),color:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),oF=p.object({schX:V.optional(),schY:V.optional(),width:V.optional(),height:V.optional(),overlay:p.array(p.string()).optional(),padding:V.optional(),paddingLeft:V.optional(),paddingRight:V.optional(),paddingTop:V.optional(),paddingBottom:V.optional(),title:p.string().optional(),titleAlignment:Kd.default("top_left"),titleColor:p.string().optional(),titleFontSize:V.optional(),titleInside:p.boolean().default(!1),strokeStyle:p.enum(["solid","dashed"]).default("solid")}).refine(e=>e.width!==void 0&&e.height!==void 0||Array.isArray(e.overlay)&&e.overlay.length>0,{message:"Must provide either both `width` and `height`, or a non-empty `overlay` array."}).refine(e=>!(e.width!==void 0&&e.height!==void 0&&Array.isArray(e.overlay)&&e.overlay.length>0),{message:"Cannot provide both `width`/`height` and `overlay` at the same time."}),sF=p.object({center:Zt,radius:V,strokeWidth:V.optional(),color:p.string().optional(),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),aF=p.object({schX:V.optional(),schY:V.optional(),width:V,height:V,rotation:ze.default(0),strokeWidth:V.optional(),color:p.string().optional(),isFilled:p.boolean().optional().default(!1),fillColor:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),cF=p.object({x1:V,y1:V,x2:V,y2:V,strokeWidth:V.optional(),color:p.string().optional(),isDashed:p.boolean().optional().default(!1)}),O1t=p.enum(["center","left","right","top","bottom"]),lF=p.object({schX:V.optional(),schY:V.optional(),text:p.string(),fontSize:p.number().default(1),anchor:p.union([O1t.describe("legacy"),Kd]).default("center"),color:p.string().default("#000000"),schRotation:ze.default(0)}),Z$t=p.object({points:p.array(Zt),isFilled:p.boolean().optional().default(!1),fillColor:p.enum(["red","blue"]).optional()}),uF=p.object({schX:V.optional(),schY:V.optional(),children:p.any().optional(),cellPadding:V.optional(),borderWidth:V.optional(),anchor:Kd.optional(),fontSize:V.optional()});It(!0);var pF=p.object({children:p.any().optional(),height:V.optional()});It(!0);var hF=p.object({children:p.string().optional(),horizontalAlign:p.enum(["left","center","right"]).optional(),verticalAlign:p.enum(["top","middle","bottom"]).optional(),fontSize:V.optional(),rowSpan:p.number().optional(),colSpan:p.number().optional(),width:V.optional(),text:p.string().optional()});It(!0);var dF=$e.extend({text:p.string(),anchorAlignment:Kd.default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:$.optional(),isKnockout:p.boolean().optional(),knockoutPadding:$.optional(),knockoutPaddingLeft:$.optional(),knockoutPaddingRight:$.optional(),knockoutPaddingTop:$.optional(),knockoutPaddingBottom:$.optional(),layers:p.array(ye).optional()}),fF=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:p.array(Ni),strokeWidth:$.optional()}),mF=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({strokeWidth:V,x1:V,y1:V,x2:V,y2:V}),_F=$e.omit({pcbRotation:!0}).extend({filled:p.boolean().default(!0).optional(),stroke:p.enum(["dashed","solid","none"]).optional(),strokeWidth:V.optional(),width:V,height:V}),yF=$e.omit({pcbRotation:!0}).extend({isFilled:p.boolean().optional(),isOutline:p.boolean().optional(),strokeWidth:V.optional(),radius:V}),oz=p.object({x:V,y:V,via:p.boolean().optional(),toLayer:ye.optional()}),gF=p.object({for:p.string().optional().describe("Selector for the port you're targeting, not required if you're inside a trace"),order:p.number().optional(),offset:Ni.or(oz).optional(),offsets:p.array(Ni).or(p.array(oz)).optional(),traceWidth:p.number().optional()}),mBt=Sg.extend({name:p.string(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),direction:Mmt,connectsTo:p.string().or(p.array(p.string())).optional()}),gBt=$e.extend({text:p.string(),anchorAlignment:p.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:p.enum(["tscircuit2024"]).optional(),fontSize:$.optional(),color:p.string().optional()});It(!0);var bF=$e.omit({pcbRotation:!0}).extend({width:V,height:V,strokeWidth:V.optional(),isFilled:p.boolean().optional(),hasStroke:p.boolean().optional(),isStrokeDashed:p.boolean().optional(),color:p.string().optional()});It(!0);var xF=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:p.array(Ni),strokeWidth:$.optional(),color:p.string().optional()});It(!0);var vF=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({x1:V,y1:V,x2:V,y2:V,strokeWidth:V.optional(),color:p.string().optional(),isDashed:p.boolean().optional()});It(!0);var sz=p.union([p.string(),Bs]),wF=$e.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({from:sz,to:sz,text:p.string().optional(),offset:V.optional(),font:p.enum(["tscircuit2024"]).optional(),fontSize:$.optional(),color:p.string().optional(),arrowSize:V.optional()});It(!0);var SF=p.array(p.any()).describe("Circuit JSON"),PF=p.object({footprintCircuitJson:p.array(p.any()),cadModel:lz.optional()}),az=p.function().args(p.string()).returns(p.promise(PF)).describe("A function that takes a path and returns Circuit JSON"),L1t=p.object({loadFromUrl:p.function().args(p.string()).returns(p.promise(PF)).describe("A function that takes a footprint file URL and returns Circuit JSON")}),z1t=p.object({engineVersionString:p.string().optional(),simulationResultCircuitJson:SF}),F1t=p.object({simulate:p.function().args(p.string()).returns(p.promise(z1t)).describe("A function that takes a SPICE string and returns a simulation result")}),cz=p.object({run:p.function().args().returns(p.promise(p.unknown())).describe("Run the autorouter"),getOutputSimpleRouteJson:p.function().args().returns(p.promise(p.any())).describe("Get the resulting SimpleRouteJson")}),D1t=p.object({createAutorouter:p.function().args(p.any(),p.any().optional()).returns(p.union([cz,p.promise(cz)])).describe("Create an autorouter instance")}),$1t=p.object({partsEngine:hz.optional(),autorouter:uz.optional(),autorouterMap:p.record(p.string(),D1t).optional(),registryApiUrl:p.string().optional(),cloudAutorouterUrl:p.string().optional(),projectName:p.string().optional(),projectBaseUrl:p.string().optional(),version:p.string().optional(),url:p.string().optional(),printBoardInformationToSilkscreen:p.boolean().optional(),localCacheEngine:p.any().optional(),pcbDisabled:p.boolean().optional(),schematicDisabled:p.boolean().optional(),partsEngineDisabled:p.boolean().optional(),spiceEngineMap:p.record(p.string(),F1t).optional(),footprintLibraryMap:p.record(p.string(),p.union([az,p.record(p.string(),p.union([SF,az]))])).optional(),footprintFileParserMap:p.record(p.string(),L1t).optional(),simSwitchFrequency:fr.optional(),simCloseAt:Rr.optional(),simOpenAt:Rr.optional(),simStartClosed:p.boolean().optional(),simStartOpen:p.boolean().optional()});It(!0);var B1t=$1t,CBt=B1t.pick({projectName:!0,projectBaseUrl:!0,version:!0,url:!0,printBoardInformationToSilkscreen:!0});It(!0);W();vt();Ls();W();var ea=Yt(vo(),1);Ls();W();function qa(){return new n4}var n4=class e{constructor(){T(this,"index",{});T(this,"array",[])}size(){return this.array.length}empty(){return this.array.length===0}itemAt(t){return this.array[t]}contains(t){return this.index[t.id()]!==void 0}find(t){let n=this.index[t.id()];return n===void 0?void 0:this.array[n]}setDefault(t,n){let i=this.index[t.id()];if(i===void 0){let r=new Tg(t,n());return this.index[t.id()]=this.array.length,this.array.push(r),r}else return this.array[i]}insert(t,n){let i=new Tg(t,n),r=this.index[t.id()];return r===void 0?(this.index[t.id()]=this.array.length,this.array.push(i)):this.array[r]=i,i}erase(t){let n=this.index[t.id()];if(n===void 0)return;this.index[t.id()]=void 0;let i=this.array[n],r=this.array.pop();return i!==r&&(this.array[n]=r,this.index[r.first.id()]=n),i}copy(){let t=new e;for(let n=0;n<this.array.length;n++){let i=this.array[n].copy();t.array[n]=i,t.index[i.first.id()]=n}return t}},Tg=class e{constructor(t,n){T(this,"first");T(this,"second");this.first=t,this.second=n}copy(){return new e(this.first,this.second)}};var js=class{constructor(t=""){T(this,"_name");T(this,"_value",0);T(this,"_context",null);T(this,"_id",j1t++);this._name=t}id(){return this._id}name(){return this._name}setName(t){this._name=t}context(){return this._context}setContext(t){this._context=t}value(){return this._value}setValue(t){this._value=t}plus(t){return new En(this,t)}minus(t){return new En(this,typeof t=="number"?-t:[-1,t])}multiply(t){return new En([t,this])}divide(t){return new En([1/t,this])}toJSON(){return{name:this._name,value:this._value}}toString(){return this._context+"["+this._name+":"+this._value+"]"}},j1t=0;var En=class e{constructor(){T(this,"_terms");T(this,"_constant");let t=Y1t(arguments);this._terms=t.terms,this._constant=t.constant}terms(){return this._terms}constant(){return this._constant}value(){let t=this._constant;for(let n=0,i=this._terms.size();n<i;n++){let r=this._terms.itemAt(n);t+=r.first.value()*r.second}return t}plus(t){return new e(this,t)}minus(t){return new e(this,typeof t=="number"?-t:[-1,t])}multiply(t){return new e([t,this])}divide(t){return new e([1/t,this])}isConstant(){return this._terms.size()==0}toString(){let t=this._terms.array.map(function(n){return n.second+"*"+n.first.toString()}).join(" + ");return!this.isConstant()&&this._constant!==0&&(t+=" + "),t+=this._constant,t}};function Y1t(e){let t=0,n=()=>0,i=qa();for(let r=0,o=e.length;r<o;++r){let s=e[r];if(typeof s=="number")t+=s;else if(s instanceof js)i.setDefault(s,n).second+=1;else if(s instanceof En){t+=s.constant();let a=s.terms();for(let c=0,l=a.size();c<l;c++){let u=a.itemAt(c);i.setDefault(u.first,n).second+=u.second}}else if(s instanceof Array){if(s.length!==2)throw new Error("array must have length 2");let a=s[0],c=s[1];if(typeof a!="number")throw new Error("array item 0 must be a number");if(c instanceof js)i.setDefault(c,n).second+=a;else if(c instanceof En){t+=c.constant()*a;let l=c.terms();for(let u=0,h=l.size();u<h;u++){let d=l.itemAt(u);i.setDefault(d.first,n).second+=d.second*a}}else throw new Error("array item 1 must be a variable or expression")}else throw new Error("invalid Expression argument: "+s)}return{terms:i,constant:t}}var Eo=class Eo{static create(t,n,i,r=1){let o=0;return o+=Math.max(0,Math.min(1e3,t*r))*1e6,o+=Math.max(0,Math.min(1e3,n*r))*1e3,o+=Math.max(0,Math.min(1e3,i*r)),o}static clip(t){return Math.max(0,Math.min(Eo.required,t))}};T(Eo,"required",Eo.create(1e3,1e3,1e3)),T(Eo,"strong",Eo.create(1,0,0)),T(Eo,"medium",Eo.create(0,1,0)),T(Eo,"weak",Eo.create(0,0,1));var wn=Eo;var Yn;(function(e){e[e.Le=0]="Le",e[e.Ge=1]="Ge",e[e.Eq=2]="Eq"})(Yn||(Yn={}));var ai=class{constructor(t,n,i,r=wn.required){T(this,"_expression");T(this,"_operator");T(this,"_strength");T(this,"_id",X1t++);this._operator=n,this._strength=wn.clip(r),i===void 0&&t instanceof En?this._expression=t:this._expression=t.minus(i)}id(){return this._id}expression(){return this._expression}op(){return this._operator}strength(){return this._strength}toString(){return this._expression.toString()+" "+["<=",">=","="][this._operator]+" 0 ("+this._strength.toString()+")"}},X1t=0;var Op=class{constructor(){T(this,"maxIterations",1e3);T(this,"_cnMap",V1t());T(this,"_rowMap",H1t());T(this,"_varMap",G1t());T(this,"_editMap",U1t());T(this,"_infeasibleRows",[]);T(this,"_objective",new Eg);T(this,"_artificial",null);T(this,"_idTick",0)}createConstraint(t,n,i,r=wn.required){let o=new ai(t,n,i,r);return this.addConstraint(o),o}addConstraint(t){if(this._cnMap.find(t)!==void 0)throw new Error("duplicate constraint");let i=this._createRow(t),r=i.row,o=i.tag,s=this._chooseSubject(r,o);if(s.type()===He.Invalid&&r.allDummies())if(Ig(r.constant()))s=o.marker;else throw new Error("unsatisfiable constraint");if(s.type()===He.Invalid){if(!this._addWithArtificialVariable(r))throw new Error("unsatisfiable constraint")}else r.solveFor(s),this._substitute(s,r),this._rowMap.insert(s,r);this._cnMap.insert(t,o),this._optimize(this._objective)}removeConstraint(t){let n=this._cnMap.erase(t);if(n===void 0)throw new Error("unknown constraint");this._removeConstraintEffects(t,n.second);let i=n.second.marker,r=this._rowMap.erase(i);if(r===void 0){let o=this._getMarkerLeavingSymbol(i);if(o.type()===He.Invalid)throw new Error("failed to find leaving row");r=this._rowMap.erase(o),r.second.solveForEx(o,i),this._substitute(i,r.second)}this._optimize(this._objective)}hasConstraint(t){return this._cnMap.contains(t)}getConstraints(){return this._cnMap.array.map(({first:t})=>t)}addEditVariable(t,n){if(this._editMap.find(t)!==void 0)throw new Error("duplicate edit variable");if(n=wn.clip(n),n===wn.required)throw new Error("bad required strength");let r=new En(t),o=new ai(r,Yn.Eq,void 0,n);this.addConstraint(o);let a={tag:this._cnMap.find(o).second,constraint:o,constant:0};this._editMap.insert(t,a)}removeEditVariable(t){let n=this._editMap.erase(t);if(n===void 0)throw new Error("unknown edit variable");this.removeConstraint(n.second.constraint)}hasEditVariable(t){return this._editMap.contains(t)}suggestValue(t,n){let i=this._editMap.find(t);if(i===void 0)throw new Error("unknown edit variable");let r=this._rowMap,o=i.second,s=n-o.constant;o.constant=n;let a=o.tag.marker,c=r.find(a);if(c!==void 0){c.second.add(-s)<0&&this._infeasibleRows.push(a),this._dualOptimize();return}let l=o.tag.other;if(c=r.find(l),c!==void 0){c.second.add(s)<0&&this._infeasibleRows.push(l),this._dualOptimize();return}for(let u=0,h=r.size();u<h;++u){let d=r.itemAt(u),_=d.second,y=_.coefficientFor(a);y!==0&&_.add(s*y)<0&&d.first.type()!==He.External&&this._infeasibleRows.push(d.first)}this._dualOptimize()}updateVariables(){let t=this._varMap,n=this._rowMap;for(let i=0,r=t.size();i<r;++i){let o=t.itemAt(i),s=n.find(o.second);s!==void 0?o.first.setValue(s.second.constant()):o.first.setValue(0)}}_getVarSymbol(t){let n=()=>this._makeSymbol(He.External);return this._varMap.setDefault(t,n).second}_createRow(t){let n=t.expression(),i=new Eg(n.constant()),r=n.terms();for(let c=0,l=r.size();c<l;++c){let u=r.itemAt(c);if(!Ig(u.second)){let h=this._getVarSymbol(u.first),d=this._rowMap.find(h);d!==void 0?i.insertRow(d.second,u.second):i.insertSymbol(h,u.second)}}let o=this._objective,s=t.strength(),a={marker:Wa,other:Wa};switch(t.op()){case Yn.Le:case Yn.Ge:{let c=t.op()===Yn.Le?1:-1,l=this._makeSymbol(He.Slack);if(a.marker=l,i.insertSymbol(l,c),s<wn.required){let u=this._makeSymbol(He.Error);a.other=u,i.insertSymbol(u,-c),o.insertSymbol(u,s)}break}case Yn.Eq:{if(s<wn.required){let c=this._makeSymbol(He.Error),l=this._makeSymbol(He.Error);a.marker=c,a.other=l,i.insertSymbol(c,-1),i.insertSymbol(l,1),o.insertSymbol(c,s),o.insertSymbol(l,s)}else{let c=this._makeSymbol(He.Dummy);a.marker=c,i.insertSymbol(c)}break}}return i.constant()<0&&i.reverseSign(),{row:i,tag:a}}_chooseSubject(t,n){let i=t.cells();for(let o=0,s=i.size();o<s;++o){let a=i.itemAt(o);if(a.first.type()===He.External)return a.first}let r=n.marker.type();return(r===He.Slack||r===He.Error)&&t.coefficientFor(n.marker)<0?n.marker:(r=n.other.type(),(r===He.Slack||r===He.Error)&&t.coefficientFor(n.other)<0?n.other:Wa)}_addWithArtificialVariable(t){let n=this._makeSymbol(He.Slack);this._rowMap.insert(n,t.copy()),this._artificial=t.copy(),this._optimize(this._artificial);let i=Ig(this._artificial.constant());this._artificial=null;let r=this._rowMap.erase(n);if(r!==void 0){let s=r.second;if(s.isConstant())return i;let a=this._anyPivotableSymbol(s);if(a.type()===He.Invalid)return!1;s.solveForEx(n,a),this._substitute(a,s),this._rowMap.insert(a,s)}let o=this._rowMap;for(let s=0,a=o.size();s<a;++s)o.itemAt(s).second.removeSymbol(n);return this._objective.removeSymbol(n),i}_substitute(t,n){let i=this._rowMap;for(let r=0,o=i.size();r<o;++r){let s=i.itemAt(r);s.second.substitute(t,n),s.second.constant()<0&&s.first.type()!==He.External&&this._infeasibleRows.push(s.first)}this._objective.substitute(t,n),this._artificial&&this._artificial.substitute(t,n)}_optimize(t){let n=0;for(;n<this.maxIterations;){let i=this._getEnteringSymbol(t);if(i.type()===He.Invalid)return;let r=this._getLeavingSymbol(i);if(r.type()===He.Invalid)throw new Error("the objective is unbounded");let o=this._rowMap.erase(r).second;o.solveForEx(r,i),this._substitute(i,o),this._rowMap.insert(i,o),n++}throw new Error("solver iterations exceeded")}_dualOptimize(){let t=this._rowMap,n=this._infeasibleRows;for(;n.length!==0;){let i=n.pop(),r=t.find(i);if(r!==void 0&&r.second.constant()<0){let o=this._getDualEnteringSymbol(r.second);if(o.type()===He.Invalid)throw new Error("dual optimize failed");let s=r.second;t.erase(i),s.solveForEx(i,o),this._substitute(o,s),t.insert(o,s)}}}_getEnteringSymbol(t){let n=t.cells();for(let i=0,r=n.size();i<r;++i){let o=n.itemAt(i),s=o.first;if(o.second<0&&s.type()!==He.Dummy)return s}return Wa}_getDualEnteringSymbol(t){let n=Number.MAX_VALUE,i=Wa,r=t.cells();for(let o=0,s=r.size();o<s;++o){let a=r.itemAt(o),c=a.first,l=a.second;if(l>0&&c.type()!==He.Dummy){let h=this._objective.coefficientFor(c)/l;h<n&&(n=h,i=c)}}return i}_getLeavingSymbol(t){let n=Number.MAX_VALUE,i=Wa,r=this._rowMap;for(let o=0,s=r.size();o<s;++o){let a=r.itemAt(o),c=a.first;if(c.type()!==He.External){let l=a.second,u=l.coefficientFor(t);if(u<0){let h=-l.constant()/u;h<n&&(n=h,i=c)}}}return i}_getMarkerLeavingSymbol(t){let n=Number.MAX_VALUE,i=n,r=n,o=Wa,s=o,a=o,c=o,l=this._rowMap;for(let u=0,h=l.size();u<h;++u){let d=l.itemAt(u),_=d.second,y=_.coefficientFor(t);if(y===0)continue;let g=d.first;if(g.type()===He.External)c=g;else if(y<0){let x=-_.constant()/y;x<i&&(i=x,s=g)}else{let x=_.constant()/y;x<r&&(r=x,a=g)}}return s!==o?s:a!==o?a:c}_removeConstraintEffects(t,n){n.marker.type()===He.Error&&this._removeMarkerEffects(n.marker,t.strength()),n.other.type()===He.Error&&this._removeMarkerEffects(n.other,t.strength())}_removeMarkerEffects(t,n){let i=this._rowMap.find(t);i!==void 0?this._objective.insertRow(i.second,-n):this._objective.insertSymbol(t,-n)}_anyPivotableSymbol(t){let n=t.cells();for(let i=0,r=n.size();i<r;++i){let o=n.itemAt(i),s=o.first.type();if(s===He.Slack||s===He.Error)return o.first}return Wa}_makeSymbol(t){return new Mg(t,this._idTick++)}};function Ig(e){let t=1e-8;return e<0?-e<t:e<t}function V1t(){return qa()}function H1t(){return qa()}function G1t(){return qa()}function U1t(){return qa()}var He;(function(e){e[e.Invalid=0]="Invalid",e[e.External=1]="External",e[e.Slack=2]="Slack",e[e.Error=3]="Error",e[e.Dummy=4]="Dummy"})(He||(He={}));var Mg=class{constructor(t,n){T(this,"_id");T(this,"_type");this._id=n,this._type=t}id(){return this._id}type(){return this._type}},Wa=new Mg(He.Invalid,-1),Eg=class e{constructor(t=0){T(this,"_cellMap",qa());T(this,"_constant");this._constant=t}cells(){return this._cellMap}constant(){return this._constant}isConstant(){return this._cellMap.empty()}allDummies(){let t=this._cellMap;for(let n=0,i=t.size();n<i;++n)if(t.itemAt(n).first.type()!==He.Dummy)return!1;return!0}copy(){let t=new e(this._constant);return t._cellMap=this._cellMap.copy(),t}add(t){return this._constant+=t}insertSymbol(t,n=1){let i=this._cellMap.setDefault(t,()=>0);Ig(i.second+=n)&&this._cellMap.erase(t)}insertRow(t,n=1){this._constant+=t._constant*n;let i=t._cellMap;for(let r=0,o=i.size();r<o;++r){let s=i.itemAt(r);this.insertSymbol(s.first,s.second*n)}}removeSymbol(t){this._cellMap.erase(t)}reverseSign(){this._constant=-this._constant;let t=this._cellMap;for(let n=0,i=t.size();n<i;++n){let r=t.itemAt(n);r.second=-r.second}}solveFor(t){let n=this._cellMap,r=-1/n.erase(t).second;this._constant*=r;for(let o=0,s=n.size();o<s;++o)n.itemAt(o).second*=r}solveForEx(t,n){this.insertSymbol(t,-1),this.solveFor(n)}coefficientFor(t){let n=this._cellMap.find(t);return n!==void 0?n.second:0}substitute(t,n){let i=this._cellMap.erase(t);i!==void 0&&this.insertRow(n,i.second)}};var sV=Yt(Mn(),1);W();vt();yi();var i4={};Ju(i4,{boundsAreaOverlap:()=>LF,boundsDistance:()=>zF,clamp:()=>Rn,computeDistanceBetweenBoxes:()=>Mo,distSq:()=>NF,distance:()=>Oi,doBoundsOverlap:()=>Ka,doSegmentsIntersect:()=>Gi,doesLineIntersectLine:()=>Za,doesSegmentIntersectRect:()=>MF,findNearestPointsBetweenBoxSets:()=>Ud,getBoundingBox:()=>$s,getSegmentIntersection:()=>IF,getUnitVectorFromDirection:()=>Ng,getUnitVectorFromPointAToB:()=>kg,grid:()=>FF,midpoint:()=>kF,onSegment:()=>zp,orientation:()=>Lp,pointToBoundsDistance:()=>CF,pointToBoxDistance:()=>EF,pointToSegmentClosestPoint:()=>OF,pointToSegmentDistance:()=>ci,range:()=>AF,segmentToBoundsMinDistance:()=>tf,segmentToBoxMinDistance:()=>RF,segmentToCircleMinDistance:()=>Cg,segmentToSegmentMinDistance:()=>Fp});function Za([e,t],[n,i],{lineThickness:r=0}={}){return r===0?Gi(e,t,n,i):q1t(e,t,n,i)<=r}function Gi(e,t,n,i){let r=Lp(e,t,n),o=Lp(e,t,i),s=Lp(n,i,e),a=Lp(n,i,t);return!!(r!==o&&s!==a||r===0&&zp(e,n,t)||o===0&&zp(e,i,t)||s===0&&zp(n,e,i)||a===0&&zp(n,t,i))}function Lp(e,t,n){let i=(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y);return i===0?0:i>0?1:2}function zp(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function q1t(e,t,n,i){if(e.x===t.x&&e.y===t.y)return ci(e,n,i);if(n.x===i.x&&n.y===i.y)return ci(n,e,t);if(Gi(e,t,n,i))return 0;let r=[ci(e,n,i),ci(t,n,i),ci(n,e,t),ci(i,e,t)];return Math.min(...r)}function ci(e,t,n){let i=(n.x-t.x)**2+(n.y-t.y)**2;if(i===0)return Oi(e,t);let r=((e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y))/i;r=Math.max(0,Math.min(1,r));let o={x:t.x+r*(n.x-t.x),y:t.y+r*(n.y-t.y)};return Oi(e,o)}function Oi(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}function IF(e,t,n,i){let r=t.x-e.x,o=t.y-e.y,s=i.x-n.x,a=i.y-n.y,c=e.x-n.x,l=e.y-n.y,u=r*a-o*s;if(Math.abs(u)<1e-10)return null;let h=(l*s-c*a)/u,d=(r*l-o*c)/u,_=1e-9;if(h>=-_&&h<=1+_&&d>=-_&&d<=1+_){let y=e.x+h*r,g=e.y+h*o;return{x:y,y:g}}return null}function MF(e,t,n){let i=c=>c.x>=n.minX&&c.x<=n.maxX&&c.y>=n.minY&&c.y<=n.maxY;if(i(e)||i(t))return!0;let r={x:n.minX,y:n.minY},o={x:n.maxX,y:n.minY},s={x:n.minX,y:n.maxY},a={x:n.maxX,y:n.maxY};return Gi(e,t,r,o)||Gi(e,t,o,a)||Gi(e,t,a,s)||Gi(e,t,s,r)}function EF(e,t){let n=t.width/2,i=t.height/2,r=t.center.x-n,o=t.center.x+n,s=t.center.y-i,a=t.center.y+i;if(e.x>=r&&e.x<=o&&e.y>=s&&e.y<=a)return 0;let c=Rn(e.x,r,o),l=Rn(e.y,s,a);return Oi(e,{x:c,y:l})}function CF(e,t){if(e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)return 0;let n=Rn(e.x,t.minX,t.maxX),i=Rn(e.y,t.minY,t.maxY);return Oi(e,{x:n,y:i})}function kF(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function NF(e,t){let n=e.x-t.x,i=e.y-t.y;return n*n+i*i}function AF(e,t,n=1){if(n===0)throw new Error("step cannot be 0");let i,r;t===void 0?(i=0,r=e):(i=e,r=t);let o=[];if(n>0)for(let s=i;s<r;s+=n)o.push(s);else for(let s=i;s>r;s+=n)o.push(s);return o}function Fp(e,t,n,i){if(e.x===t.x&&e.y===t.y)return ci(e,n,i);if(n.x===i.x&&n.y===i.y)return ci(n,e,t);if(Gi(e,t,n,i))return 0;let r=[ci(e,n,i),ci(t,n,i),ci(n,e,t),ci(i,e,t)];return Math.min(...r)}function tf(e,t,n){let i={x:n.minX,y:n.minY},r={x:n.maxX,y:n.minY},o={x:n.minX,y:n.maxY},s={x:n.maxX,y:n.maxY};if(Gi(e,t,i,r)||Gi(e,t,r,s)||Gi(e,t,s,o)||Gi(e,t,o,i)||e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY&&t.x>=n.minX&&t.x<=n.maxX&&t.y>=n.minY&&t.y<=n.maxY)return 0;let a=[ci(i,e,t),ci(r,e,t),ci(o,e,t),ci(s,e,t)];if(e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY||t.x>=n.minX&&t.x<=n.maxX&&t.y>=n.minY&&t.y<=n.maxY)return 0;if(e.x<n.minX||e.x>n.maxX||e.y<n.minY||e.y>n.maxY){let c=Rn(e.x,n.minX,n.maxX),l=Rn(e.y,n.minY,n.maxY);a.push(Oi(e,{x:c,y:l}))}if(t.x<n.minX||t.x>n.maxX||t.y<n.minY||t.y>n.maxY){let c=Rn(t.x,n.minX,n.maxX),l=Rn(t.y,n.minY,n.maxY);a.push(Oi(t,{x:c,y:l}))}return Math.min(...a)}function RF(e,t,n){let i=n.width/2,r=n.height/2,o={minX:n.center.x-i,maxX:n.center.x+i,minY:n.center.y-r,maxY:n.center.y+r};return tf(e,t,o)}function Cg(e,t,n){let i={x:n.x,y:n.y};if(e.x===t.x&&e.y===t.y)return Math.max(0,Oi(e,i)-n.radius);let r={x:t.x-e.x,y:t.y-e.y},o={x:i.x-e.x,y:i.y-e.y},s=r.x*r.x+r.y*r.y,a=Math.max(0,Math.min(1,(r.x*o.x+r.y*o.y)/s)),c={x:e.x+a*r.x,y:e.y+a*r.y},l=Oi(c,i);return Math.max(0,l-n.radius)}function OF(e,t,n){let i=n.x-t.x,r=n.y-t.y,o=i*i+r*r;if(o===0)return{x:t.x,y:t.y};let s=((e.x-t.x)*i+(e.y-t.y)*r)/o;return s=Math.max(0,Math.min(1,s)),{x:t.x+s*i,y:t.y+s*r}}var LF=(e,t)=>{let n=Math.max(0,Math.min(e.maxX,t.maxX)-Math.max(e.minX,t.minX)),i=Math.max(0,Math.min(e.maxY,t.maxY)-Math.max(e.minY,t.minY));return n*i};var zF=(e,t)=>{let n=e.maxX<t.minX?t.minX-e.maxX:t.maxX<e.minX?e.minX-t.maxX:0,i=e.maxY<t.minY?t.minY-e.maxY:t.maxY<e.minY?e.minY-t.maxY:0;return Math.sqrt(n*n+i*i)};var Ka=(e,t)=>!(e.maxX<t.minX||t.maxX<e.minX||e.maxY<t.minY||t.maxY<e.minY);var kg=(e,t)=>{let n={x:t.x-e.x,y:t.y-e.y},i=Math.sqrt(n.x**2+n.y**2);return{x:n.x/i,y:n.y/i}},Ng=e=>{switch(e){case"up":return{x:0,y:1};case"down":return{x:0,y:-1};case"left":return{x:-1,y:0};case"right":return{x:1,y:0}}};function FF({rows:e,cols:t,xSpacing:n,ySpacing:i,width:r,height:o,offsetX:s=0,offsetY:a=0,yDirection:c="cartesian",centered:l=!0}){let u=n??1,h=i??1,d=r??t*u,_=o??e*h,y=l?-d/2:0,g=l?-_/2:0,x=r?r/t:u,w=o?o/e:h,S=[];for(let E=0;E<e;E++)for(let M=0;M<t;M++){let k=E*t+M,I=s+y+M*x+x/2,N=a+E*w+w/2,C=c==="cartesian"?a+g+(e-1-E)*w+w/2:a+g+E*w+w/2;S.push({index:k,center:{x:I,y:C},topLeft:{x:I-x/2,y:C+w/2},bottomRight:{x:I+x/2,y:C-w/2},row:E,col:M})}return S}vt();ef();var DF={name:"@tscircuit/capacity-autorouter",main:"./dist/index.js",version:"0.0.132",type:"module",files:["dist"],scripts:{start:"cosmos",build:"tsup ./lib/index.ts --minify terser --external @tscircuit/core --external circuit-to-svg --format esm --dts --sourcemap",bench:"bun test tests/spatial-index-bench.test.ts",format:"biome format --write .","format:check":"biome format .","vercel-build":"cosmos-export","repomix:lib":"repomix --ignore 'testing/**,**/TwoRouteHighDensitySolver/**,**/RouteStitchingSolver/**,solvers/CapacitySegmentPointOptimizer/CapacitySegmentPointOptimizer.ts' lib","bug-report":"bun run scripts/download-bug-report.ts","bug-report-with-test":"bun run scripts/create-bug-report-test.ts"},devDependencies:{"@biomejs/biome":"^1.9.4","@radix-ui/react-icons":"^1.3.2","@radix-ui/react-menubar":"^1.1.14","@react-hook/resize-observer":"^2.0.2","@resvg/resvg-js":"^2.6.2","@tscircuit/checks":"^0.0.75","@tscircuit/circuit-json-util":"^0.0.46","@tscircuit/core":"^0.0.337","@tscircuit/math-utils":"^0.0.27","@types/bun":"^1.2.23","@types/fast-json-stable-stringify":"^2.1.2","@types/object-hash":"^3.0.6","@types/rbush":"^4.0.0","@types/react":"^19.0.8","@types/react-dom":"^19.0.3","@vercel/node":"^5.1.7","@vitejs/plugin-react":"^4.3.4","circuit-json-to-connectivity-map":"^0.0.19","circuit-to-svg":"^0.0.220",clsx:"^2.1.1",flatbush:"^4.4.0","graphics-debug":"^0.0.44","looks-same":"9",rbush:"^4.0.1",react:"18","react-cosmos":"^6.2.3","react-cosmos-plugin-vite":"^6.2.0","react-dom":"18","react-konva":"18",recharts:"^2.15.1","tailwind-merge":"^3.2.0",terser:"^5.43.1",tsup:"^8.3.6",typescript:"^5.9.3","use-mouse-matrix-transform":"^1.3.0",vite:"^6.0.11","vite-tsconfig-paths":"^5.1.4"},dependencies:{"fast-json-stable-stringify":"^2.1.0","object-hash":"^3.0.0"}};vt();yi();Ce();var $I=Yt(vo(),1);vt();var YD=Yt(Lg(),1),ZD=Yt(Lg(),1),JD=Yt(Lg(),1);var Wg=(...e)=>{let t={points:[],lines:[],circles:[],rects:[]};return e.forEach((n,i)=>{n&&(n.lines&&(t.lines=[...t.lines||[],...n.lines.map(r=>({...r,step:i}))]),n.points&&(t.points=[...t.points||[],...n.points.map(r=>({...r,step:i}))]),n.circles&&(t.circles=[...t.circles||[],...n.circles.map(r=>({...r,step:i}))]),n.rects&&(t.rects=[...t.rects||[],...n.rects.map(r=>({...r,step:i}))]))}),t},dn=class{constructor(){T(this,"MAX_ITERATIONS",1e3);T(this,"solved",!1);T(this,"failed",!1);T(this,"iterations",0);T(this,"progress",0);T(this,"error",null);T(this,"activeSubSolver");T(this,"failedSubSolvers");T(this,"timeToSolve");T(this,"stats",{});T(this,"cacheHit");T(this,"cacheKey");T(this,"cacheToSolveSpaceTransform")}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e){throw this.error=`${this.constructor.name} error: ${e}`,console.error(this.error),this.failed=!0,e}!this.solved&&this.iterations>this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,console.error(this.error),this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}solve(){let e=Date.now();for(;!this.solved&&!this.failed;)this.step();let t=Date.now();this.timeToSolve=t-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function JF(e){let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,maxX:e.center.x+t,minY:e.center.y-n,maxY:e.center.y+n}}function tc(e,t,n){return Math.max(t,Math.min(n,e))}function gi(e,t,n,i){let r=zg(e,t,n),o=zg(e,t,i),s=zg(n,i,e),a=zg(n,i,t);return r!==o&&s!==a||!(r!==0||!Fg(e,n,t))||!(o!==0||!Fg(e,i,t))||!(s!==0||!Fg(n,e,i))||!(a!==0||!Fg(n,t,i))}function zg(e,t,n){let i=(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y);return i===0?0:i>0?1:2}function Fg(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function Ui(e,t,n){let i=(n.x-t.x)**2+(n.y-t.y)**2;if(i===0)return Gt(e,t);let r=((e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y))/i;return r=Math.max(0,Math.min(1,r)),Gt(e,{x:t.x+r*(n.x-t.x),y:t.y+r*(n.y-t.y)})}function Gt(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}function ED(e,t,n,i){let r=t.x-e.x,o=t.y-e.y,s=i.x-n.x,a=i.y-n.y,c=e.x-n.x,l=e.y-n.y,u=r*a-o*s;if(Math.abs(u)<1e-10)return null;let h=(l*s-c*a)/u,d=(r*l-o*c)/u,_=1e-9;return h>=-1e-9&&h<=1+_&&d>=-1e-9&&d<=1+_?{x:e.x+h*r,y:e.y+h*o}:null}function QF(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}var CD=e=>{if("minX"in e)return e;let t=e.width/2,n=e.height/2;return{minX:e.center.x-t,minY:e.center.y-n,maxX:e.center.x+t,maxY:e.center.y+n}},k4=e=>[{x:e.minX,y:e.minY},{x:e.maxX,y:e.minY},{x:e.maxX,y:e.maxY},{x:e.minX,y:e.maxY}],kD=e=>{let t=[];for(let n=0;n<e.length;n++){let i=e[n],r=e[(n+1)%e.length];t.push([i,r])}return t},a_t=(e,t,n)=>{let i=(e.y-t.y)*(n.x-t.x)-(e.x-t.x)*(n.y-t.y);if(Math.abs(i)>1e-9)return!1;let r=(e.x-t.x)*(n.x-t.x)+(e.y-t.y)*(n.y-t.y);return r<0?!1:!(r>(n.x-t.x)**2+(n.y-t.y)**2)},ND=(e,t)=>{if(t.length<3)return!1;let n=kD(t);for(let[r,o]of n)if(a_t(e,r,o))return!0;let i=!1;for(let r=0,o=t.length-1;r<t.length;o=r++){let s=t[r].x,a=t[r].y,c=t[o].x,l=t[o].y;a>e.y!=l>e.y&&e.x<(c-s)*(e.y-a)/(l-a)+s&&(i=!i)}return i},AD=(e,t)=>{let n=k4(e),i=[[n[0],n[1]],[n[1],n[2]],[n[2],n[3]],[n[3],n[0]]],r=kD(t);for(let[o,s]of r)for(let[a,c]of i)if(gi(o,s,a,c))return!0;return!1},g4=(e,t)=>((n,i)=>!(i.length<3)&&(!!i.some(r=>((o,s)=>o.x>=s.minX&&o.x<=s.maxX&&o.y>=s.minY&&o.y<=s.maxY)(r,n))||!!k4(n).some(r=>ND(r,i))||AD(n,i)))(CD(e),t),RD=(e,t)=>((n,i)=>!(i.length<3)&&!!k4(n).every(r=>ND(r,i))&&!AD(n,i))(CD(e),t);function b4(e,t,n,i){if(e.x===t.x&&e.y===t.y)return Ui(e,n,i);if(n.x===i.x&&n.y===i.y)return Ui(n,e,t);if(gi(e,t,n,i))return 0;let r=[Ui(e,n,i),Ui(t,n,i),Ui(n,e,t),Ui(i,e,t)];return Math.min(...r)}function OD(e,t,n){let i=n.width/2,r=n.height/2;return(function(o,s,a){let c={x:a.minX,y:a.minY},l={x:a.maxX,y:a.minY},u={x:a.minX,y:a.maxY},h={x:a.maxX,y:a.maxY};if(gi(o,s,c,l)||gi(o,s,l,h)||gi(o,s,h,u)||gi(o,s,u,c)||o.x>=a.minX&&o.x<=a.maxX&&o.y>=a.minY&&o.y<=a.maxY&&s.x>=a.minX&&s.x<=a.maxX&&s.y>=a.minY&&s.y<=a.maxY)return 0;let d=[Ui(c,o,s),Ui(l,o,s),Ui(u,o,s),Ui(h,o,s)];if(o.x>=a.minX&&o.x<=a.maxX&&o.y>=a.minY&&o.y<=a.maxY||s.x>=a.minX&&s.x<=a.maxX&&s.y>=a.minY&&s.y<=a.maxY)return 0;if(o.x<a.minX||o.x>a.maxX||o.y<a.minY||o.y>a.maxY){let _=tc(o.x,a.minX,a.maxX),y=tc(o.y,a.minY,a.maxY);d.push(Gt(o,{x:_,y}))}if(s.x<a.minX||s.x>a.maxX||s.y<a.minY||s.y>a.maxY){let _=tc(s.x,a.minX,a.maxX),y=tc(s.y,a.minY,a.maxY);d.push(Gt(s,{x:_,y}))}return Math.min(...d)})(e,t,{minX:n.center.x-i,maxX:n.center.x+i,minY:n.center.y-r,maxY:n.center.y+r})}function Vp(e,t,n){let i=n.x-t.x,r=n.y-t.y,o=i*i+r*r;if(o===0)return{x:t.x,y:t.y};let s=((e.x-t.x)*i+(e.y-t.y)*r)/o;return s=Math.max(0,Math.min(1,s)),{x:t.x+s*i,y:t.y+s*r}}function br(){return br=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},br.apply(null,arguments)}function Jg(e,t){return(Jg=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n})(e,t)}function LD(e){return(LD=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)})(e)}function zD(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(zD=function(){return!!e})()}function x4(e){var t=typeof Map=="function"?new Map:void 0;return x4=function(n){if(n===null||!(function(r){try{return Function.toString.call(r).indexOf("[native code]")!==-1}catch{return typeof r=="function"}})(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(t!==void 0){if(t.has(n))return t.get(n);t.set(n,i)}function i(){return(function(r,o,s){if(zD())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,o);var c=new(r.bind.apply(r,a));return s&&Jg(c,s.prototype),c})(n,arguments,LD(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),Jg(i,n)},x4(e)}var gr=(function(e){var t,n;function i(r){var o;if(1)o=e.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+r+" for more information.")||this;else for(var s,a,c;c<s;c++);return(function(l){if(l===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return l})(o)}return n=e,(t=i).prototype=Object.create(n.prototype),t.prototype.constructor=t,Jg(t,n),i})(x4(Error));function tD(e,t){return e.substr(-t.length)===t}var c_t=/^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;function eD(e){return typeof e!="string"?e:e.match(c_t)?parseFloat(e):e}var nD=function(e){return function(t,n){n===void 0&&(n="16px");var i=t,r=n;if(typeof t=="string"){if(!tD(t,"px"))throw new gr(69,e,t);i=eD(t)}if(typeof n=="string"){if(!tD(n,"px"))throw new gr(70,e,n);r=eD(n)}if(typeof i=="string")throw new gr(71,t,e);if(typeof r=="string")throw new gr(72,n,e);return""+i/r+e}};nD("em"),nD("rem");function a4(e){return Math.round(255*e)}function l_t(e,t,n){return a4(e)+","+a4(t)+","+a4(n)}function pf(e,t,n,i){if(i===void 0&&(i=l_t),t===0)return i(n,n,n);var r=(e%360+360)%360/60,o=(1-Math.abs(2*n-1))*t,s=o*(1-Math.abs(r%2-1)),a=0,c=0,l=0;r>=0&&r<1?(a=o,c=s):r>=1&&r<2?(a=s,c=o):r>=2&&r<3?(c=o,l=s):r>=3&&r<4?(c=s,l=o):r>=4&&r<5?(a=s,l=o):r>=5&&r<6&&(a=o,l=s);var u=n-o/2;return i(a+u,c+u,l+u)}var iD={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},u_t=/^#[a-fA-F0-9]{6}$/,p_t=/^#[a-fA-F0-9]{8}$/,h_t=/^#[a-fA-F0-9]{3}$/,d_t=/^#[a-fA-F0-9]{4}$/,c4=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,f_t=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,m_t=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,__t=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function Hp(e){if(typeof e!="string")throw new gr(3);var t=(function(d){if(typeof d!="string")return d;var _=d.toLowerCase();return iD[_]?"#"+iD[_]:d})(e);if(t.match(u_t))return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16)};if(t.match(p_t)){var n=parseFloat((parseInt(""+t[7]+t[8],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16),alpha:n}}if(t.match(h_t))return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16)};if(t.match(d_t)){var i=parseFloat((parseInt(""+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16),alpha:i}}var r=c4.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var o=f_t.exec(t.substring(0,50));if(o)return{red:parseInt(""+o[1],10),green:parseInt(""+o[2],10),blue:parseInt(""+o[3],10),alpha:parseFloat(""+o[4])>1?parseFloat(""+o[4])/100:parseFloat(""+o[4])};var s=m_t.exec(t);if(s){var a="rgb("+pf(parseInt(""+s[1],10),parseInt(""+s[2],10)/100,parseInt(""+s[3],10)/100)+")",c=c4.exec(a);if(!c)throw new gr(4,t,a);return{red:parseInt(""+c[1],10),green:parseInt(""+c[2],10),blue:parseInt(""+c[3],10)}}var l=__t.exec(t.substring(0,50));if(l){var u="rgb("+pf(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",h=c4.exec(u);if(!h)throw new gr(4,t,u);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+l[4])>1?parseFloat(""+l[4])/100:parseFloat(""+l[4])}}throw new gr(5)}function ec(e){return(function(t){var n,i=t.red/255,r=t.green/255,o=t.blue/255,s=Math.max(i,r,o),a=Math.min(i,r,o),c=(s+a)/2;if(s===a)return t.alpha!==void 0?{hue:0,saturation:0,lightness:c,alpha:t.alpha}:{hue:0,saturation:0,lightness:c};var l=s-a,u=c>.5?l/(2-s-a):l/(s+a);switch(s){case i:n=(r-o)/l+(r<o?6:0);break;case r:n=(o-i)/l+2;break;default:n=(i-r)/l+4}return n*=60,t.alpha!==void 0?{hue:n,saturation:u,lightness:c,alpha:t.alpha}:{hue:n,saturation:u,lightness:c}})(Hp(e))}var v4=function(e){return e.length===7&&e[1]===e[2]&&e[3]===e[4]&&e[5]===e[6]?"#"+e[1]+e[3]+e[5]:e};function Rl(e){var t=e.toString(16);return t.length===1?"0"+t:t}function l4(e){return Rl(Math.round(255*e))}function y_t(e,t,n){return v4("#"+l4(e)+l4(t)+l4(n))}function Dg(e,t,n){return pf(e,t,n,y_t)}function w4(e,t,n){if(typeof e=="number"&&typeof t=="number"&&typeof n=="number")return v4("#"+Rl(e)+Rl(t)+Rl(n));if(typeof e=="object"&&t===void 0&&n===void 0)return v4("#"+Rl(e.red)+Rl(e.green)+Rl(e.blue));throw new gr(6)}function rb(e,t,n,i){if(typeof e=="string"&&typeof t=="number"){var r=Hp(e);return"rgba("+r.red+","+r.green+","+r.blue+","+t+")"}if(typeof e=="number"&&typeof t=="number"&&typeof n=="number"&&typeof i=="number")return i>=1?w4(e,t,n):"rgba("+e+","+t+","+n+","+i+")";if(typeof e=="object"&&t===void 0&&n===void 0&&i===void 0)return e.alpha>=1?w4(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new gr(7)}function nc(e){if(typeof e!="object")throw new gr(8);if((function(t){return typeof t.red=="number"&&typeof t.green=="number"&&typeof t.blue=="number"&&typeof t.alpha=="number"})(e))return rb(e);if((function(t){return typeof t.red=="number"&&typeof t.green=="number"&&typeof t.blue=="number"&&(typeof t.alpha!="number"||t.alpha===void 0)})(e))return w4(e);if((function(t){return typeof t.hue=="number"&&typeof t.saturation=="number"&&typeof t.lightness=="number"&&typeof t.alpha=="number"})(e))return(function(t,n,i,r){if(typeof t=="number"&&typeof n=="number"&&typeof i=="number"&&typeof r=="number")return r>=1?Dg(t,n,i):"rgba("+pf(t,n,i)+","+r+")";if(typeof t=="object"&&n===void 0&&i===void 0&&r===void 0)return t.alpha>=1?Dg(t.hue,t.saturation,t.lightness):"rgba("+pf(t.hue,t.saturation,t.lightness)+","+t.alpha+")";throw new gr(2)})(e);if((function(t){return typeof t.hue=="number"&&typeof t.saturation=="number"&&typeof t.lightness=="number"&&(typeof t.alpha!="number"||t.alpha===void 0)})(e))return(function(t,n,i){if(typeof t=="number"&&typeof n=="number"&&typeof i=="number")return Dg(t,n,i);if(typeof t=="object"&&n===void 0&&i===void 0)return Dg(t.hue,t.saturation,t.lightness);throw new gr(1)})(e);throw new gr(8)}function FD(e,t,n){return function(){var i=n.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):FD(e,t,i)}}function Lr(e){return FD(e,e.length,[])}Lr(function(e,t){if(t==="transparent")return t;var n=ec(t);return nc(br({},n,{hue:n.hue+parseFloat(e)}))});function Up(e,t,n){return Math.max(e,Math.min(t,n))}Lr(function(e,t){if(t==="transparent")return t;var n=ec(t);return nc(br({},n,{lightness:Up(0,1,n.lightness-parseFloat(e))}))});Lr(function(e,t){if(t==="transparent")return t;var n=ec(t);return nc(br({},n,{saturation:Up(0,1,n.saturation-parseFloat(e))}))});Lr(function(e,t){if(t==="transparent")return t;var n=ec(t);return nc(br({},n,{lightness:Up(0,1,n.lightness+parseFloat(e))}))});var DD=Lr(function(e,t,n){if(t==="transparent")return n;if(n==="transparent")return t;if(e===0)return n;var i=Hp(t),r=br({},i,{alpha:typeof i.alpha=="number"?i.alpha:1}),o=Hp(n),s=br({},o,{alpha:typeof o.alpha=="number"?o.alpha:1}),a=r.alpha-s.alpha,c=2*parseFloat(e)-1,l=((c*a===-1?c:c+a)/(1+c*a)+1)/2,u=1-l;return rb({red:Math.floor(r.red*l+s.red*u),green:Math.floor(r.green*l+s.green*u),blue:Math.floor(r.blue*l+s.blue*u),alpha:r.alpha*parseFloat(e)+s.alpha*(1-parseFloat(e))})});Lr(function(e,t){if(t==="transparent")return t;var n=Hp(t);return rb(br({},n,{alpha:Up(0,1,(100*(typeof n.alpha=="number"?n.alpha:1)+100*parseFloat(e))/100)}))});Lr(function(e,t){if(t==="transparent")return t;var n=ec(t);return nc(br({},n,{saturation:Up(0,1,n.saturation+parseFloat(e))}))});Lr(function(e,t){return t==="transparent"?t:nc(br({},ec(t),{hue:parseFloat(e)}))});Lr(function(e,t){return t==="transparent"?t:nc(br({},ec(t),{lightness:parseFloat(e)}))});Lr(function(e,t){return t==="transparent"?t:nc(br({},ec(t),{saturation:parseFloat(e)}))});Lr(function(e,t){return t==="transparent"?t:DD(parseFloat(e),"rgb(0, 0, 0)",t)});Lr(function(e,t){return t==="transparent"?t:DD(parseFloat(e),"rgb(255, 255, 255)",t)});var g_t=Lr(function(e,t){if(t==="transparent")return t;var n=Hp(t);return rb(br({},n,{alpha:Up(0,1,+(100*(typeof n.alpha=="number"?n.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))}),rD=["blue","orange","purple","cyan","magenta","yellowgreen","darkgoldenrod","deeppink"],S4=(e,t)=>{let n={};for(let i=0;i<e.connections.length;i++){let r=e.connections[i],o=t?.getNetConnectedToId(r.name);o&&!n[o]&&(n[o]=`hsl(${300*i/e.connections.length}, 100%, 50%)`),n[r.name]=(o?n[o]:null)??`hsl(${340*i/e.connections.length}, 100%, 50%)`}return n},Xn=(e,t)=>{try{return g_t(t,e)}catch(n){return console.error(n),e}},Ll=(e,t)=>e==="top"?0:e==="bottom"?t-1:parseInt(e.slice(5)),qo=(e,t=1)=>{let n=(("width"in e?e.width:e)/.5/2)**1.1*t;return e.availableZ?.length===1&&n>1?1:n},b_t=(e,t=.5,n=16)=>{let i=0,r=e;for(;i<n&&!(qo({width:r})<=t);)r/=2,i++;return Math.max(1,i)};function $D(e,t,n=0,i=e.length-1,r=x_t){for(;i>n;){if(i-n>600){let c=i-n+1,l=t-n+1,u=Math.log(c),h=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*h*(c-h)/c)*(l-c/2<0?-1:1);$D(e,t,Math.max(n,Math.floor(t-l*h/c+d)),Math.min(i,Math.floor(t+(c-l)*h/c+d)),r)}let o=e[t],s=n,a=i;for(rf(e,n,t),r(e[i],o)>0&&rf(e,n,i);s<a;){for(rf(e,s,a),s++,a--;r(e[s],o)<0;)s++;for(;r(e[a],o)>0;)a--}r(e[n],o)===0?rf(e,n,a):(a++,rf(e,a,i)),a<=t&&(n=a+1),t<=a&&(i=a-1)}}function rf(e,t,n){let i=e[t];e[t]=e[n],e[n]=i}function x_t(e,t){return e<t?-1:e>t?1:0}var v_t=class{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data,n=[];if(!Bg(e,t))return n;let i=this.toBBox,r=[];for(;t;){for(let o=0;o<t.children.length;o++){let s=t.children[o],a=t.leaf?i(s):s;Bg(e,a)&&(t.leaf?n.push(s):p4(e,a)?this._all(s,n):r.push(s))}t=r.pop()}return n}collides(e){let t=this.data;if(!Bg(e,t))return!1;let n=[];for(;t;){for(let i=0;i<t.children.length;i++){let r=t.children[i],o=t.leaf?this.toBBox(r):r;if(Bg(e,o)){if(t.leaf||p4(e,o))return!0;n.push(r)}}t=n.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let n=0;n<e.length;n++)this.insert(e[n]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){let n=this.data;this.data=t,t=n}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=Yp([]),this}remove(e,t){if(!e)return this;let n=this.data,i=this.toBBox(e),r=[],o=[],s,a,c;for(;n||r.length;){if(n||(n=r.pop(),a=r[r.length-1],s=o.pop(),c=!0),n.leaf){let l=w_t(e,n.children,t);if(l!==-1)return n.children.splice(l,1),r.push(n),this._condense(r),this}c||n.leaf||!p4(n,i)?a?(s++,n=a.children[s],c=!1):n=null:(r.push(n),o.push(s),s=0,a=n,n=n.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){let n=[];for(;e;)e.leaf?t.push(...e.children):n.push(...e.children),e=n.pop();return t}_build(e,t,n,i){let r=n-t+1,o,s=this._maxEntries;if(r<=s)return o=Yp(e.slice(t,n+1)),jp(o,this.toBBox),o;i||(i=Math.ceil(Math.log(r)/Math.log(s)),s=Math.ceil(r/Math.pow(s,i-1))),o=Yp([]),o.leaf=!1,o.height=i;let a=Math.ceil(r/s),c=a*Math.ceil(Math.sqrt(s));oD(e,t,n,c,this.compareMinX);for(let l=t;l<=n;l+=c){let u=Math.min(l+c-1,n);oD(e,l,u,a,this.compareMinY);for(let h=l;h<=u;h+=a){let d=Math.min(h+a-1,u);o.children.push(this._build(e,h,d,i-1))}}return jp(o,this.toBBox),o}_chooseSubtree(e,t,n,i){for(;i.push(t),!t.leaf&&i.length-1!==n;){let r,o=1/0,s=1/0;for(let a=0;a<t.children.length;a++){let c=t.children[a],l=u4(c),u=T_t(e,c)-l;u<s?(s=u,o=l<o?l:o,r=c):u===s&&l<o&&(o=l,r=c)}t=r||t.children[0]}return t}_insert(e,t,n){let i=n?e:this.toBBox(e),r=[],o=this._chooseSubtree(i,this.data,t,r);for(o.children.push(e),sf(o,i);t>=0&&r[t].children.length>this._maxEntries;)this._split(r,t),t--;this._adjustParentBBoxes(i,r,t)}_split(e,t){let n=e[t],i=n.children.length,r=this._minEntries;this._chooseSplitAxis(n,r,i);let o=this._chooseSplitIndex(n,r,i),s=Yp(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,jp(n,this.toBBox),jp(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)}_splitRoot(e,t){this.data=Yp([e,t]),this.data.height=e.height+1,this.data.leaf=!1,jp(this.data,this.toBBox)}_chooseSplitIndex(e,t,n){let i,r=1/0,o=1/0;for(let s=t;s<=n-t;s++){let a=of(e,0,s,this.toBBox),c=of(e,s,n,this.toBBox),l=I_t(a,c),u=u4(a)+u4(c);l<r?(r=l,i=s,o=u<o?u:o):l===r&&u<o&&(o=u,i=s)}return i||n-t}_chooseSplitAxis(e,t,n){let i=e.leaf?this.compareMinX:S_t,r=e.leaf?this.compareMinY:P_t;this._allDistMargin(e,t,n,i)<this._allDistMargin(e,t,n,r)&&e.children.sort(i)}_allDistMargin(e,t,n,i){e.children.sort(i);let r=this.toBBox,o=of(e,0,t,r),s=of(e,n-t,n,r),a=$g(o)+$g(s);for(let c=t;c<n-t;c++){let l=e.children[c];sf(o,e.leaf?r(l):l),a+=$g(o)}for(let c=n-t-1;c>=t;c--){let l=e.children[c];sf(s,e.leaf?r(l):l),a+=$g(s)}return a}_adjustParentBBoxes(e,t,n){for(let i=n;i>=0;i--)sf(t[i],e)}_condense(e){for(let t,n=e.length-1;n>=0;n--)e[n].children.length===0?n>0?(t=e[n-1].children,t.splice(t.indexOf(e[n]),1)):this.clear():jp(e[n],this.toBBox)}};function w_t(e,t,n){if(!n)return t.indexOf(e);for(let i=0;i<t.length;i++)if(n(e,t[i]))return i;return-1}function jp(e,t){of(e,0,e.children.length,t,e)}function of(e,t,n,i,r){r||(r=Yp(null)),r.minX=1/0,r.minY=1/0,r.maxX=-1/0,r.maxY=-1/0;for(let o=t;o<n;o++){let s=e.children[o];sf(r,e.leaf?i(s):s)}return r}function sf(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function S_t(e,t){return e.minX-t.minX}function P_t(e,t){return e.minY-t.minY}function u4(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function $g(e){return e.maxX-e.minX+(e.maxY-e.minY)}function T_t(e,t){return(Math.max(t.maxX,e.maxX)-Math.min(t.minX,e.minX))*(Math.max(t.maxY,e.maxY)-Math.min(t.minY,e.minY))}function I_t(e,t){let n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),r=Math.min(e.maxX,t.maxX),o=Math.min(e.maxY,t.maxY);return Math.max(0,r-n)*Math.max(0,o-i)}function p4(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function Bg(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function Yp(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function oD(e,t,n,i,r){let o=[t,n];for(;o.length;){if((n=o.pop())-(t=o.pop())<=i)continue;let s=t+Math.ceil((n-t)/i/2)*i;$D(e,s,t,n,r),o.push(t,s,s,n)}}var sD=class{constructor(e=9){T(this,"tree");this.tree=new v_t(e)}insert(e,t,n,i,r){this.tree.insert({minX:t,minY:n,maxX:i,maxY:r,data:e})}bulkLoad(e){let t=e.map(({item:n,minX:i,minY:r,maxX:o,maxY:s})=>({minX:i,minY:r,maxX:o,maxY:s,data:n}));this.tree.load(t)}search(e,t,n,i){return this.tree.search({minX:e,minY:t,maxX:n,maxY:i}).map(r=>r.data)}clear(){this.tree.clear()}},M_t=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(e,t){let n=this.length++;for(;n>0;){let i=n-1>>1,r=this.values[i];if(t>=r)break;this.ids[n]=this.ids[i],this.values[n]=r,n=i}this.ids[n]=e,this.values[n]=t}pop(){if(this.length===0)return;let e=this.ids,t=this.values,n=e[0],i=--this.length;if(i>0){let r=e[i],o=t[i],s=0,a=i>>1;for(;s<a;){let c=1+(s<<1),l=c+1,u=c+(+(l<i)&+(t[l]<t[c]));if(t[u]>=o)break;e[s]=e[u],t[s]=t[u],s=u}e[s]=r,t[s]=o}return n}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){this.ids.length=this.values.length=this.length}},aD=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],cD=class BD{static from(t,n=0){if(n%8!=0)throw new Error("byteOffset must be 8-byte aligned.");if(!t||t.byteLength===void 0||t.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[i,r]=new Uint8Array(t,n+0,2);if(i!==251)throw new Error("Data does not appear to be in a Flatbush format.");let o=r>>4;if(o!==3)throw new Error(`Got v${o} data when expected v3.`);let s=aD[15&r];if(!s)throw new Error("Unrecognized array type.");let[a]=new Uint16Array(t,n+2,1),[c]=new Uint32Array(t,n+4,1);return new BD(c,a,s,void 0,t,n)}constructor(t,n=16,i=Float64Array,r=ArrayBuffer,o,s=0){if(t===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(t)||t<=0)throw new Error(`Unexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+n,2),65535),this.byteOffset=s;let a=t,c=a;this._levelBounds=[4*a];do a=Math.ceil(a/this.nodeSize),c+=a,this._levelBounds.push(4*c);while(a!==1);this.ArrayType=i,this.IndexArrayType=c<16384?Uint16Array:Uint32Array;let l=aD.indexOf(i),u=4*c*i.BYTES_PER_ELEMENT;if(l<0)throw new Error(`Unexpected typed array class: ${i}.`);if(o)this.data=o,this._boxes=new i(o,s+8,4*c),this._indices=new this.IndexArrayType(o,s+8+u,c),this._pos=4*c,this.minX=this._boxes[this._pos-4],this.minY=this._boxes[this._pos-3],this.maxX=this._boxes[this._pos-2],this.maxY=this._boxes[this._pos-1];else{let h=this.data=new r(8+u+c*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new i(h,8,4*c),this._indices=new this.IndexArrayType(h,8+u,c),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(h,0,2).set([251,48+l]),new Uint16Array(h,2,1)[0]=n,new Uint32Array(h,4,1)[0]=t}this._queue=new M_t}add(t,n,i=t,r=n){let o=this._pos>>2,s=this._boxes;return this._indices[o]=o,s[this._pos++]=t,s[this._pos++]=n,s[this._pos++]=i,s[this._pos++]=r,t<this.minX&&(this.minX=t),n<this.minY&&(this.minY=n),i>this.maxX&&(this.maxX=i),r>this.maxY&&(this.maxY=r),o}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let t=this._boxes;if(this.numItems<=this.nodeSize)return t[this._pos++]=this.minX,t[this._pos++]=this.minY,t[this._pos++]=this.maxX,void(t[this._pos++]=this.maxY);let n=this.maxX-this.minX||1,i=this.maxY-this.minY||1,r=new Uint32Array(this.numItems);for(let o=0,s=0;o<this.numItems;o++){let a=t[s++],c=t[s++],l=t[s++],u=t[s++],h=Math.floor(65535*((a+l)/2-this.minX)/n),d=Math.floor(65535*((c+u)/2-this.minY)/i);r[o]=C_t(h,d)}P4(r,t,this._indices,0,this.numItems-1,this.nodeSize);for(let o=0,s=0;o<this._levelBounds.length-1;o++){let a=this._levelBounds[o];for(;s<a;){let c=s,l=t[s++],u=t[s++],h=t[s++],d=t[s++];for(let _=1;_<this.nodeSize&&s<a;_++)l=Math.min(l,t[s++]),u=Math.min(u,t[s++]),h=Math.max(h,t[s++]),d=Math.max(d,t[s++]);this._indices[this._pos>>2]=c,t[this._pos++]=l,t[this._pos++]=u,t[this._pos++]=h,t[this._pos++]=d}}}search(t,n,i,r,o){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=[],c=[];for(;s!==void 0;){let l=Math.min(s+4*this.nodeSize,lD(s,this._levelBounds));for(let u=s;u<l;u+=4){let h=this._boxes[u];if(i<h)continue;let d=this._boxes[u+1];if(r<d)continue;let _=this._boxes[u+2];if(t>_)continue;let y=this._boxes[u+3];if(n>y)continue;let g=0|this._indices[u>>2];s>=4*this.numItems?a.push(g):(o===void 0||o(g,h,d,_,y))&&c.push(g)}s=a.pop()}return c}neighbors(t,n,i=1/0,r=1/0,o){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let s=this._boxes.length-4,a=this._queue,c=[],l=r*r;t:for(;s!==void 0;){let u=Math.min(s+4*this.nodeSize,lD(s,this._levelBounds));for(let h=s;h<u;h+=4){let d=0|this._indices[h>>2],_=this._boxes[h],y=this._boxes[h+1],g=this._boxes[h+2],x=this._boxes[h+3],w=t<_?_-t:t>g?t-g:0,S=n<y?y-n:n>x?n-x:0,E=w*w+S*S;E>l||(s>=4*this.numItems?a.push(d<<1,E):(o===void 0||o(d))&&a.push(1+(d<<1),E))}for(;a.length&&1&a.peek();)if(a.peekValue()>l||(c.push(a.pop()>>1),c.length===i))break t;s=a.length?a.pop()>>1:void 0}return a.clear(),c}};function lD(e,t){let n=0,i=t.length-1;for(;n<i;){let r=n+i>>1;t[r]>e?i=r:n=r+1}return t[n]}function P4(e,t,n,i,r,o){if(Math.floor(i/o)>=Math.floor(r/o))return;let s=e[i],a=e[i+r>>1],c=e[r],l=c,u=Math.max(s,a);c>u?l=u:u===s?l=Math.max(a,c):u===a&&(l=Math.max(s,c));let h=i-1,d=r+1;for(;;){do h++;while(e[h]<l);do d--;while(e[d]>l);if(h>=d)break;E_t(e,t,n,h,d)}P4(e,t,n,i,d,o),P4(e,t,n,d+1,r,o)}function E_t(e,t,n,i,r){let o=e[i];e[i]=e[r],e[r]=o;let s=4*i,a=4*r,c=t[s],l=t[s+1],u=t[s+2],h=t[s+3];t[s]=t[a],t[s+1]=t[a+1],t[s+2]=t[a+2],t[s+3]=t[a+3],t[a]=c,t[a+1]=l,t[a+2]=u,t[a+3]=h;let d=n[i];n[i]=n[r],n[r]=d}function C_t(e,t){let n=e^t,i=65535^n,r=65535^(e|t),o=e&(65535^t),s=n|i>>1,a=n>>1^n,c=r>>1^i&o>>1^r,l=n&r>>1^o>>1^o;n=s,i=a,r=c,o=l,s=n&n>>2^i&i>>2,a=n&i>>2^i&(n^i)>>2,c^=n&r>>2^i&o>>2,l^=i&r>>2^(n^i)&o>>2,n=s,i=a,r=c,o=l,s=n&n>>4^i&i>>4,a=n&i>>4^i&(n^i)>>4,c^=n&r>>4^i&o>>4,l^=i&r>>4^(n^i)&o>>4,n=s,i=a,r=c,o=l,c^=n&r>>8^i&o>>8,l^=i&r>>8^(n^i)&o>>8,n=c^c>>1,i=l^l>>1;let u=e^t,h=i|65535^(u|n);return u=16711935&(u|u<<8),u=252645135&(u|u<<4),u=858993459&(u|u<<2),u=1431655765&(u|u<<1),h=16711935&(h|h<<8),h=252645135&(h|h<<4),h=858993459&(h|h<<2),h=1431655765&(h|h<<1),(h<<1|u)>>>0}var k_t=class{constructor(e){T(this,"index");T(this,"items",[]);T(this,"currentIndex",0);T(this,"capacity");this.capacity=Math.max(1,e),this.index=new cD(this.capacity)}insert(e,t,n,i,r){if(this.currentIndex>=this.index.numItems)throw new Error("Exceeded initial capacity");this.items[this.currentIndex]=e,this.index.add(t,n,i,r),this.currentIndex++}finish(){this.index.finish()}search(e,t,n,i){return this.index.search(e,t,n,i).map(r=>this.items[r]||null).filter(Boolean)}clear(){this.items=[],this.currentIndex=0,this.index=new cD(this.capacity)}},jD=class{constructor(e="native",t=[]){T(this,"idx");T(this,"storage",[]);e==="flatbush"?t.length===0?(this.idx=new sD,e="rbush"):this.idx=new k_t(t.length):this.idx=e==="rbush"?new sD:new class{constructor(){T(this,"shi",new N_t(t))}insert(n){}search(n,i,r,o){let s=(n+r)/2,a=(i+o)/2,c=r-n,l=o-i;return this.shi.getNodesInArea(s,a,c,l)}clear(){}},t.forEach(n=>this.insert(n)),e==="flatbush"&&t.length>0&&this.idx.finish?.()}insert(e){this.storage.push(e),this.idx.insert(e,e.center.x-e.width/2,e.center.y-e.height/2,e.center.x+e.width/2,e.center.y+e.height/2)}search(e){return this.idx.search(e.minX,e.minY,e.maxX,e.maxY)}searchArea(e,t,n,i){return this.search({minX:e-n/2,minY:t-i/2,maxX:e+n/2,maxY:t+i/2})}},N_t=class{constructor(e){T(this,"buckets");T(this,"CELL_SIZE",.4);this.obstacles=e,this.buckets=new Map;for(let t=0;t<e.length;t++){let n=e[t],i=n.center.x-n.width/2,r=n.center.y-n.height/2,o=n.center.x+n.width/2,s=n.center.y+n.height/2;for(let a=i;a<=o;a+=this.CELL_SIZE)for(let c=r;c<=s;c+=this.CELL_SIZE){let l=this.getBucketKey(a,c),u=this.buckets.get(l);u?u.push([n,t]):this.buckets.set(l,[[n,t]])}}}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getNodesInArea(e,t,n,i){let r=[],o=new Set,s=t-i/2,a=e+n/2,c=t+i/2;for(let l=e-n/2;l<=a;l+=this.CELL_SIZE)for(let u=s;u<=c;u+=this.CELL_SIZE){let h=this.getBucketKey(l,u),d=this.buckets.get(h)||[];for(let _ of d)o.has(_[1])||(o.add(_[1]),r.push(_[0]))}return r}},A_t=class{constructor(e){T(this,"buckets");T(this,"CELL_SIZE",5);this.targets=e,this.buckets=new Map;for(let t=0;t<e.length;t++){let n=e[t],i=Math.floor(n.bounds.minX/this.CELL_SIZE)*this.CELL_SIZE,r=Math.floor(n.bounds.minY/this.CELL_SIZE)*this.CELL_SIZE,o=n.bounds.maxX,s=n.bounds.maxY;for(let a=i;a<=o;a+=this.CELL_SIZE)for(let c=r;c<=s;c+=this.CELL_SIZE){let l=this.getBucketKey(a,c),u=this.buckets.get(l);u?u.push([n,t]):this.buckets.set(l,[[n,t]])}}}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getTargetsInArea(e,t,n,i){let r=[],o=new Set,s=Math.floor((e-n/2)/this.CELL_SIZE)*this.CELL_SIZE,a=Math.floor((t-i/2)/this.CELL_SIZE)*this.CELL_SIZE,c=e+n/2,l=t+i/2;for(let u=s;u<=c;u+=this.CELL_SIZE)for(let h=a;h<=l;h+=this.CELL_SIZE){let d=this.getBucketKey(u,h),_=this.buckets.get(d)||[];for(let y of _)o.has(y[1])||(o.add(y[1]),r.push(y[0]))}return r}},R_t=class extends dn{constructor(t,n={}){super();T(this,"unfinishedNodes");T(this,"finishedNodes");T(this,"nodeToXYOverlappingObstaclesMap");T(this,"layerCount");T(this,"outlinePolygon");T(this,"MAX_DEPTH",4);T(this,"targets");T(this,"targetTree");T(this,"obstacleTree");T(this,"_nextNodeCounter",0);this.srj=t,this.opts=n,this.MAX_DEPTH=n?.capacityDepth??this.MAX_DEPTH,this.MAX_ITERATIONS=1e5,this.layerCount=t.layerCount??2,this.outlinePolygon=t.outline&&t.outline.length>=3?t.outline:void 0;for(let s of t.obstacles)if(!s.zLayers){let a=[];for(let c of s.layers)a.push(Ll(c,t.layerCount));s.zLayers=a}let i={x:(t.bounds.minX+t.bounds.maxX)/2,y:(t.bounds.minY+t.bounds.maxY)/2},r={width:t.bounds.maxX-t.bounds.minX,height:t.bounds.maxY-t.bounds.minY},o=Math.max(r.width,r.height);this.unfinishedNodes=[{capacityMeshNodeId:this.getNextNodeId(),center:i,width:o,height:o,layer:"top",availableZ:Array.from({length:this.layerCount},(s,a)=>a),_depth:0,_containsTarget:!0,_containsObstacle:!0,_completelyInsideObstacle:!1}],this.finishedNodes=[],this.nodeToXYOverlappingObstaclesMap=new Map,this.obstacleTree=new jD("flatbush",this.srj.obstacles),this.targets=this.computeTargets(),this.targetTree=new A_t(this.targets)}computeTargets(){let t=[];for(let n of this.srj.connections)for(let i of n.pointsToConnect){let r=this.obstacleTree.searchArea(i.x,i.y,.01,.01).filter(a=>a.zLayers.some(c=>c===Ll(i.layer,this.layerCount))),o={minX:i.x-.005,minY:i.y-.005,maxX:i.x+.005,maxY:i.y+.005};r.length>0&&(o={minX:Math.min(...r.map(a=>a.center.x-a.width/2)),minY:Math.min(...r.map(a=>a.center.y-a.height/2)),maxX:Math.max(...r.map(a=>a.center.x+a.width/2)),maxY:Math.max(...r.map(a=>a.center.y+a.height/2))});let s={...i,connectionName:n.name,availableZ:[Ll(i.layer,this.layerCount)],bounds:o};t.push(s)}return t}getNodeBounds(t){let n=t.width/2,i=t.height/2;return{minX:t.center.x-n,maxX:t.center.x+n,minY:t.center.y-i,maxY:t.center.y+i}}getNodeRect(t){return{center:{x:t.center.x,y:t.center.y},width:t.width,height:t.height}}getNextNodeId(){return"cn"+this._nextNodeCounter++}getCapacityFromDepth(t){return(this.MAX_DEPTH-t+1)**2}getTargetIfNodeContainsTarget(t){let n=t.width>4*this.targetTree.CELL_SIZE?this.targets:this.targetTree.getTargetsInArea(t.center.x,t.center.y,t.width,t.height);for(let i of n)if(i.bounds.minX<=t.center.x+t.width/2&&i.bounds.maxX>=t.center.x-t.width/2&&i.bounds.minY<=t.center.y+t.height/2&&i.bounds.maxY>=t.center.y-t.height/2&&i.availableZ.some(r=>t.availableZ.includes(r)))return i;return null}getXYOverlappingObstacles(t){let n=this.nodeToXYOverlappingObstaclesMap.get(t.capacityMeshNodeId);if(n)return n;let i=[],r=this.getNodeBounds(t),o=r.minX,s=r.maxX,a=r.minY,c=r.maxY,l=t._parent?this.getXYOverlappingObstacles(t._parent):this.srj.obstacles;for(let u of l){let h=u.center.x-u.width/2,d=u.center.x+u.width/2,_=u.center.y-u.height/2,y=u.center.y+u.height/2;(s>=h&&o<=d&&c>=_&&a<=y||o>=h&&s<=d&&a>=_&&c<=y||h>=o&&d<=s&&_>=a&&y<=c)&&i.push(u)}return this.nodeToXYOverlappingObstaclesMap.set(t.capacityMeshNodeId,i),i}getXYZOverlappingObstacles(t){let n=this.getXYOverlappingObstacles(t),i=[];for(let r of n)t.availableZ.some(o=>r.zLayers.includes(o))&&i.push(r);return i}doesNodeOverlapObstacle(t){if(this.getXYZOverlappingObstacles(t).length>0)return!0;let n=this.getNodeBounds(t);if(this.outlinePolygon){let i=this.getNodeRect(t);if(!RD(i,this.outlinePolygon))return!0}return n.minX<this.srj.bounds.minX||n.maxX>this.srj.bounds.maxX||n.minY<this.srj.bounds.minY||n.maxY>this.srj.bounds.maxY}isNodeCompletelyInsideObstacle(t){let n=this.getXYZOverlappingObstacles(t),i=this.getNodeBounds(t);if(this.outlinePolygon){let r=this.getNodeRect(t);if(!g4(r,this.outlinePolygon))return!0}for(let r of n){let o=r.center.x-r.width/2,s=r.center.x+r.width/2,a=r.center.y-r.height/2,c=r.center.y+r.height/2;if(i.minX>=o&&i.maxX<=s&&i.minY>=a&&i.maxY<=c)return!0}return!1}getChildNodes(t){if(t._depth===this.MAX_DEPTH)return[];let n=[],i={width:t.width/2,height:t.height/2},r=[{x:t.center.x-i.width/2,y:t.center.y-i.height/2},{x:t.center.x+i.width/2,y:t.center.y-i.height/2},{x:t.center.x-i.width/2,y:t.center.y+i.height/2},{x:t.center.x+i.width/2,y:t.center.y+i.height/2}];for(let o of r){let s={capacityMeshNodeId:this.getNextNodeId(),center:o,width:i.width,height:i.height,layer:t.layer,availableZ:t.availableZ,_depth:(t._depth??0)+1,_parent:t};s._containsObstacle=this.doesNodeOverlapObstacle(s);let a=this.getTargetIfNodeContainsTarget(s);a&&(s._targetConnectionName=a.connectionName,s.availableZ=a.availableZ,s._containsTarget=!0),s._containsObstacle&&(s._completelyInsideObstacle=this.isNodeCompletelyInsideObstacle(s)),s._completelyInsideObstacle&&!s._containsTarget||n.push(s)}return n}shouldNodeBeXYSubdivided(t){return!(t._depth>=this.MAX_DEPTH)&&(!!t._containsTarget||!(!t._containsObstacle||t._completelyInsideObstacle))}_step(){let t=this.unfinishedNodes.pop();if(!t)return void(this.solved=!0);let n=this.getChildNodes(t),i=[],r=[];for(let o of n){let s=this.shouldNodeBeXYSubdivided(o);s?r.push(o):s||o._containsObstacle?!s&&o._containsTarget&&i.push(o):i.push(o)}this.unfinishedNodes.push(...r),this.finishedNodes.push(...i)}visualize(){let t={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Capacity Mesh Visualization"};if(this.outlinePolygon&&this.outlinePolygon.length>=2){let i=this.outlinePolygon.map(r=>({x:r.x,y:r.y}));i.push({...i[0]}),t.lines.push({points:i,strokeColor:"rgba(0, 136, 255, 0.95)",label:"outline"});for(let r of this.outlinePolygon)t.points.push({x:r.x,y:r.y,color:"rgba(0, 136, 255, 0.95)"})}for(let i of this.srj.obstacles)t.rects.push({center:i.center,width:i.width,height:i.height,fill:i.zLayers?.length===1&&i.zLayers?.includes(1)?"rgba(0,0,255,0.3)":"rgba(255,0,0,0.3)",stroke:"red",label:["obstacle",`z: ${i.zLayers.join(",")}`].join(`
162
162
  `)});let n=[...this.finishedNodes,...this.unfinishedNodes];for(let i of n){let r=Math.min(...i.availableZ),o=this.unfinishedNodes.length>0&&i===this.unfinishedNodes[this.unfinishedNodes.length-1];t.rects.push({center:{x:i.center.x+r*i.width*.05,y:i.center.y-r*i.width*.05},width:Math.max(i.width-2,.8*i.width),height:Math.max(i.height-2,.8*i.height),fill:i._containsObstacle?"rgba(255,0,0,0.1)":{"0,1":"rgba(0,0,0,0.1)",0:"rgba(0,200,200, 0.1)",1:"rgba(0,0,200, 0.1)"}[i.availableZ.join(",")]??"rgba(0,200,200,0.1)",stroke:o?"rgba(255,165,0,0.5)":void 0,label:[i.capacityMeshNodeId,`availableZ: ${i.availableZ.join(",")}`,`target? ${i._containsTarget??!1}`,`obs? ${i._containsObstacle??!1}`,`${i.width.toFixed(2)}x${i.height.toFixed(2)}`,`capacity: ${qo(i).toFixed(2)}`].join(`
163
163
  `)})}return t.rects.sort((i,r)=>i.center.y-r.center.y),this.srj.connections.forEach((i,r)=>{let o=rD[r%rD.length];for(let s of i.pointsToConnect)t.points.push({x:s.x,y:s.y,label:`conn-${r} (${s.layer})`,color:o})}),t}},O_t=class extends R_t{constructor(t,n={}){super(t,n);T(this,"VIA_DIAMETER",.6);T(this,"OBSTACLE_MARGIN",.1);T(this,"OVERLAP_THRESHOLD_FOR_SINGLE_LAYER_NODES",.2);this.srj=t,this.opts=n}isNodeCompletelyOutsideBounds(t){if(this.outlinePolygon){let n=this.getNodeRect(t);if(!g4(n,this.outlinePolygon))return!0}return t.center.x+t.width/2<this.srj.bounds.minX||t.center.x-t.width/2>this.srj.bounds.maxX||t.center.y+t.height/2<this.srj.bounds.minY||t.center.y-t.height/2>this.srj.bounds.maxY}isNodePartiallyOutsideBounds(t){if(this.outlinePolygon){let n=this.getNodeRect(t);return!!g4(n,this.outlinePolygon)&&!RD(n,this.outlinePolygon)}return t.center.x-t.width/2<this.srj.bounds.minX||t.center.x+t.width/2>this.srj.bounds.maxX||t.center.y-t.height/2<this.srj.bounds.minY||t.center.y+t.height/2>this.srj.bounds.maxY}getObstacleCoveragePercentage(t){let n=this.getXYZOverlappingObstacles(t);if(n.length===0)return 0;let i=t.center.x-t.width/2,r=t.center.x+t.width/2,o=t.center.y-t.height/2,s=t.center.y+t.height/2,a=t.width*t.height,c=0;for(let l of n){let u=Math.max(i,l.center.x-l.width/2),h=Math.min(r,l.center.x+l.width/2),d=Math.max(o,l.center.y-l.height/2),_=Math.min(s,l.center.y+l.height/2);u<h&&d<_&&(c+=(h-u)*(_-d))}return c/a}shouldFilterSingleLayerNodeForObstacle(t){return t.availableZ.length!==1||!t._containsObstacle?!1:this.getObstacleCoveragePercentage(t)>this.OVERLAP_THRESHOLD_FOR_SINGLE_LAYER_NODES}shouldFilterNodeForObstacle(t){return!!t._containsObstacle&&(t.availableZ.length!==1||this.shouldFilterSingleLayerNodeForObstacle(t))}createChildNodeAtPosition(t,n){let i={capacityMeshNodeId:this.getNextNodeId(),center:n.center,width:n.width,height:n.height,layer:t.layer,availableZ:n.availableZ,_depth:n._depth??(t._depth??0)+1,_parent:t},r=this.getXYZOverlappingObstacles(i);i._containsObstacle=r.length>0||this.isNodePartiallyOutsideBounds(i);let o=this.getTargetIfNodeContainsTarget(i);return o&&(i._targetConnectionName=o.connectionName,i._containsTarget=!0),i._containsObstacle&&(i._completelyInsideObstacle=this.isNodeCompletelyInsideObstacle(i)),i}getZSubdivisionChildNodes(t){if(t.availableZ.length===1)return[];let n=[],i=t.availableZ.map(r=>[r]);for(let r of i){let o=this.createChildNodeAtPosition(t,{center:{...t.center},width:t.width,height:t.height,availableZ:r,_depth:t._depth});this.isNodeCompletelyOutsideBounds(o)||n.push(o)}return n}getChildNodes(t){if(t._depth>=this.MAX_DEPTH)return[];let n=[],i={width:t.width/2,height:t.height/2},r=[{x:t.center.x-i.width/2,y:t.center.y-i.height/2},{x:t.center.x+i.width/2,y:t.center.y-i.height/2},{x:t.center.x-i.width/2,y:t.center.y+i.height/2},{x:t.center.x+i.width/2,y:t.center.y+i.height/2}];for(let o of r){let s=this.createChildNodeAtPosition(t,{center:o,width:i.width,height:i.height,availableZ:t.availableZ});this.isNodeCompletelyOutsideBounds(s)||n.push(s)}return n}shouldNodeBeXYSubdivided(t){return!(t._depth>=this.MAX_DEPTH)&&(!!t._containsTarget||t.availableZ.length===1&&t._depth<=this.MAX_DEPTH||!(!t._containsObstacle||t._completelyInsideObstacle))}_step(){let t=this.unfinishedNodes.pop();if(!t)return void(this.solved=!0);let n=this.getChildNodes(t),i=[],r=[];for(let o of n){let s=this.shouldNodeBeXYSubdivided(o),a=o.availableZ.length>1&&!s&&(o._containsObstacle||o.width<this.VIA_DIAMETER+this.OBSTACLE_MARGIN);if(s)r.push(o);else if(s||this.shouldFilterNodeForObstacle(o)||a)if(!s&&o._containsTarget)if(a){let c=this.getZSubdivisionChildNodes(o);i.push(...c.filter(l=>l._containsTarget||!this.shouldFilterNodeForObstacle(l)))}else i.push(o);else a&&i.push(...this.getZSubdivisionChildNodes(o).filter(c=>!this.shouldFilterNodeForObstacle(c)));else i.push(o)}this.unfinishedNodes.push(...r),this.finishedNodes.push(...i)}};function hf(e){let t=new Map;for(let n of e)for(let i of n.nodeIds)t.set(i,[...t.get(i)??[],n]);return t}var L_t=class extends dn{constructor({nodes:t,edges:n,capacityPaths:i,colorMap:r}){super();T(this,"nodes");T(this,"edges");T(this,"capacityPaths");T(this,"nodeMap");T(this,"nodeEdgeMap");T(this,"unprocessedNodeIds");T(this,"nodePortSegments");T(this,"colorMap");this.nodes=t,this.edges=n,this.nodeMap=new Map(t.map(o=>[o.capacityMeshNodeId,o])),this.nodeEdgeMap=hf(n),this.capacityPaths=i,this.colorMap=r??{},this.unprocessedNodeIds=[...new Set(i.flatMap(o=>o.nodeIds))],this.nodePortSegments=new Map}step(){let t=this.unprocessedNodeIds.pop();if(!t)return void(this.solved=!0);let n=[];for(let s of this.capacityPaths){let a=s.nodeIds.indexOf(t);a!==-1&&n.push({path:s,indexOfNodeInPath:a})}let i=this.nodeMap.get(t),r=[];for(let{path:s,indexOfNodeInPath:a}of n){let c=s.nodeIds[a-1],l=s.nodeIds[a+1];for(let u of[c,l]){let h=this.nodeMap.get(u);if(!h)continue;let d=z_t(i,h),_=h.availableZ.filter(g=>i.availableZ.includes(g));if(_.length===0)continue;let y={capacityMeshNodeId:t,start:d.start,end:d.end,connectionNames:[s.connectionName],availableZ:_};r.push(y)}}let o=(function(s){let a=[],c=s.map(l=>({...l,connectionNames:[...l.connectionNames],availableZ:[...l.availableZ].sort((u,h)=>u-h)}));for(;c.length>0;){let l=c.pop(),u=!1;for(let h=0;h<a.length;h++){let d=a[h],_=jg(d.start,l.start)&&jg(d.end,l.end)||jg(d.start,l.end)&&jg(d.end,l.start),y=F_t(d.availableZ,l.availableZ);if(_&&y){let g=new Set(d.connectionNames);l.connectionNames.forEach(x=>g.add(x)),d.connectionNames=Array.from(g),u=!0;break}}u||a.push(l)}return a})(r);this.nodePortSegments.set(t,o)}visualize(){let t={lines:[],points:[],rects:[],circles:[]};return this.nodePortSegments.forEach((n,i)=>{this.nodeMap.get(i),n.forEach(r=>{r.start.x,r.end.x;for(let o=0;o<r.connectionNames.length;o++){let s={x:.05*Math.max(...r.availableZ),y:.05*Math.max(...r.availableZ)},a={x:(r.start.x+r.end.x)/2,y:(r.start.y+r.end.y)/2},c={x:a.x+s.x,y:a.y+s.y};s.x>0&&t.lines.push({points:[a,c],strokeColor:"rgba(0, 0, 0, 0.25)",strokeDash:"5 5"}),t.points.push({x:c.x,y:c.y,label:`${i}: ${r.connectionNames.join(", ")}
164
164
  availableZ: ${r.availableZ.join(",")}
@@ -241,7 +241,7 @@ ${a._facingDirection??Yf(a,s)}`,x:a.x,y:a.y,color:lo(a.pinId,.8)})}for(let s of
241
241
  ${_.message}`):_}}let s=i.nodes.count()-1;for(let a=0;a<i.V.length;a++){let c=i.V[a];c&&(c.index=s+a)}for(let a of i.S){let c=t.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by switch ${a.name}`);a.model=c,a.isOn=!1}for(let a of i.D){let c=n.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by diode ${a.name}`);a.model=c}return i}var Ge=class Zs{constructor(t=0,n=0){T(this,"re");T(this,"im");this.re=t,this.im=n}static from(t,n=0){return new Zs(t,n)}static fromPolar(t,n=0){let i=n*Math.PI/180;return new Zs(t*Math.cos(i),t*Math.sin(i))}clone(){return new Zs(this.re,this.im)}add(t){return new Zs(this.re+t.re,this.im+t.im)}sub(t){return new Zs(this.re-t.re,this.im-t.im)}mul(t){return new Zs(this.re*t.re-this.im*t.im,this.re*t.im+this.im*t.re)}div(t){let n=t.re*t.re+t.im*t.im;if(n<Vn)throw new Error("Complex divide by ~0");return new Zs((this.re*t.re+this.im*t.im)/n,(this.im*t.re-this.re*t.im)/n)}inv(){let t=this.re*this.re+this.im*this.im;if(t<Vn)throw new Error("Complex invert by ~0");return new Zs(this.re/t,-this.im/t)}abs(){return Math.hypot(this.re,this.im)}phaseDeg(){return Math.atan2(this.im,this.re)*180/Math.PI}};function X2t(e,t){let n=e.length;for(let r=0;r<n;r++){let o=e[r],s=t[r];if(!o||!s)throw new Error("Matrix dimensions mismatch");let a=o.map(c=>c.clone());a.push(s.clone()),e[r]=a}for(let r=0;r<n;r++){let o=r,s=e[r];if(!s)throw new Error("Matrix row missing");let a=s[r]?.abs()??0;for(let u=r+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=h[r]?.abs()??0;d>a&&(a=d,o=u)}if(a<Vn)throw new Error("Singular matrix (complex)");if(o!==r){let u=e[r];e[r]=e[o],e[o]=u}let c=e[r];if(!c)throw new Error("Pivot row missing");let l=c[r];if(!l)throw new Error("Zero pivot encountered");for(let u=r+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=h[r];if(!d)continue;let _=d.div(l);if(!(_.abs()<Vn))for(let y=r;y<=n;y++){let g=h[y],x=c[y];!g||!x||(h[y]=g.sub(_.mul(x)))}}}let i=new Array(n);for(let r=n-1;r>=0;r--){let o=e[r];if(!o)throw new Error("Matrix row missing");let s=o[n];if(!s)throw new Error("Augmented column missing");for(let c=r+1;c<n;c++){let l=o[c],u=i[c];!l||!u||(s=s.sub(l.mul(u)))}let a=o[r];if(!a)throw new Error("Zero pivot on back-substitution");i[r]=s.div(a)}return i}function V2t(e,t,n){if(e<=0||t<=0)throw new Error(".ac frequencies must be > 0");t<e&&([e,t]=[t,e]);let i=Math.log10(t/e),r=Math.max(1,Math.ceil(i*n)),o=[];for(let a=0;a<=r;a++)o.push(e*Math.pow(10,a/n));let s=o[o.length-1];return(s==null||s<t*(1-Vn))&&o.push(t),o}function aI(e,t,n,i,r){let o=t.matrixIndexOfNode(n),s=t.matrixIndexOfNode(i);if(o>=0){let a=e[o];if(!a)throw new Error("Matrix row missing while stamping");a[o]=a[o]?.add(r)??r}if(s>=0){let a=e[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=a[s]?.add(r)??r}if(o>=0&&s>=0){let a=e[o],c=e[s];if(!a||!c)throw new Error("Matrix row missing while stamping");a[s]=a[s]?.sub(r)??Ge.from(0,0).sub(r),c[o]=c[o]?.sub(r)??Ge.from(0,0).sub(r)}}function H2t(e,t,n,i,r){let o=n.matrixIndexOfNode(i.n1),s=n.matrixIndexOfNode(i.n2),a=i.index,c=Ge.from(1,0);if(o>=0){let u=e[o];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.add(c)??c}if(s>=0){let u=e[s];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.sub(c)??Ge.from(0,0).sub(c)}let l=e[a];if(!l)throw new Error("Branch row missing while stamping voltage source");o>=0&&(l[o]=l[o]?.add(c)??c),s>=0&&(l[s]=l[s]?.sub(c)??Ge.from(0,0).sub(c)),t[a]=(t[a]??Ge.from(0,0)).add(r)}function G2t(e){var d,_,y,g;if(!e.analyses.ac)return null;let{mode:t,N:n,f1:i,f2:r}=e.analyses.ac,o=e.nodes.count()-1,s=e.V.length,a=o+s,c=t==="dec"?V2t(i,r,n):(()=>{let x=[],w=Math.max(2,n),S=(r-i)/(w-1);for(let E=0;E<w;E++)x.push(i+E*S);return x})(),l={};e.nodes.rev.forEach((x,w)=>{w!==0&&(l[x]=[])});let u={},h=2*Math.PI;for(let x of c){let w=Array.from({length:a},()=>Array.from({length:a},()=>Ge.from(0,0))),S=Array.from({length:a},()=>Ge.from(0,0));for(let M of e.R){if(M.R<=0)throw new Error(`R ${M.name} must be > 0`);let k=Ge.from(1/M.R,0);aI(w,e.nodes,M.n1,M.n2,k)}for(let M of e.C){let k=Ge.from(0,h*x*M.C);aI(w,e.nodes,M.n1,M.n2,k)}for(let M of e.L){let k=Ge.from(0,h*x*M.L),I=k.abs()<Vn?Ge.from(0,0):Ge.from(1,0).div(k);aI(w,e.nodes,M.n1,M.n2,I)}for(let M of e.V){let k=Ge.fromPolar(M.acMag||0,M.acPhaseDeg||0);H2t(w,S,e.nodes,M,k)}let E=X2t(w,S);for(let M=1;M<e.nodes.count();M++){let k=M-1,I=e.nodes.rev[M];if(!I)continue;let N=l[I];N&&N.push(E[k]??Ge.from(0,0))}for(let M of e.R){let k=M.n1===0?Ge.from(0,0):E[M.n1-1]??Ge.from(0,0),I=M.n2===0?Ge.from(0,0):E[M.n2-1]??Ge.from(0,0),C=Ge.from(1/M.R,0).mul(k.sub(I));(u[d=M.name]||(u[d]=[])).push(C)}for(let M of e.C){let k=M.n1===0?Ge.from(0,0):E[M.n1-1]??Ge.from(0,0),I=M.n2===0?Ge.from(0,0):E[M.n2-1]??Ge.from(0,0),C=Ge.from(0,h*x*M.C).mul(k.sub(I));(u[_=M.name]||(u[_]=[])).push(C)}for(let M of e.L){let k=M.n1===0?Ge.from(0,0):E[M.n1-1]??Ge.from(0,0),I=M.n2===0?Ge.from(0,0):E[M.n2-1]??Ge.from(0,0),N=Ge.from(0,h*x*M.L),A=(N.abs()<Vn?Ge.from(0,0):Ge.from(1,0).div(N)).mul(k.sub(I));(u[y=M.name]||(u[y]=[])).push(A)}for(let M of e.V){let k=E[M.index]??Ge.from(0,0);(u[g=M.name]||(u[g]=[])).push(k)}}return{freqs:c,nodeVoltages:l,elementCurrents:u}}function U2t(e,t){let n=e.length;for(let r=0;r<n;r++){let o=e[r],s=t[r];if(!o||s==null)throw new Error("Matrix dimensions mismatch");let a=o.slice();a.push(s),e[r]=a}for(let r=0;r<n;r++){let o=r,s=e[r];if(!s)throw new Error("Matrix row missing");let a=Math.abs(s[r]??0);for(let u=r+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=Math.abs(h[r]??0);d>a&&(a=d,o=u)}if(a<Vn)throw new Error("Singular matrix (real)");if(o!==r){let u=e[r];e[r]=e[o],e[o]=u}let c=e[r];if(!c)throw new Error("Pivot row missing");let l=c[r];if(l==null)throw new Error("Zero pivot encountered");for(let u=r+1;u<n;u++){let h=e[u];if(!h)throw new Error("Matrix row missing");let d=h[r];if(d==null)continue;let _=d/l;if(!(Math.abs(_)<Vn))for(let y=r;y<=n;y++){let g=h[y],x=c[y];g==null||x==null||(h[y]=g-_*x)}}}let i=new Array(n).fill(0);for(let r=n-1;r>=0;r--){let o=e[r];if(!o)throw new Error("Matrix row missing");let s=o[n];if(s==null)throw new Error("Augmented column missing");for(let c=r+1;c<n;c++){let l=o[c],u=i[c];l==null||u==null||(s-=l*u)}let a=o[r];if(a==null)throw new Error("Zero pivot on back-substitution");i[r]=s/a}return i}function Xf(e,t,n,i,r){let o=t.matrixIndexOfNode(n),s=t.matrixIndexOfNode(i);if(o>=0){let a=e[o];if(!a)throw new Error("Matrix row missing while stamping");a[o]=(a[o]??0)+r}if(s>=0){let a=e[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=(a[s]??0)+r}if(o>=0&&s>=0){let a=e[o],c=e[s];if(!a||!c)throw new Error("Matrix row missing while stamping");a[s]=(a[s]??0)-r,c[o]=(c[o]??0)-r}}function cI(e,t,n,i,r){let o=t.matrixIndexOfNode(n),s=t.matrixIndexOfNode(i);o>=0&&(e[o]=(e[o]??0)-r),s>=0&&(e[s]=(e[s]??0)+r)}function q2t(e,t,n,i,r){let o=n.matrixIndexOfNode(i.n1),s=n.matrixIndexOfNode(i.n2),a=i.index;if(o>=0){let l=e[o];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)+1}if(s>=0){let l=e[s];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)-1}let c=e[a];if(!c)throw new Error("Branch row missing while stamping voltage source");o>=0&&(c[o]=(c[o]??0)+1),s>=0&&(c[s]=(c[s]??0)-1),t[a]=(t[a]??0)+r}function W2t(e){var _,y,g,x,w,S;if(!e.analyses.tran)return null;let{dt:t,tstop:n}=e.analyses.tran,i=t>Vn?t:Math.max(n/1e3,Vn),r=Math.max(1,Math.ceil(n/Math.max(i,Vn))),o=r>0?n/r:n,s=e.nodes.count()-1,a=e.V.length,c=s+a,l=[],u={};e.nodes.rev.forEach((E,M)=>{M!==0&&(u[E]=[])});let h={},d=0;for(let E=0;E<=r;E++,d=E*o){l.push(d);let M=new Array(c).fill(0);for(let k=0;k<20;k++){let I=Array.from({length:c},()=>new Array(c).fill(0)),N=new Array(c).fill(0);for(let O of e.R){let B=1/O.R;Xf(I,e.nodes,O.n1,O.n2,B)}for(let O of e.C){let B=O.C/Math.max(o,Vn);Xf(I,e.nodes,O.n1,O.n2,B);let D=-B*O.vPrev;cI(N,e.nodes,O.n1,O.n2,D)}for(let O of e.L){let B=Math.max(o,Vn)/O.L;Xf(I,e.nodes,O.n1,O.n2,B),cI(N,e.nodes,O.n1,O.n2,O.iPrev)}for(let O of e.S){let B=O.model;if(!B)continue;let D=O.isOn?B.Ron:B.Roff,Y=1/Math.max(Math.abs(D),Vn);Xf(I,e.nodes,O.n1,O.n2,Y)}for(let O of e.V){let B=O.waveform?O.waveform(d):O.dc||0;q2t(I,N,e.nodes,O,B)}let C=.02585;for(let O of e.D){let B=O.model;if(!B)continue;let{nPlus:D,nMinus:X}=O,Y=e.nodes.matrixIndexOfNode(D),H=e.nodes.matrixIndexOfNode(X),K=D===0?0:M[Y]??0,Z=X===0?0:M[H]??0,ut=K-Z,st=k===0?O.vdPrev:ut,it=B.N*C,tt=st;st>.8&&(tt=.8),st<-1&&(tt=-1);let ht=Math.exp(tt/it),gt=B.Is*(ht-1),St=Math.max(B.Is/it*ht,1e-12),Ot=gt-St*tt;Xf(I,e.nodes,D,X,St),cI(N,e.nodes,D,X,Ot)}M=U2t(I,N);let A=!1;for(let O of e.S){let B=O.model;if(!B)continue;let D=O.ncPos===0?0:M[O.ncPos-1]??0,X=O.ncNeg===0?0:M[O.ncNeg-1]??0,Y=D-X,H=O.isOn;O.isOn?Y<B.Voff&&(H=!1):Y>B.Von&&(H=!0),H!==O.isOn&&(O.isOn=H,A=!0)}if(!A||k===19)break}for(let k=1;k<e.nodes.count();k++){let I=k-1,N=e.nodes.rev[k];if(!N)continue;let C=u[N];C&&C.push(M[I]??0)}for(let k of e.R){let I=k.n1===0?0:M[k.n1-1]??0,N=k.n2===0?0:M[k.n2-1]??0,C=(I-N)/k.R;(h[_=k.name]||(h[_]=[])).push(C)}for(let k of e.C){let I=k.n1===0?0:M[k.n1-1]??0,N=k.n2===0?0:M[k.n2-1]??0,C=k.C*(I-N-k.vPrev)/Math.max(o,Vn);(h[y=k.name]||(h[y]=[])).push(C)}for(let k of e.L){let I=k.n1===0?0:M[k.n1-1]??0,N=k.n2===0?0:M[k.n2-1]??0,A=Math.max(o,Vn)/k.L*(I-N)+k.iPrev;(h[g=k.name]||(h[g]=[])).push(A)}for(let k of e.V){let I=M[k.index]??0;(h[x=k.name]||(h[x]=[])).push(I)}for(let k of e.S){let I=k.model;if(!I)continue;let N=k.n1===0?0:M[k.n1-1]??0,C=k.n2===0?0:M[k.n2-1]??0,A=k.isOn?I.Ron:I.Roff,O=Math.max(Math.abs(A),Vn),B=(N-C)/O;(h[w=k.name]||(h[w]=[])).push(B)}for(let k of e.D){if(!k.model)continue;let{nPlus:I,nMinus:N,model:C}=k,A=I===0?0:M[I-1]??0,O=N===0?0:M[N-1]??0,B=A-O,X=C.N*.02585,Y=Math.exp(B/X),H=C.Is*(Y-1);(h[S=k.name]||(h[S]=[])).push(H)}for(let k of e.C){let I=k.n1===0?0:M[k.n1-1]??0,N=k.n2===0?0:M[k.n2-1]??0;k.vPrev=I-N}for(let k of e.L){let I=k.n1===0?0:M[k.n1-1]??0,N=k.n2===0?0:M[k.n2-1]??0,C=Math.max(o,Vn)/k.L;k.iPrev=C*(I-N)+k.iPrev}for(let k of e.D){let I=k.nPlus===0?0:M[k.nPlus-1]??0,N=k.nMinus===0?0:M[k.nMinus-1]??0;k.vdPrev=I-N}}if(e.probes.tran.length>0){let E={},M=e.probes.tran.map(k=>k.toUpperCase());for(let k in u)M.includes(k.toUpperCase())&&(E[k]=u[k]);return{times:l,nodeVoltages:E,elementCurrents:h}}return{times:l,nodeVoltages:u,elementCurrents:h}}function sY(e){let t=Y2t(e),n=G2t(t),i=W2t(t);return{circuit:t,ac:n,tran:i}}function aY(e,t,n){if(!e||!t.analyses.tran)return[];let{dt:i,tstop:r}=t.analyses.tran,{times:o,nodeVoltages:s}=e,a=[];for(let c in s){let l=s[c];a.push({type:"simulation_transient_voltage_graph",simulation_transient_voltage_graph_id:`stvg_${n}_${c}`,simulation_experiment_id:n,timestamps_ms:o.map(u=>u*1e3),voltage_levels:l,time_per_step:i*1e3,start_time_ms:0,end_time_ms:r*1e3,name:`${c} (spicey)`})}return a}yi();Ce();yi();Ce();Ce();vt();Ce();Ce();Ho();Ce();yi();Ce();yi();Ce();Ce();yi();Ce();function cY(e,t,n,i){return Math.sqrt((n-e)**2+(i-t)**2)}var Z2t=e=>{let t=e.filter(o=>o.type==="pcb_port"),n=e.filter(o=>o.type==="pcb_smtpad"),i=e.filter(o=>o.type==="pcb_trace");function r(o,s={}){let a=s.traceWidth||0,c=t.find(l=>cY(l.x,l.y,o.x,o.y)<.01);if(c)return c.pcb_port_id;if(s.isFirstOrLastPoint){let l=n.find(u=>{if(u.shape==="rect")return Math.abs(o.x-u.x)<u.width/2+a/2&&Math.abs(o.y-u.y)<u.height/2+a/2;if(u.shape==="circle")return cY(o.x,o.y,u.x,u.y)<u.radius});if(l)return l.pcb_port_id??null}return null}for(let o of i)for(let s=0;s<o.route.length;s++){let a=o.route[s],c=s===0||s===o.route.length-1;if(a.route_type==="wire"){if(!a.start_pcb_port_id&&s===0){let l=r(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.start_pcb_port_id=l)}if(!a.end_pcb_port_id&&s===o.route.length-1){let l=r(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.end_pcb_port_id=l)}}}};function uY(e){Z2t(e);let t=e.filter(s=>s.type==="source_trace"),n=e.filter(s=>s.type==="pcb_port"),i=[],r=si(e),o=new Map;for(let s of n)o.set(s.source_port_id,s);for(let s of t){let a=s.connected_source_port_ids;if(a.length<2)continue;let c=[],l=[];for(let y of a){let g=o.get(y);g?c.push(g):l.push(y)}if(c.length<2)continue;let u=c[0],h=r.getNetConnectedToId(u.pcb_port_id);r.getIdsConnectedToNet(h).filter(y=>e.some(g=>g.type==="pcb_trace"&&("pcb_trace_id"in g&&g.pcb_trace_id===y||"route_id"in g&&g.route_id===y))).length===0&&new Set(c.map(g=>g.pcb_component_id)).size>1&&i.push({type:"pcb_port_not_connected_error",message:`pcb_port_not_connected_error: Pcb ports [${c.map(g=>g.pcb_port_id).join(", ")}] are not connected together through the same net.`,error_type:"pcb_port_not_connected_error",pcb_port_ids:c.map(g=>g.pcb_port_id),pcb_component_ids:c.map(g=>g.pcb_component_id),pcb_port_not_connected_error_id:`pcb_port_not_connected_error_trace_${s.source_trace_id}`})}return i}var K2t=class{constructor({objects:e,getBounds:t,getId:n,CELL_SIZE:i}){T(this,"buckets");T(this,"objectsById");T(this,"getBounds");T(this,"getId");T(this,"CELL_SIZE",.4);T(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=t,this.getId=n??(()=>this._getNextId()),this.CELL_SIZE=i??this.CELL_SIZE;for(let r of e)this.addObject(r)}_getNextId(){return`${this._idCounter++}`}addObject(e){let t=this.getBounds(e),n=this.getId(e),i={...e,spatialIndexId:n};this.objectsById.set(n,i);let r=Math.floor(t.minX/this.CELL_SIZE),o=Math.floor(t.minY/this.CELL_SIZE),s=Math.floor(t.maxX/this.CELL_SIZE),a=Math.floor(t.maxY/this.CELL_SIZE);for(let c=r;c<=s;c++)for(let l=o;l<=a;l++){let u=`${c}x${l}`,h=this.buckets.get(u);h?h.push(i):this.buckets.set(u,[i])}}removeObject(e){let t=this.objectsById.get(e);if(!t)return!1;this.objectsById.delete(e);let n=this.getBounds(t),i=Math.floor(n.minX/this.CELL_SIZE),r=Math.floor(n.minY/this.CELL_SIZE),o=Math.floor(n.maxX/this.CELL_SIZE),s=Math.floor(n.maxY/this.CELL_SIZE);for(let a=i;a<=o;a++)for(let c=r;c<=s;c++){let l=`${a}x${c}`,u=this.buckets.get(l);if(u){let h=u.findIndex(d=>d.spatialIndexId===e);h!==-1&&(u.splice(h,1),u.length===0&&this.buckets.delete(l))}}return!0}getBucketKey(e,t){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(t/this.CELL_SIZE)}`}getObjectsInBounds(e,t=0){let n=[],i=new Set,r=Math.floor((e.minX-t)/this.CELL_SIZE),o=Math.floor((e.minY-t)/this.CELL_SIZE),s=Math.floor((e.maxX+t)/this.CELL_SIZE),a=Math.floor((e.maxY+t)/this.CELL_SIZE);for(let c=r;c<=s;c++)for(let l=o;l<=a;l++){let u=`${c}x${l}`,h=this.buckets.get(u)||[];for(let d of h){let _=d.spatialIndexId;i.has(_)||(i.add(_),n.push(d))}}return n}},Vf=e=>e.type==="pcb_trace_segment"?{minX:Math.min(e.x1,e.x2),minY:Math.min(e.y1,e.y2),maxX:Math.max(e.x1,e.x2),maxY:Math.max(e.y1,e.y2)}:$p([e]),lI=.1,J2t=.15;var Q2t=.2,tvt=.3,Hf=.005;function evt(e){let t=new Set;for(let n of e.route)n.route_type==="wire"&&(n.start_pcb_port_id&&t.add(n.start_pcb_port_id),n.end_pcb_port_id&&t.add(n.end_pcb_port_id));return Array.from(t)}function uI(e){let t=new Set;for(let n of e)for(let i of evt(n))t.add(i);return Array.from(t)}var nvt=(e,t)=>{let n={x:e.x1,y:e.y1},i={x:e.x2,y:e.y2},r={x:t.x1,y:t.y1},o={x:t.x2,y:t.y2},s={x:i.x-n.x,y:i.y-n.y},a={x:o.x-r.x,y:o.y-r.y},c=s.x*s.x+s.y*s.y,l=a.x*a.x+a.y*a.y;if(c===0||l===0){if(c===0&&l===0)return{x:(n.x+r.x)/2,y:(n.y+r.y)/2};if(c===0){let B=rs(((n.x-r.x)*a.x+(n.y-r.y)*a.y)/l,0,1),D={x:r.x+B*a.x,y:r.y+B*a.y};return{x:(n.x+D.x)/2,y:(n.y+D.y)/2}}let A=rs(((r.x-n.x)*s.x+(r.y-n.y)*s.y)/c,0,1),O={x:n.x+A*s.x,y:n.y+A*s.y};return{x:(O.x+r.x)/2,y:(O.y+r.y)/2}}let u={x:n.x-r.x,y:n.y-r.y},h=s.x*s.x+s.y*s.y,d=s.x*a.x+s.y*a.y,_=s.x*u.x+s.y*u.y,y=a.x*a.x+a.y*a.y,g=a.x*u.x+a.y*u.y,x=h*y-d*d;if(x<1e-10)return ivt(n,i,r,o,s,a,c,l);let w=(d*g-y*_)/x,S=(h*g-d*_)/x;w=rs(w,0,1),S=rs(S,0,1),S=(w*d+g)/y,S=rs(S,0,1),w=(S*d-_)/h,w=rs(w,0,1);let E={x:n.x+w*s.x,y:n.y+w*s.y},M={x:r.x+S*a.x,y:r.y+S*a.y},k=E.x-M.x,I=E.y-M.y,N=Math.sqrt(k*k+I*I);return{x:(E.x+M.x)/2,y:(E.y+M.y)/2}},ivt=(e,t,n,i,r,o,s,a)=>{let c=((n.x-e.x)*r.x+(n.y-e.y)*r.y)/s;c=rs(c,0,1);let l={x:e.x+c*r.x,y:e.y+c*r.y},u=((i.x-e.x)*r.x+(i.y-e.y)*r.y)/s;u=rs(u,0,1);let h={x:e.x+u*r.x,y:e.y+u*r.y},d=((e.x-n.x)*o.x+(e.y-n.y)*o.y)/a;d=rs(d,0,1);let _={x:n.x+d*o.x,y:n.y+d*o.y},y=((t.x-n.x)*o.x+(t.y-n.y)*o.y)/a;y=rs(y,0,1);let g={x:n.x+y*o.x,y:n.y+y*o.y},w=[{pointA:l,pointB:n,distance:Math.sqrt((l.x-n.x)**2+(l.y-n.y)**2)},{pointA:h,pointB:i,distance:Math.sqrt((h.x-i.x)**2+(h.y-i.y)**2)},{pointA:e,pointB:_,distance:Math.sqrt((e.x-_.x)**2+(e.y-_.y)**2)},{pointA:t,pointB:g,distance:Math.sqrt((t.x-g.x)**2+(t.y-g.y)**2)}].reduce((S,E)=>E.distance<S.distance?E:S);return{x:(w.pointA.x+w.pointB.x)/2,y:(w.pointA.y+w.pointB.y)/2}},rs=(e,t,n)=>Math.max(t,Math.min(n,e)),rvt=e=>{if(e.type==="pcb_via"||e.type==="pcb_plated_hole"&&e.shape==="circle")return e.outer_diameter/2;if(e.type==="pcb_hole"&&e.hole_shape==="circle")return e.hole_diameter/2;if(e.type==="pcb_smtpad"&&e.shape==="circle")return e.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(e)}`)},lY=(e,t)=>{let n={x:e.x1,y:e.y1},i={x:e.x2,y:e.y2},r=t.minX,o=t.minY,s=t.maxX,a=t.maxY;if(n.x===i.x&&n.y===i.y){let C=Math.max(r,Math.min(s,n.x)),A=Math.max(o,Math.min(a,n.y));return C===n.x&&A===n.y?{x:n.x,y:n.y}:{x:C,y:A}}let c=i.x-n.x,l=i.y-n.y,u=c!==0?(r-n.x)/c:Number.NEGATIVE_INFINITY,h=c!==0?(s-n.x)/c:Number.POSITIVE_INFINITY,d=l!==0?(o-n.y)/l:Number.NEGATIVE_INFINITY,_=l!==0?(a-n.y)/l:Number.POSITIVE_INFINITY,y=Math.max(Math.min(u,h),Math.min(d,_)),g=Math.min(Math.max(u,h),Math.max(d,_));if(y<=g&&g>=0&&y<=1){let C=Math.max(0,Math.min(1,y));return{x:n.x+C*c,y:n.y+C*l}}let x={x:Math.max(r,Math.min(s,n.x)),y:Math.max(o,Math.min(a,n.y))},w={x:Math.max(r,Math.min(s,i.x)),y:Math.max(o,Math.min(a,i.y))},S=(x.x-n.x)**2+(x.y-n.y)**2,E=(w.x-i.x)**2+(w.y-i.y)**2,M=[{start:{x:r,y:o},end:{x:s,y:o}},{start:{x:s,y:o},end:{x:s,y:a}},{start:{x:s,y:a},end:{x:r,y:a}},{start:{x:r,y:a},end:{x:r,y:o}}],k=Math.min(S,E),I=S<=E?x:w,N=(C,A,O)=>Math.max(A,Math.min(O,C));for(let C of M){let A={x:i.x-n.x,y:i.y-n.y},O={x:C.end.x-C.start.x,y:C.end.y-C.start.y},B={x:n.x-C.start.x,y:n.y-C.start.y},D=A.x*A.x+A.y*A.y,X=A.x*O.x+A.y*O.y,Y=A.x*B.x+A.y*B.y,H=O.x*O.x+O.y*O.y,K=O.x*B.x+O.y*B.y,Z=D*H-X*X;if(Math.abs(Z)<1e-10)continue;let ut=(X*K-H*Y)/Z,st=(D*K-X*Y)/Z;ut=N(ut,0,1),st=N(st,0,1);let it={x:n.x+ut*A.x,y:n.y+ut*A.y},tt={x:C.start.x+st*O.x,y:C.start.y+st*O.y},ht=it.x-tt.x,gt=it.y-tt.y,St=ht*ht+gt*gt;St<k&&(k=St,I={x:(it.x+tt.x)/2,y:(it.y+tt.y)/2})}return I};function ovt(e){return e.type==="pcb_trace_segment"?[e.layer]:e.type==="pcb_smtpad"?[e.layer]:e.type==="pcb_plated_hole"?Array.isArray(e.layers)?e.layers:[...hp]:e.type==="pcb_hole"?[...hp]:e.type==="pcb_via"?Array.isArray(e.layers)?e.layers:[...hp]:e.type==="pcb_keepout"?Array.isArray(e.layers)?e.layers:[]:[]}function pY(e,{connMap:t}={}){let n=[];t??(t=si(e));let r=We(e).pcb_trace.list().flatMap(y=>{let g=[];for(let x=0;x<y.route.length-1;x++){let w=y.route[x],S=y.route[x+1];w.route_type==="wire"&&S.route_type==="wire"&&w.layer===S.layer&&g.push({type:"pcb_trace_segment",pcb_trace_id:y.pcb_trace_id,_pcbTrace:y,thickness:"width"in w?w.width:"width"in S?S.width:J2t,layer:w.layer,x1:w.x,y1:w.y,x2:S.x,y2:S.y})}return g}),o=We(e).pcb_smtpad.list(),s=We(e).pcb_plated_hole.list(),a=We(e).pcb_hole.list(),c=We(e).pcb_via.list(),l=We(e).pcb_keepout.list(),u=[...r,...o,...s,...a,...c,...l],h=new K2t({objects:u,getBounds:Vf}),d=y=>so(e,y),_=new Set;for(let y of r){let g=lI,x=Vf(y),w=h.getObjectsInBounds(x,g+y.thickness/2);if(!(y.x1===y.x2&&y.y1===y.y2))for(let S of w){if(!ovt(S).includes(y.layer))continue;if(S.type==="pcb_trace_segment"){let I=S;if(y.layer!==I.layer||t.areIdsConnected(y.pcb_trace_id,I.pcb_trace_id))continue;let N=Fp({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},{x:I.x1,y:I.y1},{x:I.x2,y:I.y2})-y.thickness/2-I.thickness/2;if(N>lI-Hf)continue;let C=`overlap_${y.pcb_trace_id}_${I.pcb_trace_id}`,A=`overlap_${I.pcb_trace_id}_${y.pcb_trace_id}`;if(_.has(C)||_.has(A))continue;_.add(C),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(y.pcb_trace_id)} overlaps with ${d(I.pcb_trace_id)} ${N<0?"(accidental contact)":`(gap: ${N.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:C,pcb_component_ids:[],center:nvt(y,I),pcb_port_ids:uI([y._pcbTrace,I._pcbTrace])});continue}let E=Uo(S);if(t.areIdsConnected(y.pcb_trace_id,"pcb_trace_id"in S?S.pcb_trace_id:E))continue;if(S.type==="pcb_via"||S.type==="pcb_plated_hole"&&S.shape==="circle"||S.type==="pcb_hole"||S.type==="pcb_smtpad"&&S.shape==="circle"){let I=rvt(S),C=Cg({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},{x:S.x,y:S.y,radius:I})-y.thickness/2;if(C>lI-Hf)continue;let A=`overlap_${y.pcb_trace_id}_${E}`;if(_.has(A))continue;_.add(A),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(y.pcb_trace_id)} overlaps with ${S.type} "${d(Uo(S))}" ${C<0?"(accidental contact)":`(gap: ${C.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,center:lY(y,Vf(S)),source_trace_id:"",pcb_trace_error_id:A,pcb_component_ids:["pcb_component_id"in S?S.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...uI([y._pcbTrace]),"pcb_port_id"in S?S.pcb_port_id:void 0].filter(Boolean)})}let k=tf({x:y.x1,y:y.y1},{x:y.x2,y:y.y2},Vf(S))-y.thickness/2;if(k+Hf<g){let I=`overlap_${y.pcb_trace_id}_${E}`;if(_.has(I))continue;_.add(I),n.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${d(y.pcb_trace_id)} overlaps with ${S.type} "${d(Uo(S))}" ${k<0?"(accidental contact)":`(gap: ${k.toFixed(3)}mm)`}`,pcb_trace_id:y.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:I,pcb_component_ids:["pcb_component_id"in S?S.pcb_component_id:void 0].filter(Boolean),center:lY(y,Vf(S)),pcb_port_ids:[...uI([y._pcbTrace]),"pcb_port_id"in S?S.pcb_port_id:void 0].filter(Boolean)})}}}return n}function hY(e){return e.area()>=0}function dY({center:e,size:t,rotationDeg:n=0}){let i=e.x,r=e.y,o=t.width/2,s=t.height/2,a=[new ns(i-o,r-s),new ns(i+o,r-s),new ns(i+o,r+s),new ns(i-o,r+s)],c=new Ff(a);if(n){let l=fg(n,i,r),u=a.map(h=>{let d=mn(l,{x:h.x,y:h.y});return new ns(d.x,d.y)});c=new Ff(u)}return hY(c)||c.reverse(),c}function svt({board:e}){if(e.outline&&e.outline.length>0){let t=e.outline.map(i=>new ns(i.x,i.y)),n=new Ff(t);return hY(n)||n.reverse(),n}return e.center&&typeof e.width=="number"&&typeof e.height=="number"?dY({center:e.center,size:{width:e.width,height:e.height},rotationDeg:0}):null}function avt({circuitJson:e,component:t}){if(t.source_component_id){let n=e.find(i=>i.type==="source_component"&&i.source_component_id===t.source_component_id);if(n&&"name"in n&&n.name)return n.name}return so(e,t.pcb_component_id)||"Unknown"}function cvt(e,t,n,i,r,o){let s=new ns(n.x,n.y);if(!t.contains(s)){let g=t.distanceTo(s);return Array.isArray(g)?g[0]:Number(g)||0}let a=i/2,c=r/2,l=[{x:n.x-a,y:n.y-c},{x:n.x+a,y:n.y-c},{x:n.x+a,y:n.y+c},{x:n.x-a,y:n.y+c}],u=[];for(let g=0;g<4;g++){let x=(g+1)%4;u.push({x:(l[g].x+l[x].x)/2,y:(l[g].y+l[x].y)/2})}let h=fg(o,n.x,n.y),d=g=>{let x=mn(h,g);return new ns(x.x,x.y)},_=l.concat(u).map(d),y=0;for(let g of _)if(!t.contains(g)){let x=t.distanceTo(g),w=Array.isArray(x)?x[0]:Number(x)||0;w>y&&(y=w)}if(y>0)return y;try{let g=FT.intersect(e,t),x=0;g?Array.isArray(g)?x=g.reduce((S,E)=>S+(typeof E.area=="function"?E.area():0),0):typeof g.area=="function"?x=g.area():x=0:x=0;let w=e.area();if(x>0&&x<w){let S=1-x/w,E=Math.abs(i),M=Math.abs(r);return Math.min(E,M)*S}else return .1}catch{return .1}}function fY(e){let t=e.find(o=>o.type==="pcb_board");if(!t)return[];let n=svt({board:t});if(!n)return[];let i=e.filter(o=>o.type==="pcb_component");if(i.length===0)return[];let r=[];for(let o of i){if(!o.center||typeof o.width!="number"||typeof o.height!="number"||o.width<=0||o.height<=0)continue;let s=dY({center:o.center,size:{width:o.width,height:o.height},rotationDeg:o.rotation||0});if(s.area()===0||n.contains(s))continue;let c=cvt(s,n,o.center,o.width,o.height,o.rotation||0),l=avt({circuitJson:e,component:o}),u=Math.round(c*100)/100;r.push({type:"pcb_component_outside_board_error",error_type:"pcb_component_outside_board_error",pcb_component_outside_board_error_id:`pcb_component_outside_board_${o.pcb_component_id}`,message:`Component ${l} (${o.pcb_component_id}) extends outside board boundaries by ${u}mm`,pcb_component_id:o.pcb_component_id,pcb_board_id:t.pcb_board_id,component_center:o.center,component_bounds:{min_x:s.box.xmin,max_x:s.box.xmax,min_y:s.box.ymin,max_y:s.box.ymax},subcircuit_id:o.subcircuit_id,source_component_id:o.source_component_id})}return r}function lvt(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function mY(e,{connMap:t,minSpacing:n=Q2t}={}){let i=e.filter(s=>s.type==="pcb_via");if(i.length<2)return[];t??(t=si(e));let r=[],o=new Set;for(let s=0;s<i.length;s++)for(let a=s+1;a<i.length;a++){let c=i[s],l=i[a];if(!t.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=lvt(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+Hf>=n)continue;let h=[c.pcb_via_id,l.pcb_via_id].sort().join("_");o.has(h)||(o.add(h),r.push({type:"pcb_via_clearance_error",pcb_error_id:`same_net_vias_close_${h}`,message:`Vias ${so(e,c.pcb_via_id)} and ${so(e,l.pcb_via_id)} are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:n,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return r}function uvt(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function _Y(e,{connMap:t,minSpacing:n=tvt}={}){let i=e.filter(s=>s.type==="pcb_via");if(i.length<2)return[];t??(t=si(e));let r=[],o=new Set;for(let s=0;s<i.length;s++)for(let a=s+1;a<i.length;a++){let c=i[s],l=i[a];if(t.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=uvt(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+Hf>=n)continue;let h=[c.pcb_via_id,l.pcb_via_id].sort().join("_");o.has(h)||(o.add(h),r.push({type:"pcb_via_clearance_error",pcb_error_id:`different_net_vias_close_${h}`,message:`Vias ${so(e,c.pcb_via_id)} and ${so(e,l.pcb_via_id)} from different nets are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:n,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return r}var pvt=.2;function hvt(e){if(e.outline&&e.outline.length>0)return e.outline.map(t=>({x:t.x,y:t.y}));if(e.center&&typeof e.width=="number"&&typeof e.height=="number"){let t=e.center.x,n=e.center.y,i=e.width/2,r=e.height/2;return[{x:t-i,y:n-r},{x:t+i,y:n-r},{x:t+i,y:n+r},{x:t-i,y:n+r}]}return null}function yY(e,t={}){let n=[],i=t.margin??pvt,r=e.find(a=>a.type==="pcb_board");if(!r)return n;let o=hvt(r);if(!o)return n;let s=We(e).pcb_trace.list();for(let a of s)if(!(a.route.length<2))for(let c=0;c<a.route.length-1;c++){let l=a.route[c],u=a.route[c+1];if(l.route_type!=="wire"||u.route_type!=="wire")continue;let h="width"in l?l.width:"width"in u?u.width:.1,d={x:l.x,y:l.y},_={x:u.x,y:u.y},y=1/0;for(let x=0;x<o.length;x++){let w=o[x],S=o[(x+1)%o.length],E=Fp(d,_,w,S);E<y&&(y=E)}let g=h/2+i;if(y<g){let x={type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:`trace_too_close_to_board_${a.pcb_trace_id}_segment_${c}`,message:`Trace too close to board edge (${y.toFixed(3)}mm < ${g.toFixed(3)}mm required, margin: ${i}mm)`,pcb_trace_id:a.pcb_trace_id,source_trace_id:a.source_trace_id||"",center:{x:(d.x+_.x)/2,y:(d.y+_.y)/2},pcb_component_ids:[],pcb_port_ids:[]};n.push(x)}}return n}function dvt(e,t){let n=$p([e]),i=$p([t]);return Ka(n,i)}function gY(e){let t=[],n=si(e),i=We(e).pcb_smtpad.list(),r=We(e).pcb_plated_hole.list(),o=We(e).pcb_hole.list(),s=new Map;for(let c of i){let l=c.pcb_component_id||`standalone_pad_${Uo(c)}`;s.has(l)||s.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),s.get(l).elements.push(c)}for(let c of r){let l=c.pcb_component_id||`standalone_plated_hole_${Uo(c)}`;s.has(l)||s.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),s.get(l).elements.push(c)}for(let c of o){let l=`standalone_hole_${Uo(c)}`;s.set(l,{component_id:l,elements:[c],bounds:{minX:0,minY:0,maxX:0,maxY:0}})}for(let[c,l]of s)l.elements.length>0&&(l.bounds=$p(l.elements));let a=Array.from(s.values());for(let c=0;c<a.length;c++)for(let l=c+1;l<a.length;l++){let u=a[c],h=a[l];if(Ka(u.bounds,h.bounds))for(let d of u.elements)for(let _ of h.elements){let y=Uo(d),g=Uo(_);if(!(d.type==="pcb_smtpad"&&_.type==="pcb_smtpad"&&n.areIdsConnected(y,g))&&dvt(d,_)){let x={type:"pcb_footprint_overlap_error",pcb_error_id:`pcb_footprint_overlap_${y}_${g}`,error_type:"pcb_footprint_overlap_error",message:`PCB component ${d.type} "${y}" overlaps with ${_.type} "${g}"`};(d.type==="pcb_smtpad"||_.type==="pcb_smtpad")&&(x.pcb_smtpad_ids=[],d.type==="pcb_smtpad"&&x.pcb_smtpad_ids.push(y),_.type==="pcb_smtpad"&&x.pcb_smtpad_ids.push(g)),(d.type==="pcb_plated_hole"||_.type==="pcb_plated_hole")&&(x.pcb_plated_hole_ids=[],d.type==="pcb_plated_hole"&&x.pcb_plated_hole_ids.push(y),_.type==="pcb_plated_hole"&&x.pcb_plated_hole_ids.push(g)),(d.type==="pcb_hole"||_.type==="pcb_hole")&&(x.pcb_hole_ids=[],d.type==="pcb_hole"&&x.pcb_hole_ids.push(y),_.type==="pcb_hole"&&x.pcb_hole_ids.push(g)),t.push(x)}}}return t}var pI=[{value:1e12,symbol:"T"},{value:1e9,symbol:"G"},{value:1e6,symbol:"M"},{value:1e3,symbol:"k"},{value:1,symbol:""},{value:.001,symbol:"m"},{value:1e-6,symbol:"\xB5"},{value:1e-9,symbol:"n"},{value:1e-12,symbol:"p"}];function ti(e){if(e==null)return"";if(e===0)return"0";let t=Math.abs(e),n=pI.find(o=>{let s=t/o.value;return s>=1&&s<1e3})||pI[pI.length-1],r=(e/n.value).toPrecision(3);return r.includes(".")&&!/\.0+$/.test(r)&&(r=r.replace(/0+$/,"")),r=r.replace(/\.0+$/,""),`${r}${n.symbol}`}vt();W();ef();yi();Ls();Ce();var vH=Yt(vo(),1);var YI=Yt(Mn(),1),wh=Yt(vo(),1),UJt=Yt(vo(),1);var Kl=Yt(Gl(),1);var wH=Yt(Gl(),1),SH=Yt(Gl(),1);var PH=Yt(Gl(),1);var TH=Yt(Gl(),1);var IH=Yt(Gl(),1),MH=Yt(vo(),1);var QSt=Object.defineProperty,tPt=(e,t)=>{for(var n in t)QSt(e,n,{get:t[n],enumerable:!0})},ZX={};tPt(ZX,{AnalogSimulation:()=>bH,Battery:()=>JV,Board:()=>SV,Breakout:()=>VV,BreakoutPoint:()=>HV,CadAssembly:()=>uV,CadModel:()=>lV,Capacitor:()=>PV,Chip:()=>px,Constraint:()=>OV,CopperPour:()=>KV,Crystal:()=>rH,Cutout:()=>am,Diode:()=>IV,FabricationNoteDimension:()=>DV,FabricationNotePath:()=>zV,FabricationNoteRect:()=>LV,FabricationNoteText:()=>FV,Footprint:()=>aV,Fuse:()=>MV,Group:()=>Th,Hole:()=>sm,Inductor:()=>eH,Jumper:()=>EV,Keepout:()=>ix,Led:()=>kV,Mosfet:()=>sH,Net:()=>HI,NetLabel:()=>GV,NormalComponent:()=>On,PcbNoteDimension:()=>YV,PcbNoteLine:()=>$V,PcbNotePath:()=>jV,PcbNoteRect:()=>BV,PcbTrace:()=>qI,PinHeader:()=>QV,Pinout:()=>TV,PlatedHole:()=>Sh,Port:()=>Di,Potentiometer:()=>nH,PowerSource:()=>NV,PrimitiveComponent:()=>be,PushButton:()=>iH,Renderable:()=>XI,Resistor:()=>RV,Resonator:()=>tH,SchematicArc:()=>hH,SchematicBox:()=>fH,SchematicCell:()=>yH,SchematicCircle:()=>dH,SchematicLine:()=>uH,SchematicRect:()=>pH,SchematicRow:()=>_H,SchematicTable:()=>mH,SchematicText:()=>lH,SilkscreenCircle:()=>UV,SilkscreenLine:()=>WV,SilkscreenPath:()=>UI,SilkscreenRect:()=>qV,SilkscreenText:()=>ax,SmtPad:()=>nx,SolderJumper:()=>CV,Subcircuit:()=>XV,Switch:()=>aH,Symbol:()=>gH,TestPoint:()=>cH,Trace:()=>ko,TraceHint:()=>KI,Transistor:()=>oH,Via:()=>ZV,VoltageProbe:()=>xH,VoltageSource:()=>AV});var ePt=(0,QX.default)("tscircuit:renderable"),ta=["ReactSubtreesRender","SourceNameDuplicateComponentRemoval","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","AssignFallbackProps","CreateTracesFromProps","CreateTracesFromNetLabels","CreateTraceHintsFromProps","SourceGroupRender","AssignNameToUnnamedComponents","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SourceDesignRuleChecks","SimulationRender","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicComponentSizeCalculation","SchematicLayout","SchematicTraceRender","SchematicReplaceNetLabelsWithSymbols","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbComponentSizeCalculation","PcbComponentAnchorAlignment","PcbLayout","PcbBoardAutoSize","PcbTraceHintRender","PcbManualTraceRender","PcbTraceRender","PcbRouteNetIslands","PcbCopperPourRender","PcbDesignRuleChecks","SilkscreenOverlapAdjustment","CadModelRender","PartsEngineRender","SimulationSpiceEngineRender"],nPt={PcbFootprintLayout:["PcbFootprintStringRender"],PcbComponentSizeCalculation:["PcbFootprintStringRender"],PcbLayout:["PcbFootprintStringRender"],PcbBoardAutoSize:["PcbFootprintStringRender"],PcbTraceHintRender:["PcbFootprintStringRender"],PcbManualTraceRender:["PcbFootprintStringRender"],PcbCopperPourRender:["PcbFootprintStringRender","PcbTraceRender","PcbRouteNetIslands"],PcbTraceRender:["PcbFootprintStringRender"],PcbRouteNetIslands:["PcbFootprintStringRender"],PcbDesignRuleChecks:["PcbFootprintStringRender"],SilkscreenOverlapAdjustment:["PcbFootprintStringRender"],CadModelRender:["PcbFootprintStringRender"],PartsEngineRender:["PcbFootprintStringRender"],PcbComponentAnchorAlignment:["PcbFootprintStringRender"]},iPt=0,XI=class{constructor(e){T(this,"renderPhaseStates");T(this,"shouldBeRemoved",!1);T(this,"children");T(this,"isPcbPrimitive",!1);T(this,"isSchematicPrimitive",!1);T(this,"_renderId");T(this,"_currentRenderPhase",null);T(this,"_asyncEffects",[]);T(this,"parent",null);this._renderId=`${iPt++}`,this.children=[],this.renderPhaseStates={};for(let t of ta)this.renderPhaseStates[t]={initialized:!1,dirty:!1}}_markDirty(e){this.renderPhaseStates[e].dirty=!0;let t=ta.indexOf(e);for(let n=t+1;n<ta.length;n++)this.renderPhaseStates[ta[n]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(e)}_queueAsyncEffect(e,t){let n={promise:t(),phase:this._currentRenderPhase,effectName:e,complete:!1};this._asyncEffects.push(n),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:e,componentDisplayName:this.getString(),phase:n.phase}),n.promise.then(()=>{n.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:n.phase})}).catch(i=>{console.error(`Async effect error in ${n.phase} "${e}":
242
242
  ${i.stack}`),n.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:n.phase,error:i.toString()})})}_emitRenderLifecycleEvent(e,t){ePt(`${e}:${t} ${this.getString()}`);let n=`renderable:renderLifecycle:${e}:${t}`,i={renderId:this._renderId,componentDisplayName:this.getString(),type:n};"root"in this&&this.root&&(this.root.emit(n,i),this.root.emit("renderable:renderLifecycle:anyEvent",{...i,type:n}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(e=>!e.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(e){for(let t of this._asyncEffects)if(!t.complete&&t.phase===e)return!0;for(let t of this.children)if(t._hasIncompleteAsyncEffectsInSubtreeForPhase(e))return!0;return!1}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(e=>e.getRenderGraph())}}runRenderCycle(){for(let e of ta)this.runRenderPhaseForChildren(e),this.runRenderPhase(e)}runRenderPhase(e){this._currentRenderPhase=e;let t=this.renderPhaseStates[e],n=t.initialized,i=t.dirty;if(!n&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&n){this._emitRenderLifecycleEvent(e,"start"),this?.[`remove${e}`]?.(),t.initialized=!1,t.dirty=!1,this._emitRenderLifecycleEvent(e,"end");return}let r=ta.indexOf(e)-1;if(r>=0){let s=ta[r];if(this._asyncEffects.filter(c=>c.phase===s).some(c=>!c.complete))return}let o=nPt[e]||[];for(let s of o)if(this._hasIncompleteAsyncEffectsInSubtreeForPhase(s))return;if(this._emitRenderLifecycleEvent(e,"start"),n){i&&(this?.[`update${e}`]?.(),t.dirty=!1),this._emitRenderLifecycleEvent(e,"end");return}t.dirty=!1,this?.[`doInitial${e}`]?.(),t.initialized=!0,this._emitRenderLifecycleEvent(e,"end")}runRenderPhaseForChildren(e){for(let t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}renderError(e){throw typeof e=="string"?new Error(e):new Error(JSON.stringify(e,null,2))}},ex={},tV=e=>{let t=Object.fromEntries(Object.entries(e).map(([n,i])=>[n.toLowerCase(),i]));Object.assign(ex,e),Object.assign(ex,t)},rPt=class extends Error{constructor(e,t,n){let i,r=Object.keys(n).filter(c=>c!=="_errors"),o=[],s=t.pinLabels;if(s)for(let[c,l]of Object.entries(s)){let u=Array.isArray(l)?l:[l];for(let h of u)typeof h=="string"&&(h.startsWith(" ")||h.endsWith(" "))&&o.push(`pinLabels.${c} ("${h}" has leading or trailing spaces)`)}let a=r.map(c=>c==="pinLabels"&&o.length>0?o.join(", "):n[c]._errors[0]?`${c} (${n[c]._errors[0]})`:`${c} (${JSON.stringify(n[c])})`).join(", ");"name"in t?i=`Invalid props for ${e} "${t.name}": ${a}`:"footprint"in t&&typeof t.footprint=="string"?i=`Invalid props for ${e} (unnamed ${t.footprint} component): ${a}`:i=`Invalid props for ${e} (unnamed): ${a}`,super(i),this.componentName=e,this.originalProps=t,this.formattedError=n}};function EI(e,t){let n=t.match(/^#(\w+)/);if(n)return e.props.id===n[1];let i=t.match(/^\.(\w+)/);if(i)return e.isMatchingNameOrAlias(i[1]);let[r,...o]=t.split(/(?=[#.[])/);return r==="pin"&&(r="port"),r&&r!=="*"&&e.lowercaseComponentName!==r.toLowerCase()?!1:o.every(s=>{if(s.startsWith("#"))return e.props.id===s.slice(1);if(s.startsWith("."))return e.isMatchingNameOrAlias(s.slice(1));let a=s.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!a)return!0;let[,c,l]=a;return e.props[c].toString()===l})}var VI={isTag:e=>!0,getParent:e=>e.parent,getChildren:e=>e.children,getName:e=>e.lowercaseComponentName,getAttributeValue:(e,t)=>{if(t==="class"&&"getNameAndAliases"in e)return e.getNameAndAliases().join(" ");if(t==="name"&&e._parsedProps?.name)return e._parsedProps.name;if(e._parsedProps&&t in e._parsedProps){let i=e._parsedProps[t];return typeof i=="string"?i:i!=null?String(i):null}if(t in e){let i=e[t];return typeof i=="string"?i:i!=null?String(i):null}let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e){let r=e[i];return typeof r=="string"?r:r!=null?String(r):null}}return null},hasAttrib:(e,t)=>{if(t==="class")return!!e._parsedProps?.name;if(e._parsedProps&&t in e._parsedProps||t in e)return!0;let n=e._attributeLowerToCamelNameMap;if(n){let i=n[t];if(i&&i in e)return!0}return!1},getSiblings:e=>e.parent?e.parent.children:[],prevElementSibling:e=>{if(!e.parent)return null;let t=e.parent.children,n=t.indexOf(e);return n>0?t[n-1]:null},getText:()=>"",removeSubsets:e=>e.filter((t,n)=>!e.some((i,r)=>n!==r&&i!==t&&i.getDescendants().includes(t))),existsOne:(e,t)=>t.some(e),findAll:(e,t)=>{let n=[],i=r=>{e(r)&&n.push(r);for(let o of r.children)i(o)};for(let r of t)i(r);return n},findOne:(e,t)=>{for(let n of t){if(e(n))return n;let i=n.children;if(i.length>0){let r=VI.findOne(e,i);if(r)return r}}return null},equals:(e,t)=>e._renderId===t._renderId,isHovered:e=>!1,isVisited:e=>!1,isActive:e=>!1},oPt={...VI,getChildren:e=>e.children.filter(t=>!t.isSubcircuit)},IX={...VI,getChildren:e=>e.children.filter(t=>t.isSubcircuit)},MX=e=>{if(/net\.[^\s>]*\./.test(e))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(e))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(e)){let t=e.match(/net\.([^ >]+)/),n=t?t[1]:"";throw new Error(`Net name "${n}" cannot start with a number, try using a prefix like "VBUS1"`)}return e.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(t,n,i,r)=>{let o=/^\d+$/.test(r)?`pin${r}`:r;return`${n}.${i} > .${o}`}).trim()},CI={adapter:oPt,cacheResults:!0},be=class extends XI{constructor(t){super(t);T(this,"parent",null);T(this,"children");T(this,"childrenPendingRemoval");T(this,"props");T(this,"_parsedProps");T(this,"externallyAddedAliases");T(this,"isPrimitiveContainer",!1);T(this,"canHaveTextChildren",!1);T(this,"source_group_id",null);T(this,"source_component_id",null);T(this,"schematic_component_id",null);T(this,"pcb_component_id",null);T(this,"cad_component_id",null);T(this,"fallbackUnassignedName");T(this,"_cachedSelectAllQueries",new Map);T(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=t??{},this.externallyAddedAliases=[];let i=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(t??{});if(i.success)this._parsedProps=i.data;else throw new rPt(this.lowercaseComponentName,this.props,i.error.format())}get config(){return{componentName:"",zodProps:p.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(t){let n=this;for(;n;){if(n._parsedProps&&t in n._parsedProps)return n._parsedProps[t];n=n.parent}if(this.root?.platform&&t in this.root.platform)return this.root.platform[t]}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(t){let n=this.config.zodProps.parse({...this.props,...t}),i=this.props;this.props=n,this._parsedProps=this.config.zodProps.parse(t),this.onPropsChange({oldProps:i,newProps:n,changedProps:Object.keys(t)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation:t}=this.props;return typeof t=="string"?parseFloat(t):t??null}computePcbPropsTransform(){let{_parsedProps:t}=this,n=this._getPcbRotationBeforeLayout()??0;return Jn(vn(t.pcbX??0,t.pcbY??0),Ba(n*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let t=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(t&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let n=this._getPcbRotationBeforeLayout()??0;return Jn(this.parent?._computePcbGlobalTransformBeforeLayout()??Ai(),Jn(vn(t.x,t.y),Ba(n*Math.PI/180)))}if(this.isPcbPrimitive){let n=this.getPrimitiveContainer();if(n&&n._parsedProps.layer==="bottom")return Jn(this.parent?._computePcbGlobalTransformBeforeLayout()??Ai(),f6(),this.computePcbPropsTransform())}return Jn(this.parent?._computePcbGlobalTransformBeforeLayout()??Ai(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}getParentNormalComponent(){let t=this.parent;for(;t;){if(t.isPrimitiveContainer&&t.doInitialPcbComponentRender)return t;t=t.parent}return null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let t=this.getPrimitiveContainer(),n=t?t._parsedProps.layer==="bottom":!1;return{isFlipped:n,maybeFlipLayer:r=>n?r==="top"?"bottom":"top":r}}_setPositionFromLayout(t){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:t}=this;return Jn(vn(t.schX??0,t.schY??0))}computeSchematicGlobalTransform(){let t=this._getSchematicGlobalManualPlacementTransform(this);return t||Jn(this.parent?.computeSchematicGlobalTransform?.()??Ai(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:t}=this,n=this.config.schematicSymbolName,i={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},r=t.schOrientation!==void 0?i[t.schOrientation]:t.schRotation;if(r===void 0&&(r=0),r=r%360,r<0&&(r+=360),t.schRotation!==void 0&&r%90!==0)throw new Error(`Schematic rotation ${t.schRotation} is not supported for ${this.componentName}`);let o=`${n}_horz`,s=`${n}_vert`,a=`${n}_up`,c=`${n}_down`,l=`${n}_left`,u=`${n}_right`;if(u in Qn&&r===0)return u;if(a in Qn&&r===90)return a;if(l in Qn&&r===180)return l;if(c in Qn&&r===270)return c;if(o in Qn&&(r===0||r===180))return o;if(s in Qn&&(r===90||r===270))return s;if(n in Qn)return n}_getSchematicSymbolNameOrThrow(){let t=this._getSchematicSymbolName();if(!t)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return t}getSchematicSymbol(){let t=this._getSchematicSymbolName();return t?Qn[t]??null:null}_getPcbManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n?.pcb_placements;if(!i)return null;for(let r of i)if(EI(t,r.selector)||t.props.name===r.selector)return De(this._computePcbGlobalTransformBeforeLayout(),r.center);return null}_getSchematicManualPlacementForComponent(t){if(!this.isSubcircuit)return null;let n=this.props.manualEdits;if(!n)return null;let i=n.schematic_placements;if(!i)return null;for(let r of i)if(EI(t,r.selector)||t.props.name===r.selector)return De(this.computeSchematicGlobalTransform(),r.center);return null}_getSchematicGlobalManualPlacementTransform(t){let n=this.getSubcircuit()?._parsedProps.manualEdits;if(!n)return null;for(let i of n.schematic_placements??[])if((EI(t,i.selector)||t.props.name===i.selector)&&i.relative_to==="group_center")return Jn(this.parent?._computePcbGlobalTransformBeforeLayout()??Ai(),vn(i.center.x,i.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return De(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return De(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(t){this.parent=t}onPropsChange(t){}onChildChanged(t){this.parent?.onChildChanged?.(t)}add(t){let n=t.__text;if(typeof n=="string"){if(this.canHaveTextChildren||n.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${n}"`)}if(Object.keys(t).length!==0){if(this.lowercaseComponentName==="board"&&t.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(!t.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(t)}"`);t.onAddToParent(this),t.parent=this,this.children.push(t)}}addAll(t){for(let n of t)this.add(n)}remove(t){this.children=this.children.filter(n=>n!==t),this.childrenPendingRemoval.push(t),t.shouldBeRemoved=!0}getSubcircuitSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?n:`${this.parent.getSubcircuitSelector()} > ${n}`}getFullPathSelector(){let t=this.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName,i=this.parent?.getFullPathSelector?.();return i?`${i} > ${n}`:n}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(t){return this.getNameAndAliases().includes(t)}isMatchingAnyOf(t){return this.getNameAndAliases().some(n=>t.map(i=>i.toString()).includes(n))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(t){let n=[this.componentName,this.lowercaseComponentName],i=[this.name].filter(Boolean),r=t.trim().split(/\> /)[0],o=r[0];return r.length>1?!1:!!(t==="*"||t[0]==="#"&&t.slice(1)===this.props.id||t[0]==="."&&i.includes(t.slice(1))||/^[a-zA-Z0-9_]/.test(o)&&n.includes(o))}getSubcircuit(){if(this.isSubcircuit)return this;let t=this.parent?.getSubcircuit?.();if(!t)throw new Error("Component is not inside an opaque group (no board?)");return t}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let t=this.selectAll("port");for(let n of t){let r=(n.getParentNormalComponent?.()??n.parent)?.getNameAndAliases(),o=n.getNameAndAliases();if(r)for(let s of r)for(let a of o){let c=[`.${s} > .${a}`,`.${s} .${a}`];for(let l of c){let u=this._cachedSelectAllQueries.get(l);u?u.push(n):this._cachedSelectAllQueries.set(l,[n])}}}for(let[n,i]of this._cachedSelectAllQueries.entries())i.length===1&&this._cachedSelectOneQueries.set(n,i[0])}selectAll(t){if(this._cachedSelectAllQueries.has(t))return this._cachedSelectAllQueries.get(t);let n=MX(t),i=L5(n,this,CI);if(i.length>0)return this._cachedSelectAllQueries.set(t,i),i;let[r,...o]=n.split(" "),s=hg(r,this,{adapter:IX});if(!s)return[];let a=s.selectAll(o.join(" "));return this._cachedSelectAllQueries.set(t,a),a}selectOne(t,n){if(this._cachedSelectOneQueries.has(t))return this._cachedSelectOneQueries.get(t);let i=MX(t);n?.port&&(n.type="port");let r=null;if(n?.type&&(r=L5(i,this,CI).find(l=>l.lowercaseComponentName===n.type)),r??(r=hg(i,this,CI)),r)return this._cachedSelectOneQueries.set(t,r),r;let[o,...s]=i.split(" "),a=hg(o,this,{adapter:IX});return a?(r=a.selectOne(s.join(" "),n),this._cachedSelectOneQueries.set(t,r),r):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:t}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[t(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?this.root?._getBoard()?.allLayers??["top","bottom"]:[]}return[]}getDescendants(){let t=[];for(let n of this.children)t.push(n),t.push(...n.getDescendants());return t}getSelectableDescendants(){let t=[];for(let n of this.children)n.isSubcircuit?t.push(n):(t.push(n),t.push(...n.getSelectableDescendants()));return t}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this;return{schWidth:t.schWidth,schHeight:t.schHeight}}renderError(t){if(typeof t=="string")return super.renderError(t);switch(t.type){case"pcb_placement_error":this.root?.db.pcb_placement_error.insert(t);break;case"pcb_via_clearance_error":this.root?.db.pcb_via_clearance_error.insert(t);break;case"pcb_trace_error":this.root?.db.pcb_trace_error.insert(t);break;case"pcb_manual_edit_conflict_warning":this.root?.db.pcb_manual_edit_conflict_warning.insert(t);break;default:this.root?.db.pcb_placement_error.insert(t)}}getString(){let{lowercaseComponentName:t,_parsedProps:n,parent:i}=this;return n?.pinNumber!==void 0&&i?.props?.name&&n?.name?`<${t}#${this._renderId}(pin:${n.pinNumber} .${i?.props.name}>.${n.name}) />`:i?.props?.name&&n?.name?`<${t}#${this._renderId}(.${i?.props.name}>.${n?.name}) />`:n?.from&&n?.to?`<${t}#${this._renderId}(from:${n.from} to:${n?.to}) />`:n?.name?`<${t}#${this._renderId} name=".${n?.name}" />`:n?.portHints?`<${t}#${this._renderId}(${n.portHints.map(r=>`.${r}`).join(", ")}) />`:`<${t}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},sPt=class extends be{constructor(e,t){super(e),this._parsedProps={...e,error:t,type:e.type||"unknown",component_name:e.name,error_type:"source_failed_to_create_component_error",message:t instanceof Error?t.message:String(t),pcbX:e.pcbX,pcbY:e.pcbY,schX:e.schX,schY:e.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:p.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let e=this._getGlobalPcbPositionBeforeLayout(),t=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:e,schematic_center:t})}}};function aPt(e,t){return new sPt(e,t)}function cPt(e,t){let n=e;return n.__tsci={...t},e}var lPt={supportsMutation:!0,createInstance(e,t){let n=ex[e];if(!n)throw Object.keys(ex).length===0?new Error("No components registered in catalogue, did you forget to import lib/register-catalogue in your test file?"):new Error(`Unsupported component type "${e}". No element with this name is registered in the @tscircuit/core catalogue. Check for typos or see https://docs.tscircuit.com/category/built-in-elements for a list of valid components. To add your own component, see docs/CREATING_NEW_COMPONENTS.md`);try{return cPt(new n(t),{})}catch(i){return aPt({...t,componentType:e},i)}},createTextInstance(e){return{__text:e}},appendInitialChild(e,t){e.add(t)},appendChild(e,t){e.add(t)},appendChildToContainer(e,t){e.add(t)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(e){return e},preparePortalMount(e){throw new Error("Function not implemented.")},scheduleTimeout(e,t){throw new Error("Function not implemented.")},cancelTimeout(e){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(e){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(e,t)=>{throw new Error("Function not implemented.")},getInstanceFromScope:e=>{throw new Error("Function not implemented.")},detachDeletedInstance:e=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>Qb.DefaultEventPriority,getCurrentUpdatePriority:()=>Qb.DefaultEventPriority,resolveUpdatePriority:()=>Qb.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},Zb=(0,JX.default)(lPt),eV=e=>{let t={children:[],props:{name:"$root"},add(o){o.parent=this,this.children.push(o)},computePcbGlobalTransform(){return Ai()}},n=[],i=Zb.createContainer(t,0,null,!1,null,"tsci",o=>{console.log("Error in createContainer"),console.error(o),n.push(o)},null);if(Zb.updateContainerSync(e,i,null,()=>{}),Zb.flushSyncWork(),n.length>0)throw n[0];let r=Zb.getPublicRootInstance(i);return r||t.children[0]},cm=(e,t)=>{if(typeof e=="number")return e;if(e.startsWith("pin"))return Number(e.slice(3));if(!t)throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`);for(let n in t)if((Array.isArray(t[n])?t[n]:[t[n]]).includes(e))return Number(n.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${e}"`)},uPt=(e,t)=>{if(!e)return;let n={},i={};for(let[r,o]of Object.entries(e)){let s=cm(r,t);i[s]={...i[s],...o}}for(let[r,o]of Object.entries(i)){let s=`pin${r}`;n[s]={bottom_margin:o.bottomMargin,left_margin:o.leftMargin,right_margin:o.rightMargin,top_margin:o.topMargin}}return n},pPt=e=>{if(e){if("leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e)return{left_side:e.leftSide,right_side:e.rightSide,top_side:e.topSide,bottom_side:e.bottomSide};if("leftPinCount"in e||"rightPinCount"in e||"topPinCount"in e||"bottomPinCount"in e)return{left_size:e.leftPinCount,right_size:e.rightPinCount,top_size:e.topPinCount,bottom_size:e.bottomPinCount};if("leftSize"in e||"rightSize"in e||"topSize"in e||"bottomSize"in e)return{left_size:e.leftSize,right_size:e.rightSize,top_size:e.topSize,bottom_size:e.bottomSize}}};function nV(e){let t=[];for(let n=0;n<e.length-1;n++)t.push([e[n],e[n+1]]);return t}var hPt=p.object({name:p.string().refine(e=>!/[+-]/.test(e),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),HI=class extends be{constructor(){super(...arguments);T(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:hPt}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=n.name.startsWith("GND"),r=n.name.startsWith("V"),o=t.source_net.insert({name:n.name,member_source_group_ids:[],is_ground:i,is_power:r,is_positive_voltage_source:r});this.source_net_id=o.source_net_id}doInitialSourceParentAttachment(){let t=this.getSubcircuit();if(!t)return;let{db:n}=this.root;n.source_net.update(this.source_net_id,{subcircuit_id:t.subcircuit_id})}getAllConnectedPorts(){let t=this.getSubcircuit().selectAll("port"),n=[];for(let i of t){let r=i._getDirectlyConnectedTraces();for(let o of r)if(o._isExplicitlyConnectedToNet(this)){n.push(i);break}}return n}_getAllDirectlyConnectedTraces(){let t=this.getSubcircuit().selectAll("trace"),n=[];for(let i of t)i._isExplicitlyConnectedToNet(this)&&n.push(i);return n}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getAllDirectlyConnectedTraces().filter(s=>(s._portsRoutedOnPcb?.length??0)>0),r=[];for(let s of i){let a=s._portsRoutedOnPcb,c=r.find(l=>a.some(u=>l.ports.includes(u)));if(!c){r.push({ports:[...a],traces:[s]});continue}c.traces.push(s),c.ports.push(...a)}if(r.length===0)return;let o=nV(r);for(let[s,a]of o){let c=s.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),l=a.ports.map(w=>w._getGlobalPcbPositionBeforeLayout()),u=1/0,h=[-1,-1];for(let w=0;w<c.length;w++){let S=c[w];for(let E=0;E<l.length;E++){let M=l[E],k=Math.sqrt((S.x-M.x)**2+(S.y-M.y)**2);k<u&&(u=k,h=[w,E])}}let d=s.ports[h[0]],_=a.ports[h[1]],y=t.toArray().filter(w=>w.type==="pcb_smtpad"||w.type==="pcb_trace"||w.type==="pcb_plated_hole"||w.type==="pcb_hole"||w.type==="source_port"||w.type==="pcb_port"),{solution:g}=ez(y.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[d.source_port_id,_.source_port_id]}])),x=g[0];if(!x){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[d.pcb_component_id,_.pcb_component_id].filter(Boolean),pcb_port_ids:[d.pcb_port_id,_.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}t.pcb_trace.insert(x)}}renderError(t){if(typeof t=="string")return super.renderError(t);this.root?.db.pcb_trace_error.insert(t)}},GI=(e,t)=>{for(let n of t)if(typeof n=="string"&&n.startsWith("net.")){if(/net\.[^\s>]*\./.test(n))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(n))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(n)){let r=n.split("net.")[1];throw new Error(`Net name "${r}" cannot start with a number, try using a prefix like "VBUS1"`)}let i=e.getSubcircuit();if(!i.selectOne(n)){let r=new HI({name:n.split("net.")[1]});i.add(r)}}},nx=class extends be{constructor(){super(...arguments);T(this,"pcb_smtpad_id",null);T(this,"matchedPort",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:Mz}}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="polygon"){let n=t.points,i=n.map(l=>l.x),r=n.map(l=>l.y),o=Math.min(...i),s=Math.max(...i),a=Math.min(...r),c=Math.max(...r);return{width:s-o,height:c-a}}if(t.shape==="pill")return{width:t.width,height:t.height};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.coveredWithSolderMask??!1,r=!i;if(!n.portHints)return;let o=this.getSubcircuit(),s=this._getGlobalPcbPositionBeforeLayout(),l=(To(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,u=.01,h=Math.abs(l)<u||Math.abs(l-180)<u||Math.abs(l-360)<u,d=Math.abs(l-90)<u||Math.abs(l-270)<u,_=Math.abs(l-360)<u?0:l,{maybeFlipLayer:y}=this._getPcbPrimitiveFlippedHelpers(),g=null,x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;n.shape==="circle"?(g=t.pcb_smtpad.insert({pcb_component_id:x,pcb_port_id:this.matchedPort?.pcb_port_id,layer:y(n.layer??"top"),shape:"circle",radius:n.radius,port_hints:n.portHints.map(w=>w.toString()),is_covered_with_solder_mask:i,x:s.x,y:s.y,subcircuit_id:o?.subcircuit_id??void 0}),r&&t.pcb_solder_paste.insert({layer:g.layer,shape:"circle",radius:g.radius*.7,x:g.x,y:g.y,pcb_component_id:g.pcb_component_id,pcb_smtpad_id:g.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):n.shape==="rect"?(g=h||d?t.pcb_smtpad.insert({pcb_component_id:x,pcb_port_id:this.matchedPort?.pcb_port_id,layer:y(n.layer??"top"),shape:"rect",width:d?n.height:n.width,height:d?n.width:n.height,port_hints:n.portHints.map(w=>w.toString()),is_covered_with_solder_mask:i,x:s.x,y:s.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):t.pcb_smtpad.insert({pcb_component_id:x,layer:y(n.layer??"top"),shape:"rotated_rect",width:n.width,height:n.height,x:s.x,y:s.y,ccw_rotation:_,port_hints:n.portHints.map(w=>w.toString()),is_covered_with_solder_mask:i,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&g.shape==="rect"&&t.pcb_solder_paste.insert({layer:y(n.layer??"top"),shape:"rect",width:g.width*.7,height:g.height*.7,x:g.x,y:g.y,pcb_component_id:g.pcb_component_id,pcb_smtpad_id:g.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&g.shape==="rotated_rect"&&t.pcb_solder_paste.insert({layer:y(n.layer??"top"),shape:"rotated_rect",width:g.width*.7,height:g.height*.7,x:g.x,y:g.y,ccw_rotation:_,pcb_component_id:g.pcb_component_id,pcb_smtpad_id:g.pcb_smtpad_id,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):n.shape==="polygon"?g=t.pcb_smtpad.insert({pcb_component_id:x,pcb_port_id:this.matchedPort?.pcb_port_id,layer:y(n.layer??"top"),shape:"polygon",points:n.points.map(w=>({x:w.x+s.x,y:w.y+s.y})),port_hints:n.portHints.map(w=>w.toString()),is_covered_with_solder_mask:i,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):n.shape==="pill"&&(g=t.pcb_smtpad.insert({pcb_component_id:x,pcb_port_id:this.matchedPort?.pcb_port_id,layer:y(n.layer??"top"),shape:"pill",x:s.x,y:s.y,radius:n.radius,height:n.height,width:n.width,port_hints:n.portHints.map(w=>w.toString()),is_covered_with_solder_mask:i,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})),g&&(this.pcb_smtpad_id=g.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_smtpad.get(this.pcb_smtpad_id);if(n.shape==="rect")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.width/2,top:n.y+n.height/2,right:n.x+n.width/2,bottom:n.y-n.height/2},width:n.width,height:n.height};if(n.shape==="rotated_rect"){let i=n.ccw_rotation*Math.PI/180,r=Math.cos(i),o=Math.sin(i),s=n.width/2,a=n.height/2,c=Math.abs(s*r)+Math.abs(a*o),l=Math.abs(s*o)+Math.abs(a*r);return{center:{x:n.x,y:n.y},bounds:{left:n.x-c,right:n.x+c,top:n.y-l,bottom:n.y+l},width:c*2,height:l*2}}if(n.shape==="circle")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.radius,top:n.y-n.radius,right:n.x+n.radius,bottom:n.y+n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){let i=n.points,r=i.map(u=>u.x),o=i.map(u=>u.y),s=Math.min(...r),a=Math.max(...r),c=Math.min(...o),l=Math.max(...o);return{center:{x:(s+a)/2,y:(c+l)/2},bounds:{left:s,top:l,right:a,bottom:c},width:a-s,height:l-c}}if(n.shape==="pill"){let i=n.width/2,r=n.height/2;return{center:{x:n.x,y:n.y},bounds:{left:n.x-i,top:n.y-r,right:n.x+i,bottom:n.y+r},width:n.width,height:n.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${n.shape}"`)}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_smtpad.update(this.pcb_smtpad_id,{x:t.x,y:t.y});let i=n.pcb_solder_paste.list().find(r=>r.pcb_smtpad_id===this.pcb_smtpad_id);i&&n.pcb_solder_paste.update(i.pcb_solder_paste_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}},UI=class extends be{constructor(){super(...arguments);T(this,"pcb_silkscreen_path_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:fF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_path.insert({pcb_component_id:a,layer:r,route:n.route.map(l=>{let u=De(o,{x:l.x,y:l.y});return{...l,x:u.x,y:u.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=c.pcb_silkscreen_path_id}_setPositionFromLayout(t){let{db:n}=this.root,{_parsedProps:i}=this,r=n.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!r)return;let o=0,s=0;for(let u of r.route)o+=u.x,s+=u.y;o/=r.route.length,s/=r.route.length;let a=t.x-o,c=t.y-s,l=r.route.map(u=>({...u,x:u.x+a,y:u.y+c}));n.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:l})}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-r}}},dPt=p.object({route:p.array(n_),source_trace_id:p.string().optional()}),qI=class extends be{constructor(){super(...arguments);T(this,"pcb_trace_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:dPt}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),r=this.getSubcircuit(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),s=this._computePcbGlobalTransformBeforeLayout(),a=n.route.map(l=>{let{x:u,y:h,...d}=l,_=De(s,{x:u,y:h});return l.route_type==="wire"&&l.layer?{..._,...d,layer:o(l.layer)}:{..._,...d}}),c=t.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:n.source_trace_id,route:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=c.pcb_trace_id}getPcbSize(){let{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y),s.route_type==="wire"&&(n=Math.min(n,s.x-s.width/2),i=Math.max(i,s.x+s.width/2),r=Math.min(r,s.y-s.width/2),o=Math.max(o,s.y+s.width/2));return n===1/0||i===-1/0||r===1/0||o===-1/0?{width:0,height:0}:{width:i-n,height:o-r}}},Sh=class extends be{constructor(){super(...arguments);T(this,"pcb_plated_hole_id",null);T(this,"matchedPort",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:yz}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.outerDiameter,height:t.outerDiameter};if(t.shape==="oval"||t.shape==="pill")return{width:t.outerWidth,height:t.outerHeight};if(t.shape==="circular_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};if(t.shape==="pill_hole_with_rect_pad")return{width:t.rectPadWidth,height:t.rectPadHeight};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_plated_hole.get(this.pcb_plated_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y+i.height/2,right:n.x+i.width/2,bottom:n.y-i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:t.x,y:t.y}),this.matchedPort?._setPositionFromLayout(t)}doInitialPortMatching(){let t=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let n of t)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,o=this.getSubcircuit();if(n.shape==="circle"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:n.outerDiameter,hole_diameter:n.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="pill"&&n.rectPad){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:n.pcbRotation??0,rect_ccw_rotation:n.pcbRotation??0,rect_pad_width:n.outerWidth,rect_pad_height:n.outerHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill"||n.shape==="oval"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:n.shape,port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:n.pcbRotation??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(n.shape==="circular_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:n.holeDiameter,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,rect_border_radius:n.rectBorderRadius??0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}else if(n.shape==="pill_hole_with_rect_pad"){let s=t.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:n.holeWidth,hole_height:n.holeHeight,rect_pad_width:n.rectPadWidth,rect_pad_height:n.rectPadHeight,hole_offset_x:n.holeOffsetX,hole_offset_y:n.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=s.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},ix=class extends be{constructor(){super(...arguments);T(this,"pcb_keepout_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:Jz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let t=this.getSubcircuit(),{db:n}=this.root,{_parsedProps:i}=this,r=this._getGlobalPcbPositionBeforeLayout(),o=To(this._computePcbGlobalTransformBeforeLayout()),s=Math.abs(o.rotation.angle*(180/Math.PI)-90)%180<.01,a=null;i.shape==="circle"?a=n.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:r.x,y:r.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0}):i.shape==="rect"&&(a=n.pcb_keepout.insert({layers:["top"],shape:"rect",...s?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:r.x,y:r.y},subcircuit_id:t?.subcircuit_id??void 0,pcb_group_id:t?.getGroup()?.pcb_group_id??void 0})),a&&(this.pcb_keepout_id=a.pcb_keepout_id)}},sm=class extends be{constructor(){super(...arguments);T(this,"pcb_hole_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:Ez}}getPcbSize(){let{_parsedProps:t}=this,n=t.shape==="pill";return{width:n?t.width:t.diameter,height:n?t.height:t.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this._getGlobalPcbPositionBeforeLayout();if(n.shape==="pill")if(n.pcbRotation&&n.pcbRotation!==0){let o=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"rotated_pill",hole_width:n.width,hole_height:n.height,x:r.x,y:r.y,ccw_rotation:n.pcbRotation,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=o.pcb_hole_id}else{let o=t.pcb_hole.insert({type:"pcb_hole",hole_shape:"pill",hole_width:n.width,hole_height:n.height,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=o.pcb_hole_id}else{let o=t.pcb_hole.insert({hole_shape:"circle",hole_diameter:n.diameter,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=o.pcb_hole_id}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_hole.get(this.pcb_hole_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_hole.update(this.pcb_hole_id,{x:t.x,y:t.y})}},ax=class extends be{constructor(){super(...arguments);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:dF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),r=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:o,isFlipped:s}=this._getPcbPrimitiveFlippedHelpers(),a=this.getSubcircuit(),c=0;if(n.pcbRotation!==void 0&&n.pcbRotation!==0)c=n.pcbRotation;else{let h=this._computePcbGlobalTransformBeforeLayout();c=To(h).rotation.angle*180/Math.PI}s&&(c=(c+180)%360);let l=new Set(n.layers);n.layer&&l.add(n.layer);let u=l.size>0?Array.from(l):["top"];for(let h of u)t.pcb_silkscreen_text.insert({anchor_alignment:n.anchorAlignment,anchor_position:{x:r.x,y:r.y},font:n.font??"tscircuit2024",font_size:n.fontSize??1,layer:o(h),text:n.text??"",ccw_rotation:c,pcb_component_id:i.pcb_component_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:t}=this,n=t.fontSize??1,r=(t.text??"").length*n,o=n;return{width:r*n,height:o*n}}},am=class extends be{constructor(){super(...arguments);T(this,"pcb_cutout_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:Iz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this.getGroup()?.pcb_group_id??void 0,o=this._getGlobalPcbPositionBeforeLayout(),a=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,c;if(n.shape==="rect"){let l=typeof a=="string"?parseInt(a.replace("deg",""),10):a,u=Math.abs(l%180)===90,h={shape:"rect",center:o,width:u?n.height:n.width,height:u?n.width:n.height,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(h)}else if(n.shape==="circle"){let l={shape:"circle",center:o,radius:n.radius,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(l)}else if(n.shape==="polygon"){let l=this._computePcbGlobalTransformBeforeLayout(),h={shape:"polygon",points:n.points.map(d=>De(l,d)),subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=t.pcb_cutout.insert(h)}c&&(this.pcb_cutout_id=c.pcb_cutout_id)}getPcbSize(){let{_parsedProps:t}=this;if(t.shape==="rect")return{width:t.width,height:t.height};if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){if(t.points.length===0)return{width:0,height:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let s of t.points)n=Math.min(n,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-r}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_cutout.get(this.pcb_cutout_id);if(!n)return super._getPcbCircuitJsonBounds();if(n.shape==="rect")return{center:n.center,bounds:{left:n.center.x-n.width/2,top:n.center.y+n.height/2,right:n.center.x+n.width/2,bottom:n.center.y-n.height/2},width:n.width,height:n.height};if(n.shape==="circle")return{center:n.center,bounds:{left:n.center.x-n.radius,top:n.center.y+n.radius,right:n.center.x+n.radius,bottom:n.center.y-n.radius},width:n.radius*2,height:n.radius*2};if(n.shape==="polygon"){if(n.points.length===0)return super._getPcbCircuitJsonBounds();let i=1/0,r=-1/0,o=1/0,s=-1/0;for(let a of n.points)i=Math.min(i,a.x),r=Math.max(r,a.x),o=Math.min(o,a.y),s=Math.max(s,a.y);return{center:{x:(i+r)/2,y:(o+s)/2},bounds:{left:i,top:s,right:r,bottom:o},width:r-i,height:s-o}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(t){if(!this.pcb_cutout_id)return;let{db:n}=this.root,i=n.pcb_cutout.get(this.pcb_cutout_id);if(i){if(i.shape==="rect"||i.shape==="circle")n.pcb_cutout.update(this.pcb_cutout_id,{...i,center:t});else if(i.shape==="polygon"){let r=this._getPcbCircuitJsonBounds().center,o=t.x-r.x,s=t.y-r.y,a=i.points.map(c=>({x:c.x+o,y:c.y+s}));n.pcb_cutout.update(this.pcb_cutout_id,{...i,points:a})}}}},fPt=({elm:e,pinLabels:t,layer:n,readableRotation:i,anchorAlignment:r})=>{let o=e.text.replace(/[{}]/g,"").toLowerCase(),s=o;if(Array.isArray(t)){let a=parseInt(o.replace(/[^\d]/g,""),10)-1;s=String(t[a]??o)}else typeof t=="object"&&(s=String(t[o]??o));return new ax({anchorAlignment:r||"center",text:s??o,layer:n||"top",fontSize:e.font_size+.2,pcbX:isNaN(e.anchor_position.x)?0:e.anchor_position.x,pcbY:e.anchor_position.y,pcbRotation:i??0})},mPt=(e,t)=>{let n=parseInt(e||"0",10),i;return t!=null?i=t-n:i=n,(i%360+360)%360},nm=({componentName:e,componentRotation:t,footprint:n,pinLabels:i,pcbPinLabels:r},o)=>{let s=[];for(let a of o)if(a.type==="pcb_smtpad"&&a.shape==="rect")s.push(new nx({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"rect",height:a.height,width:a.width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius}));else if(a.type==="pcb_smtpad"&&a.shape==="circle")s.push(new nx({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"circle",radius:a.radius,portHints:a.port_hints}));else if(a.type==="pcb_silkscreen_path")s.push(new UI({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?s.push(new Sh({pcbX:a.x,pcbY:a.y,shape:"circle",holeDiameter:a.hole_diameter,outerDiameter:a.outer_diameter,portHints:a.port_hints})):a.shape==="circular_hole_with_rect_pad"?s.push(new Sh({pcbX:a.x,pcbY:a.y,shape:"circular_hole_with_rect_pad",holeDiameter:a.hole_diameter,rectPadHeight:a.rect_pad_height,rectPadWidth:a.rect_pad_width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y})):a.shape==="pill"||a.shape==="oval"?s.push(new Sh({pcbX:a.x,pcbY:a.y,shape:a.shape,holeWidth:a.hole_width,holeHeight:a.hole_height,outerWidth:a.outer_width,outerHeight:a.outer_height,portHints:a.port_hints})):a.shape==="pill_hole_with_rect_pad"&&s.push(new Sh({pcbX:a.x,pcbY:a.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:a.hole_width,holeHeight:a.hole_height,rectPadWidth:a.rect_pad_width,rectPadHeight:a.rect_pad_height,portHints:a.port_hints,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y}));else if(a.type==="pcb_keepout"&&a.shape==="circle")s.push(new ix({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius}));else if(a.type==="pcb_keepout"&&a.shape==="rect")s.push(new ix({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height}));else if(a.type==="pcb_hole"&&a.hole_shape==="circle")s.push(new sm({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_hole"&&a.hole_shape==="pill")s.push(new sm({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height}));else if(a.type==="pcb_hole"&&a.hole_shape==="rotated_pill")s.push(new sm({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height,pcbRotation:a.ccw_rotation}));else if(a.type==="pcb_cutout")a.shape==="rect"?s.push(new am({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height})):a.shape==="circle"?s.push(new am({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius})):a.shape==="polygon"&&s.push(new am({shape:"polygon",points:a.points}));else if(a.type==="pcb_silkscreen_text"){let c=mPt(t,a.ccw_rotation);n.includes("pinrow")&&a.text.includes("PIN")?s.push(fPt({elm:a,pinLabels:r??i,layer:a.layer,readableRotation:c,anchorAlignment:a.anchor_alignment})):s.push(new ax({anchorAlignment:a.anchor_alignment||"center",text:e,fontSize:a.font_size+.2,pcbX:Number.isNaN(a.anchor_position.x)?0:a.anchor_position.x,pcbY:a.anchor_position.y,pcbRotation:c??0}))}else a.type==="pcb_trace"&&s.push(new qI({route:a.route}));return s};function cx(e){let t=1/0,n=1/0,i=-1/0,r=-1/0,o=!1;for(let c of e)if(c.isPcbPrimitive&&!c.componentName.startsWith("Silkscreen")){let{x:l,y:u}=c._getGlobalPcbPositionBeforeLayout(),{width:h,height:d}=c.getPcbSize();t=Math.min(t,l-h/2),n=Math.min(n,u-d/2),i=Math.max(i,l+h/2),r=Math.max(r,u+d/2),o=!0}else if(c.children.length>0){let l=cx(c.children);(l.width>0||l.height>0)&&(t=Math.min(t,l.minX),n=Math.min(n,l.minY),i=Math.max(i,l.maxX),r=Math.max(r,l.maxY),o=!0)}if(!o)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let s=i-t,a=r-n;return s<0&&(s=0),a<0&&(a=0),{minX:t,minY:n,maxX:i,maxY:r,width:s,height:a}}function EX(e){let t=e%360;return t<0?t+360:t}function _Pt(e,t,n,i){return i==="counterclockwise"?n>=t?e>=t&&e<=n:e>=t||e<=n:n<=t?e<=t&&e>=n:e<=t||e>=n}function yPt(e){let t=e.center,n=e.radius,i=e.start_angle_degrees,r=e.end_angle_degrees,o=e.direction??"counterclockwise";if(!t||typeof t.x!="number"||typeof t.y!="number"||typeof n!="number"||typeof i!="number"||typeof r!="number")return null;let s=EX(i),a=EX(r),c=new Set([s,a]),l=[0,90,180,270];for(let y of l)_Pt(y,s,a,o)&&c.add(y);let u=1/0,h=1/0,d=-1/0,_=-1/0;for(let y of c){let g=y*Math.PI/180,x=t.x+n*Math.cos(g),w=t.y+n*Math.sin(g);u=Math.min(u,x),d=Math.max(d,x),h=Math.min(h,w),_=Math.max(_,w)}return!Number.isFinite(u)||!Number.isFinite(h)?null:{minX:u,maxX:d,minY:h,maxY:_}}function iV(e){let t=1/0,n=1/0,i=-1/0,r=-1/0;for(let o of e){let s,a,c,l;if(o.type==="schematic_component")s=o.center?.x,a=o.center?.y,c=o.size?.width,l=o.size?.height;else if(o.type==="schematic_box")s=o.x,a=o.y,c=o.width,l=o.height;else if(o.type==="schematic_port")s=o.center?.x,a=o.center?.y,c=.2,l=.2;else if(o.type==="schematic_text")s=o.position?.x,a=o.position?.y,c=(o.text?.length??0)*.1,l=.2;else if(o.type==="schematic_line"){let u=o.x1??0,h=o.y1??0,d=o.x2??0,_=o.y2??0;s=(u+d)/2,a=(h+_)/2,c=Math.abs(d-u),l=Math.abs(_-h)}else if(o.type==="schematic_rect")s=o.center?.x,a=o.center?.y,c=o.width,l=o.height;else if(o.type==="schematic_circle"){s=o.center?.x,a=o.center?.y;let u=o.radius;typeof u=="number"&&(c=u*2,l=u*2)}else if(o.type==="schematic_arc"){let u=yPt(o);u&&(t=Math.min(t,u.minX),i=Math.max(i,u.maxX),n=Math.min(n,u.minY),r=Math.max(r,u.maxY));continue}typeof s=="number"&&typeof a=="number"&&typeof c=="number"&&typeof l=="number"&&(t=Math.min(t,s-c/2),i=Math.max(i,s+c/2),n=Math.min(n,a-l/2),r=Math.max(r,a+l/2))}return{minX:t,maxX:i,minY:n,maxY:r}}function gPt(e,t){let n=t.x-e.x,i=t.y-e.y;return Math.abs(n)>Math.abs(i)?n>=0?"right":"left":i>=0?"up":"down"}var CX=e=>{if(e.length<=1)return!0;let t=e.map(o=>{let s=o._getPcbCircuitJsonBounds();return{left:s.bounds.left,right:s.bounds.right,top:s.bounds.top,bottom:s.bounds.bottom}}),n=Array(t.length).fill(!1).map(()=>Array(t.length).fill(!1));for(let o=0;o<t.length;o++)for(let s=o+1;s<t.length;s++){let a=t[o],c=t[s];n[o][s]=n[s][o]=!(a.right<c.left||a.left>c.right||a.bottom>c.top||a.top<c.bottom)}let i=new Set,r=o=>{i.add(o);for(let s=0;s<t.length;s++)n[o][s]&&!i.has(s)&&r(s)};return r(0),i.size===t.length},kX=e=>{if(e.length===0)throw new Error("Cannot get center of empty PCB primitives array");let t=e.map(r=>r._getPcbCircuitJsonBounds().center).filter(Boolean),n=t.reduce((r,o)=>r+o.x,0),i=t.reduce((r,o)=>r+o.y,0);return{x:n/t.length,y:i/t.length}},bPt=p.object({name:p.string().optional(),pinNumber:p.number().optional(),aliases:p.array(p.string()).optional(),layer:p.string().optional(),layers:p.array(p.string()).optional(),schX:p.number().optional(),schY:p.number().optional(),direction:p.enum(["up","down","left","right"]).optional()}),Di=class extends be{constructor(t,n={}){if(!t.name&&t.pinNumber!==void 0&&(t.name=`pin${t.pinNumber}`),!t.name)throw new Error("Port must have a name or a pinNumber");super(t);T(this,"source_port_id",null);T(this,"pcb_port_id",null);T(this,"schematic_port_id",null);T(this,"schematicSymbolPortDef",null);T(this,"matchedComponents");T(this,"facingDirection",null);T(this,"originDescription",null);n.originDescription&&(this.originDescription=n.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:bPt}}_isBoardPinoutFromAttributes(){let t=this.parent;if(t?._parsedProps?.pinAttributes){let n=t._parsedProps.pinAttributes;for(let i of this.getNameAndAliases())if(n[i]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let t=this.matchedComponents.find(i=>i.isPcbPrimitive),n=this.parent;if(n&&!n.props.footprint)throw new Error(`${n.componentName} "${n.props.name}" does not have a footprint. Add a footprint prop, e.g. <${n.componentName.toLowerCase()} footprint="..." />`);if(!t)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return t?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:t}=this.root,n=t.pcb_port.get(this.pcb_port_id);return{center:{x:n.x,y:n.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let t=this.parent;if(!t||!t._getInternallyConnectedPins)return[];let n=t._getInternallyConnectedPins();for(let i of n)if(i.some(r=>r===this))return i;return[]}_hasSchematicPort(){let{schX:t,schY:n}=this._parsedProps;if(t!==void 0&&n!==void 0)return!0;let i=this.getParentNormalComponent();if(i?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(a=>a.schematicSymbolPortDef));let o=i?._getSchematicBoxDimensions();return!!(o&&this.props.pinNumber!==void 0&&o.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let{schX:t,schY:n}=this._parsedProps;if(t!==void 0&&n!==void 0)return{x:t,y:n};let i=this.getParentNormalComponent(),r=i?.getSchematicSymbol();if(r){let s=this.schematicSymbolPortDef;if(!s&&(s=this._getPortsInternallyConnectedToThisPort().find(c=>c.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!s))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);let a=Jn(i.computeSchematicGlobalTransform(),vn(-r.center.x,-r.center.y));return De(a,s)}let o=i?._getSchematicBoxDimensions();if(o&&this.props.pinNumber!==void 0){let s=o.getPortPositionByPinNumber(this.props.pinNumber);if(!s)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return De(i.computeSchematicGlobalTransform(),s)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:t}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let n=t.schematic_port.get(this.schematic_port_id);if(!n)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return n.center}registerMatch(t){this.matchedComponents.push(t)}getNameAndAliases(){let{_parsedProps:t}=this;return Array.from(new Set([...t.name?[t.name]:[],...t.aliases??[],...typeof t.pinNumber=="number"?[`pin${t.pinNumber}`,t.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let t=this.parent?._parsedProps?.pinAttributes;if(!t)return[];let n=[];for(let i of this.getNameAndAliases()){let r=t[i];r&&n.push(r)}return n}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(t=>t.includeInBoardPinout===!0)}isMatchingPort(t){return this.isMatchingAnyOf(t.getNameAndAliases())}getPortSelector(){return`.${(this.getParentNormalComponent()??this.parent)?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:t,layers:n}=this._parsedProps;return n||(t?[t]:Array.from(new Set(this.matchedComponents.flatMap(i=>i.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(i=>!i._couldNotFindPort).filter(i=>i._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getNameAndAliases(),r=this.getParentNormalComponent(),s=(this.parent?.source_component_id?this.parent:r)?.source_component_id??null,a=t.source_port.insert({name:n.name,pin_number:n.pinNumber,port_hints:i,source_component_id:s,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=a.source_port_id}doInitialSourceParentAttachment(){let{db:t}=this.root,n=this.getParentNormalComponent(),i=this.parent?.source_component_id?this.parent:n;if(!i?.source_component_id)throw new Error(`${this.getString()} has no parent source component (parent: ${this.parent?.getString()})`);t.source_port.update(this.source_port_id,{source_component_id:i.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=i.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{matchedComponents:n}=this,i=this.getParentNormalComponent(),r=this.parent?.pcb_component_id?this.parent:i;if(!r?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()}, parentNormalComponent: ${i?.getString()})`);let o=n.filter(a=>a.isPcbPrimitive);if(o.length===0)return;let s=null;if(o.length===1&&(s=o[0]._getPcbCircuitJsonBounds().center),o.length>1){if(!CX(o))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${o.map(a=>a.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);s=kX(o)}if(s){let a=this.getSubcircuit(),c=this._shouldIncludeInBoardPinout(),l=t.pcb_port.insert({pcb_component_id:r.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...c?{is_board_pinout:!0}:{},...s,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=l.pcb_port_id}else{let a=o[0];throw new Error(`${a.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;if(this.pcb_port_id)return;let n=this.matchedComponents.filter(l=>l.isPcbPrimitive);if(n.length===0)return;let i=null;if(n.length===1&&(i=n[0]._getPcbCircuitJsonBounds().center),n.length>1)try{CX(n)&&(i=kX(n))}catch{}if(!i)return;let r=this.getParentNormalComponent(),o=this.parent?.pcb_component_id?this.parent:r,s=this.getSubcircuit(),a=this._shouldIncludeInBoardPinout(),c=t.pcb_port.insert({pcb_component_id:o?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...a?{is_board_pinout:!0}:{},...i,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=c.pcb_port_id}doInitialSchematicPortRender(){let{db:t}=this.root,{_parsedProps:n}=this,{schX:i,schY:r}=n,o=i!==void 0&&r!==void 0?this.getParentNormalComponent():this.getPrimitiveContainer();if(!o||!this._hasSchematicPort())return;let s=o._getGlobalSchematicPositionBeforeLayout(),a=this._getGlobalSchematicPositionBeforeLayout(),c=null,l=o._getSchematicBoxDimensions();l&&n.pinNumber!==void 0&&(c=l.getPortPositionByPinNumber(n.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&t.schematic_debug_object.insert({shape:"rect",center:a,size:{width:.1,height:.1},label:"obstacle"}),c?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[c.side]:this.facingDirection=gPt(s,a);let u=t.source_port.get(this.source_port_id),h=[];for(let w of u?.port_hints??[])w.match(/^(pin)?\d+$/)||w.match(/^(left|right)/)&&!u?.name.match(/^(left|right)/)||h.push(w);let d,_=this.getParentNormalComponent();_?.props?.showPinAliases&&h.length>0?d=h.join("/"):h.length>0&&(d=h[0]);let g={type:"schematic_port",schematic_component_id:_?.schematic_component_id,center:a,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:c?.side,pin_number:n.pinNumber,true_ccw_index:c?.trueIndex,display_pin_label:d,is_connected:!1};for(let w of this._getMatchingPinAttributes())w.requiresPower&&(g.has_input_arrow=!0),w.providesPower&&(g.has_output_arrow=!0);let x=t.schematic_port.insert(g);this.schematic_port_id=x.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_port_id&&n.pcb_port.update(this.pcb_port_id,{x:t.x,y:t.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(t=>t.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},rV=e=>{let t=e.find(n=>/^(pin)?\d+$/.test(n));return t?Number.parseInt(t.replace(/^pin/,"")):null};function em(e,t){let n=rV(e);if(!n)return null;let r=[...e.filter(o=>o.toString()!==n.toString()&&o!==`pin${n}`),...t?.additionalAliases?.[`pin${n}`]??[]];return new Di({pinNumber:n,aliases:r})}var xPt=e=>{for(let t of["leftSide","rightSide","topSide","bottomSide"])if(t in e&&typeof e[t]=="number")throw new Error(`A number was specified for "${t}", you probably meant to use "size" not "side"`);return"leftSide"in e||"rightSide"in e||"topSide"in e||"bottomSide"in e},vPt=e=>{if(xPt(e))return{leftSize:e.leftSide?.pins.length??0,rightSize:e.rightSide?.pins.length??0,topSize:e.topSide?.pins.length??0,bottomSize:e.bottomSide?.pins.length??0};let{leftSize:t=0,rightSize:n=0,topSize:i=0,bottomSize:r=0}=e;return{leftSize:t,rightSize:n,topSize:i,bottomSize:r}};function oV(e){let t=e;return t.leftSide!==void 0||t.rightSide!==void 0||t.topSide!==void 0||t.bottomSide!==void 0}var wPt=e=>{let t=e.portDistanceFromEdge??.4,n=e.schPortArrangement?vPt(e.schPortArrangement):null,i={left:0,right:0,top:0,bottom:0},r=e.pinCount??null;if(r===null)if(n)r=n.leftSize+n.rightSize+n.topSize;else throw new Error("Could not determine pin count for the schematic box");if(r&&!n){let y=Math.floor(r/2);n={leftSize:r-y,rightSize:y,topSize:0,bottomSize:0}}n||(n={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let o=({side:y,sideIndex:g,truePinIndex:x})=>{if(!e.schPortArrangement||!oV(e.schPortArrangement))return x+1;let w={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[y],S=e.schPortArrangement?.[`${y}Side`]?.direction??w,E=e.schPortArrangement?.[`${y}Side`]?.pins,M=g;return S!==w&&(M=E.length-g-1),cm(E[M],e.pinLabels)},s=[],a=0,c=0;for(let y=0;y<n.leftSize;y++){let g=o({side:"left",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.topMargin&&(a+=x.topMargin),s.push({trueIndex:c,pinNumber:g,side:"left",distanceFromOrthogonalEdge:a}),x?.bottomMargin&&(a+=x.bottomMargin),y===n.leftSize-1?i.left=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.bottomSize;y++){let g=o({side:"bottom",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.leftMargin&&(a+=x.leftMargin),s.push({trueIndex:c,pinNumber:g,side:"bottom",distanceFromOrthogonalEdge:a}),x?.rightMargin&&(a+=x.rightMargin),y===n.bottomSize-1?i.bottom=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.rightSize;y++){let g=o({side:"right",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.bottomMargin&&(a+=x.bottomMargin),s.push({trueIndex:c,pinNumber:g,side:"right",distanceFromOrthogonalEdge:a}),x?.topMargin&&(a+=x.topMargin),y===n.rightSize-1?i.right=a:a+=e.schPinSpacing,c++}a=0;for(let y=0;y<n.topSize;y++){let g=o({side:"top",sideIndex:y,truePinIndex:c}),x=e.numericSchPinStyle?.[`pin${g}`]??e.numericSchPinStyle?.[g];x?.rightMargin&&(a+=x.rightMargin),s.push({trueIndex:c,pinNumber:g,side:"top",distanceFromOrthogonalEdge:a}),x?.leftMargin&&(a+=x.leftMargin),y===n.topSize-1?i.top=a:a+=e.schPinSpacing,c++}let l=e.schWidth;if(l===void 0){l=Math.max(i.top+e.schPinSpacing*2,i.bottom+e.schPinSpacing*2);let y=e.pinLabels?Math.max(...Object.values(e.pinLabels).map(x=>x.length*.1)):0,g=y>0?1.1:0;l=Math.max(l,y+g)}let u=e.schHeight;u||(u=Math.max(i.left+e.schPinSpacing*2,i.right+e.schPinSpacing*2));let h={left:{x:-l/2-t,y:i.left/2},bottom:{x:-i.bottom/2,y:-u/2-t},right:{x:l/2+t,y:-i.right/2},top:{x:i.top/2,y:u/2+t}},d={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},_=s.map(y=>{let{distanceFromOrthogonalEdge:g,side:x}=y,w=h[x],S=d[x];return{x:w.x+g*S.x,y:w.y+g*S.y,...y}});return{getPortPositionByPinNumber(y){let g=_.find(x=>x.pinNumber.toString()===y.toString());return g||null},getSize(){return{width:l,height:u}},getSizeIncludingPins(){return{width:l+(n.leftSize||n.rightSize?.4:0),height:u+(n.topSize||n.bottomSize?.4:0)}},pinCount:r}},SPt=(0,sV.default)("tscircuit:core:footprint"),aV=class extends be{get config(){return{componentName:"Footprint",zodProps:kz}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let e=this.children.filter(h=>h.componentName==="Constraint");if(e.length===0)return;let{isFlipped:t}=this._getPcbPrimitiveFlippedHelpers(),n=h=>t&&"left"in h&&"right"in h?{...h,left:h.right,right:h.left}:h,i=e.flatMap(h=>h._getAllReferencedComponents().componentsWithSelectors).map(({component:h,selector:d,componentSelector:_,edge:y})=>({component:h,selector:d,componentSelector:_,edge:y,bounds:h._getPcbCircuitJsonBounds()}));if(i.some(h=>h.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function r(h){return i.find(({selector:d})=>d===h)}let o=new Op,s={};function a(h){return h in s||(s[h]=new js(h),o.addEditVariable(s[h],wn.weak)),s[h]}for(let{selector:h,bounds:d}of i){let _=a(`${h}_x`),y=a(`${h}_y`);o.suggestValue(_,d.center.x),o.suggestValue(y,d.center.y)}for(let h of e){let d=h._parsedProps;if("xDist"in d){let{xDist:_,left:y,right:g,edgeToEdge:x,centerToCenter:w}=n(d),S=a(`${y}_x`),E=a(`${g}_x`),M=r(y)?.bounds,k=r(g)?.bounds;if(w){let I=new En(E,[-1,S]);o.addConstraint(new ai(I,Yn.Eq,d.xDist,wn.required))}else if(x){let I=new En(E,-k.width/2,[-1,S],-M.width/2);o.addConstraint(new ai(I,Yn.Eq,d.xDist,wn.required))}}else if("yDist"in d){let{yDist:_,top:y,bottom:g,edgeToEdge:x,centerToCenter:w}=d,S=a(`${y}_y`),E=a(`${g}_y`),M=r(y)?.bounds,k=r(g)?.bounds;if(w){let I=new En(S,[-1,E]);o.addConstraint(new ai(I,Yn.Eq,d.yDist,wn.required))}else if(x){let I=new En(S,M.height/2,[-1,E],-k.height/2);o.addConstraint(new ai(I,Yn.Eq,d.yDist,wn.required))}}else if("sameY"in d){let{for:_}=d;if(_.length<2)continue;let y=_.map(x=>a(`${x}_y`)),g=new En(...y.slice(1));o.addConstraint(new ai(g,Yn.Eq,y[0],wn.required))}else if("sameX"in d){let{for:_}=d;if(_.length<2)continue;let y=_.map(x=>a(`${x}_x`)),g=new En(...y.slice(1));o.addConstraint(new ai(g,Yn.Eq,y[0],wn.required))}}o.updateVariables(),SPt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(s).map(([h,d])=>({var:h,val:d.value()}))));let c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:h,bounds:{width:d,height:_}}of i){let y=a(`${h}_x`),g=a(`${h}_y`),x=y.value()-d/2,w=y.value()+d/2,S=g.value()+_/2,E=g.value()-_/2;c.left=Math.min(c.left,x),c.right=Math.max(c.right,w),c.top=Math.max(c.top,S),c.bottom=Math.min(c.bottom,E)}let l={x:-(c.right+c.left)/2,y:-(c.top+c.bottom)/2},u=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();l.x+=u.x,l.y+=u.y;for(let{component:h,selector:d}of i){let _=a(`${d}_x`),y=a(`${d}_y`);h._setPositionFromLayout({x:_.value()+l.x,y:y.value()+l.y})}}},cV=e=>{if(!e)return null;let n=e.split("?")[0].split("#")[0],i=n.split("/").pop()??n;return i.includes(".")?i.split(".").pop()?.toLowerCase()??null:null},kI=p.union([p.number(),p.string()]),NX=p.object({x:kI,y:kI,z:kI}),lV=class extends be{get config(){return{componentName:"CadModel",zodProps:eF}}doInitialCadModelRender(){let e=this._findParentWithPcbComponent();if(!e||!e.pcb_component_id)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=e._getPcbCircuitJsonBounds(),r=t.pcb_component.get(e.pcb_component_id),o=this._parsedProps;if(!o||typeof o.modelUrl!="string")return;let s=e._computePcbGlobalTransformBeforeLayout(),c=To(s).rotation.angle*180/Math.PI,l=NX.parse({x:0,y:0,z:0});if(typeof o.rotationOffset=="number")l.z=Number(o.rotationOffset);else if(typeof o.rotationOffset=="object"){let g=NX.parse(o.rotationOffset);l.x=Number(g.x),l.y=Number(g.y),l.z=Number(g.z)}let u=wg.parse({x:o.pcbX??0,y:o.pcbY??0,z:o.pcbZ??0,...typeof o.positionOffset=="object"?o.positionOffset:{}}),h=e.props.layer==="bottom"?"bottom":"top",d=cV(o.modelUrl),_={};d==="stl"?_.model_stl_url=this._addCachebustToModelUrl(o.modelUrl):d==="obj"?_.model_obj_url=this._addCachebustToModelUrl(o.modelUrl):d==="gltf"?_.model_gltf_url=this._addCachebustToModelUrl(o.modelUrl):d==="glb"?_.model_glb_url=this._addCachebustToModelUrl(o.modelUrl):d==="step"||d==="stp"?_.model_step_url=this._addCachebustToModelUrl(o.modelUrl):d==="wrl"||d==="vrml"?_.model_wrl_url=this._addCachebustToModelUrl(o.modelUrl):_.model_stl_url=this._addCachebustToModelUrl(o.modelUrl);let y=t.cad_component.insert({position:{x:i.center.x+Number(u.x),y:i.center.y+Number(u.y),z:(h==="bottom"?-n/2:n/2)+Number(u.z)},rotation:{x:Number(l.x),y:(h==="top"?0:180)+Number(l.y),z:h==="bottom"?-(c+Number(l.z))+180:c+Number(l.z)},pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,model_unit_to_mm_scale_factor:typeof o.modelUnitToMmScale=="number"?o.modelUnitToMmScale:void 0,..._});this.cad_component_id=y.cad_component_id}_findParentWithPcbComponent(){let e=this.parent;for(;e&&!e.pcb_component_id;)e=e.parent;return e}_addCachebustToModelUrl(e){if(!e||!e.includes("modelcdn.tscircuit.com"))return e;let t=this.root?.getClientOrigin()??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(t)}`}},uV=class extends be{constructor(){super(...arguments);T(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:tF}}},PPt=(e,t)=>{if(!e)return;let n={};for(let[i,r]of Object.entries(e)){let o=cm(i,t),s={leftMargin:r.marginLeft??r.leftMargin,rightMargin:r.marginRight??r.rightMargin,topMargin:r.marginTop??r.topMargin,bottomMargin:r.marginBottom??r.bottomMargin};n[`pin${o}`]={...n[`pin${o}`],...s}}return n},AX=class{constructor({input:e}){T(this,"input");this.input=e}solveAndMapToTraces(){let e=[];for(let t of this.input.connections){if(t.pointsToConnect.length!==2)continue;let[n,i]=t.pointsToConnect,r={type:"pcb_trace",pcb_trace_id:"",connection_name:t.name,route:[{route_type:"wire",x:n.x,y:n.y,layer:"top",width:.1},{route_type:"wire",x:i.x,y:i.y,layer:"top",width:.1}]};e.push(r)}return e}},TPt=e=>{let t=Math.min(...e.map(o=>o.center.x)),n=Math.max(...e.map(o=>o.center.x)),i=Math.min(...e.map(o=>o.center.y)),r=Math.max(...e.map(o=>o.center.y));return{minX:t,maxX:n,minY:i,maxY:r}},RX=["top","bottom","inner1","inner2"],tx=(e,t=[])=>{let n=[];if(t.length===0){let a=e[0].layers;for(let c of a)n.push(...tx(e.slice(1),[c]));return n}if(e.length===0)return[];let i=e[0],r=i.via||i.optional_via,o=t[t.length-1];if(e.length===1){let a=i;return a.layers&&r?a.layers.map(c=>({layer_path:[...t,c]})):a.layers?.includes(o)?[{layer_path:[...t,o]}]:[]}if(!r)return i.layers&&!i.layers.includes(o)?[]:tx(e.slice(1),t.concat([o]));let s=(i.optional_via?RX:RX.filter(a=>a!==o)).filter(a=>!i.layers||i.layers?.includes(a));for(let a of s)n.push(...tx(e.slice(1),t.concat(a)));return n};function OX(e){let t={x:e.to.x-e.from.x,y:e.to.y-e.from.y},n=Math.abs(t.x),i=Math.abs(t.y);return n>i?t.x>0?"right":"left":t.y>0?"down":"up"}function gh(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}var IPt=e=>{if(e.length===1)return e[0];if(e.some(c=>c.length===0))throw new Error("Cannot merge routes with zero length");let t=[],n=e[0][0],i=e[0][e[0].length-1],r=e[1][0],o=e[1][e[1].length-1],s=Math.min(gh(n,r),gh(n,o)),a=Math.min(gh(i,r),gh(i,o));s<a?t.push(...e[0].reverse()):t.push(...e[0]);for(let c=1;c<e.length;c++){let l=t[t.length-1],u=e[c],h=u[0],d=u[u.length-1],_=gh(l,h),y=gh(l,d);_<y?t.push(...u):t.push(...u.reverse())}for(let c=1;c<t.length-1;c++){let l=t[c-1],u=t[c];l.route_type==="wire"&&u.route_type==="wire"&&l.layer!==u.layer&&t.splice(c,0,{x:l.x,y:l.y,from_layer:l.layer,to_layer:u.layer,route_type:"via"})}return t},MPt=(e,t)=>{let n="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e,i="_getGlobalPcbPositionBeforeLayout"in t?t._getGlobalPcbPositionBeforeLayout():t;return Math.sqrt((n.x-i.x)**2+(n.y-i.y)**2)};function EPt(e,t){if(t.length===0)throw new Error("No candidates given to getClosest method");let n=t[0],i=1/0;for(let r of t){let o=MPt(e,r);o<i&&(n=r,i=o)}return n}var CPt=(e,t)=>{let n=0;n+=e.length??0,n+=t.filter(i=>i.is_crossing).length;for(let i=1;i<t.length;i++){let r=t[i-1],o=t[i],s=Math.abs(r.from.x-r.to.x)<.01,a=Math.abs(o.from.x-o.to.x)<.01;s!==a&&n++}return n},lm=e=>({up:"bottom",down:"top",left:"right",right:"left"})[e]??null,zI=({firstEdge:e,firstEdgePort:t,firstDominantDirection:n,lastEdge:i,lastEdgePort:r,lastDominantDirection:o})=>{if(e&&t)return zI({lastEdge:{from:e.to,to:e.from},lastEdgePort:t,lastDominantDirection:n}).reverse().map(a=>({from:a.to,to:a.from}));let s=[];if(i&&r){let a={x:i.to.x,y:i.to.y};o==="left"||o==="right"?(a.x=r.position.x,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...r.position}})):(a.y=r.position.y,s.push({from:i.to,to:{...a}}),s.push({from:a,to:{...r.position}}))}return s=s.filter(a=>Oi(a.from,a.to)>.01),s};function kPt(e){try{return[e(),null]}catch(t){return[null,t]}}var NPt=(e,{db:t})=>{let n=e.map(i=>{let r=t.source_port.get(i.source_port_id);if(!r?.source_component_id)return null;let o=t.source_component.get(r.source_component_id);return o?.ftype==="simple_capacitor"?o.max_decoupling_trace_length:null}).filter(i=>i!==null);if(n.length!==0)return Math.min(...n)};function APt({ports:e,nets:t}){if(e.length>=2)return`${e[0]?.selector} to ${e[1]?.selector}`;if(e.length===1&&t.length===1)return`${e[0]?.selector} to net.${t[0]._parsedProps.name}`}var RPt=(e,{db:t})=>{let n=t.pcb_board.list()[0];if(n.outline){let c=n.outline,l=(u,h)=>{let d=!1;for(let _=0,y=h.length-1;_<h.length;y=_++){let g=h[_].x,x=h[_].y,w=h[y].x,S=h[y].y;x>u.y!=S>u.y&&u.x<(w-g)*(u.y-x)/(S-x)+g&&(d=!d)}return d};return e.some(u=>!l(u,c))}let i=n.width,r=n.height,o=n.center.x,s=n.center.y;return e.some(c=>c.x<o-i/2||c.y<s-r/2||c.x>o+i/2||c.y>s+r/2)},LX=(e,t)=>Math.abs(e-t)<1e-4,OPt=(e,t,{viaDiameter:n=.5}={})=>{let i=[];for(let r=0;r<e.length-1;r++){let[o,s]=[e[r],e[r+1]],a=r-1>=0?e[r-1]:null,c=LX(o.y,s.y),l=LX(o.x,s.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${t}, start: (${o.x}, ${o.y}), end: (${s.x}, ${s.y})`);let u={type:"rect",layers:[o.layer],center:{x:(o.x+s.x)/2,y:(o.y+s.y)/2},width:c?Math.abs(o.x-s.x):.1,height:l?Math.abs(o.y-s.y):.1,connectedTo:[t]};if(i.push(u),a&&a.layer===o.layer&&o.layer!==s.layer){let h={type:"rect",layers:[o.layer,s.layer],center:{x:o.x,y:o.y},connectedTo:[t],width:n,height:n};i.push(h)}}return i};function pV(e,t=4){let{center:n,width:i,height:r,rotation:o}=e,s=[],a=o*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(o%360+360)%360;if(r<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let d=i/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*c,x=-y*l,w=d*1.1,S=Math.abs(r*c)+Math.abs(d*l);s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}else{let d=r/t;for(let _=0;_<t;_++){let y=(_-t/2+.5)*d,g=-y*l,x=y*c,w=Math.abs(i*c)+Math.abs(d*l),S=d*1.1;s.push({center:{x:n.x+g,y:n.y+x},width:w,height:S})}}return s}function LPt(e,t={}){if(e.length<3)return[];let{rectHeight:n=.1}=t,i=[],r=e.map(a=>a.y),o=Math.min(...r),s=Math.max(...r);for(let a=o;a<s;a+=n){let c=a+n/2,l=[];for(let u=0;u<e.length;u++){let h=e[u],d=e[(u+1)%e.length];if(h.y<=c&&d.y>c||d.y<=c&&h.y>c){let _=(c-h.y)*(d.x-h.x)/(d.y-h.y)+h.x;l.push(_)}}l.sort((u,h)=>u-h);for(let u=0;u<l.length;u+=2)if(u+1<l.length){let h=l[u],_=l[u+1]-h;_>1e-6&&i.push({center:{x:h+_/2,y:c},width:_,height:n})}}return i}function zPt(e,t={}){let{center:n,radius:i}=e,{rectHeight:r=.1}=t,o=[],s=Math.ceil(i*2/r);for(let a=0;a<s;a++){let c=n.y-i+(a+.5)*r,l=c-n.y,u=Math.sqrt(i*i-l*l);u>0&&o.push({center:{x:n.x,y:c},width:u*2,height:r})}return o}var gc=["top","inner1","inner2","bottom"],WI=(e,t)=>{let n=r=>t?r.concat(r.map(o=>t?.getNetConnectedToId(o)).filter(Boolean)):r,i=[];for(let r of e)if(r.type==="pcb_smtpad"){if(r.shape==="circle")i.push({type:"oval",layers:[r.layer],center:{x:r.x,y:r.y},width:r.radius*2,height:r.radius*2,connectedTo:n([r.pcb_smtpad_id])});else if(r.shape==="rect")i.push({type:"rect",layers:[r.layer],center:{x:r.x,y:r.y},width:r.width,height:r.height,connectedTo:n([r.pcb_smtpad_id])});else if(r.shape==="rotated_rect"){let o={center:{x:r.x,y:r.y},width:r.width,height:r.height,rotation:r.ccw_rotation},s=pV(o);for(let a of s)i.push({type:"rect",layers:[r.layer],center:a.center,width:a.width,height:a.height,connectedTo:n([r.pcb_smtpad_id])})}}else if(r.type==="pcb_keepout")r.shape==="circle"?i.push({type:"oval",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.radius*2,height:r.radius*2,connectedTo:[]}):r.shape==="rect"&&i.push({type:"rect",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.type==="pcb_cutout"){if(r.shape==="rect")i.push({type:"rect",layers:gc,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.shape==="circle"){let o=zPt({center:r.center,radius:r.radius},{rectHeight:.6});for(let s of o)i.push({type:"rect",layers:gc,center:s.center,width:s.width,height:s.height,connectedTo:[]})}else if(r.shape==="polygon"){let o=LPt(r.points,{rectHeight:.6});for(let s of o)i.push({type:"rect",layers:gc,center:s.center,width:s.width,height:s.height,connectedTo:[]})}}else if(r.type==="pcb_hole")r.hole_shape==="oval"?i.push({type:"oval",center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="square"?i.push({type:"rect",layers:gc,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]}):(r.hole_shape==="round"||r.hole_shape==="circle")&&i.push({type:"rect",layers:gc,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]});else if(r.type==="pcb_plated_hole")r.shape==="circle"?i.push({type:"oval",layers:gc,center:{x:r.x,y:r.y},width:r.outer_diameter,height:r.outer_diameter,connectedTo:n([r.pcb_plated_hole_id])}):r.shape==="circular_hole_with_rect_pad"?i.push({type:"rect",layers:gc,center:{x:r.x,y:r.y},width:r.rect_pad_width,height:r.rect_pad_height,connectedTo:n([r.pcb_plated_hole_id])}):(r.shape==="oval"||r.shape==="pill")&&i.push({type:"oval",layers:gc,center:{x:r.x,y:r.y},width:r.outer_width,height:r.outer_height,connectedTo:n([r.pcb_plated_hole_id])});else if(r.type==="pcb_trace"){let o=OPt(r.route.map(s=>({x:s.x,y:s.y,layer:"layer"in s?s.layer:s.from_layer})),r.source_trace_id);i.push(...o)}else r.type==="pcb_via"&&i.push({type:"rect",layers:r.layers,center:{x:r.x,y:r.y},connectedTo:[],width:r.outer_diameter,height:r.outer_diameter});return i},bc=({anchor_position:e,anchor_side:t,text:n,font_size:i=.18})=>{let r=.1*(i/.18),o=n.length*r,s=i,a={...e};switch(t){case"right":a.x-=o/2;break;case"left":a.x+=o/2;break;case"top":a.y-=s/2;break;case"bottom":a.y+=s/2;break}return a},ZI=({db:e,source_trace_id:t,sameNetOnly:n,differentNetOnly:i})=>{!n&&!i&&(i=!0);let r=e.source_trace.get(t),o=[];for(let s of e.schematic_trace.list()){if(s.source_trace_id===t)continue;let c=e.source_trace.get(s.source_trace_id)?.subcircuit_connectivity_map_key===r.subcircuit_connectivity_map_key;i&&c||n&&!c||o.push(s)}return o},FPt=({edges:e,otherEdges:t})=>{let n=[...e];for(let i=0;i<n.length;i++){if(i>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let r=n[i],o=Math.abs(r.from.x-r.to.x)<.01?"vertical":r.from.y===r.to.y?"horizontal":"not-orthogonal";if(o==="not-orthogonal")continue;let s=[];for(let g of t){let x=g.from.x===g.to.x?"vertical":g.from.y===g.to.y?"horizontal":"not-orthogonal";if(x==="not-orthogonal"||o===x)continue;if(Za([r.from,r.to],[g.from,g.to],{lineThickness:.01})){let S=o==="vertical"?r.from.x:g.from.x,E=o==="vertical"?g.from.y:r.from.y,M={x:S,y:E};s.push({otherEdge:g,crossingPoint:M,distanceFromEdgeFrom:Oi(r.from,M)})}}if(s.length===0)continue;let a=s[0];for(let g of s)g.distanceFromEdgeFrom<a.distanceFromEdgeFrom&&(a=g);let c=a.crossingPoint,l=.075;if(c.x===r.from.x&&c.y===r.from.y)continue;let u=kg(r.from,c),h={x:c.x-u.x*l/2,y:c.y-u.y*l/2},d={x:c.x+u.x*l/2,y:c.y+u.y*l/2},_=Oi(d,r.to)<l,y=[{from:r.from,to:h},{from:h,to:d,is_crossing:!0},{from:d,to:r.to}];n.splice(i,1,...y),i+=y.length-2,_&&i++}return n},FI=.001,bh=(e,t)=>{let n=Math.min(t.from.x,t.to.x),i=Math.max(t.from.x,t.to.x),r=Math.min(t.from.y,t.to.y),o=Math.max(t.from.y,t.to.y);return e.x>=n&&e.x<=i&&e.y>=r&&e.y<=o},zX=e=>{let t=Math.abs(e.from.x-e.to.x)<FI,n=Math.abs(e.from.y-e.to.y)<FI;return t?"vertical":n?"horizontal":"diagonal"},DPt=(e,t)=>{let n=zX(e),i=zX(t);if(n===i)return null;if(n==="vertical"&&i==="horizontal"||n==="horizontal"&&i==="vertical"){let h=n==="vertical"?e:t,d=n==="horizontal"?e:t,_=h.from.x,y=d.from.y,g={x:_,y};return bh(g,e)&&bh(g,t)?g:null}if(n==="vertical"||i==="vertical"){let h=n==="vertical"?e:t,d=n==="vertical"?t:e,_=h.from.x,y=(d.to.y-d.from.y)/(d.to.x-d.from.x),g=d.from.y-y*d.from.x,x=y*_+g,w={x:_,y:x};return bh(w,e)&&bh(w,t)?w:null}let r=(e.to.y-e.from.y)/(e.to.x-e.from.x),o=e.from.y-r*e.from.x,s=(t.to.y-t.from.y)/(t.to.x-t.from.x),a=t.from.y-s*t.from.x;if(Math.abs(r-s)<FI)return null;let c=(a-o)/(r-s),l=r*c+o,u={x:c,y:l};return bh(u,e)&&bh(u,t)?u:null},$Pt=({edges:e,db:t,source_trace_id:n})=>{let i=ZI({db:t,source_trace_id:n,sameNetOnly:!0}).flatMap(o=>o.edges),r=new Map;for(let o of e)for(let s of i){let a=DPt(o,s);if(a){let c=`${a.x.toFixed(6)},${a.y.toFixed(6)}`;r.has(c)||r.set(c,a)}}return Array.from(r.values())};function BPt(e,t={}){let{minX:n,maxX:i,minY:r,maxY:o}=e,s=t.padding??1;if(!isFinite(n)||!isFinite(i)||!isFinite(r)||!isFinite(o))return[];let a=n-s,c=i+s,l=o+s,u=r-s,h=.01;return[{type:"rect",layers:["top"],center:{x:(a+c)/2,y:l},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(a+c)/2,y:u},width:c-a,height:h,connectedTo:[]},{type:"rect",layers:["top"],center:{x:a,y:(l+u)/2},width:h,height:l-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:c,y:(l+u)/2},width:h,height:l-u,connectedTo:[]}]}var jPt=e=>{let t=e.root.db,n=e._findConnectedPorts().ports??[],i=new Set(n.map(s=>s.schematic_port_id)),r=[];for(let s of t.toArray()){if(s.type==="schematic_component"){let a=!!s.symbol_name,c=s.size.width>s.size.height?"horz":"vert";r.push({type:"rect",layers:["top"],center:s.center,width:s.size.width+(a&&c==="horz"?-.5:0),height:s.size.height+(a&&c==="vert"?-.5:0),connectedTo:[]})}if(s.type==="schematic_port"){if(i.has(s.schematic_port_id))continue;let a=s.facing_direction?Ng(s.facing_direction):{x:0,y:0};r.push({type:"rect",layers:["top"],center:{x:s.center.x-a.x*.1,y:s.center.y-a.y*.1},width:.1+Math.abs(a.x)*.3,height:.1+Math.abs(a.y)*.3,connectedTo:[]})}s.type==="schematic_text"&&r.push({type:"rect",layers:["top"],center:s.position,width:(s.text?.length??0)*.1,height:.2,connectedTo:[]}),s.type==="schematic_box"&&r.push({type:"rect",layers:["top"],center:{x:s.x,y:s.y},width:s.width,height:s.height,connectedTo:[]})}let o=iV(t.toArray());return r.push(...BPt(o,{padding:1})),r},YPt=({edges:e,db:t,source_trace_id:n})=>{let i=t.source_trace.get(n),r=ZI({db:t,source_trace_id:n,differentNetOnly:!0}).flatMap(s=>s.edges),o=s=>{let{from:a,to:c}=s;return a.x===c.x?"vertical":"horizontal"};for(let s of e){let a=o(s),c=()=>r.find(u=>o(u)===a&&Za([s.from,s.to],[u.from,u.to],{lineThickness:.05})),l=c();for(;l;)a==="horizontal"?(s.from.y+=.1,s.to.y+=.1):(s.from.x+=.1,s.to.x+=.1),l=c()}},DI=e=>{switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},XPt=DF.version??"unknown",im=class extends Error{constructor(e){super(`${e} (capacity-autorouter@${XPt})`),this.name="AutorouterError"}},rx=class extends Error{constructor(e){super(e.message),this.errorData=e,this.name="TraceConnectionError"}},VPt=e=>{if(e.root?._featureMspSchematicTraceRouting||e._couldNotFindPort||e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let r,o;try{let Y=e._findConnectedPorts();r=Y.allPortsFound,o=Y.portsWithSelectors??[]}catch(Y){if(Y instanceof rx){t.source_trace_not_connected_error.insert({...Y.errorData,error_type:"source_trace_not_connected_error"});return}throw Y}let{netsWithSelectors:s}=e._findConnectedNets();if(!r)return;let c=o.map(Y=>Y.port.schematic_port_id).sort().join(","),l=e.root?._getBoard();if(l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.has(c))return;let u={name:e.source_trace_id,pointsToConnect:[]},h=jPt(e),d=o.filter(({port:Y})=>Y.schematic_port_id!==null).map(({port:Y})=>({port:Y,position:Y._getGlobalSchematicPositionAfterLayout(),schematic_port_id:Y.schematic_port_id??void 0,facingDirection:Y.facingDirection}));if(d.length===1&&s.length===1){let Y=s[0].net,{port:H,position:K}=d[0],Z=e.getSubcircuit().selectAll("netlabel").find(it=>{let tt=it._parsedProps.connection??it._parsedProps.connectsTo;return tt?Array.isArray(tt)?tt.some(gt=>e.getSubcircuit().selectOne(gt,{port:!0})===H):e.getSubcircuit().selectOne(tt,{port:!0})===H:!1});if(!Z){let it=t.schematic_net_label.getWhere({source_trace_id:e.source_trace_id});it&&(Z=it)}if(Z){let it="_getGlobalSchematicPositionBeforeLayout"in Z?Z._getGlobalSchematicPositionBeforeLayout():Z.anchor_position,tt=[];K.x===it.x||K.y===it.y?tt.push({from:K,to:it}):(tt.push({from:K,to:{x:it.x,y:K.y}}),tt.push({from:{x:it.x,y:K.y},to:it}));let ht=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:tt,junctions:[],subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=ht.schematic_trace_id;return}if(e.props.schDisplayLabel){let it=lm(H.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel,source_net_id:Y.source_net_id,anchor_position:K,center:bc({anchor_position:K,anchor_side:it,text:e.props.schDisplayLabel}),anchor_side:it});return}let ut=lm(H.facingDirection)??"bottom",st=t.schematic_net_label.insert({text:Y._parsedProps.name,source_net_id:Y.source_net_id,anchor_position:K,center:bc({anchor_position:K,anchor_side:ut,text:Y._parsedProps.name}),anchor_side:ut});return}if(e.props.schDisplayLabel&&("from"in e.props&&"to"in e.props||"path"in e.props)){e._doInitialSchematicTraceRenderWithDisplayLabel();return}if(d.length<2)return;let g=(()=>{let Y=[];for(let K=0;K<d.length-1;K++){let Z=d[K],ut=d[K+1],st=Ja({x:Z.position.x,y:Z.position.y,facingDirection:DI(Z.facingDirection)},{x:ut.position.x,y:ut.position.y,facingDirection:DI(ut.facingDirection)});for(let it=0;it<st.length-1;it++)Y.push({from:st[it],to:st[it+1]})}let H=(K,Z)=>{let ut=Z.width/2,st=Z.height/2,it=Z.center.x-ut,tt=Z.center.x+ut,ht=Z.center.y-st,gt=Z.center.y+st,St=dt=>dt.x>=it&&dt.x<=tt&&dt.y>=ht&&dt.y<=gt;return St(K.from)||St(K.to)?!0:[[{x:it,y:ht},{x:tt,y:ht}],[{x:tt,y:ht},{x:tt,y:gt}],[{x:tt,y:gt},{x:it,y:gt}],[{x:it,y:gt},{x:it,y:ht}]].some(dt=>Za([K.from,K.to],dt,{lineThickness:0}))};for(let K of Y)for(let Z of h)if(H(K,Z))return null;return Y})();g&&g.length===0&&(g=null),u.pointsToConnect=d.map(({position:Y})=>({...Y,layer:"top"}));let x=TPt(h),w=2,S={minTraceWidth:.1,obstacles:h,connections:[u],bounds:{minX:x.minX-w,maxX:x.maxX+w,minY:x.minY-w,maxY:x.maxY+w},layerCount:1},E=bg,M=!1;if(e.getSubcircuit().props._schDirectLineRoutingEnabled&&(E=AX,M=!0),!g){let H=new E({input:S,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(H.length===0){if(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection()){e._doInitialSchematicTraceRenderWithDisplayLabel();return}H=new AX({input:S}).solveAndMapToTraces(),M=!0}let[{route:K}]=H;g=[];for(let Z=0;Z<K.length-1;Z++)g.push({from:K[Z],to:K[Z+1]})}let k=e.source_trace_id,I=[];if(!M){YPt({edges:g,db:t,source_trace_id:k});let Y=ZI({db:t,source_trace_id:k,differentNetOnly:!0}).flatMap(H=>H.edges);g=FPt({edges:g,otherEdges:Y}),I=$Pt({edges:g,db:t,source_trace_id:e.source_trace_id})}if(!g||g.length===0)return;let N=g[g.length-1],C=d[d.length-1],A=OX(N);g.push(...zI({lastEdge:N,lastEdgePort:C,lastDominantDirection:A}));let O=g[0],B=d[0],D=OX(O);if(g.unshift(...zI({firstEdge:O,firstEdgePort:B,firstDominantDirection:D})),!e.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(e.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&CPt(I,g)>=5&&(e._isSymbolToChipConnection()||e._isSymbolToSymbolConnection()||e._isChipToChipConnection())){e._doInitialSchematicTraceRenderWithDisplayLabel();return}let X=t.schematic_trace.insert({source_trace_id:e.source_trace_id,edges:g,junctions:I,subcircuit_connectivity_map_key:e.subcircuit_connectivity_map_key??void 0});e.schematic_trace_id=X.schematic_trace_id;for(let{port:Y}of o)Y.schematic_port_id&&t.schematic_port.update(Y.schematic_port_id,{is_connected:!0});l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.add(c)};function hV(e){let t=0;for(let n=0;n<e.length;n++){let i=e[n];if(i.route_type==="wire"){let r=e[n+1];if(r){let o=r.x-i.x,s=r.y-i.y;t+=Math.sqrt(o*o+s*s)}}else i.route_type==="via"&&(t+=1.6)}return t}var Kb=e=>({...e._getGlobalPcbPositionAfterLayout(),layers:e.getAvailablePcbLayers()}),HPt=!1;function GPt(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e,r=e.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(r._parsedProps.routingDisabled)return;let o=r._parsedProps.pcbRouteCache?.pcbTraces;if(o){let A=t.pcb_trace.insert({route:o.flatMap(O=>O.route),source_trace_id:e.source_trace_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});e.pcb_trace_id=A.pcb_trace_id;return}if(n.pcbPath&&n.pcbPath.length>0||!r._shouldUseTraceByTraceRouting())return;let{allPortsFound:s,ports:a}=e._findConnectedPorts(),c=[];if(!s)return;let l=[];for(let A of a)A._hasMatchedPcbPrimitive()||l.push(A);if(l.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${l.map(A=>A.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(A=>A.pcb_port_id).filter(Boolean)});return}let u=e._findConnectedNets().netsWithSelectors;if(a.length===0&&u.length===2){e.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(a.length===1&&u.length===1){let A=a[0],B=u[0].net.getAllConnectedPorts().filter(X=>X!==A);if(B.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let D=EPt(A,B);c.push(D),a.push(D)}else if(a.length>1&&u.length>=1){e.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}let h=a.flatMap(A=>A.matchedComponents.filter(O=>O.componentName==="TraceHint")),d=(e._parsedProps.pcbRouteHints??[]).concat(h.flatMap(A=>A.getPcbRouteHints()));if(a.length>2){e.renderError(`Trace has more than two ports (${a.map(A=>A.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(e.getSubcircuit().selectAll("trace").filter(A=>A.renderPhaseStates.PcbTraceRender.initialized).some(A=>A._portsRoutedOnPcb.length===a.length&&A._portsRoutedOnPcb.every(O=>a.includes(O))))return;let g=[];d.length===0?g=[Kb(a[0]),Kb(a[1])]:g=[Kb(a[0]),...d,Kb(a[1])];let x=tx(g);if(HPt&&x.length===0){e.renderError(`Could not find a common layer (using hints) for trace ${e.getString()}`);return}let w=si(e.root.db.toArray()),[S,E]=kPt(()=>WI(e.root.db.toArray()));if(E){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Error getting obstacles for autorouting: ${E.message}`,source_trace_id:e.source_trace_id,center:{x:0,y:0},pcb_port_ids:a.map(A=>A.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[]});return}for(let A of S)if(A.connectedTo.length>0){let B=w.getNetConnectedToId(A.connectedTo[0]);B&&A.connectedTo.push(B)}let M=[];if(x.length===0)M=g;else{let A=x[0].layer_path;M=g.map((O,B)=>O.via?{...O,via_to_layer:A[B]}:{...O,layers:[A[B]]})}M[0].pcb_port_id=a[0].pcb_port_id,M[M.length-1].pcb_port_id=a[1].pcb_port_id;let k=[];for(let[A,O]of nV(M)){let B="via_to_layer"in A?A.via_to_layer:null,D=2,X="layers"in A&&A.layers.length===1?A.layers[0]:B??"top",Y="layers"in O&&O.layers.length===1?O.layers[0]:B??"top",H="pcb_port_id"in A?A.pcb_port_id:null,K="pcb_port_id"in O?O.pcb_port_id:null,Z=e.getSubcircuit()._parsedProps.minTraceWidth??.16,ut=new bg({OBSTACLE_MARGIN:Z*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(H&&K),connMap:w,input:{obstacles:S,minTraceWidth:Z,connections:[{name:e.source_trace_id,pointsToConnect:[{...A,layer:X,pcb_port_id:H},{...O,layer:Y,pcb_port_id:K}]}],layerCount:e.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(A.x,O.x)-D,maxX:Math.max(A.x,O.x)+D,minY:Math.min(A.y,O.y)-D,maxY:Math.max(A.y,O.y)+D}}}),st=null;try{st=ut.solveAndMapToTraces()}catch(ht){e.renderError({type:"pcb_trace_error",pcb_trace_error_id:e.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${ht.message}`,source_trace_id:e.pcb_trace_id,center:{x:(A.x+O.x)/2,y:(A.y+O.y)/2},pcb_port_ids:a.map(gt=>gt.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(gt=>gt.pcb_component_id)})}if(!st)return;if(st.length===0){e.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:e.pcb_trace_id,message:`Could not find a route for ${e}`,source_trace_id:e.source_trace_id,center:{x:(A.x+O.x)/2,y:(A.y+O.y)/2},pcb_port_ids:a.map(ht=>ht.pcb_port_id),pcb_trace_id:e.pcb_trace_id,pcb_component_ids:a.map(ht=>ht.pcb_component_id)});return}let[it]=st;B&&(it.route=it.route.map(ht=>(ht.route_type==="wire"&&!ht.layer&&(ht.layer=B),ht))),H&&it.route[0].route_type==="wire"&&(it.route[0].start_pcb_port_id=H);let tt=it.route[it.route.length-1];K&&tt.route_type==="wire"&&(tt.end_pcb_port_id=K),k.push(it.route)}let I=IPt(k),N=hV(I),C=t.pcb_trace.insert({route:I,source_trace_id:e.source_trace_id,subcircuit_id:e.getSubcircuit()?.subcircuit_id,trace_length:N});e._portsRoutedOnPcb=a,e.pcb_trace_id=C.pcb_trace_id;for(let A of I)A.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:C.pcb_trace_id,x:A.x,y:A.y,hole_diameter:.3,outer_diameter:.6,layers:[A.from_layer,A.to_layer],from_layer:A.from_layer,to_layer:A.to_layer});e._insertErrorIfTraceIsOutsideBoard(I,a)}function UPt(e){if(e.root?.pcbDisabled)return;let{db:t}=e.root,{_parsedProps:n}=e,i=e.getSubcircuit();if(!n.pcbPath||n.pcbPath.length===0)return;let{allPortsFound:r,ports:o,portsWithSelectors:s}=e._findConnectedPorts();if(!r)return;let a=[];for(let S of o)S._hasMatchedPcbPrimitive()||a.push(S);if(a.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:e.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${e} wasn't routed. Missing ports: ${a.map(S=>S.getString()).join(", ")}`,pcb_trace_id:e.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:a.map(S=>S.pcb_port_id).filter(Boolean)});return}let c;n.pcbPathRelativeTo&&(c=s.find(S=>S.selector===n.pcbPathRelativeTo)?.port,c||(c=e.getSubcircuit().selectOne(n.pcbPathRelativeTo))),c||(c=o[0]);let l=o.find(S=>S!==c)??o[1],u=c.getAvailablePcbLayers()[0]||"top",h=n.thickness??e.getSubcircuit()._parsedProps.minTraceWidth??.16,d=c._getGlobalPcbPositionAfterLayout(),_=l._getGlobalPcbPositionAfterLayout(),y=[];y.push({route_type:"wire",x:d.x,y:d.y,width:h,layer:u,start_pcb_port_id:c.pcb_port_id});let g=c?._computePcbGlobalTransformBeforeLayout?.()||Ai();for(let S of n.pcbPath){let E=De(g,{x:S.x,y:S.y});y.push({route_type:"wire",x:E.x,y:E.y,width:h,layer:u})}y.push({route_type:"wire",x:_.x,y:_.y,width:h,layer:u,end_pcb_port_id:l.pcb_port_id});let x=hV(y),w=t.pcb_trace.insert({route:y,source_trace_id:e.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,trace_length:x});e._portsRoutedOnPcb=o,e.pcb_trace_id=w.pcb_trace_id,e._insertErrorIfTraceIsOutsideBoard(y,o)}function qPt(e){if(e.root?.schematicDisabled)return;let{db:t}=e.root,{_parsedProps:n,parent:i}=e;if(!i)throw new Error("Trace has no parent");let{allPortsFound:r,portsWithSelectors:o}=e._findConnectedPorts();if(!r)return;let s=o.map(({port:M})=>({port:M,position:M._getGlobalSchematicPositionAfterLayout(),schematic_port_id:M.schematic_port_id,facingDirection:M.facingDirection}));if(s.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let a,c,l=s[0].position,u=s[0].port;if("path"in e.props){if(e.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[a,c]=e.props.path}else{if(!("from"in e.props&&"to"in e.props))throw new Error("Missing 'from' or 'to' properties in props.");a=e.props.from,c=e.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${a}).`);let h=s[1].position,d=s[1].port;if(!d.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);let _=t.schematic_net_label.list().find(M=>M.source_net_id===u.source_port_id),y=t.schematic_net_label.list().find(M=>M.source_net_id===d.source_port_id),[g,x]=o.map(({port:M})=>M),S=g.parent?.config.shouldRenderAsSchematicBox?`${g?.parent?.props.name}_${g?.props.name}`:`${x?.parent?.props.name}_${x?.props.name}`,E=e.props.schDisplayLabel??S;if(_&&_.text!==E&&(_.text=`${E} / ${_.text}`),y&&y?.text!==E&&(y.text=`${E} / ${y.text}`),!y){let M=lm(d.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:d.source_port_id,anchor_position:h,center:bc({anchor_position:h,anchor_side:M,text:e.props.schDisplayLabel??S}),anchor_side:M})}if(!_){let M=lm(u.facingDirection)??"bottom";t.schematic_net_label.insert({text:e.props.schDisplayLabel??S,source_net_id:u.source_port_id,anchor_position:l,center:bc({anchor_position:l,anchor_side:M,text:e.props.schDisplayLabel??S}),anchor_side:M})}}function WPt(e){let{_parsedProps:t,parent:n}=e;if(!n)throw new Error("Trace has no parent");let r=e.getTracePortPathSelectors().map(o=>({selector:o,port:e.getSubcircuit().selectOne(o,{type:"port"})??null}));for(let{selector:o,port:s}of r)if(!s){let a,c,l=o.lastIndexOf(".");if(l!==-1&&l>o.lastIndexOf(" "))a=o.slice(0,l),c=o.slice(l+1);else{let M=o.match(/^(.*[ >])?([^ >]+)$/);a=M?.[1]?.trim()??"",c=M?.[2]??o}let u=a?e.getSubcircuit().selectOne(a):null;if(!u&&a&&!/[.#\[]/.test(a)&&(u=e.getSubcircuit().selectOne(`.${a}`)),!u){let M=a?`Could not find port for selector "${o}". Component "${a}" not found`:`Could not find port for selector "${o}"`,k=e.getSubcircuit(),I=k.getGroup();throw new rx({error_type:"source_trace_not_connected_error",message:M,subcircuit_id:k.subcircuit_id??void 0,source_group_id:I?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[o]})}let h=u.children.filter(M=>M.componentName==="Port"),d=c.includes(".")?c.split(".").pop()??"":c,_=h.flatMap(M=>M.getNameAndAliases()),y=_.some(M=>!/^(pin\d+|\d+)$/.test(M)),g=Array.from(new Set(_)).join(", "),x;h.length===0?x="It has no ports":y?x=`It has [${g}]`:x=`It has ${h.length} pins and no pinLabels (consider adding pinLabels)`;let w=`Could not find port for selector "${o}". Component "${u.props.name??a}" found, but does not have pin "${d}". ${x}`,S=e.getSubcircuit(),E=S.getGroup();throw new rx({error_type:"source_trace_not_connected_error",message:w,subcircuit_id:S.subcircuit_id??void 0,source_group_id:E?.source_group_id??void 0,source_trace_id:e.source_trace_id??void 0,selectors_not_found:[o]})}return r.some(o=>!o.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:r,ports:r.map(({port:o})=>o)}}var ko=class extends be{constructor(t){super(t);T(this,"source_trace_id",null);T(this,"pcb_trace_id",null);T(this,"schematic_trace_id",null);T(this,"_portsRoutedOnPcb");T(this,"subcircuit_connectivity_map_key",null);T(this,"_traceConnectionHash",null);T(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}get config(){return{zodProps:Cz,componentName:"Trace"}}_getTracePortOrNetSelectorListFromProps(){return"from"in this.props&&"to"in this.props?[typeof this.props.from=="string"?this.props.from:this.props.from.getPortSelector(),typeof this.props.to=="string"?this.props.to:this.props.to.getPortSelector()]:"path"in this.props?this.props.path.map(t=>typeof t=="string"?t:t.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(t=>!t.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(t=>t.includes("net."))}_findConnectedPorts(){return WPt(this)}_resolveNet(t){let n=this.getSubcircuit().selectOne(t,{type:"net"});if(n)return n;let i=t.match(/^net\.(.+)$/),r=i?i[1]:null;return r&&this.root._getBoard().getDescendants().find(s=>s.componentName==="Net"&&s._parsedProps.name===r)||null}_findConnectedNets(){let t=this.getTracePathNetSelectors().map(i=>({selector:i,net:this._resolveNet(i)})),n=t.filter(i=>!i.net);return n.length>0&&this.renderError(`Could not find net for selector "${n[0].selector}" inside ${this}`),{netsWithSelectors:t,nets:t.map(i=>i.net)}}_getAllTracesConnectedToSameNet(){let t=this.getSubcircuit().selectAll("trace"),n=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return t.filter(r=>{if(r===this)return!1;let o=r._findConnectedNets().nets,s=r._findConnectedPorts().ports??[];return o.some(a=>n.includes(a))||s.some(a=>i.includes(a))})}_isExplicitlyConnectedToPort(t){let{allPortsFound:n,portsWithSelectors:i}=this._findConnectedPorts();return n?i.map(o=>o.port).includes(t):!1}_isExplicitlyConnectedToNet(t){return this._findConnectedNets().nets.includes(t)}doInitialCreateNetsFromProps(){GI(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();return!t||!n?null:[...n].sort((o,s)=>(o.pcb_port_id||"").localeCompare(s.pcb_port_id||"")).map(o=>o.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}let r,o;try{let h=this._findConnectedPorts();r=h.allPortsFound,o=h.portsWithSelectors??[]}catch(h){if(h instanceof rx){t.source_trace_not_connected_error.insert({...h.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw h}if(!r)return;this._traceConnectionHash=this._computeTraceConnectionHash();let a=t.source_trace.list().find(h=>h.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&h.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(a){this.source_trace_id=a.source_trace_id;return}let c=this._findConnectedNets().nets,l=APt({ports:o,nets:c}),u=t.source_trace.insert({connected_source_port_ids:o.map(h=>h.port.source_port_id),connected_source_net_ids:c.map(h=>h.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:NPt(o.map(h=>h.port),{db:t})??n.maxLength,display_name:l,min_trace_thickness:n.thickness});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(t,n){let{db:i}=this.root;RPt(t,{db:i})&&i.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:n.map(o=>o.pcb_port_id)})}doInitialPcbManualTraceRender(){UPt(this)}doInitialPcbTraceRender(){GPt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){qPt(this)}_isSymbolToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=i.parent.config.shouldRenderAsSchematicBox,s=r.parent.config.shouldRenderAsSchematicBox;return o&&!s||!o&&s}_isSymbolToSymbolConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=!i.parent.config.shouldRenderAsSchematicBox,s=!r.parent.config.shouldRenderAsSchematicBox;return o&&s}_isChipToChipConnection(){let{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;let[i,r]=n;if(!i?.parent||!r?.parent)return!1;let o=i.parent.config.shouldRenderAsSchematicBox,s=r.parent.config.shouldRenderAsSchematicBox;return o&&s}doInitialSchematicTraceRender(){VPt(this)}},ZPt=e=>{let{db:t}=e.root;if(e.pcb_component_id){let n=t.pcb_component.get(e.pcb_component_id);return n?{width:n.width,height:n.height}:null}if(e.pcb_group_id){let n=t.pcb_group.get(e.pcb_group_id);return n?{width:n.width,height:n.height}:null}return null},KPt=(e,t)=>{let{db:n}=e.root,i=n.toArray();if(e.pcb_component_id){Ag(i,e.pcb_component_id,t);return}if(e.source_group_id){Rg(i,e.source_group_id,t);return}throw new Error(`Cannot reposition component ${e.getString()}: no pcb_component_id or source_group_id`)},JPt=e=>{let{db:t}=e.root;if(!e.source_component_id)return;let n=e.selectAll("port"),i=t.source_trace.list(),r=new Set;for(let s of i)for(let a of s.connected_source_port_ids)r.add(a);let o=e._getInternallyConnectedPins();for(let s of o)if(s.some(a=>a.source_port_id&&r.has(a.source_port_id)))for(let a of s)a.source_port_id&&r.add(a.source_port_id);for(let s of n)s.source_port_id&&QPt(e,s)&&(r.has(s.source_port_id)||t.source_pin_missing_trace_warning.insert({message:`Port ${s.getNameAndAliases()[0]} on ${e.props.name} is missing a trace`,source_component_id:e.source_component_id,source_port_id:s.source_port_id,subcircuit_id:e.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},QPt=(e,t)=>{if(e.config.componentName==="Chip"){let n=e.props.pinAttributes;if(!n)return!1;for(let i of t.getNameAndAliases()){let r=n[i];if(r?.requiresPower||r?.requiresGround||r?.requiresVoltage!==void 0)return!0}return!1}return!0};function t3t(e){let t=e.font_size,n=e.text.length*t*.6,i=t,r=e.anchor_alignment||"center",o=e.anchor_position.x,s=e.anchor_position.y;switch(r){case"top_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y+i/2;break;case"top_center":o=e.anchor_position.x,s=e.anchor_position.y+i/2;break;case"top_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y+i/2;break;case"center_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y;break;case"center":o=e.anchor_position.x,s=e.anchor_position.y;break;case"center_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y;break;case"bottom_left":o=e.anchor_position.x+n/2,s=e.anchor_position.y-i/2;break;case"bottom_center":o=e.anchor_position.x,s=e.anchor_position.y-i/2;break;case"bottom_right":o=e.anchor_position.x-n/2,s=e.anchor_position.y-i/2;break;default:o=e.anchor_position.x,s=e.anchor_position.y;break}return{x:o-n/2,y:s-i/2,width:n,height:i}}function e3t(e){if(!e._adjustSilkscreenTextAutomatically||e.root?.pcbDisabled||!e.pcb_component_id)return;let{db:t}=e.root,i=e._getPcbCircuitJsonBounds().center,r=t.pcb_silkscreen_text.list({pcb_component_id:e.pcb_component_id}).filter(c=>c.text===e.name);if(r.length===0)return;let a=e.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(c=>c!==e&&c.pcb_component_id).map(c=>{let l=c._getPcbCircuitJsonBounds(),u={center:l.center,width:l.width,height:l.height};return $s(u)});for(let c of r){let l=c.anchor_position,u=t3t(c),h={center:{x:u.x+u.width/2,y:u.y+u.height/2},width:u.width,height:u.height},d=$s(h);if(!a.some(E=>Ka(d,E)))continue;let y=2*i.x-l.x,g=2*i.y-l.y,x={center:{x:y,y:g},width:u.width,height:u.height},w=$s(x);a.some(E=>Ka(w,E))||t.pcb_silkscreen_text.update(c.pcb_silkscreen_text_id,{anchor_position:{x:y,y:g}})}}function n3t(e){if(!e)return{validPinLabels:e,invalidPinLabelsMessages:[]};let t={},n=[];for(let[i,r]of Object.entries(e)){let o=Array.isArray(r)?r.slice():[r],s=[];for(let a of o)i3t(i,a)?s.push(a):n.push(`Invalid pin label: ${i} = '${a}' - excluding from component. Please use a valid pin label.`);s.length>0&&(t[i]=Array.isArray(r)?s:s[0])}return{validPinLabels:Object.keys(t).length>0?t:void 0,invalidPinLabelsMessages:n}}function i3t(e,t){try{let n={name:"test",footprint:"test",pinLabels:{[e]:t}};return Rp.safeParse(n).success}catch{return!1}}var um=e=>e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/"),BI=e=>{if(um(e))return null;let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t),i=e.slice(t+1);return!n||!i?null:{footprintLib:n,footprintName:i}},r3t=(e,t)=>{if(!t||!e.startsWith("/"))return e;try{let n=new URL(t);return new URL(e,n.origin).toString()}catch{return e}};function o3t(e,t){let{footprint:n}=e.props;if(n??(n=e._getImpliedFootprintString?.()),!n)return;let{pcbRotation:i,pinLabels:r,pcbPinLabels:o}=e.props,s=cV(String(n)),a=s?e.root?.platform?.footprintFileParserMap?.[s]:null;if(typeof n=="string"&&um(n)&&a){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let c=e.root?.platform?.projectBaseUrl,l=r3t(n,c);t("load-footprint-from-platform-file-parser",async()=>{try{let u=await a.loadFromUrl(n).catch(()=>a.loadFromUrl(l)),h=nm({componentName:e.name,componentRotation:i,footprint:l,pinLabels:r,pcbPinLabels:o},u.footprintCircuitJson);e.addAll(h),e._markDirty("InitializePortsFromChildren")}catch(u){let h=e.root?.db;if(h&&e.source_component_id&&e.pcb_component_id){let d=e.getSubcircuit(),_=`${e.getString()} failed to load footprint "${l}": `+(u instanceof Error?u.message:String(u)),y=dp.parse({type:"external_footprint_load_error",message:_,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:d.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:l});h.external_footprint_load_error.insert(y)}throw u}});return}if(typeof n=="string"&&um(n)){if(e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let c=n;t("load-footprint-url",async()=>{try{let l=await fetch(c);if(!l.ok)throw new Error(`Failed to fetch footprint: ${l.status}`);let u=await l.json(),h=nm({componentName:e.name,componentRotation:i,footprint:c,pinLabels:r,pcbPinLabels:o},u);e.addAll(h),e._markDirty("InitializePortsFromChildren")}catch(l){let u=e.root?.db;if(u&&e.source_component_id&&e.pcb_component_id){let h=e.getSubcircuit(),d=`${e.getString()} failed to load external footprint "${c}": `+(l instanceof Error?l.message:String(l)),_=dp.parse({type:"external_footprint_load_error",message:d,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:h.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(_)}throw l}});return}if(typeof n=="string"){let c=BI(n);if(!c||e._hasStartedFootprintUrlLoad)return;e._hasStartedFootprintUrlLoad=!0;let u=e.root?.platform?.footprintLibraryMap?.[c.footprintLib],h;if(typeof u=="function"&&(h=u),!h)return;t("load-lib-footprint",async()=>{try{let d=await h(c.footprintName),_=null;if(Array.isArray(d)?_=d:Array.isArray(d.footprintCircuitJson)&&(_=d.footprintCircuitJson),!_)return;let y=nm({componentName:e.name,componentRotation:i,footprint:n,pinLabels:r,pcbPinLabels:o},_);e.addAll(y),!Array.isArray(d)&&d.cadModel&&(e._asyncFootprintCadModel=d.cadModel);for(let g of e.children)g.componentName==="Port"&&g._markDirty?.("PcbPortRender");e._markDirty("InitializePortsFromChildren")}catch(d){let _=e.root?.db;if(_&&e.source_component_id&&e.pcb_component_id){let y=e.getSubcircuit(),g=`${e.getString()} failed to load external footprint "${n}": `+(d instanceof Error?d.message:String(d)),x=dp.parse({type:"external_footprint_load_error",message:g,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:y.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0,footprinter_string:n});_.external_footprint_load_error.insert(x)}throw d}});return}if(!(0,$I.isValidElement)(n)&&n.componentName==="Footprint"&&e.add(n),Array.isArray(n)&&!(0,$I.isValidElement)(n)&&n.length>0){try{let c=nm({componentName:e.name,componentRotation:i,footprint:"",pinLabels:r,pcbPinLabels:o},n);e.addAll(c)}catch(c){let l=e.root?.db;if(l&&e.source_component_id&&e.pcb_component_id){let u=e.getSubcircuit(),h=`${e.getString()} failed to load json footprint: `+(c instanceof Error?c.message:String(c)),d=i_.parse({type:"circuit_json_footprint_load_error",message:h,pcb_component_id:e.pcb_component_id,source_component_id:e.source_component_id,subcircuit_id:u.subcircuit_id??void 0,pcb_group_id:e.getGroup()?.pcb_group_id??void 0});l.circuit_json_footprint_load_error.insert(d)}throw c}return}}function s3t(e){if(e.root?.pcbDisabled||!e.pcb_component_id)return;let{pcbX:t,pcbY:n}=e._parsedProps,i=e.props?.pcbPositionAnchor;if(!i||t===void 0&&n===void 0)return;let r=cx(e.children);if(r.width===0||r.height===0)return;let s={...{x:(r.minX+r.maxX)/2,y:(r.minY+r.maxY)/2}},a=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(i)){let u={left:r.minX,right:r.maxX,top:r.minY,bottom:r.maxY};switch(i){case"center":a=s;break;case"top_left":a={x:u.left,y:u.top};break;case"top_center":a={x:s.x,y:u.top};break;case"top_right":a={x:u.right,y:u.top};break;case"center_left":a={x:u.left,y:s.y};break;case"center_right":a={x:u.right,y:s.y};break;case"bottom_left":a={x:u.left,y:u.bottom};break;case"bottom_center":a={x:s.x,y:u.bottom};break;case"bottom_right":a={x:u.right,y:u.bottom};break}}else try{let u=e.portMap[i];u&&(a=u._getGlobalPcbPositionBeforeLayout())}catch{}if(!a)return;let l={...s};t!==void 0&&(l.x+=t-a.x),n!==void 0&&(l.y+=n-a.y),(Math.abs(l.x-s.x)>1e-6||Math.abs(l.y-s.y)>1e-6)&&e._repositionOnPcb(l)}var a3t=(0,KX.default)("tscircuit:core"),c3t=p.object({x:ze,y:ze,z:ze}),On=class extends be{constructor(t){let n={...t},i=[];if(n.pinLabels&&!Array.isArray(n.pinLabels)){let{validPinLabels:r,invalidPinLabelsMessages:o}=n3t(n.pinLabels);n.pinLabels=r,i=o}super(n);T(this,"reactSubtrees",[]);T(this,"_impliedFootprint");T(this,"isPrimitiveContainer",!0);T(this,"_isNormalComponent",!0);T(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});T(this,"_asyncSupplierPartNumbers");T(this,"_asyncFootprintCadModel");T(this,"_isCadModelChild");T(this,"pcb_missing_footprint_error_id");T(this,"_hasStartedFootprintUrlLoad",!1);T(this,"_invalidPinLabelMessages",[]);T(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=i,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(n=>n.map(i=>typeof i=="number"?`pin${i}`:i))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let t=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(r=>r!==this&&r._isNormalComponent&&r.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let r=this._getGlobalPcbPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout();t.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:r,schematic_center:o}),this.shouldBeRemoved=!0;let s=[...this.children];for(let a of s)this.remove(a)}}initPorts(t={}){if(this.root?.schematicDisabled)return;let{config:n}=this,i=[],r=this._getSchematicPortArrangement();if(r&&!this._parsedProps.pinLabels){for(let l in r){let u=r[l].pins;if(Array.isArray(u))for(let h of u){let d=cm(h,this._parsedProps.pinLabels);i.push(new Di({pinNumber:d,aliases:t.additionalAliases?.[`pin${d}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let a=["left","right","top","bottom"],c=1;for(let l of a){let u=r[`${l}Size`];for(let h=0;h<u;h++)i.push(new Di({pinNumber:c++,aliases:t.additionalAliases?.[`pin${c}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let o=this._parsedProps.pinLabels;if(o)for(let[a,c]of Object.entries(o)){a=a.replace("pin","");let l=i.find(d=>d._parsedProps.pinNumber===Number(a)),u=Array.isArray(c)?c[0]:c,h=Array.isArray(c)?c.slice(1):[];l?(l.externallyAddedAliases.push(u,...h),l.props.name=u):(l=new Di({pinNumber:parseInt(a),name:u,aliases:[...h,...t.additionalAliases?.[`pin${parseInt(a)}`]??[]]},{originDescription:`pinLabels:pin${a}`}),i.push(l))}if(n.schematicSymbolName&&!t.ignoreSymbolPorts){let a=Qn[this._getSchematicSymbolNameOrThrow()];if(!a)return;for(let c of a.ports){let l=rV(c.labels);if(!l)continue;let u=i.find(h=>h._parsedProps.pinNumber===Number(l));if(u)u.schematicSymbolPortDef=c;else{let h=em(c.labels.concat(t.additionalAliases?.[`pin${l}`]??[]));h&&(h.originDescription=`schematicSymbol:labels[0]:${c.labels[0]}`,h.schematicSymbolPortDef=c,i.push(h))}}this.addAll(i)}if(!this._getSchematicPortArrangement()){let a=this.getPortsFromFootprint(t);for(let c of a)i.some(l=>l.isMatchingAnyOf(c.getNameAndAliases()))||i.push(c)}let s=t.pinCount??this._getPinCount()??0;for(let a=1;a<=s;a++){if(i.find(l=>l._parsedProps.pinNumber===a))continue;if(!r){i.push(new Di({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]}));continue}let c=[...r.leftSide?.pins??[],...r.rightSide?.pins??[],...r.topSide?.pins??[],...r.bottomSide?.pins??[]].map(l=>cm(l,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(l=>l in r)&&(c=Array.from({length:this._getPinCount()},(l,u)=>u+1)),c.includes(a)&&i.push(new Di({pinNumber:a,aliases:t.additionalAliases?.[`pin${a}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${a}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:t,pinLabels:n,pcbPinLabels:i}=this.props,{footprint:r}=this.props;if(r??(r=this._getImpliedFootprintString?.()),!!r&&typeof r=="string"){if(um(r)||BI(r))return;let o=mw.string(r).soup(),s=nm({componentName:this.name??this.componentName,componentRotation:t,footprint:r,pinLabels:n,pcbPinLabels:i},o);this.addAll(s)}}get portMap(){return new Proxy({},{get:(t,n)=>{let i=this.children.find(r=>r.componentName==="Port"&&r.isMatchingNameOrAlias(n));if(!i)throw new Error(`There was an issue finding the port "${n.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return i}})}getInstanceForReactElement(t){for(let n of this.reactSubtrees)if(n.element===t)return n.component;return null}doInitialSourceRender(){let t=this.config.sourceFtype;if(!t)return;let{db:n}=this.root,{_parsedProps:i}=this,r=n.source_component.insert({ftype:t,name:this.name,manufacturer_part_number:i.manufacturerPartNumber??i.mfn,supplier_part_numbers:i.supplierPartNumbers});this.source_component_id=r.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let o of this._invalidPinLabelMessages){let s="pinLabels",a=o.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);a&&(s=`pinLabels['${a[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:s,message:o,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:n}=this.config,{_parsedProps:i}=this;i.symbol&&(0,ea.isValidElement)(i.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(i.symbol):n?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let r=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&r){if(!this.schematic_component_id)return;let o=e_.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});t.schematic_manual_edit_conflict_warning.insert(o)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let t=[];for(let n of this.internallyConnectedPinNames){let i=[];for(let r of n)i.push(this.portMap[r]);t.push(i)}return t}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicSymbolNameOrThrow(),r=Qn[i],o=this._getGlobalSchematicPositionBeforeLayout();if(r){let s=t.schematic_component.insert({center:o,size:r.size,source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name:i,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=s.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(t){if(this.root?.schematicDisabled)return;let{db:n}=this.root,i=this._getGlobalSchematicPositionBeforeLayout(),r=n.schematic_component.insert({center:i,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1});this.schematic_component_id=r.schematic_component_id}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicBoxDimensions(),r={};if(Array.isArray(n.pinLabels))n.pinLabels.forEach((_,y)=>{r[String(y+1)]=_});else for(let[_,y]of Object.entries(n.pinLabels??{}))r[_]=Array.isArray(y)?y[0]:y;let o=this._getGlobalSchematicPositionBeforeLayout(),s=this._getSchematicPortArrangement(),a=t.schematic_component.insert({center:o,rotation:n.schRotation??0,size:i.getSize(),port_arrangement:pPt(s),pin_spacing:n.schPinSpacing??.2,pin_styles:uPt(n.schPinStyle,n.pinLabels),port_labels:r,source_component_id:this.source_component_id}),c=s?.topSide!==void 0||s?.bottomSide!==void 0,l=i?.getSize().width,u=i?.getSize().height,h=t.schematic_text.insert({text:n.manufacturerPartNumber??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(l??0)/2+.1:o.x-(l??0)/2,y:c?o.y+(u??0)/2+.35:o.y-(u??0)/2-.13},color:"#006464",font_size:.18}),d=t.schematic_text.insert({text:n.name??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(l??0)/2+.1:o.x-(l??0)/2,y:c?o.y+(u??0)/2+.55:o.y+(u??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=a.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this._computePcbGlobalTransformBeforeLayout(),s=To(r).rotation.angle*180/Math.PI,a=t.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:n.layer??"top",rotation:n.pcbRotation??s,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});if(!(n.footprint??this._getImpliedFootprintString())&&!this.isGroup){let u=t.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=u.pcb_missing_footprint_error_id}this.pcb_component_id=a.pcb_component_id;let l=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&l){let u=r_.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0});t.pcb_manual_edit_conflict_warning.insert(u)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:t}=this.root,{_parsedProps:n}=this,i=cx(this.children);if(i.width===0||i.height===0)return;let r={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};t.pcb_component.update(this.pcb_component_id,{center:r,width:i.width,height:i.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db:t}=this.root;if(!t.schematic_component.get(this.schematic_component_id))return;let i=[],r=u=>{for(let h of u){if(h.isSchematicPrimitive&&h.componentName==="SchematicLine"){let d=t.schematic_line.get(h.schematic_line_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicRect"){let d=t.schematic_rect.get(h.schematic_rect_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicCircle"){let d=t.schematic_circle.get(h.schematic_circle_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicArc"){let d=t.schematic_arc.get(h.schematic_arc_id);d&&i.push(d)}if(h.isSchematicPrimitive&&h.componentName==="SchematicText"){let d=t.schematic_text.get(h.schematic_text_id);d&&i.push(d)}h.children&&h.children.length>0&&r(h.children)}};if(r(this.children),i.length===0)return;let o=iV(i),s=Math.abs(o.maxX-o.minX),a=Math.abs(o.maxY-o.minY);if(s===0&&a===0)return;let c=(o.minX+o.maxX)/2,l=(o.minY+o.maxY)/2;t.schematic_component.update(this.schematic_component_id,{center:{x:c,y:l},size:{width:s,height:a}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){s3t(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(t){let n=eV(t);return{element:t,component:n}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let t=this.props.footprint;(0,ea.isValidElement)(t)&&(this.children.some(o=>o.componentName==="Footprint")||this.add(t));let n=this.props.symbol;(0,ea.isValidElement)(n)&&(this.children.some(o=>o.componentName==="Symbol")||this.add(n));let i=this.props.cadModel;if((0,ea.isValidElement)(i)){this._isCadModelChild=!0;let r=this.children.some(s=>s.componentName==="CadAssembly"),o=this.children.some(s=>s.componentName==="CadModel");!r&&!o&&this.add(i)}}doInitialPcbFootprintStringRender(){o3t(this,(t,n)=>this._queueAsyncEffect(t,n))}_hasExistingPortExactly(t){return this.children.filter(i=>i.componentName==="Port").some(i=>{let r=t.getNameAndAliases(),o=i.getNameAndAliases();return r.length===o.length&&r.every(s=>o.includes(s))})}add(t){let n;if((0,ea.isValidElement)(t)){let i=this._renderReactSubtree(t);this.reactSubtrees.push(i),n=i.component}else n=t;if(n.componentName==="Port"){if(this._hasExistingPortExactly(n))return;let r=this.children.filter(o=>o.componentName==="Port").find(o=>o.isMatchingAnyOf(n.getNameAndAliases()));r&&a3t(`Similar ports added. Port 1: ${r}, Port 2: ${n}`)}super.add(n)}getPortsFromFootprint(t){let{footprint:n}=this.props;if((!n||(0,ea.isValidElement)(n))&&(n=this.children.find(r=>r.componentName==="Footprint")),typeof n=="string"){if(um(n))return[];if(BI(n))return[];let r=mw.string(n).soup(),o=[];for(let s of r)if("port_hints"in s&&s.port_hints){let a=em(s.port_hints,t);if(!a)continue;a.originDescription=`footprint:string:${n}:port_hints[0]:${s.port_hints[0]}`,o.push(a)}return o}if(!(0,ea.isValidElement)(n)&&n&&n.componentName==="Footprint"){let r=n,o=1,s=[];for(let a of r.children){if(!a.props.portHints)continue;let c=a.props.portHints;c.some(h=>h.startsWith("pin"))||(c=[...c,`pin${o}`]),o++;let u=em(c);u&&(u.originDescription=`footprint:${n}`,s.push(u))}return s}let i=[];if(!n){for(let r of this.children)if(r.props.portHints&&r.isPcbPrimitive){let o=em(r.props.portHints);o&&i.push(o)}}return i}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:t}=this;if(!t.schematicSymbolName)return[];let n=Qn[t.schematicSymbolName];if(!n)return[];let i=[];for(let r of n.ports){let o=em(r.labels);o&&(o.schematicSymbolPortDef=r,i.push(o))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:t}=this,n=[];if(t.connections)for(let[i,r]of Object.entries(t.connections)){let o=Array.isArray(r)?r:[r];for(let s of o)n.push(String(s))}return n}_createNetsFromProps(t){GI(this,t)}_getPcbCircuitJsonBounds(){let{db:t}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let n=t.pcb_component.get(this.pcb_component_id);return{center:{x:n.center.x,y:n.center.y},bounds:{left:n.center.x-n.width/2,top:n.center.y-n.height/2,right:n.center.x+n.width/2,bottom:n.center.y+n.height/2},width:n.width,height:n.height}}_getPinCountFromSchematicPortArrangement(){let t=this._getSchematicPortArrangement();if(!t)return 0;if(!oV(t))return(t.leftSize??t.leftPinCount??0)+(t.rightSize??t.rightPinCount??0)+(t.topSize??t.topPinCount??0)+(t.bottomSize??t.bottomPinCount??0);let{leftSide:i,rightSide:r,topSide:o,bottomSide:s}=t;return Math.max(...i?.pins??[],...r?.pins??[],...o?.pins??[],...s?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let n=this.getPortsFromFootprint();if(n.length>0)return n.length;let{pinLabels:i}=this._parsedProps;if(i){if(Array.isArray(i))return i.length;let r=Object.keys(i).map(o=>o.startsWith("pin")?parseInt(o.slice(3)):parseInt(o)).filter(o=>!Number.isNaN(o));return r.length>0?Math.max(...r):Object.keys(i).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:t}=this,n=this._getPinCount(),i=t.schPinSpacing??.2;return wPt({schWidth:t.schWidth,schHeight:t.schHeight,schPinSpacing:i,numericSchPinStyle:PPt(t.schPinStyle,t.pinLabels),pinCount:n,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:t.pinLabels})}getFootprinterString(){return typeof this._parsedProps.footprint=="string"?this._parsedProps.footprint:null}doInitialCadModelRender(){if(this._isCadModelChild)return;let{db:t}=this.root,{boardThickness:n=0}=this.root?._getBoard()??{},i=this._parsedProps.cadModel,r=i===void 0?this._asyncFootprintCadModel:i,o=this.getFootprinterString()??this._getImpliedFootprintString();if(!this.pcb_component_id||!r&&!o||r===null)return;let s=this._getPcbCircuitJsonBounds(),a=t.pcb_component.get(this.pcb_component_id);if(typeof r=="string")throw new Error("String cadModel not yet implemented");let c=c3t.parse({x:0,y:0,z:typeof r?.rotationOffset=="number"?r.rotationOffset:0,...typeof r?.rotationOffset=="object"?r.rotationOffset??{}:{}}),l=pl.parse({x:0,y:0,z:0,...typeof r?.positionOffset=="object"?r.positionOffset:{}}),u=this.props.layer==="bottom"?"bottom":"top",h=this._computePcbGlobalTransformBeforeLayout(),_=To(h).rotation.angle*180/Math.PI,y=t.cad_component.insert({position:{x:s.center.x+l.x,y:s.center.y+l.y,z:(u==="bottom"?-n/2:n/2)+l.z},rotation:{x:c.x,y:(u==="top"?0:180)+c.y,z:u==="bottom"?-(_+c.z)+180:_+c.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(r??{})?this._addCachebustToModelUrl(r.stlUrl):void 0,model_obj_url:"objUrl"in(r??{})?this._addCachebustToModelUrl(r.objUrl):void 0,model_mtl_url:"mtlUrl"in(r??{})?this._addCachebustToModelUrl(r.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(r??{})?this._addCachebustToModelUrl(r.gltfUrl):void 0,model_glb_url:"glbUrl"in(r??{})?this._addCachebustToModelUrl(r.glbUrl):void 0,model_step_url:"stepUrl"in(r??{})?this._addCachebustToModelUrl(r.stepUrl):void 0,model_wrl_url:"wrlUrl"in(r??{})?this._addCachebustToModelUrl(r.wrlUrl):void 0,model_jscad:"jscad"in(r??{})?r.jscad:void 0,model_unit_to_mm_scale_factor:typeof r?.modelUnitToMmScale=="number"?r.modelUnitToMmScale:void 0,footprinter_string:typeof o=="string"&&!r?o:void 0});this.cad_component_id=y.cad_component_id}_addCachebustToModelUrl(t){if(!t||!t.includes("modelcdn.tscircuit.com"))return t;let n=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(n)}`}_getPartsEngineCacheKey(t,n){return JSON.stringify({ftype:t.ftype,name:t.name,manufacturer_part_number:t.manufacturer_part_number,footprinterString:n})}async _getSupplierPartNumbers(t,n,i){if(this.props.doNotPlace)return{};let r=this.root?.platform?.localCacheEngine,o=this._getPartsEngineCacheKey(n,i);if(r){let c=await r.getItem(o);if(c)try{return JSON.parse(c)}catch{}}let s=await Promise.resolve(t.findPart({sourceComponent:n,footprinterString:i})),a=s==="Not found"?{}:s;if(r)try{await r.setItem(o,JSON.stringify(a))}catch{}return a}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let t=this.getInheritedProperty("partsEngine");if(!t)return;let{db:n}=this.root,i=n.source_component.get(this.source_component_id);if(!i||i.supplier_part_numbers)return;let r;this.props.footprint&&typeof this.props.footprint=="string"&&(r=this.props.footprint);let o=this._getSupplierPartNumbers(t,i,r);if(!(o instanceof Promise)){n.source_component.update(this.source_component_id,{supplier_part_numbers:o});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await o,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(n&&!n.supplier_part_numbers&&this._asyncSupplierPartNumbers){t.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:t}=this;t.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:t}=this;if(t.connections)for(let[n,i]of Object.entries(t.connections)){let r=Array.isArray(i)?i:[i];for(let o of r)this.add(new ko({from:`.${this.name} > .${n}`,to:String(o)}))}}doInitialSourceDesignRuleChecks(){JPt(this)}_getMinimumFlexContainerSize(){return ZPt(this)}_repositionOnPcb(t){return KPt(this,t)}doInitialSilkscreenOverlapAdjustment(){return e3t(this)}isRelativelyPositioned(){return this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0}},l3t=({boardAnchorPosition:e,boardAnchorAlignment:t,width:n,height:i})=>{let{x:r,y:o}=e,s=r,a=o;switch(t){case"top_left":s=r+n/2,a=o-i/2;break;case"top_right":s=r-n/2,a=o-i/2;break;case"bottom_left":s=r+n/2,a=o+i/2;break;case"bottom_right":s=r-n/2,a=o+i/2;break;case"top":s=r,a=o-i/2;break;case"bottom":s=r,a=o+i/2;break;case"left":s=r+n/2,a=o;break;case"right":s=r-n/2,a=o;break;case"center":default:break}return{x:s,y:a}},u3t=class{constructor(e,t={}){T(this,"input");T(this,"isRouting",!1);T(this,"solver");T(this,"eventHandlers",{complete:[],error:[],progress:[]});T(this,"cycleCount",0);T(this,"stepDelay");T(this,"timeoutId");this.input=e;let{capacityDepth:n,targetMinCapacity:i,stepDelay:r=0}=t;this.solver=new t$(e,{capacityDepth:n,targetMinCapacity:i,cacheProvider:null}),this.stepDelay=r}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new im(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let e=Date.now(),t=this.solver.iterations;for(;Date.now()-e<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let n=(this.solver.iterations-t)/(Date.now()-e)*1e3;this.cycleCount++;let i=this.solver?.preview()||void 0,r=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,progress:r,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(e){this.emitEvent({type:"error",error:e instanceof Error?new im(e.message):new im(String(e))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(e,t){e==="complete"?this.eventHandlers.complete.push(t):e==="error"?this.eventHandlers.error.push(t):e==="progress"&&this.eventHandlers.progress.push(t)}emitEvent(e){if(e.type==="complete")for(let t of this.eventHandlers.complete)t(e);else if(e.type==="error")for(let t of this.eventHandlers.error)t(e);else if(e.type==="progress")for(let t of this.eventHandlers.progress)t(e)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new im(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},KI=class extends be{constructor(){super(...arguments);T(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:gF}}doInitialPortMatching(){let{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)return;if(i.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!i)throw new Error("TraceHint has no parent");if(!n.for){this.renderError(`TraceHint has no for property (${this})`);return}let r=i.selectOne(n.for,{type:"port"});r||this.renderError(`${this} could not find port for selector "${n.for}"`),this.matchedPort=r,r.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:t}=this,n=t.offset?[t.offset]:t.offsets;if(!n)return[];let i=this._computePcbGlobalTransformBeforeLayout();return n.map(r=>({...De(i,r),via:r.via,to_layer:r.to_layer,trace_width:r.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this;t.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},dV=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,pcb_placements:[...n.pcb_placements??[]]};for(let r of t)if(r.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:o,new_center:s}=r,a=ke(e).pcb_component.get(o);if(!a)continue;let c=ke(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.pcb_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.pcb_placements[l]=u:i.pcb_placements.push(u)}return i},fV=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i={...n,schematic_placements:[...n.schematic_placements??[]]};for(let r of t)if(r.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:o,new_center:s}=r,a=ke(e).schematic_component.get(o);if(!a||!a.source_component_id)continue;let c=ke(e).source_component.get(a.source_component_id);if(!c)continue;let l=i.schematic_placements?.findIndex(h=>h.selector===c.name),u={selector:c.name,center:s,relative_to:"group_center"};l>=0?i.schematic_placements[l]=u:i.schematic_placements.push(u)}return i},p3t=({circuitJson:e,editEvents:t,manualEditsFile:n})=>{let i=t.filter(s=>s.edit_event_type==="edit_schematic_component_location"),r=t.filter(s=>s.edit_event_type==="edit_pcb_component_location"),o=n;return i.length>0&&(o=fV({circuitJson:e,editEvents:i,manualEditsFile:o})),r.length>0&&(o=dV({circuitJson:e,editEvents:r,manualEditsFile:o})),o},h3t=(e,t)=>{if(ke(e).pcb_trace_hint.get(t.pcb_trace_hint_id))e=e.map(i=>i.pcb_trace_hint_id===t.pcb_trace_hint_id?{...i,route:t.route}:i);else{let i=ke(e).pcb_port.get(t.pcb_port_id);e=e.filter(r=>!(r.type==="pcb_trace_hint"&&r.pcb_port_id===t.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:t.pcb_trace_hint_id,route:t.route,pcb_port_id:t.pcb_port_id,pcb_component_id:i?.pcb_component_id}])}return e},d3t=({circuitJson:e,editEvents:t})=>{e=JSON.parse(JSON.stringify(e));for(let n of t)if(n.edit_event_type==="edit_pcb_component_location"){let i=e.find(o=>o.type==="pcb_component"&&o.pcb_component_id===n.pcb_component_id);if((!i||i.center.x!==n.new_center.x||i.center.y!==n.new_center.y)&&n.original_center){let o=vn(n.new_center.x-n.original_center.x,n.new_center.y-n.original_center.y);e=e.map(s=>s.pcb_component_id!==n.pcb_component_id?s:o4(s,o))}}else n.edit_event_type==="edit_schematic_component_location"?e=e.map(i=>i.type==="schematic_component"&&i.schematic_component_id===n.schematic_component_id?{...i,center:n.new_center}:i):n.edit_event_type==="edit_pcb_trace_hint"&&(e=h3t(e,n));return e},mV=(e,t)=>{let n=e.source_group.list(),i=[],r=o=>{let s=n.filter(a=>a.parent_subcircuit_id===o);for(let a of s)a.subcircuit_id&&(i.push(a.subcircuit_id),r(a.subcircuit_id))};return r(t),i},jI=({db:e,circuitJson:t,subcircuit_id:n,minTraceWidth:i=.1})=>{if(!e&&t&&(e=ke(t)),!e)throw new Error("db or circuitJson is required");let r=e.pcb_trace_hint.list(),o=n?new Set([n]):null;if(n){let N=mV(e,n);for(let C of N)o.add(C)}let s=(t??e.toArray()).filter(N=>!n||"subcircuit_id"in N&&o.has(N.subcircuit_id)),a=e.pcb_board.list()[0];e=ke(s);let c=si(s),l=WI([...e.pcb_component.list(),...e.pcb_smtpad.list(),...e.pcb_plated_hole.list(),...e.pcb_hole.list(),...e.pcb_via.list(),...e.pcb_cutout.list()].filter(N=>!n||o?.has(N.subcircuit_id)),c);for(let N of l){let C=N.connectedTo.flatMap(A=>c.getIdsConnectedToNet(A));N.connectedTo.push(...C)}let u=l.flatMap(N=>[{x:N.center.x-N.width/2,y:N.center.y-N.height/2},{x:N.center.x+N.width/2,y:N.center.y+N.height/2}]).concat(a?.outline??[]),h;if(a&&!a.outline?h={minX:a.center.x-a.width/2,maxX:a.center.x+a.width/2,minY:a.center.y-a.height/2,maxY:a.center.y+a.height/2}:h={minX:Math.min(...u.map(N=>N.x))-1,maxX:Math.max(...u.map(N=>N.x))+1,minY:Math.min(...u.map(N=>N.y))-1,maxY:Math.max(...u.map(N=>N.y))+1},n){let N=e.pcb_group.getWhere({subcircuit_id:n});if(N){let C={minX:N.center.x-N.width/2,maxX:N.center.x+N.width/2,minY:N.center.y-N.height/2,maxY:N.center.y+N.height/2};h={minX:Math.min(h.minX,C.minX),maxX:Math.max(h.maxX,C.maxX),minY:Math.min(h.minY,C.minY),maxY:Math.max(h.maxY,C.maxY)}}}let d=new Set(e.pcb_trace.list().map(N=>N.source_trace_id).filter(N=>!!N)),_=e.source_trace.list().filter(N=>!d.has(N.source_trace_id)).map(N=>{let C=N.connected_source_port_ids.map(H=>{let K=e.source_port.get(H),Z=e.pcb_port.getWhere({source_port_id:H});return{...K,...Z}});if(C.length<2)return null;let[A,O]=C,B=A.layers?.[0]??"top",D=O.layers?.[0]??"top",X=r.filter(H=>H.pcb_port_id===A.pcb_port_id||H.pcb_port_id===O.pcb_port_id),Y=[];for(let H of X){let Z=e.pcb_port.get(H.pcb_port_id)?.layers?.[0]??"top";for(let ut of H.route)Y.push({x:ut.x,y:ut.y,layer:Z})}return{name:N.source_trace_id??c.getNetConnectedToId(N.source_trace_id)??"",source_trace_id:N.source_trace_id,pointsToConnect:[{x:A.x,y:A.y,layer:B,pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},...Y,{x:O.x,y:O.y,layer:D,pointId:O.pcb_port_id,pcb_port_id:O.pcb_port_id}]}}).filter(N=>N!==null),y=new Map(_.map(N=>[N.source_trace_id,N])),g=e.source_net.list().filter(N=>!n||o?.has(N.subcircuit_id)),x=[];for(let N of g){let C=e.source_trace.list().filter(A=>A.connected_source_net_ids?.includes(N.source_net_id));x.push({name:N.source_net_id??c.getNetConnectedToId(N.source_net_id),pointsToConnect:C.flatMap(A=>e.pcb_port.list().filter(B=>A.connected_source_port_ids.includes(B.source_port_id)).map(B=>({x:B.x,y:B.y,layer:B.layers?.[0]??"top",pointId:B.pcb_port_id,pcb_port_id:B.pcb_port_id})))})}let w=e.pcb_breakout_point.list().filter(N=>!n||o?.has(N.subcircuit_id)),S=[],E=new Map;for(let N of w){let C={x:N.x,y:N.y,layer:"top"};if(N.source_trace_id){let A=y.get(N.source_trace_id)??E.get(N.source_trace_id);if(A)A.pointsToConnect.push(C);else{let O={name:N.source_trace_id,source_trace_id:N.source_trace_id,pointsToConnect:[C]};S.push(O),E.set(N.source_trace_id,O)}}else if(N.source_net_id){let A=x.find(O=>O.name===N.source_net_id);A?A.pointsToConnect.push(C):S.push({name:N.source_net_id,pointsToConnect:[C]})}else if(N.source_port_id){let A=e.pcb_port.getWhere({source_port_id:N.source_port_id});A&&S.push({name:N.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:A.x,y:A.y,layer:A.layers?.[0]??"top",pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},C]})}}let M=[..._,...x,...S],k=new Map;for(let N of M)for(let C of N.pointsToConnect)C.pointId&&k.set(C.pointId,N);let I=e.pcb_trace.list().filter(N=>!n||o?.has(N.subcircuit_id));for(let N of I){let C=new Set;for(let B of N.route)B.start_pcb_port_id&&C.add(B.start_pcb_port_id),B.end_pcb_port_id&&C.add(B.end_pcb_port_id);if(C.size<2)continue;let A=C.values().next().value;if(!A)continue;let O=k.get(A);O&&[...C].every(B=>k.get(B)===O)&&(O.externallyConnectedPointIds??(O.externallyConnectedPointIds=[]),O.externallyConnectedPointIds.push([...C]))}return{simpleRouteJson:{bounds:h,obstacles:l,connections:M,layerCount:a?.num_layers??2,minTraceWidth:i,outline:a?.outline?.map(N=>({...N}))},connMap:c}},f3t=e=>{let t={};if(!e)return t;for(let i of ta)t[i]=0;let n=new Map;for(let i of e){let[,,r,o]=i.type.split(":");if(o==="start"){n.set(`${r}:${i.renderId}`,i);continue}if(o==="end"){let s=n.get(`${r}:${i.renderId}`);if(s){let a=i.createdAt-s.createdAt;t[r]=(t[r]||0)+a}}}return t},m3t=e=>{let t=e.map(c=>[...new Set(c)]),n=t.map(()=>[]),i=t.map(()=>null);for(let c=0;c<t.length;c++)for(let l of t[c])if(/^\d+$/.test(l)){i[c]=Number.parseInt(l);break}let r=0,o=new Set;for(let c=0;c<i.length;c++){let l=i[c];if(l===null||l<1)continue;if(!o.has(l)){o.add(l),n[c].push(`pin${l}`),r=Math.max(r,l);continue}let u=0;for(let h of n[c])h.startsWith(`pin${l}_alt`)&&u++;n[c].push(`pin${l}_alt${u+1}`)}for(let c=0;c<n.length;c++)n[c][0]?.includes("_alt")&&(r++,n[c].unshift(`pin${r}`));for(let c=0;c<n.length;c++)n[c].length===0&&(r++,n[c].push(`pin${r}`));let s={};for(let c of t)for(let l of c)/^\d+$/.test(l)||(s[l]=(s[l]??0)+1);let a={};for(let c=0;c<t.length;c++){let l=t[c];for(let u of l)/^\d+$/.test(u)||(s[u]===1?n[c].push(u):(a[u]=(a[u]??0)+1,n[c].push(`${u}${a[u]}`)))}return n};function JI({db:e,schematicComponentId:t,deltaX:n,deltaY:i}){let r=e.schematic_rect.list({schematic_component_id:t});for(let c of r)c.center.x+=n,c.center.y+=i;let o=e.schematic_line.list({schematic_component_id:t});for(let c of o)c.x1+=n,c.y1+=i,c.x2+=n,c.y2+=i;let s=e.schematic_circle.list({schematic_component_id:t});for(let c of s)c.center.x+=n,c.center.y+=i;let a=e.schematic_arc.list({schematic_component_id:t});for(let c of a)c.center.x+=n,c.center.y+=i}var FX=(0,_V.default)("Group_doInitialSchematicLayoutMatchAdapt");function _3t(e){let{db:t}=e.root,n=nf(t.toArray(),{source_group_id:e.source_group_id}),i=O4(n);FX.enabled&&global.debugGraphics?.push(ac(i,{title:`floatingBpcGraph-${e.name}`}));let r=O4(n),o={boxes:r.boxes,pins:r.pins.map(c=>({...c,color:c.color.replace("not_connected","normal")}))},{result:s}=CB([{variantName:"default",floatingGraph:r},{variantName:"noNotConnected",floatingGraph:o}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(r.boxes.filter(c=>r.pins.filter(h=>h.boxId===c.boxId).filter(h=>!h.color.includes("center")).length<=2).map(c=>c.boxId)),corpus:{}});FX.enabled&&global.debugGraphics?.push(ac(s,{title:`laidOutBpcGraph-${e.name}`}));let a=e._getGlobalSchematicPositionBeforeLayout();for(let c of s.boxes){if(!c.center)continue;let l=t.schematic_component.get(c.boxId);if(l){let h={x:c.center.x+a.x,y:c.center.y+a.y},d=t.schematic_port.list({schematic_component_id:l.schematic_component_id}),_=t.schematic_text.list({schematic_component_id:l.schematic_component_id}),y={x:h.x-l.center.x,y:h.y-l.center.y};for(let g of d)g.center.x+=y.x,g.center.y+=y.y;for(let g of _)g.position.x+=y.x,g.position.y+=y.y;JI({db:t,schematicComponentId:l.schematic_component_id,deltaX:y.x,deltaY:y.y}),l.center=h;continue}let u=t.schematic_net_label.get(c.boxId);if(u){let h=s.pins.find(_=>_.boxId===c.boxId&&_.color==="netlabel_center");if(!h)throw new Error(`No pin found for net label: ${c.boxId}`);let d={x:c.center.x+a.x,y:c.center.y+a.y};u.center=d,u.anchor_position={x:d.x+h.offset.x,y:d.y+h.offset.y};continue}console.error(`No schematic element found for box: ${c.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var pe=(0,yV.default)("Group_doInitialSchematicLayoutMatchpack");function DX(e){switch(e){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function $X(e,t){let n=["right","up","left","down"],i=n.indexOf(e);if(i===-1)return e;let r=Math.round(t/90),o=(i+r)%4;return n[o<0?o+4:o]}function y3t(e,t,n){let i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};pe(`[${n.name}] Processing ${e.childNodes.length} child nodes for input problem`),e.childNodes.forEach((o,s)=>{if(pe(`[${n.name}] Processing child ${s}: nodeType=${o.nodeType}`),o.nodeType==="component"?pe(`[${n.name}] - Component: ${o.sourceComponent?.name}`):o.nodeType==="group"&&pe(`[${n.name}] - Group: ${o.sourceGroup?.name}`),o.nodeType==="component"&&o.sourceComponent){let a=o.sourceComponent.name||`chip_${s}`,c=t.schematic_component.getWhere({source_component_id:o.sourceComponent.source_component_id});if(!c)return;let l=n.children.find(S=>S.source_component_id===o.sourceComponent?.source_component_id),u=[0,90,180,270];l?._parsedProps?.schOrientation&&(u=[0]),l?._parsedProps?.schRotation!==void 0&&(u=[0]);let h=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,d=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,_=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,y=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0;l?.config.shouldRenderAsSchematicBox&&(_+=.4,y+=.4);let g=(d-h)/2,x=(_-y)/2;i.chipMap[a]={chipId:a,pins:[],size:{x:(c.size?.width||1)+h+d,y:(c.size?.height||1)+_+y},availableRotations:u};let w=t.schematic_port.list({schematic_component_id:c.schematic_component_id});for(let S of w){let E=t.source_port.get(S.source_port_id);if(!E)continue;let M=`${a}.${E.pin_number||E.name||S.schematic_port_id}`;i.chipMap[a].pins.push(M);let k=DX(S.facing_direction);i.chipPinMap[M]={pinId:M,offset:{x:(S.center?.x||0)-(c.center.x||0)+g,y:(S.center?.y||0)-(c.center.y||0)+x},side:k}}}else if(o.nodeType==="group"&&o.sourceGroup){let a=o.sourceGroup.name||`group_${s}`;pe(`[${n.name}] Processing nested group: ${a}`);let c=t.schematic_group?.getWhere?.({source_group_id:o.sourceGroup.source_group_id}),l=n.children.find(u=>u.source_group_id===o.sourceGroup?.source_group_id);if(pe(`[${n.name}] Found schematic_group for ${a}:`,c),c){pe(`[${n.name}] Treating group ${a} as composite chip`);let u=t.schematic_component.list({schematic_group_id:c.schematic_group_id});pe(`[${n.name}] Group ${a} has ${u.length} components:`,u.map(A=>A.source_component_id));let h=1/0,d=-1/0,_=1/0,y=-1/0,g=!1;for(let A of u)if(A.center&&A.size){g=!0;let O=A.size.width/2,B=A.size.height/2;h=Math.min(h,A.center.x-O),d=Math.max(d,A.center.x+O),_=Math.min(_,A.center.y-B),y=Math.max(y,A.center.y+B)}let x=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,w=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,S=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,E=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0,M=(w-x)/2,k=(S-E)/2,I=(g?d-h:2)+x+w,N=(g?y-_:2)+S+E;pe(`[${n.name}] Group ${a} computed size: ${I} x ${N}`);let C=[];for(let A of u){let O=t.schematic_port.list({schematic_component_id:A.schematic_component_id});for(let B of O){let D=t.source_port.get(B.source_port_id);if(!D)continue;let X=`${a}.${D.pin_number||D.name||B.schematic_port_id}`;C.push(X);let Y=c.center||{x:0,y:0},H=DX(B.facing_direction);i.chipPinMap[X]={pinId:X,offset:{x:(B.center?.x||0)-Y.x+M,y:(B.center?.y||0)-Y.y+k},side:H}}}pe(`[${n.name}] Group ${a} has ${C.length} pins:`,C),i.chipMap[a]={chipId:a,pins:C,size:{x:I,y:N}},pe(`[${n.name}] Added group ${a} to chipMap`)}else pe(`[${n.name}] Warning: No schematic_group found for group ${a}`)}}),pe(`[${n.name}] Creating connections using connectivity keys`);let r=new Map;for(let[o,s]of Object.entries(i.chipMap))for(let a of s.pins){let c=a.split(".").pop(),l=e.childNodes.find(u=>u.nodeType==="component"&&u.sourceComponent?u.sourceComponent.name===o:u.nodeType==="group"&&u.sourceGroup?`group_${e.childNodes.indexOf(u)}`===o:!1);if(l?.nodeType==="group"&&l.sourceGroup){let u=t.schematic_group?.getWhere?.({source_group_id:l.sourceGroup.source_group_id});if(u){let h=t.schematic_component.list({schematic_group_id:u.schematic_group_id});for(let d of h){let _=t.source_port.list({source_component_id:d.source_component_id});for(let y of _){let g=y.pin_number||y.name;if(String(g)===String(c))if(y.subcircuit_connectivity_map_key){let x=y.subcircuit_connectivity_map_key;r.has(x)||r.set(x,[]),r.get(x).push(a),pe(`[${n.name}] \u2713 Pin ${a} has connectivity key: ${x}`)}else pe(`[${n.name}] Pin ${a} has no connectivity key`)}}}}else if(l?.nodeType==="component"&&l.sourceComponent){let u=t.source_port.list({source_component_id:l.sourceComponent.source_component_id});for(let h of u){let d=h.pin_number||h.name;if(String(d)===String(c)&&h.subcircuit_connectivity_map_key){let _=h.subcircuit_connectivity_map_key;r.has(_)||r.set(_,[]),r.get(_).push(a),pe(`[${n.name}] Pin ${a} has connectivity key: ${_}`)}}}}pe(`[${n.name}] Found ${r.size} connectivity groups:`,Array.from(r.entries()).map(([o,s])=>({key:o,pins:s})));for(let[o,s]of r)if(s.length>=2){let a=t.source_trace.list().filter(u=>u.subcircuit_connectivity_map_key===o),c=a.some(u=>u.connected_source_net_ids&&u.connected_source_net_ids.length>0),l=a.some(u=>u.connected_source_port_ids&&u.connected_source_port_ids.length>=2);if(pe(`[${n.name}] Connectivity ${o}: hasNetConnections=${c}, hasDirectConnections=${l}`),l){for(let u of a)if(u.connected_source_port_ids&&u.connected_source_port_ids.length>=2){let h=[];for(let d of u.connected_source_port_ids)for(let _ of s){let y=_.split(".").pop(),g=t.source_port.get(d);if(g&&String(g.pin_number||g.name)===String(y)){let x=_.split(".")[0],w=e.childNodes.find(S=>S.nodeType==="component"&&S.sourceComponent?S.sourceComponent.name===x:S.nodeType==="group"&&S.sourceGroup?`group_${e.childNodes.indexOf(S)}`===x:!1);w?.nodeType==="component"&&w.sourceComponent&&t.source_port.list({source_component_id:w.sourceComponent.source_component_id}).some(E=>E.source_port_id===d)&&h.push(_)}}for(let d=0;d<h.length;d++)for(let _=d+1;_<h.length;_++){let y=h[d],g=h[_];i.pinStrongConnMap[`${y}-${g}`]=!0,i.pinStrongConnMap[`${g}-${y}`]=!0,pe(`[${n.name}] Created strong connection: ${y} <-> ${g}`)}}}if(c){let u=t.source_net.getWhere({subcircuit_connectivity_map_key:o}),h=u?.is_ground??!1,d=u?.is_power??!1;i.netMap[o]={netId:o,isGround:h,isPositiveVoltageSource:d};for(let _ of s)i.netConnMap[`${_}-${o}`]=!0;pe(`[${n.name}] Created net ${o} with ${s.length} pins:`,s)}}return i}function g3t(e){let{db:t}=e.root,n=Bp(t.toArray(),{source_group_id:e.source_group_id});if(pe(`[${e.name}] Starting matchpack layout with ${n.childNodes.length} children`),pe(`[${e.name}] Tree structure:`,JSON.stringify(n,null,2)),n.childNodes.length<=1){pe(`[${e.name}] Only ${n.childNodes.length} children, skipping layout`);return}pe("Converting circuit tree to InputProblem...");let i=y3t(n,t,e);pe.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${e.name}`,content:JSON.stringify(i,null,2)});let r=new Rj(i);if(pe("Starting LayoutPipelineSolver..."),pe.enabled&&global.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-initial-${e.name}`})}if(r.solve(),pe(`Solver completed in ${r.iterations} iterations`),pe(`Solved: ${r.solved}, Failed: ${r.failed}`),r.failed)throw pe(`Solver failed with error: ${r.error}`),new Error(`Matchpack layout solver failed: ${r.error}`);let o=r.getOutputLayout();if(pe("OutputLayout:",JSON.stringify(o,null,2)),pe("Solver completed successfully:",!r.failed),pe.enabled&&global.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-final-${e.name}`})}let s=r.checkForOverlaps(o);if(s.length>0){pe(`Warning: Found ${s.length} overlapping components:`);for(let c of s)pe(` ${c.chip1} overlaps ${c.chip2} (area: ${c.overlapArea})`)}let a=e._getGlobalSchematicPositionBeforeLayout();pe(`Group offset: x=${a.x}, y=${a.y}`),pe(`Applying layout results for ${Object.keys(o.chipPlacements).length} chip placements`);for(let[c,l]of Object.entries(o.chipPlacements)){pe(`Processing placement for chip: ${c} at (${l.x}, ${l.y})`);let u=n.childNodes.find(d=>{if(d.nodeType==="component"&&d.sourceComponent){let _=d.sourceComponent.name===c;return pe(` Checking component ${d.sourceComponent.name}: matches=${_}`),_}if(d.nodeType==="group"&&d.sourceGroup){let _=d.sourceGroup.name,y=`group_${n.childNodes.indexOf(d)}`,g=y===c;return pe(` Checking group ${_} (expected chipId: ${y}): matches=${g}`),g}return!1});if(!u){pe(`Warning: No tree node found for chip: ${c}`),pe("Available tree nodes:",n.childNodes.map((d,_)=>({type:d.nodeType,name:d.nodeType==="component"?d.sourceComponent?.name:d.sourceGroup?.name,expectedChipId:d.nodeType==="group"?`group_${_}`:d.sourceComponent?.name})));continue}let h={x:l.x+a.x,y:l.y+a.y};if(u.nodeType==="component"&&u.sourceComponent){let d=t.schematic_component.getWhere({source_component_id:u.sourceComponent.source_component_id});if(d){pe(`Moving component ${c} to (${h.x}, ${h.y})`);let _=t.schematic_port.list({schematic_component_id:d.schematic_component_id}),y=t.schematic_text.list({schematic_component_id:d.schematic_component_id}),g={x:h.x-d.center.x,y:h.y-d.center.y};for(let x of _)x.center.x+=g.x,x.center.y+=g.y;for(let x of y)x.position.x+=g.x,x.position.y+=g.y;if(JI({db:t,schematicComponentId:d.schematic_component_id,deltaX:g.x,deltaY:g.y}),d.center=h,l.ccwRotationDegrees!==0){pe(`Component ${c} has rotation: ${l.ccwRotationDegrees}\xB0`);let x=l.ccwRotationDegrees*Math.PI/180,w=Math.cos(x),S=Math.sin(x);for(let E of _){let M=E.center.x-h.x,k=E.center.y-h.y,I=M*w-k*S,N=M*S+k*w;E.center.x=h.x+I,E.center.y=h.y+N;let C=E.facing_direction||"right";E.facing_direction=$X(C,l.ccwRotationDegrees)}for(let E of y){let M=E.position.x-h.x,k=E.position.y-h.y,I=M*w-k*S,N=M*S+k*w;E.position.x=h.x+I,E.position.y=h.y+N}if(d.symbol_name){let E=d.symbol_name.match(/_(right|left|up|down)$/);E&&(d.symbol_name=d.symbol_name.replace(E[0],`_${$X(E[1],l.ccwRotationDegrees)}`))}}}}else if(u.nodeType==="group"&&u.sourceGroup){let d=t.schematic_group?.getWhere?.({source_group_id:u.sourceGroup.source_group_id});if(d){pe(`Moving group ${c} to (${h.x}, ${h.y}) from (${d.center?.x}, ${d.center?.y})`);let _=t.schematic_component.list({schematic_group_id:d.schematic_group_id});pe(`Group ${c} has ${_.length} components to move`);let y=d.center||{x:0,y:0},g={x:h.x-y.x,y:h.y-y.y};pe(`Position delta for group ${c}: (${g.x}, ${g.y})`);for(let x of _)if(x.center){let w={...x.center};x.center.x+=g.x,x.center.y+=g.y,pe(`Moved component ${x.source_component_id} from (${w.x}, ${w.y}) to (${x.center.x}, ${x.center.y})`);let S=t.schematic_port.list({schematic_component_id:x.schematic_component_id}),E=t.schematic_text.list({schematic_component_id:x.schematic_component_id});for(let M of S)M.center&&(M.center.x+=g.x,M.center.y+=g.y);for(let M of E)M.position&&(M.position.x+=g.x,M.position.y+=g.y)}d.center=h,pe(`Updated group ${c} center to (${h.x}, ${h.y})`)}}}pe("Matchpack layout completed successfully")}function b3t(e){if(!e.isSubcircuit)return;let{db:t}=e.root,n=e.selectAll("trace"),i=new Np({});i.addConnections(n.map(a=>{let c=t.source_trace.get(a.source_trace_id);return c?[c.source_trace_id,...c.connected_source_port_ids,...c.connected_source_net_ids]:null}).filter(a=>a!==null));let{name:r}=e._parsedProps;for(let a of n){if(!a.source_trace_id)continue;let c=i.getNetConnectedToId(a.source_trace_id);c&&(a.subcircuit_connectivity_map_key=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`,t.source_trace.update(a.source_trace_id,{subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}))}let o=new Set;for(let a of n){if(!a.source_trace_id)continue;let c=t.source_trace.get(a.source_trace_id);if(c)for(let l of c.connected_source_port_ids)o.add(l)}for(let a of o){let c=i.getNetConnectedToId(a);if(!c)continue;let l=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`;t.source_port.update(a,{subcircuit_connectivity_map_key:l})}let s=new Set;for(let a of n){if(!a.source_trace_id)continue;let c=t.source_trace.get(a.source_trace_id);if(c)for(let l of c.connected_source_net_ids)s.add(l)}for(let a of s){let c=i.getNetConnectedToId(a);if(!c)continue;let l=`${r??`unnamedsubcircuit${e._renderId}`}_${c}`;t.source_net.update(a,{subcircuit_connectivity_map_key:l})}}function x3t(e){let{db:t}=e.root,n=e._parsedProps,i=e.children.filter(k=>{let I=k._parsedProps?.schX!==void 0||k._parsedProps?.schY!==void 0;return k.schematic_component_id&&!I});if(i.length===0)return;let r=0,o=0;for(let k of i){let I=t.schematic_component.get(k.schematic_component_id);I?.size&&(r=Math.max(r,I.size.width),o=Math.max(o,I.size.height))}r===0&&i.length>0&&(r=1),o===0&&i.length>0&&(o=1);let s=n.gridCols,a,c=n.gridGap,l=n.gridRowGap,u=n.gridColumnGap;n.schLayout?.grid&&(s=n.schLayout.grid.cols??s,a=n.schLayout.grid.rows,c=n.schLayout.gridGap??c,l=n.schLayout.gridRowGap??l,u=n.schLayout.gridColumnGap??u);let h,d;s!==void 0&&a!==void 0?(h=s,d=a):s!==void 0?(h=s,d=Math.ceil(i.length/h)):a!==void 0?(d=a,h=Math.ceil(i.length/d)):(h=Math.ceil(Math.sqrt(i.length)),d=Math.ceil(i.length/h)),h===0&&i.length>0&&(h=1),d===0&&i.length>0&&(d=i.length);let _,y,g=k=>{if(k!==void 0)return typeof k=="number"?k:$.parse(k)};if(l!==void 0||u!==void 0){let k=typeof c=="object"&&c!==null?c.x:c,I=typeof c=="object"&&c!==null?c.y:c;_=g(u??k)??1,y=g(l??I)??1}else if(typeof c=="number")_=c,y=c;else if(typeof c=="string"){let k=$.parse(c);_=k,y=k}else if(typeof c=="object"&&c!==null){let k=c.x,I=c.y;_=typeof k=="number"?k:$.parse(k??"0mm"),y=typeof I=="number"?I:$.parse(I??"0mm")}else _=1,y=1;let x=h*r+Math.max(0,h-1)*_,w=d*o+Math.max(0,d-1)*y,S=e._getGlobalSchematicPositionBeforeLayout(),E=S.x-x/2+r/2,M=S.y+w/2-o/2;for(let k=0;k<i.length;k++){let I=i[k];if(!I.schematic_component_id)continue;let N=Math.floor(k/h),C=k%h;if(N>=d||C>=h){console.warn(`Schematic grid layout: Child ${I.getString()} at index ${k} (row ${N}, col ${C}) exceeds specified grid dimensions (${d}x${h}). Skipping placement.`);continue}let A=E+C*(r+_),O=M-N*(o+y),B=t.schematic_component.get(I.schematic_component_id);if(B){let D=B.center,X={x:A,y:O};t.schematic_component.update(I.schematic_component_id,{center:X});let Y=X.x-D.x,H=X.y-D.y,K=t.schematic_port.list({schematic_component_id:I.schematic_component_id});for(let ut of K)t.schematic_port.update(ut.schematic_port_id,{center:{x:ut.center.x+Y,y:ut.center.y+H}});let Z=t.schematic_text.list({schematic_component_id:I.schematic_component_id});for(let ut of Z)t.schematic_text.update(ut.schematic_text_id,{position:{x:ut.position.x+Y,y:ut.position.y+H}});JI({db:t,schematicComponentId:I.schematic_component_id,deltaX:Y,deltaY:H})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:x,height:w,center:S})}var BX=(e,t)=>{let{sourceComponent:n,sourceGroup:i}=t;if(t.nodeType==="component"){let r=e.schematic_component.getWhere({source_component_id:n?.source_component_id});return r?.size?{width:r.size.width,height:r.size.height}:null}if(t.nodeType==="group"){let r=e.schematic_group.getWhere({source_group_id:i?.source_group_id});if(r?.width&&r?.height)return{width:r.width,height:r.height};let o=e.schematic_component.list({schematic_group_id:r?.schematic_group_id}),s=1/0,a=-1/0,c=1/0,l=-1/0;for(let d of o)if(d.center&&d.size){let _=d.size.width/2,y=d.size.height/2;s=Math.min(s,d.center.x-_),a=Math.max(a,d.center.x+_),c=Math.min(c,d.center.y-y),l=Math.max(l,d.center.y+y)}let u=a-s,h=l-c;return{width:u,height:h}}return null},v3t=e=>{let{db:t}=e.root,n=e._parsedProps,i=Bp(t.toArray(),{source_group_id:e.source_group_id}),r=n.schJustifyContent??n.justifyContent,o=n.schAlignItems??n.alignItems,s=n.schFlexGap??n.schGap??n.gap,a=n.schFlexDirection??"row",c={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[r??"space-between"],l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[o??"center"];if(!c)throw new Error(`Invalid justifyContent value: "${r}"`);if(!l)throw new Error(`Invalid alignItems value: "${o}"`);let u=0,h=0;typeof s=="object"?(u=s.y??0,h=s.x??0):typeof s=="number"?(u=s,h=s):typeof s=="string"&&(u=$.parse(s),h=$.parse(s));let d,_=n.width??n.schWidth??void 0,y=n.height??n.schHeight??void 0;(_===void 0||y===void 0)&&(d=Og(i.childNodes.map(M=>BX(t,M)).filter(M=>M!==null),{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h}),_=d.width,y=d.height);let x=new Db(_,y,{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:h});for(let M of i.childNodes){let k=BX(t,M);x.addChild({metadata:M,width:k?.width??0,height:k?.height??0,flexBasis:k?a==="row"?k.width:k.height:void 0})}x.build();let w={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let M of x.children)w.minX=Math.min(w.minX,M.position.x),w.minY=Math.min(w.minY,M.position.y),w.maxX=Math.max(w.maxX,M.position.x+M.size.width),w.maxY=Math.max(w.maxY,M.position.y+M.size.height);w.width=w.maxX-w.minX,w.height=w.maxY-w.minY;let S={x:-(w.maxX+w.minX)/2,y:-(w.maxY+w.minY)/2},E=t.toArray();for(let M of x.children){let{sourceComponent:k,sourceGroup:I}=M.metadata;if(k){let N=t.schematic_component.getWhere({source_component_id:k.source_component_id});if(!N)continue;UF(E,N.schematic_component_id,{x:M.position.x+M.size.width/2+S.x,y:M.position.y+M.size.height/2+S.y})}if(I){if(!t.schematic_group.getWhere({source_group_id:I.source_group_id}))continue;WF(E,I.source_group_id,{x:M.position.x+M.size.width/2+S.x,y:M.position.y+M.size.height/2+S.y})}}e.schematic_group_id&&t.schematic_group.update(e.schematic_group_id,{width:w.width,height:w.height})},NI=1;function w3t(e){let{db:t}=e.root,n=e._parsedProps,i=S3t(e);if(i.length===0)return;let r=P3t({db:t,pcbChildren:i}),o=T3t(n),s=I3t({props:n,pcbChildren:i,childDimensions:r,gridConfig:o}),a=C3t({pcbChildren:i,childDimensions:r,gridLayout:s,gridConfig:o}),{itemCoordinates:c}=a.layout();k3t({db:t,group:e,pcbChildren:i,itemCoordinates:c,gridLayout:s}),N3t({db:t,group:e,props:n,gridLayout:s})}function S3t(e){return e.children.filter(t=>t.pcb_component_id||t.pcb_group_id)}function P3t(e){let{db:t,pcbChildren:n}=e,i=0,r=0;for(let o of n){let s=0,a=0;if(o.pcb_group_id){let c=t.pcb_group.get(o.pcb_group_id);s=c?.width??0,a=c?.height??0}else if(o.pcb_component_id){let c=t.pcb_component.get(o.pcb_component_id);s=c?.width??0,a=c?.height??0}i=Math.max(i,s),r=Math.max(r,a)}return{width:i,height:r}}function T3t(e){let t=e.pcbGridCols??e.gridCols??e.pcbLayout?.grid?.cols,n=e.pcbGridRows??e.pcbLayout?.grid?.rows,i=e.pcbGridTemplateColumns,r=e.pcbGridTemplateRows,o=h=>h===void 0?NI:typeof h=="number"?h:$.parse(h),s=e.pcbGridGap??e.gridGap??e.pcbLayout?.gridGap,a=e.pcbGridRowGap??e.gridRowGap??e.pcbLayout?.gridRowGap,c=e.pcbGridColumnGap??e.gridColumnGap??e.pcbLayout?.gridColumnGap,l=NI,u=NI;if(a!==void 0||c!==void 0){let h=typeof s=="object"?s?.x:s,d=typeof s=="object"?s?.y:s;l=o(c??h),u=o(a??d)}else if(typeof s=="object"&&s!==null)l=o(s.x),u=o(s.y);else{let h=o(s);l=h,u=h}return{cols:t,rows:n,gapX:l,gapY:u,templateColumns:i,templateRows:r}}function I3t(e){let{props:t,pcbChildren:n,childDimensions:i,gridConfig:r}=e;return t.pcbGridTemplateColumns||t.pcbGridTemplateRows?M3t({props:t,gridConfig:r,pcbChildren:n,childDimensions:i}):E3t({gridConfig:r,pcbChildren:n,childDimensions:i})}function M3t(e){let{props:t,gridConfig:n,pcbChildren:i,childDimensions:r}=e,o=t.pcbGridTemplateColumns??"",s=t.pcbGridTemplateRows??"",a=d=>{let _=d.match(/repeat\((\d+),/);return _?parseInt(_[1]):Math.ceil(Math.sqrt(i.length))},c=t.pcbGridTemplateColumns?a(o):Math.ceil(Math.sqrt(i.length)),l=t.pcbGridTemplateRows?a(s):Math.ceil(i.length/c),u=c*r.width+Math.max(0,c-1)*n.gapX,h=l*r.height+Math.max(0,l-1)*n.gapY;return{gridTemplateColumns:o,gridTemplateRows:s,containerWidth:u,containerHeight:h}}function E3t(e){let{gridConfig:t,pcbChildren:n,childDimensions:i}=e,r,o;t.cols!==void 0&&t.rows!==void 0?(r=t.cols,o=t.rows):t.cols!==void 0?(r=t.cols,o=Math.ceil(n.length/r)):t.rows!==void 0?(o=t.rows,r=Math.ceil(n.length/o)):(r=Math.ceil(Math.sqrt(n.length)),o=Math.ceil(n.length/r)),r=Math.max(1,r),o=Math.max(1,o);let s=r*i.width+Math.max(0,r-1)*t.gapX,a=o*i.height+Math.max(0,o-1)*t.gapY,c=`repeat(${r}, ${i.width}px)`,l=`repeat(${o}, ${i.height}px)`;return{gridTemplateColumns:c,gridTemplateRows:l,containerWidth:s,containerHeight:a}}function C3t(e){let{pcbChildren:t,childDimensions:n,gridLayout:i,gridConfig:r}=e,o=t.map((s,a)=>({key:s.getString()||`child-${a}`,contentWidth:n.width,contentHeight:n.height}));return new Yj({containerWidth:i.containerWidth,containerHeight:i.containerHeight,gridTemplateColumns:i.gridTemplateColumns,gridTemplateRows:i.gridTemplateRows,gap:[r.gapY,r.gapX],children:o})}function k3t(e){let{db:t,group:n,pcbChildren:i,itemCoordinates:r,gridLayout:o}=e,s=n._getGlobalPcbPositionBeforeLayout(),a=t.toArray();for(let c=0;c<i.length;c++){let l=i[c],u=l.getString()||`child-${c}`,h=r[u];if(!h){console.warn(`PCB grid layout: No coordinates found for child ${u}`);continue}let d=s.x-o.containerWidth/2+h.x+h.width/2,_=s.y+o.containerHeight/2-h.y-h.height/2;if(l.pcb_component_id)Ag(a,l.pcb_component_id,{x:d,y:_});else{let y=l;y.pcb_group_id&&y.source_group_id&&Rg(a,y.source_group_id,{x:d,y:_})}}}function N3t(e){let{db:t,group:n,props:i,gridLayout:r}=e;if(n.pcb_group_id){let o=n._getGlobalPcbPositionBeforeLayout();t.pcb_group.update(n.pcb_group_id,{width:i.width??r.containerWidth,height:i.height??r.containerHeight,center:o})}}function A3t(e){let t={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof e=="object"&&!e.preset)return{local:!(e.serverUrl||e.serverMode||e.serverCacheEnabled),...t,...e};let n=typeof e=="object"?e.preset:e,i=typeof e=="object"?e:{};switch(n){case"auto-local":return{local:!0,groupMode:"subcircuit"};case"sequential-trace":return{local:!0,groupMode:"sequential-trace"};case"subcircuit":return{local:!0,groupMode:"subcircuit"};case"auto-cloud":{let{preset:r,local:o,groupMode:s,...a}=i;return{local:!1,groupMode:"subcircuit",...t,...a}}default:return{local:!0,groupMode:"subcircuit"}}}var R3t=(e,t)=>{let n=e.children.filter(h=>h.componentName==="Constraint"&&h._parsedProps.pcb),i=new Map,r={},o=h=>(r[h]!==h&&(r[h]=o(r[h])),r[h]),s=(h,d)=>{let _=o(h),y=o(d);_!==y&&(r[y]=_)},a=h=>{h in r||(r[h]=h)},c=h=>{let d=h.startsWith(".")?h.slice(1):h;return e.children.find(y=>y.name===d)?.pcb_component_id??void 0};for(let h of n){let d=h._parsedProps;if("left"in d&&"right"in d){let _=c(d.left),y=c(d.right);_&&y&&(a(_),a(y),s(_,y))}else if("top"in d&&"bottom"in d){let _=c(d.top),y=c(d.bottom);_&&y&&(a(_),a(y),s(_,y))}else if("for"in d&&Array.isArray(d.for)){let _=d.for.map(y=>c(y)).filter(y=>!!y);for(let y of _)a(y);for(let y=1;y<_.length;y++)s(_[0],_[y])}}for(let h of Object.keys(r)){let d=o(h);i.has(d)||i.set(d,{componentIds:[],constraints:[]}),i.get(d).componentIds.push(h)}for(let h of n){let d=h._parsedProps,_;if("left"in d?_=c(d.left):"top"in d?_=c(d.top):"for"in d&&(_=c(d.for[0])),!_)continue;let y=o(_);i.get(y)?.constraints.push(h)}let l={},u=Object.fromEntries(t.components.map(h=>[h.componentId,h]));for(let[h,d]of i.entries()){if(d.componentIds.length<=1)continue;let _=new Op,y={},g=(A,O)=>{let B=`${A}_${O}`;return y[B]||(y[B]=new js(B)),y[B]},x=d.componentIds[0];_.addConstraint(new ai(g(x,"x"),Yn.Eq,0,wn.required)),_.addConstraint(new ai(g(x,"y"),Yn.Eq,0,wn.required));for(let A of d.constraints){let O=A._parsedProps;if("xDist"in O){let B=c(O.left),D=c(O.right);B&&D&&_.addConstraint(new ai(new En(g(D,"x"),[-1,g(B,"x")]),Yn.Eq,O.xDist,wn.required))}else if("yDist"in O){let B=c(O.top),D=c(O.bottom);B&&D&&_.addConstraint(new ai(new En(g(B,"y"),[-1,g(D,"y")]),Yn.Eq,O.yDist,wn.required))}else if("sameX"in O&&Array.isArray(O.for)){let B=O.for.map(D=>c(D)).filter(D=>!!D);if(B.length>1){let D=g(B[0],"x");for(let X=1;X<B.length;X++)_.addConstraint(new ai(new En(g(B[X],"x"),[-1,D]),Yn.Eq,0,wn.required))}}else if("sameY"in O&&Array.isArray(O.for)){let B=O.for.map(D=>c(D)).filter(D=>!!D);if(B.length>1){let D=g(B[0],"y");for(let X=1;X<B.length;X++)_.addConstraint(new ai(new En(g(B[X],"y"),[-1,D]),Yn.Eq,0,wn.required))}}}_.updateVariables();let w={};for(let A of d.componentIds)w[A]={x:g(A,"x").value(),y:g(A,"y").value()};let S=1/0,E=1/0,M=-1/0,k=-1/0;for(let A of d.componentIds){let O=u[A],B=w[A];if(O)for(let D of O.pads){let X=B.x+D.offset.x,Y=B.y+D.offset.y;S=Math.min(S,X-D.size.x/2),M=Math.max(M,X+D.size.x/2),E=Math.min(E,Y-D.size.y/2),k=Math.max(k,Y+D.size.y/2)}}let I={x:(S+M)/2,y:(E+k)/2},N=[],C={};for(let A of d.componentIds){let O=u[A],B=w[A];if(O){C[A]={x:B.x-I.x,y:B.y-I.y};for(let D of O.pads)N.push({padId:D.padId,networkId:D.networkId,type:D.type,size:D.size,offset:{x:B.x+D.offset.x-I.x,y:B.y+D.offset.y-I.y}})}}t.components=t.components.filter(A=>!d.componentIds.includes(A.componentId)),t.components.push({componentId:d.componentIds[0],pads:N,availableRotationDegrees:[0]}),d.relativeCenters=C,l[d.componentIds[0]]=d}return l},rm=(e,t,n)=>{if(t===n)return!0;let i=e.source_group.get(t);return!i||!i.parent_source_group_id?!1:rm(e,i.parent_source_group_id,n)},O3t=(e,t,n)=>{let{db:i}=e.root;for(let r of t.components){let{center:o,componentId:s,ccwRotationOffset:a,ccwRotationDegrees:c}=r,l=n[s];if(l){let w=(c??a??0)*Math.PI/180;for(let S of l.componentIds){let E=l.relativeCenters[S];if(!E)continue;let M={x:E.x*Math.cos(w)-E.y*Math.sin(w),y:E.x*Math.sin(w)+E.y*Math.cos(w)},k=i.pcb_component.get(S);if(!k)continue;let I=k.center,N=Jn(e._computePcbGlobalTransformBeforeLayout(),vn(o.x+M.x,o.y+M.y),Ba(w),vn(-I.x,-I.y)),C=i.toArray().filter(A=>"pcb_component_id"in A&&A.pcb_component_id===S);Dp(C,N)}continue}let u=i.pcb_component.get(s);if(u){let x=e.source_group_id,S=i.source_component.get(u.source_component_id)?.source_group_id;if(S!==void 0&&!rm(i,S,x))continue;let E=u.center,M=c??a??0,k=Jn(e._computePcbGlobalTransformBeforeLayout(),vn(o.x,o.y),Ba(M*Math.PI/180),vn(-E.x,-E.y)),I=i.toArray().filter(N=>"pcb_component_id"in N&&N.pcb_component_id===s);Dp(I,k);continue}let h=i.pcb_group.list().find(x=>x.source_group_id===s);if(!h)continue;let d=h.center,_=c??a??0,y=Jn(e._computePcbGlobalTransformBeforeLayout(),vn(o.x,o.y),Ba(_*Math.PI/180),vn(-d.x,-d.y)),g=i.toArray().filter(x=>{if("source_group_id"in x&&x.source_group_id&&(x.source_group_id===s||rm(i,x.source_group_id,s)))return!0;if("source_component_id"in x&&x.source_component_id){let w=i.source_component.get(x.source_component_id);if(w?.source_group_id&&(w.source_group_id===s||rm(i,w.source_group_id,s)))return!0}if("pcb_component_id"in x&&x.pcb_component_id){let w=i.pcb_component.get(x.pcb_component_id);if(w?.source_component_id){let S=i.source_component.get(w.source_component_id);if(S?.source_group_id&&(S.source_group_id===s||rm(i,S.source_group_id,s)))return!0}}return!1});Dp(g,y),i.pcb_group.update(h.pcb_group_id,{center:o})}},L3t="1mm",jX=(0,gV.default)("Group_doInitialPcbLayoutPack"),z3t=e=>{let{db:t}=e.root,{_parsedProps:n}=e,{packOrderStrategy:i,packPlacementStrategy:r,gap:o,pcbGap:s,pcbPackGap:a}=n,c=a??s??o,l=$.parse(c??L3t),u={},h=new Set,d=S=>{if(S?.pcb_component_id&&S?._parsedProps){let E=S._parsedProps,M=$.parse(E.pcbMarginLeft??E.pcbMarginX??0),k=$.parse(E.pcbMarginRight??E.pcbMarginX??0),I=$.parse(E.pcbMarginTop??E.pcbMarginY??0),N=$.parse(E.pcbMarginBottom??E.pcbMarginY??0);(M||k||I||N)&&(u[S.pcb_component_id]={left:M,right:k,top:I,bottom:N})}S?.children&&S.children.forEach(d)};d(e);let _=new Set;for(let S of e.children){let E=S;E._isNormalComponent&&E.isRelativelyPositioned?.()&&(E.pcb_component_id&&h.add(E.pcb_component_id),E.pcb_group_id&&_.add(E.pcb_group_id))}let y=t.toArray().filter(S=>S.type==="pcb_component"?!h.has(S.pcb_component_id):S.type==="pcb_group"?!_.has(S.pcb_group_id):!0),g={...Nj(kj(y,{source_group_id:e.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:u})),orderStrategy:i??"largest_to_smallest",placementStrategy:r??"minimum_sum_squared_distance_to_network",minGap:l},x=R3t(e,g);jX.enabled&&(e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${e.name}`,content:JSON.stringify(t.toArray())}),e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${e.name}`,content:g}));let w=Lb(g);if(jX.enabled){let S=VT(w);S.title=`packOutput-${e.name}`,global.debugGraphics?.push(S)}O3t(e,w,x)},F3t=e=>{let{db:t}=e.root,{_parsedProps:n}=e,i=e.children.filter(k=>k.pcb_component_id||k.pcb_group_id);if(i.some(k=>{let I=k._parsedProps;return I?.pcbX!==void 0||I?.pcbY!==void 0}))return;let o=n.pcbJustifyContent??n.justifyContent,s=n.pcbAlignItems??n.alignItems,a=n.pcbFlexGap??n.pcbGap??n.gap,c=n.pcbFlexDirection??"row",l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[o??"space-between"],u={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[s??"center"];if(!l)throw new Error(`Invalid justifyContent value: "${o}"`);if(!u)throw new Error(`Invalid alignItems value: "${s}"`);let h=0,d=0;typeof a=="object"?(h=a.y??0,d=a.x??0):typeof a=="number"?(h=a,d=a):typeof a=="string"&&(h=$.parse(a),d=$.parse(a));let _,y=n.width??n.pcbWidth??void 0,g=n.height??n.pcbHeight??void 0;(y===void 0||g===void 0)&&(_=Og(i.map(k=>k._getMinimumFlexContainerSize()).filter(k=>k!==null),{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d}),y=_.width,g=_.height);let w=new Db(y,g,{alignItems:u,justifyContent:l,direction:c,rowGap:h,columnGap:d});for(let k of i){let I=k._getMinimumFlexContainerSize();w.addChild({metadata:k,width:I?.width??0,height:I?.height??0,flexBasis:I?c==="row"?I.width:I.height:void 0})}w.build();let S={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let k of w.children)S.minX=Math.min(S.minX,k.position.x),S.minY=Math.min(S.minY,k.position.y),S.maxX=Math.max(S.maxX,k.position.x+k.size.width),S.maxY=Math.max(S.maxY,k.position.y+k.size.height);S.width=S.maxX-S.minX,S.height=S.maxY-S.minY;let E=e._getGlobalPcbPositionBeforeLayout(),M={x:E.x-(S.maxX+S.minX)/2,y:E.y-(S.maxY+S.minY)/2};for(let k of w.children)k.metadata._repositionOnPcb({x:k.position.x+k.size.width/2+M.x,y:k.position.y+k.size.height/2+M.y});t.pcb_group.update(e.pcb_group_id,{width:S.width,height:S.height,center:E})};function D3t(e){let{db:t}=e.root,n=new Map,i=new Map,r=new Set,s=e.selectAll("trace").filter(O=>O._parsedProps?.schDisplayLabel),a=e.selectAll("group"),c=[e.schematic_group_id,...a.map(O=>O.schematic_group_id)],l=t.schematic_component.list().filter(O=>c.includes(O.schematic_group_id)),u=[],h=new Map,d=new Map;for(let O of l){let B=O.schematic_component_id,D=[],X=t.source_component.getWhere({source_component_id:O.source_component_id}),Y=t.schematic_port.list({schematic_component_id:O.schematic_component_id});for(let H of Y){let K=`${X?.name??O.schematic_component_id}.${H.pin_number}`;h.set(K,H.schematic_port_id),d.set(H.schematic_port_id,K)}for(let H of Y){let K=d.get(H.schematic_port_id);D.push({pinId:K,x:H.center.x,y:H.center.y})}u.push({chipId:B,center:O.center,width:O.size.width,height:O.size.height,pins:D})}let _=new Set,y=new Map,g=new Map,x=new Map;for(let O of l){let B=t.schematic_port.list({schematic_component_id:O.schematic_component_id});for(let D of B)_.add(D.schematic_port_id),D.source_port_id&&(y.set(D.schematic_port_id,D.source_port_id),g.set(D.source_port_id,D.schematic_port_id))}let w=new Set;e.subcircuit_id&&w.add(e.subcircuit_id);for(let O of a)O.subcircuit_id&&w.add(O.subcircuit_id);let E=t.source_trace.list().filter(O=>{if(O.subcircuit_id===e.subcircuit_id)return!0;for(let B of O.connected_source_port_ids)if(g.has(B))return!0;return!1}).flatMap(O=>O.connected_source_net_ids);for(let O of E){let B=t.source_net.get(O);B?.subcircuit_id&&w.add(B.subcircuit_id)}let M=[],k=new Map;for(let O of t.source_trace.list()){if(O.subcircuit_id&&!w.has(O.subcircuit_id))continue;let B=(O.connected_source_port_ids??[]).map(D=>g.get(D)).filter(D=>!!D&&_.has(D));if(B.length>=2){let[D,X]=B.slice(0,2),Y=[D,X].sort().join("::");if(!k.has(Y)){k.set(Y,O.source_trace_id);let H=O.display_name??O.source_trace_id;O.subcircuit_connectivity_map_key&&(r.add(O.subcircuit_connectivity_map_key),x.set(H,O.subcircuit_connectivity_map_key),i.set(O.subcircuit_connectivity_map_key,H)),M.push({pinIds:[D,X].map(K=>d.get(K)),netId:H})}}}let I=[];for(let O of t.source_net.list().filter(B=>!B.subcircuit_id||w.has(B.subcircuit_id)))O.subcircuit_connectivity_map_key&&(r.add(O.subcircuit_connectivity_map_key),n.set(O.subcircuit_connectivity_map_key,O));let N=new Map;for(let[O,B]of y){let D=t.source_port.get(B);if(!D?.subcircuit_connectivity_map_key)continue;let X=D.subcircuit_connectivity_map_key;r.add(X),N.has(X)||N.set(X,[]),N.get(X).push(O)}for(let[O,B]of N){let D=n.get(O);if(D&&B.length>=2){let X=String(D.name||D.source_net_id||O);x.set(X,O),i.set(O,X);let H=.1*(.18/.18),K=Number((String(X).length*H).toFixed(2));I.push({netId:X,pinIds:B.map(Z=>d.get(Z)),netLabelWidth:K})}}let C=(()=>{let O={},B=new Set(I.map(D=>D.netId));for(let D of t.source_net.list().filter(X=>!X.subcircuit_id||w.has(X.subcircuit_id)))D.name&&B.has(D.name)&&(D.is_ground||D.name.toLowerCase().startsWith("gnd")?O[D.name]=["y-"]:D.is_power||D.name.toLowerCase().startsWith("v")?O[D.name]=["y+"]:O[D.name]=["x-","x+"]);return O})();return{inputProblem:{chips:u,directConnections:M,netConnections:I,availableNetLabelOrientations:C,maxMspPairDistance:e._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:h,pairKeyToSourceTraceId:k,sckToSourceNet:n,sckToUserNetId:i,userNetIdToSck:x,allSourceAndSchematicPortIdsInScope:_,schPortIdToSourcePortId:y,displayLabelTraces:s,allScks:r}}var Wi=1e-6;function YX(e){let t=Math.abs(e.to.x-e.from.x),n=Math.abs(e.to.y-e.from.y);return t>=n}function ox(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}function XX(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function VX(e,t,n){let i=ox(e,t);if(i<Wi)return 0;let r=((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/((t.x-e.x)*(t.x-e.x)+(t.y-e.y)*(t.y-e.y));return Math.max(0,Math.min(1,r))*i}function Jb(e,t,n,i){return e*i-t*n}function $3t(e,t,n,i){let r={x:t.x-e.x,y:t.y-e.y},o={x:i.x-n.x,y:i.y-n.y},s=Jb(r.x,r.y,o.x,o.y),a={x:n.x-e.x,y:n.y-e.y},c=Jb(a.x,a.y,r.x,r.y);if(Math.abs(s)<Wi&&Math.abs(c)<Wi||Math.abs(s)<Wi&&Math.abs(c)>=Wi)return null;let l=Jb(a.x,a.y,o.x,o.y)/s,u=Jb(a.x,a.y,r.x,r.y)/s;return l<-Wi||l>1+Wi||u<-Wi||u>1+Wi?null:{x:e.x+l*r.x,y:e.y+l*r.y}}function B3t(e,t=Wi){if(e.length===0)return e;e.sort((r,o)=>r.start-o.start);let n=[],i={...e[0]};for(let r=1;r<e.length;r++){let o=e[r];o.start<=i.end+t?i.end=Math.max(i.end,o.end):(n.push(i),i={...o})}return n.push(i),n}function j3t(e,t,n){let i=ox(e.from,e.to);if(i<Wi||t.length===0)return[e];let r=n/2,o=t.map(h=>({start:Math.max(0,h-r),end:Math.min(i,h+r)})).filter(h=>h.end-h.start>Wi),s=B3t(o),a=[],c=0,l={x:e.to.x-e.from.x,y:e.to.y-e.from.y},u=(h,d,_)=>{if(d-h<=Wi)return;let y=h/i,g=d/i;a.push({from:XX(e.from,e.to,y),to:XX(e.from,e.to,g),..._?{is_crossing:!0}:{}})};for(let h of s)h.start-c>Wi&&u(c,h.start,!1),u(h.start,h.end,!0),c=h.end;return i-c>Wi&&u(c,i,!1),a.length>0?a:[e]}function Y3t(e,t={}){let n=t.crossSegmentLength??.075,i=t.tolerance??Wi,r=new Map,o=c=>`${c.traceIdx}:${c.edgeIdx}`,s=c=>e[c.traceIdx].edges[c.edgeIdx];for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=l.edges[u];for(let d=c;d<e.length;d++){let _=e[d];for(let y=d===c?u+1:0;y<_.edges.length;y++){let g=_.edges[y],x=$3t(h.from,h.to,g.from,g.to);if(!x)continue;let w=ox(h.from,h.to),S=ox(g.from,g.to);if(w<i||S<i)continue;let E=VX(h.from,h.to,x),M=VX(g.from,g.to,x),k=E<=i||Math.abs(w-E)<=i||Number.isNaN(E),I=M<=i||Math.abs(S-M)<=i||Number.isNaN(M);if(!k&&!I){let N=YX(h),C=YX(g),A;if(N!==C)A=N;else{let D=Math.abs(h.to.x-h.from.x),X=Math.abs(h.to.y-h.from.y),Y=Math.abs(g.to.x-g.from.x),H=Math.abs(g.to.y-g.from.y),K=D-X,Z=Y-H;A=K===Z?!0:K>Z}let O=o({traceIdx:A?c:d,edgeIdx:A?u:y}),B=r.get(O)??[];B.push(A?E:M),r.set(O,B)}}}}}let a=e.map(c=>({source_trace_id:c.source_trace_id,edges:[]}));for(let c=0;c<e.length;c++){let l=e[c];for(let u=0;u<l.edges.length;u++){let h=o({traceIdx:c,edgeIdx:u}),d=r.get(h)??[];if(d.length===0){a[c].edges.push(l.edges[u]);continue}let _=Array.from(new Set(d.map(g=>Number(g.toFixed(6))))).sort((g,x)=>g-x),y=j3t(l.edges[u],_,n);a[c].edges.push(...y)}}return a}var os=1e-6;function sx(e,t,n=os){return Math.abs(e-t)<=n}function Ph(e,t,n=os){return sx(e.x,t.x,n)&&sx(e.y,t.y,n)}function HX(e,t,n,i=os){let r=Math.min(t.x,n.x)-i,o=Math.max(t.x,n.x)+i,s=Math.min(t.y,n.y)-i,a=Math.max(t.y,n.y)+i;return e.x<r||e.x>o||e.y<s||e.y>a?!1:Math.abs((n.x-t.x)*(e.y-t.y)-(n.y-t.y)*(e.x-t.x))<=i}function GX(e,t=os){let n=new Map;for(let i of e){let r=`${i.x.toFixed(6)},${i.y.toFixed(6)}`;n.has(r)||n.set(r,i)}return Array.from(n.values())}function UX(e){return{x:e.to.x-e.from.x,y:e.to.y-e.from.y}}function AI(e,t,n=os){let i=UX(e),r=UX(t),o=Math.hypot(i.x,i.y),s=Math.hypot(r.x,r.y);if(o<n||s<n)return!0;let a=i.x*r.y-i.y*r.x;return Math.abs(a)<=n*o*s}function om(e,t,n=os){return e.edges.filter(i=>Ph(i.from,t,n)||Ph(i.to,t,n))}function qX(e,t,n=os){for(let i of e.edges){if(Ph(i.from,t,n))return i.from;if(Ph(i.to,t,n))return i.to}return null}function X3t(e,t,n=os){let i=Ph(e.from,t,n)||sx(e.from.x,t.x,n)&&sx(e.from.y,t.y,n)?e.to:e.from,r=i.x-t.x,o=i.y-t.y;return Math.abs(r)<n&&Math.abs(o)<n?null:Math.abs(r)>=Math.abs(o)?r>=0?"right":"left":o>=0?"up":"down"}function xh(e,t,n=os){let i=om(e,t,n);if(i.length<2)return null;let r=i.map(h=>X3t(h,t,n)),o=r.includes("up"),s=r.includes("down"),a=r.includes("left"),c=r.includes("right"),l=o?"up":s?"down":null,u=c?"right":a?"left":null;return l&&u?`${l}-${u}`:null}function V3t(e,t={}){let n=t.tolerance??os,i={};for(let o of e)i[o.source_trace_id]=[];let r=e.map(o=>{let s=[];for(let a of o.edges)s.push(a.from,a.to);return GX(s,n)});for(let o=0;o<e.length;o++){let s=e[o],a=r[o];for(let c=o+1;c<e.length;c++){let l=e[c],u=r[c];for(let h of a)for(let d of u)if(Ph(h,d,n)){let _=om(s,h,n),y=om(l,d,n),g=_.some(E=>y.some(M=>!AI(E,M,n))),x=xh(s,h,n),w=xh(l,d,n);g&&!(x!==null&&w!==null&&x===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(d))}for(let h of a)for(let d of l.edges)if(HX(h,d.from,d.to,n)){let y=om(s,h,n).some(E=>!AI(E,d,n)),g=xh(s,h,n),x=qX(l,h,n*1e3),w=x?xh(l,x,n):null;y&&!(g!==null&&w!==null&&g===w)&&(i[s.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(h))}for(let h of u)for(let d of s.edges)if(HX(h,d.from,d.to,n)){let y=om(l,h,n).some(E=>!AI(d,E,n)),g=xh(l,h,n),x=qX(s,h,n*1e3),w=x?xh(s,x,n):null;y&&!(w!==null&&g!==null&&w===g)&&(i[l.source_trace_id].push(h),s.source_trace_id!==l.source_trace_id&&i[s.source_trace_id].push(h))}}}for(let o of Object.keys(i))i[o]=GX(i[o],n);return i}var RI=(0,xV.default)("Group_doInitialSchematicTraceRender");function H3t(e){let{group:t,solver:n,pinIdToSchematicPortId:i,userNetIdToSck:r}=e,{db:o}=t.root,s=n.traceLabelOverlapAvoidanceSolver?.getOutput().traces??n.schematicTraceLinesSolver?.solvedTracePaths,a=[];RI(`Traces inside SchematicTraceSolver output: ${(s??[]).length}`);for(let u of s??[]){let h=u?.tracePath;if(!Array.isArray(h)||h.length<2){RI(`Skipping trace ${u?.pinIds.join(",")} because it has less than 2 points`);continue}let d=[];for(let g=0;g<h.length-1;g++)d.push({from:{x:h[g].x,y:h[g].y},to:{x:h[g+1].x,y:h[g+1].y}});let _=null,y;if(Array.isArray(u?.pins)&&u.pins.length===2){let g=i.get(u.pins[0]?.pinId),x=i.get(u.pins[1]?.pinId);if(g&&x){for(let w of[g,x])o.schematic_port.get(w)&&o.schematic_port.update(w,{is_connected:!0});y=r.get(String(u.userNetId))}}_||(_=`solver_${u?.mspPairId}`,y=r.get(String(u.userNetId))),a.push({source_trace_id:_,edges:d,subcircuit_connectivity_map_key:y})}RI(`Applying ${a.length} traces from SchematicTraceSolver output`);let c=Y3t(a.map(u=>({source_trace_id:u.source_trace_id,edges:u.edges}))),l=V3t(c);for(let u of c)o.schematic_trace.insert({source_trace_id:u.source_trace_id,edges:u.edges,junctions:l[u.source_trace_id]??[],subcircuit_connectivity_map_key:a.find(h=>h.source_trace_id===u.source_trace_id)?.subcircuit_connectivity_map_key})}var G3t=e=>{switch(e){case"x+":return"left";case"x-":return"right";case"y+":return"bottom";case"y-":return"top";case"left":return"right";case"top":return"bottom";case"right":return"left";case"bottom":return"top"}},U3t=e=>{for(let n of e){let i=n._getDirectlyConnectedTraces();for(let r of i){let o=r._parsedProps.schDisplayLabel;if(o)return{name:o,wasAssignedDisplayLabel:!0}}}return{name:e.map(n=>n._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},OI=(0,vV.default)("Group_doInitialSchematicTraceRender");function q3t(e){let{group:t,solver:n,sckToSourceNet:i,allScks:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,userNetIdToSck:a,pinIdToSchematicPortId:c,schematicPortIdsWithPreExistingNetLabels:l,schematicPortIdsWithRoutedTraces:u}=e,{db:h}=t.root,d=n.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],_=n.mspConnectionPairSolver.globalConnMap;for(let y of d){OI(`processing placement: ${y.netId}`);let g=_.getIdsConnectedToNet(y.globalConnNetId).find(O=>a.get(O)),x=a.get(g),w=y.anchorPoint,S=y.orientation,E=G3t(S),M=x?i.get(x):void 0,k=y.pinIds.map(O=>c.get(O));if(k.some(O=>l.has(O))){OI(`skipping net label placement for "${y.netId}" REASON:schematic port has pre-existing net label`);continue}if(M){let O=M.name,B=bc({anchor_position:w,anchor_side:E,text:O});h.schematic_net_label.insert({text:O,anchor_position:w,center:B,anchor_side:E,...M?.source_net_id?{source_net_id:M.source_net_id}:{}});continue}let I=t.selectAll("port").filter(O=>O._getSubcircuitConnectivityKey()===x),{name:N,wasAssignedDisplayLabel:C}=U3t(I);if(!C&&k.some(O=>u.has(O))){OI(`skipping net label placement for "${y.netId}" REASON:schematic port has routed traces and no display label`);continue}let A=bc({anchor_position:w,anchor_side:E,text:N});h.schematic_net_label.insert({text:N,anchor_position:w,center:A,anchor_side:E})}}var W3t=({allSourceAndSchematicPortIdsInScope:e,group:t,schPortIdToSourcePortId:n,sckToSourceNet:i,pinIdToSchematicPortId:r,schematicPortIdsWithPreExistingNetLabels:o})=>{let{db:s}=t.root;for(let a of Array.from(e)){let c=s.schematic_port.get(a);if(!c||c.is_connected)continue;let l=n.get(a);if(!l)continue;let h=s.source_port.get(l)?.subcircuit_connectivity_map_key;if(!h)continue;let d=i.get(h);if(!d||s.schematic_net_label.list().some(w=>Math.abs(w.anchor_position.x-c.center.x)<.1&&Math.abs(w.anchor_position.y-c.center.y)<.1?d.source_net_id&&w.source_net_id?w.source_net_id===d.source_net_id:w.text===(d.name||h):!1))continue;let y=d.name||d.source_net_id||h,g=lm(c.facing_direction||"right")||"right",x=bc({anchor_position:c.center,anchor_side:g,text:y});s.schematic_net_label.insert({text:y,anchor_position:c.center,center:x,anchor_side:g,...d.source_net_id?{source_net_id:d.source_net_id}:{}})}},Z3t=e=>{let t=new Set,n=e.selectAll("netlabel");for(let i of n){let r=i._getConnectedPorts();for(let o of r)o.schematic_port_id&&t.add(o.schematic_port_id)}return t},K3t=({solver:e,pinIdToSchematicPortId:t})=>{let n=e.schematicTraceLinesSolver.solvedTracePaths,i=new Set;for(let r of n)for(let o of r.pinIds){let s=t.get(o);s&&i.add(s)}return i},J3t=(0,bV.default)("Group_doInitialSchematicTraceRender"),Q3t=e=>{if(!e.root?._featureMspSchematicTraceRouting||!e.isSubcircuit||e.root?.schematicDisabled)return;let{inputProblem:t,pinIdToSchematicPortId:n,pairKeyToSourceTraceId:i,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,displayLabelTraces:a,allScks:c,userNetIdToSck:l}=D3t(e),u=Z3t(e);J3t.enabled&&e.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(t,null,2)});let h=new iY(t);h.solve();let d=K3t({solver:h,pinIdToSchematicPortId:n});H3t({group:e,solver:h,pinIdToSchematicPortId:n,userNetIdToSck:l}),q3t({group:e,solver:h,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,pinIdToSchematicPortId:n,allScks:c,userNetIdToSck:l,schematicPortIdsWithPreExistingNetLabels:u,schematicPortIdsWithRoutedTraces:d}),W3t({group:e,allSourceAndSchematicPortIdsInScope:o,schPortIdToSourcePortId:s,sckToSourceNet:r,pinIdToSchematicPortId:n,schematicPortIdsWithPreExistingNetLabels:u})},t5t=()=>({async simulate(e){let t="spice-experiment-1",{circuit:n,tran:i}=sY(e);return{simulationResultCircuitJson:aY(i,n,t)}}}),Qs=(0,wV.default)("tscircuit:core:Group_doInitialSimulationSpiceEngineRender");function e5t(e){if(!e.isSubcircuit)return;let{root:t}=e;if(!t||e.selectAll("analogsimulation").length===0)return;let i={...t.platform?.spiceEngineMap};i.spicey||(i.spicey=t5t());let r=t.db.toArray(),o;try{o=oY(r).toSpiceString(),Qs(`Generated SPICE string:
243
243
  ${o}`)}catch(s){Qs(`Failed to convert circuit JSON to SPICE: ${s}`);return}for(let[s,a]of Object.entries(i))Qs(`Queueing simulation for spice engine: ${s}`),e._queueAsyncEffect(`spice-simulation-${s}`,async()=>{try{Qs(`Running simulation with engine: ${s}`);let c=await a.simulate(o);Qs(`Simulation completed, received ${c.simulationResultCircuitJson.length} elements`);let l=t.db.simulation_experiment.list()[0];if(!l){Qs("No simulation experiment found, skipping result insertion");return}for(let u of c.simulationResultCircuitJson){u.type==="simulation_transient_voltage_graph"&&(u.simulation_experiment_id=l.simulation_experiment_id);let h=u.type;h&&t.db[h]?(t.db[h].insert(u),Qs(`Inserted ${h} into database`)):(Qs(`Warning: Unknown element type ${h}, adding to raw db`),t.db._addElement(u))}e._markDirty("SimulationSpiceEngineRender")}catch(c){Qs(`Simulation failed for engine ${s}: ${c}`)}})}var Th=class extends On{constructor(){super(...arguments);T(this,"pcb_group_id",null);T(this,"schematic_group_id",null);T(this,"subcircuit_id",null);T(this,"_hasStartedAsyncAutorouting",!1);T(this,"_asyncAutoroutingResult",null);T(this,"unnamedElementCounter",{})}get config(){return{zodProps:dz,componentName:"Group"}}doInitialSourceGroupRender(){let{db:t}=this.root,n=typeof this._parsedProps.name=="string"&&this._parsedProps.name.length>0,i=t.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit,was_automatically_named:!n});this.source_group_id=i.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${i.source_group_id}`,t.source_group.update(i.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:t}=this.root;for(let n of this.children)t.source_component.update(n.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:t}=this.root,n=this.parent?.getGroup?.();if(n?.source_group_id&&t.source_group.update(this.source_group_id,{parent_source_group_id:n.source_group_id}),!this.isSubcircuit)return;let i=this.parent?.getSubcircuit?.()?.subcircuit_id;i&&t.source_group.update(this.source_group_id,{parent_subcircuit_id:i})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:n.autorouter?{trace_clearance:n.autorouter.traceClearance}:void 0});this.pcb_group_id=i.pcb_group_id;for(let r of this.children)t.pcb_component.update(r.pcb_component_id,{pcb_group_id:i.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this._parsedProps,i=cx(this.children);if(this.pcb_group_id){let r=i.width,o=i.height,s=(i.minX+i.maxX)/2,a=(i.minY+i.maxY)/2;if(this.isSubcircuit){let{padLeft:u,padRight:h,padTop:d,padBottom:_}=this._resolvePcbPadding();r+=u+h,o+=d+_,s+=(h-u)/2,a+=(d-_)/2}let l=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0?t.pcb_group.get(this.pcb_group_id)?.center??{x:s,y:a}:{x:s,y:a};t.pcb_group.update(this.pcb_group_id,{width:Number(n.width??r),height:Number(n.height??o),center:l})}}getNextAvailableName(t){var n,i;return(n=this.unnamedElementCounter)[i=t.lowercaseComponentName]??(n[i]=1),`unnamed_${t.lowercaseComponentName}${this.unnamedElementCounter[t.lowercaseComponentName]++}`}_resolvePcbPadding(){let t=this._parsedProps,n=t.pcbLayout,i=h=>{let d=n?.[h],_=t[h];if(typeof d=="number")return d;if(typeof _=="number")return _},r=i("padding")??0,o=i("paddingX"),s=i("paddingY"),a=i("paddingLeft")??o??r,c=i("paddingRight")??o??r,l=i("paddingTop")??s??r,u=i("paddingBottom")??s??r;return{padLeft:a,padRight:c,padTop:l,padBottom:u}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:t}=this,{db:n}=this.root,i=t;if(!this.isSubcircuit)return;let r=i.manualEdits?.manual_trace_hints;if(r)for(let o of r)this.add(new KI({for:o.pcb_port_selector,offsets:o.offsets}))}doInitialSourceAddConnectivityMapKey(){b3t(this)}_areChildSubcircuitsRouted(){let t=this.selectAll("group").filter(n=>n.isSubcircuit);for(let n of t)if(n._shouldRouteAsync()&&!n._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let t=this._getAutorouterConfig();return t.groupMode==="sequential-trace"?!1:!!(t.local&&t.groupMode==="subcircuit"||!t.local)}_hasTracesToRoute(){let t=(0,vh.default)("tscircuit:core:_hasTracesToRoute"),n=this.selectAll("trace");return t(`[${this.getString()}] has ${n.length} traces to route`),n.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:t}=this.root,n=(0,vh.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),i=this._parsedProps,r=this._getAutorouterConfig(),o=r.serverUrl,s=r.serverMode,a=(u,h)=>(n("fetching",u),h.headers&&(h.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(u,h)),c=this.root.db.toArray().filter(u=>u.type.startsWith("source_")||u.type.startsWith("pcb_"));if(s==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:h}=await a(`${o}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:jI({db:t,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(d=>d.json());this._asyncAutoroutingResult=h,this._markDirty("PcbTraceRender");return}let{autorouting_result:u}=await a(`${o}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:c,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());this._asyncAutoroutingResult=u,this._markDirty("PcbTraceRender");return}let{autorouting_job:l}=await a(`${o}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:c,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:r.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(u=>u.json());for(;;){let{autorouting_job:u}=await a(`${o}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());if(u.is_finished){let{autorouting_job_output:h}=await a(`${o}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(d=>d.json());this._asyncAutoroutingResult={output_pcb_traces:h.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(u.has_error){let h=new im(`Autorouting job failed: ${JSON.stringify(u.error)}`);throw t.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,error_type:"pcb_autorouting_error",message:h.message}),h}await new Promise(h=>setTimeout(h,100))}}async _runLocalAutorouting(){let{db:t}=this.root,n=this._parsedProps,i=(0,vh.default)("tscircuit:core:_runLocalAutorouting");i(`[${this.getString()}] starting local autorouting`);let r=this._getAutorouterConfig(),{simpleRouteJson:o}=jI({db:t,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(i.enabled&&global.debugOutputArray?.push({name:`simpleroutejson-${this.props.name}.json`,obj:o}),i.enabled){let c=N4(o);c.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(c)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:o});let s;r.algorithmFn?s=await r.algorithmFn(o):s=new u3t(o,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity});let a=new Promise((c,l)=>{s.on("complete",u=>{i(`[${this.getString()}] local autorouting complete`),c(u.traces)}),s.on("error",u=>{i(`[${this.getString()}] local autorouting error: ${u.error.message}`),l(u.error)})});s.on("progress",c=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...c})}),s.start();try{let c=await a;this._asyncAutoroutingResult={output_pcb_traces:c},this._markDirty("PcbTraceRender")}catch(c){let{db:l}=this.root;throw l.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:c instanceof Error?c.message:String(c)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:c instanceof Error?c.message:String(c)},simpleRouteJson:o}),c}finally{s.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let t=(0,vh.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){t(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}t(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){Q3t(this)}updatePcbTraceRender(){let t=(0,vh.default)("tscircuit:core:updatePcbTraceRender");if(t(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(t(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:n}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){t(`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){t(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:t}=this.root,{traces:n}=this._asyncAutoroutingResult.output_simple_route_json;if(n)for(let i of n){let r=t.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:t}=this._asyncAutoroutingResult;if(!t)return;let{db:n}=this.root;for(let i of t)if(i.type==="pcb_trace"){if(i.subcircuit_id=this.subcircuit_id,i.connection_name){let r=i.connection_name;i.source_trace_id=r}n.pcb_trace.insert(i)}for(let i of t)if(i.type!=="pcb_via"&&i.type==="pcb_trace")for(let r of i.route)r.route_type==="via"&&n.pcb_via.insert({pcb_trace_id:i.pcb_trace_id,x:r.x,y:r.y,hole_diameter:.3,outer_diameter:.6,layers:[r.from_layer,r.to_layer],from_layer:r.from_layer,to_layer:r.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=i.schematic_group_id;for(let r of this.children)r.schematic_component_id&&t.schematic_component.update(r.schematic_component_id,{schematic_group_id:i.schematic_group_id})}_getSchematicLayoutMode(){let t=this._parsedProps;if(t.schLayout?.layoutMode==="none"||t.schLayout?.layoutMode==="relative")return"relative";if(t.schLayout?.matchAdapt)return"match-adapt";if(t.schLayout?.flex)return"flex";if(t.schLayout?.grid)return"grid";if(t.schMatchAdapt)return"match-adapt";if(t.schFlex)return"flex";if(t.schGrid)return"grid";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";if(t.relative||t.schRelative)return"relative";let n=this.children.some(r=>{let o=r._parsedProps;return o?.schX!==void 0||o?.schY!==void 0}),i=(t.manualEdits?.schematic_placements?.length??0)>0;return!n&&!i?"match-adapt":"relative"}doInitialSchematicLayout(){let t=this._getSchematicLayoutMode();t==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),t==="grid"&&this._doInitialSchematicLayoutGrid(),t==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){_3t(this)}_doInitialSchematicLayoutMatchpack(){g3t(this)}_doInitialSchematicLayoutGrid(){x3t(this)}_doInitialSchematicLayoutFlex(){v3t(this)}_getPcbLayoutMode(){let t=this._parsedProps;if(t.pcbRelative)return"none";if(t.pcbLayout?.matchAdapt)return"match-adapt";if(t.pcbLayout?.flex)return"flex";if(t.pcbLayout?.grid)return"grid";if(t.pcbLayout?.pack)return"pack";if(t.pcbFlex)return"flex";if(t.pcbGrid)return"grid";if(t.pcbPack||t.pack)return"pack";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";let n=t.pcbX!==void 0||t.pcbY!==void 0,i=(t.manualEdits?.pcb_placements?.length??0)>0,r=this.children.reduce((o,s)=>{if(!s.pcb_component_id&&!s.pcb_group_id)return o;let a=s._parsedProps,c=a?.pcbX!==void 0||a?.pcbY!==void 0;return o+(c?0:1)},0);return!n&&!i&&r>1?"pack":"none"}doInitialPcbLayout(){let t=this._getPcbLayoutMode();t==="grid"?this._doInitialPcbLayoutGrid():t==="pack"?this._doInitialPcbLayoutPack():t==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){w3t(this)}_doInitialPcbLayoutPack(){z3t(this)}_doInitialPcbLayoutFlex(){F3t(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._parsedProps;if(!n.border)return;let i=typeof n.schWidth=="number"?n.schWidth:void 0,r=typeof n.schHeight=="number"?n.schHeight:void 0,o=typeof n.schPadding=="number"?n.schPadding:0,s=typeof n.schPaddingLeft=="number"?n.schPaddingLeft:o,a=typeof n.schPaddingRight=="number"?n.schPaddingRight:o,c=typeof n.schPaddingTop=="number"?n.schPaddingTop:o,l=typeof n.schPaddingBottom=="number"?n.schPaddingBottom:o,u=this.schematic_group_id?t.schematic_group.get(this.schematic_group_id):null;if(u&&(i===void 0&&typeof u.width=="number"&&(i=u.width),r===void 0&&typeof u.height=="number"&&(r=u.height)),i===void 0||r===void 0)return;let h=u?.center??this._getGlobalSchematicPositionBeforeLayout(),d=h.x-i/2-s,_=h.y-r/2-l,y=i+s+a,g=r+c+l;t.schematic_box.insert({width:y,height:g,x:d,y:_,is_dashed:n.border?.dashed??!1})}_determineSideFromPosition(t,n){if(!t.center||!n.center)return"left";let i=t.center.x-n.center.x,r=t.center.y-n.center.y;return Math.abs(i)>Math.abs(r)?i>0?"right":"left":r>0?"bottom":"top"}_calculateSchematicBounds(t){if(t.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let n=1/0,i=-1/0,r=1/0,o=-1/0;for(let a of t)n=Math.min(n,a.centerX),i=Math.max(i,a.centerX),r=Math.min(r,a.centerY),o=Math.max(o,a.centerY);let s=2;return{minX:n-s,maxX:i+s,minY:r-s,maxY:o+s}}_getAutorouterConfig(){let t=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return A3t(t)}_getSubcircuitLayerCount(){let t=this.getInheritedProperty("layers");return typeof t=="number"?t:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(this.isSubcircuit){let n=new Map;for(let i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){let r=n.get(i._parsedProps.name)||[];r.push(i),n.set(i._parsedProps.name,r)}for(let[i,r]of n.entries())r.length>1&&t.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:r.map(o=>o.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:t}=this.root,n=t;for(let i of n.schematic_net_label.list()){let r=n.source_net.get(i.source_net_id),o=i.text||r?.name||"";if(i.anchor_side==="top"&&/^gnd/i.test(o)){n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_down"});continue}i.anchor_side==="bottom"&&/^v/i.test(o)&&n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_up"})}}doInitialSimulationSpiceEngineRender(){e5t(this)}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(t){return super._repositionOnPcb(t)}},WX=(e,t,n)=>{let i=Math.min(n,e/2,t/2),r=Math.max(1,Math.ceil(Math.PI/2*i)),o=Math.PI/2/r,s=e/2,a=t/2,c=[];c.push({x:-s+i,y:-a}),c.push({x:s-i,y:-a});for(let l=1;l<=r;l++){let u=-Math.PI/2+l*o;c.push({x:s-i+i*Math.cos(u),y:-a+i+i*Math.sin(u)})}c.push({x:s,y:a-i});for(let l=1;l<=r;l++){let u=0+l*o;c.push({x:s-i+i*Math.cos(u),y:a-i+i*Math.sin(u)})}c.push({x:-s+i,y:a});for(let l=1;l<=r;l++){let u=Math.PI/2+l*o;c.push({x:-s+i+i*Math.cos(u),y:a-i+i*Math.sin(u)})}c.push({x:-s,y:-a+i});for(let l=1;l<=r;l++){let u=Math.PI+l*o;c.push({x:-s+i+i*Math.cos(u),y:-a+i+i*Math.sin(u)})}return c},SV=class extends Th{constructor(){super(...arguments);T(this,"pcb_board_id",null);T(this,"source_board_id",null);T(this,"_drcChecksComplete",!1);T(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:t4}}get boardThickness(){let{_parsedProps:t}=this;return 1.4}get allLayers(){return(this._parsedProps.layers??2)===4?["top","bottom","inner1","inner2"]:["top","bottom"]}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db:t}=this.root,{_parsedProps:n}=this;if(n.width&&n.height)return;let i=1/0,r=1/0,o=-1/0,s=-1/0,a=mV(t,this.subcircuit_id),c=new Set([this.subcircuit_id,...a]),l=t.pcb_component.list().filter(k=>k.subcircuit_id&&c.has(k.subcircuit_id)),u=t.pcb_group.list().filter(k=>k.subcircuit_id&&c.has(k.subcircuit_id)),h=!1,d=(k,I,N)=>{I===0||N===0||(h=!0,i=Math.min(i,k.x-I/2),r=Math.min(r,k.y-N/2),o=Math.max(o,k.x+I/2),s=Math.max(s,k.y+N/2))};for(let k of l)d(k.center,k.width,k.height);for(let k of u)d(k.center,k.width,k.height);if(n.boardAnchorPosition){let{x:k,y:I}=n.boardAnchorPosition;i=Math.min(i,k),r=Math.min(r,I),o=Math.max(o,k),s=Math.max(s,I)}let _=2,y=h?o-i+_*2:0,g=h?s-r+_*2:0,x={x:h?(i+o)/2+(n.outlineOffsetX??0):n.outlineOffsetX??0,y:h?(r+s)/2+(n.outlineOffsetY??0):n.outlineOffsetY??0},w=n.width??y,S=n.height??g,E=n.outline;!E&&n.borderRadius!=null&&w>0&&S>0&&(E=WX(w,S,n.borderRadius));let M={width:w,height:S,center:x};E&&(M.outline=E.map(k=>({x:k.x+(n.outlineOffsetX??0),y:k.y+(n.outlineOffsetY??0)}))),t.pcb_board.update(this.pcb_board_id,M)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let t=this.root?.platform;if(!t?.printBoardInformationToSilkscreen)return;let n=this.root.db.pcb_board.get(this.pcb_board_id);if(!n)return;let i=[];if(t.projectName&&i.push(t.projectName),t.version&&i.push(`v${t.version}`),t.url&&i.push(t.url),i.length===0)return;let r=i.join(`
244
- `),a={x:n.center.x+n.width/2-.25,y:n.center.y-n.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:r,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialSourceRender(){super.doInitialSourceRender();let{db:t}=this.root,n=t.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=n.source_board_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.width??0,r=n.height??0,o={x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)},{boardAnchorPosition:s,boardAnchorAlignment:a}=n;if(s&&(o=l3t({boardAnchorPosition:s,boardAnchorAlignment:a??"center",width:i,height:r})),n.outline){let u=n.outline.map(x=>x.x),h=n.outline.map(x=>x.y),d=Math.min(...u),_=Math.max(...u),y=Math.min(...h),g=Math.max(...h);i=_-d,r=g-y,o={x:(d+_)/2+(n.outlineOffsetX??0),y:(y+g)/2+(n.outlineOffsetY??0)}}let c=n.outline;!c&&n.borderRadius!=null&&i>0&&r>0&&(c=WX(i,r,n.borderRadius));let l=t.pcb_board.insert({center:o,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:r,outline:c?.map(u=>({x:u.x+(n.outlineOffsetX??0),y:u.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=l.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:t}=this.root;this.pcb_board_id&&(t.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return Ai()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let n=pY(t.toArray());for(let l of n)t.pcb_trace_error.insert(l);let i=uY(t.toArray());for(let l of i)t.pcb_port_not_connected_error.insert(l);let r=fY(t.toArray());for(let l of r)t.pcb_component_outside_board_error.insert(l);let o=yY(t.toArray());for(let l of o)t.pcb_trace_error.insert(l);let s=_Y(t.toArray());for(let l of s)t.pcb_via_clearance_error.insert(l);let a=mY(t.toArray());for(let l of a)t.pcb_via_clearance_error.insert(l);let c=gY(t.toArray());for(let l of c)t.pcb_footprint_overlap_error.insert(l)}_emitRenderLifecycleEvent(t,n){super._emitRenderLifecycleEvent(t,n),n==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t})}},n5t=new Proxy({},{get:(e,t)=>t}),na=n5t,lx="rgba(132, 0, 0)",ux=.12,PV=class extends On{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:Sz,sourceFtype:na.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let t=this.props.capacitance,n=typeof t=="string"?t:`${ti(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${n}/${ti(this._parsedProps.maxVoltageRating)}V`:n}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new ko({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new ko({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,capacitance:n.capacitance,max_voltage_rating:n.maxVoltageRating,max_decoupling_trace_length:n.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!n.polarized});this.source_component_id=i.source_component_id}},px=class extends On{constructor(t){super(t);T(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:Rp,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);let{_parsedProps:n}=this;if(n.externallyConnectedPins){let i=new Set;for(let[r,o]of n.externallyConnectedPins)i.add(r),i.add(o);for(let r of i)if(!this.children.find(s=>s instanceof Di&&s.isMatchingAnyOf([r]))){let s=r.match(/^pin(\d+)$/);if(s){let a=parseInt(s[1]);this.add(new Di({pinNumber:a,aliases:[r]}))}else this.add(new Di({name:r,aliases:[r]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:t}=this;t?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:t}=this;if(t.externallyConnectedPins)for(let[n,i]of t.externallyConnectedPins)this.add(new ko({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:t}=this.root,{pinAttributes:n}=this.props;if(!n)return;let i=null,r=null,o,s=this.selectAll("port");for(let h of s)for(let d of h.getNameAndAliases())if(n[d]){let _=n[d];_.providesPower&&(i=h,o=_.providesVoltage),_.providesGround&&(r=h)}if(!i||!r||o===void 0)return;let a=t.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=t.source_port.get(r.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=t.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=t.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||t.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:r.source_port_id,negative_source_net_id:u.source_net_id,voltage:o})}},TV=class extends px{constructor(e){super(e)}get config(){return{...super.config,componentName:"Pinout",zodProps:fz}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}},IV=class extends On{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"anode",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"cathode",this.portMap.pin2)}get config(){let t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},n=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"diode",componentName:"Diode",zodProps:Bz,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},MV=class extends On{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:_z,sourceFtype:na.simple_fuse}}_getSchematicSymbolDisplayValue(){let e=this._parsedProps.currentRating,t=this._parsedProps.voltageRating,n=typeof e=="string"?parseFloat(e):e,i=typeof t=="string"?parseFloat(t):t;return`${ti(n)}A / ${ti(i)}V`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=typeof t.currentRating=="string"?parseFloat(t.currentRating):t.currentRating,i=typeof t.voltageRating=="string"?parseFloat(t.voltageRating):t.voltageRating,r=e.source_component.insert({name:this.name,ftype:na.simple_fuse,current_rating_amps:n,voltage_rating_volts:i,display_current_rating:`${ti(n)}A`,display_voltage_rating:`${ti(i)}V`});this.source_component_id=r.source_component_id}},EV=class extends On{constructor(){super(...arguments);T(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:e4,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},CV=class extends On{constructor(){super(...arguments);T(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(t){return this.selectOne(`port.${t}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let t=this.children.filter(n=>n.componentName==="Port").map(n=>n.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){let t=this._parsedProps??this.props,n=t.pinCount;if(t.pinCount==null&&!t.footprint&&(n=2),t.pinCount==null){let o=(t.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),s=o.length>0?Math.max(...o):0,a=t.pinLabels?Object.keys(t.pinLabels).length:0,c=Math.max(s,a);(c===2||c===3)&&(n=c),n==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(n=this.getPortsFromFootprint().length)}let i="";n?i+=`solderjumper${n}`:i="solderjumper";let r=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?r=Array.from(new Set(t.bridgedPins.flat().map(o=>this._getPinNumberFromBridgedPinName(o)).filter(o=>o!==null))).sort((o,s)=>o-s):t.bridged&&n&&(r=Array.from({length:n},(o,s)=>s+1)),r.length>0&&(i+=`_bridged${r.join("")}`),{schematicSymbolName:t.symbolName??i,componentName:"SolderJumper",zodProps:mz,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);n==null&&!this._parsedProps.footprint&&(n=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},kV=class extends On{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"anode",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"cathode",this.portMap.pin2)}get config(){let t={laser:"laser_diode"},n=this.props.laser?"laser":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"led",componentName:"Led",zodProps:Yz,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}getFootprinterString(){let t=super.getFootprinterString();return t&&this.props.color?`${t}_color(${this.props.color})`:t}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:n.wavelength,color:n.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},NV=class extends On{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"positive",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:nF,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Di({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Di({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},i5t=Fn.extend({voltage:oi.optional(),frequency:fr.optional(),peakToPeakVoltage:oi.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:ze.optional(),dutyCycle:p.number().optional()}),AV=class extends On{constructor(){super(...arguments);T(this,"terminal1",this.portMap.terminal1);T(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:i5t,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.portMap.terminal1,r=this.portMap.terminal2;t.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:r.source_port_id,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle})}},RV=class extends On{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:gz,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${ti(this._parsedProps.resistance)}\u03A9`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,this.props.pulldownFor,this.props.pulldownTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new ko({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new ko({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new ko({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new ko({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,resistance:n.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}},r5t=["leftedge","rightedge","topedge","bottomedge","center"],OV=class extends be{get config(){return{componentName:"Constraint",zodProps:Tz}}constructor(e){if(super(e),("xdist"in e||"ydist"in e)&&!("edgeToEdge"in e)&&!("centerToCenter"in e))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in e&&e.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let e=[],t=this.getPrimitiveContainer();function n(i){let r=i.split(" ").pop(),o=r5t.includes(r)?r:void 0,s=o?i.replace(` ${o}`,""):i,a=t.selectOne(s,{pcbPrimitive:!0});a&&e.push({selector:i,component:a,componentSelector:s,edge:o})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},LV=class extends be{constructor(){super(...arguments);T(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:Gz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for FabricationNoteRect. Must be "top" or "bottom".`);let o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,s=this.getSubcircuit(),a=t.pcb_fabrication_note_rect.insert({pcb_component_id:o,layer:r,color:n.color,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,stroke_width:n.strokeWidth??1,is_filled:n.isFilled??!1,has_stroke:n.hasStroke??!1,is_stroke_dashed:n.isStrokeDashed??!1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.fabrication_note_rect_id=a.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},zV=class extends be{constructor(){super(...arguments);T(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:Uz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this.getSubcircuit(),{_parsedProps:i}=this,r=i.layer??"top";if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_fabrication_note_path.insert({pcb_component_id:s,layer:r,color:i.color,route:i.route.map(c=>{let l=De(o,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:n?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},FV=class extends be{get config(){return{componentName:"FabricationNoteText",zodProps:Hz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this.getSubcircuit();e.pcb_fabrication_note_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:t.pcbX??0,y:t.pcbY??0},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:"top",color:t.color,text:t.text??"",pcb_component_id:n.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},DV=class extends be{constructor(){super(...arguments);T(this,"fabrication_note_dimension_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:qz}}_resolvePoint(t,n){if(typeof t=="string"){let o=this.getSubcircuit().selectOne(t);return o?o._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${t}"`),De(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,r=typeof t.y=="string"?parseFloat(t.y):t.y;return De(n,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(n.from,i),o=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),l=c(n.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for FabricationNoteDimension. Must be "top" or "bottom".`);let u=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,h=t.pcb_fabrication_note_dimension.insert({pcb_component_id:u,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,layer:l,from:r,to:o,text:n.text,offset:n.offset,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.fabrication_note_dimension_id=h.pcb_fabrication_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}},$V=class extends be{constructor(){super(...arguments);T(this,"pcb_note_line_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:vF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this.getGroup(),o=this._computePcbGlobalTransformBeforeLayout(),s=De(o,{x:n.x1,y:n.y1}),a=De(o,{x:n.x2,y:n.y2}),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.pcb_note_line.insert({pcb_component_id:c,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,x1:s.x,y1:s.y,x2:a.x,y2:a.y,stroke_width:n.strokeWidth??.1,color:n.color,is_dashed:n.isDashed});this.pcb_note_line_id=l.pcb_note_line_id}getPcbSize(){let{_parsedProps:t}=this;return{width:Math.abs(t.x2-t.x1),height:Math.abs(t.y2-t.y1)}}},BV=class extends be{constructor(){super(...arguments);T(this,"pcb_note_rect_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:bF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=De(i,{x:0,y:0}),o=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_rect.insert({pcb_component_id:a,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,center:r,width:n.width,height:n.height,stroke_width:n.strokeWidth??.1,is_filled:n.isFilled??!1,has_stroke:n.hasStroke??!0,is_stroke_dashed:n.isStrokeDashed??!1,color:n.color});this.pcb_note_rect_id=c.pcb_note_rect_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.width=="string"?parseFloat(t.width):t.width,i=typeof t.height=="string"?parseFloat(t.height):t.height;return{width:n,height:i}}},jV=class extends be{constructor(){super(...arguments);T(this,"pcb_note_path_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:xF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this.getSubcircuit(),o=this.getGroup(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=n.route.map(l=>{let{x:u,y:h,...d}=l,_=typeof u=="string"?parseFloat(u):u,y=typeof h=="string"?parseFloat(h):h,g=De(i,{x:_,y});return{...d,x:g.x,y:g.y}}),c=t.pcb_note_path.insert({pcb_component_id:s,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,route:a,stroke_width:n.strokeWidth??.1,color:n.color});this.pcb_note_path_id=c.pcb_note_path_id}getPcbSize(){let{_parsedProps:t}=this;if(t.route.length===0)return{width:0,height:0};let n=t.route.map(c=>typeof c.x=="string"?parseFloat(c.x):c.x),i=t.route.map(c=>typeof c.y=="string"?parseFloat(c.y):c.y),r=Math.min(...n),o=Math.max(...n),s=Math.min(...i),a=Math.max(...i);return{width:o-r,height:a-s}}},YV=class extends be{constructor(){super(...arguments);T(this,"pcb_note_dimension_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:wF}}_resolvePoint(t,n){if(typeof t=="string"){let o=this.getSubcircuit().selectOne(t);return o?o._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${t}"`),De(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,r=typeof t.y=="string"?parseFloat(t.y):t.y;return De(n,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(n.from,i),o=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.pcb_note_dimension.insert({pcb_component_id:c,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,from:r,to:o,text:n.text,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.pcb_note_dimension_id=l.pcb_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}},XV=class extends Th{constructor(e){super({...e,subcircuit:!0})}},VV=class extends Th{constructor(e){super({...e,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!this.pcb_group_id)return;let n=e.pcb_group.get(this.pcb_group_id),i=t.paddingLeft??t.padding??0,r=t.paddingRight??t.padding??0,o=t.paddingTop??t.padding??0,s=t.paddingBottom??t.padding??0;e.pcb_group.update(this.pcb_group_id,{width:n.width+i+r,height:n.height+o+s,center:{x:n.center.x+(r-i)/2,y:n.center.y+(o-s)/2}})}},HV=class extends be{constructor(){super(...arguments);T(this,"pcb_breakout_point_id",null);T(this,"matchedPort",null);T(this,"matchedNet",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:Kz}}_matchConnection(){let{connection:t}=this._parsedProps,n=this.getSubcircuit();n&&(this.matchedPort=n.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=n.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}_getSourceTraceIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;this._matchConnection();let{pcbX:n=0,pcbY:i=0}=this._parsedProps,r=this.parent?.getGroup(),o=this.getSubcircuit();if(!r||!r.pcb_group_id)return;let s=t.pcb_breakout_point.insert({pcb_group_id:r.pcb_group_id,subcircuit_id:o?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:n,y:i});this.pcb_breakout_point_id=s.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:t=0,pcbY:n=0}=this._parsedProps;return{center:{x:t,y:n},bounds:{left:t,top:n,right:t,bottom:n},width:0,height:0}}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_breakout_point_id&&n.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:t.x,y:t.y})}getPcbSize(){return{width:0,height:0}}},GV=class extends be{constructor(){super(...arguments);T(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:Oz}}_getAnchorSide(){let{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getConnectedPorts();if(r.length===0)return"right";let o=r[0]._getGlobalSchematicPositionBeforeLayout(),s=o.x-i.x,a=o.y-i.y;if(Math.abs(s)>Math.abs(a)){if(s>0)return"right";if(s<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let t=this._resolveConnectsTo();if(!t)return[];let n=[];for(let i of t){let r=this.getSubcircuit().selectOne(i);r&&n.push(r)}return n}computeSchematicPropsTransform(){let{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){let n=this._getConnectedPorts();if(n.length>0){let i=n[0]._getGlobalSchematicPositionBeforeLayout(),r=De(this.parent?.computeSchematicGlobalTransform?.()??Ai(),{x:0,y:0});return vn(i.x-r.x,i.y-r.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),o=n.anchorSide??"right",s=bc({anchor_position:i,anchor_side:o,text:n.net}),a=t.schematic_net_label.insert({text:n.net,source_net_id:r.source_net_id,anchor_position:i,center:s,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo??t.connection;if(Array.isArray(n))return n;if(typeof n=="string")return[n]}_getNetName(){let{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;t.net&&GI(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let t=this._resolveConnectsTo();if(t)for(let n of t)this.add(new ko({from:n,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._resolveConnectsTo();if(!n||n.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getAnchorSide(),s={left:"x-",right:"x+",top:"y+",bottom:"y-"}[r],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of n){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id??""));if(w&&(u=t.schematic_trace.list().some(S=>S.source_trace_id===w.source_trace_id)),u)continue}let h=l._getGlobalSchematicPositionAfterLayout(),d=DI(l.facingDirection??"right")??"x+",_=Ja({x:h.x,y:h.y,facingDirection:d},{x:i.x,y:i.y,facingDirection:s});if(!Array.isArray(_)||_.length<2)continue;let y=[];for(let w=0;w<_.length-1;w++)y.push({from:{x:_[w].x,y:_[w].y},to:{x:_[w+1].x,y:_[w+1].y}});let g,x;if(a?.source_net_id&&l.source_port_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id));g=w?.source_trace_id,x=w?.subcircuit_connectivity_map_key||t.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}t.schematic_trace.insert({source_trace_id:g,edges:y,junctions:[],subcircuit_connectivity_map_key:x}),t.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},UV=class extends be{constructor(){super(...arguments);T(this,"pcb_silkscreen_circle_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:yF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenCircle. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_circle.insert({pcb_component_id:a,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},qV=class extends be{constructor(){super(...arguments);T(this,"pcb_silkscreen_rect_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:_F}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenRect. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_rect.insert({pcb_component_id:s,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},WV=class extends be{constructor(){super(...arguments);T(this,"pcb_silkscreen_line_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:mF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenLine. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_line.insert({pcb_component_id:s,layer:r,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:o?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},ZV=class extends be{constructor(t){super(t);T(this,"pcb_via_id",null);T(this,"matchedPort",null);T(this,"isPcbPrimitive",!0);T(this,"source_manually_placed_via_id",null);let n=this._getLayers();this._parsedProps.layers=n,this.initPorts()}get config(){return{componentName:"Via",zodProps:Wz}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}_getLayers(){let{fromLayer:t="top",toLayer:n="bottom"}=this._parsedProps;return t===n?[t]:[t,n]}initPorts(){let t=this._parsedProps.layers;for(let i of t){let r=new Di({name:i,layer:i});r.registerMatch(this),this.add(r)}let n=new Di({name:"pin1"});n.registerMatch(this),this.add(n)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_component.insert({center:i,width:n.outerDiameter,height:n.outerDiameter,layer:n.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:r?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=o.pcb_component_id}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getGroup(),r=this.getSubcircuit(),o=t.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:n.net??"",subcircuit_id:r?.subcircuit_id??void 0});this.source_component_id=o.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_via.insert({x:i.x,y:i.y,hole_diameter:n.holeDiameter,outer_diameter:n.outerDiameter,layers:["bottom","top"],from_layer:n.fromLayer||"bottom",to_layer:n.toLayer||"top",subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_via_id=o.pcb_via_id}},KV=class extends be{constructor(){super(...arguments);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:Qz}}getPcbSize(){return{width:0,height:0}}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit().selectOne(n.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${n.connectsTo}" not found for copper pour`);return}let r=t.pcb_board.list()[0];if(!r){this.renderError("No board found for copper pour");return}let o;r.outline&&r.outline.length>0?o=new z.Polygon(r.outline.map(_=>z.point(_.x,_.y))):o=new z.Polygon(new z.Box(r.center.x-r.width/2,r.center.y-r.height/2,r.center.x+r.width/2,r.center.y+r.height/2).toPoints());let s=si(t.toArray()),a=WI(t.toArray(),s).filter(_=>_.layers.includes(n.layer));for(let _ of t.pcb_trace.list())if(_.route)for(let y=0;y<_.route.length-1;y++){let g=_.route[y],x=_.route[y+1];if(g.route_type!=="wire"||x.route_type!=="wire"||g.layer!==n.layer)continue;let w=g.width;if(w===0)continue;let S=Math.hypot(g.x-x.x,g.y-x.y);if(S===0)continue;let E=(g.x+x.x)/2,M=(g.y+x.y)/2,k=Math.atan2(x.y-g.y,x.x-g.x)*180/Math.PI,N=pV({center:{x:E,y:M},width:S,height:w,rotation:k});for(let C of N)a.push({type:"rect",layers:[g.layer],center:C.center,width:C.width,height:C.height,connectedTo:_.source_trace_id?[_.source_trace_id]:[],obstacle_type:"trace"})}let c=[],l=[],u=n.traceMargin??.2,h=n.padMargin??.2;for(let _ of a){if(_.connectedTo.some(w=>s.areIdsConnected(w,i.source_net_id)))continue;if(_.type==="oval"&&_.width===_.height){let w=_.width/2+h;l.push({center:_.center,radius:w});continue}if(_.type==="rect"&&_.width===_.height&&_.connectedTo.length===0){let w=_.width/2;l.push({center:_.center,radius:w});continue}let g=u,x=new z.Box(_.center.x-_.width/2-g,_.center.y-_.height/2-g,_.center.x+_.width/2+g,_.center.y+_.height/2+g);c.push(new z.Polygon(x.toPoints()))}let d=o;if(c.length>0){let _=c.reduce((y,g)=>z.BooleanOperations.unify(y,g));_&&!_.isEmpty()&&(d=z.BooleanOperations.subtract(o,_))}Array.isArray(d)||(d=[d]);for(let _ of d){let y=_.splitToIslands();for(let g of y){if(g.isEmpty())continue;let x=[...g.faces],w=x.find(I=>I.orientation()===z.ORIENTATION.CCW),S=x.filter(I=>I.orientation()===z.ORIENTATION.CW);if(!w)continue;if(!t.pcb_copper_pour){this.renderError("db.pcb_copper_pour not found. The database schema may be outdated.");return}let E=I=>I.edges.map(N=>{let C={x:N.start.x,y:N.start.y};if(N.isArc){let A=Math.tan(N.shape.sweep/4);Math.abs(A)>1e-9&&(C.bulge=A)}return C});w.reverse();let M=E(w),k=S.map(I=>(I.reverse(),{vertices:E(I)}));for(let I of l){let N=z.point(I.center.x,I.center.y);g.contains(N)&&k.push({vertices:[{x:I.center.x,y:I.center.y-I.radius,bulge:1},{x:I.center.x,y:I.center.y+I.radius,bulge:1}]})}t.pcb_copper_pour.insert({shape:"brep",layer:n.layer,brep_shape:{outer_ring:{vertices:M},inner_rings:k},source_net_id:i.source_net_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0})}}})}},JV=class extends On{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:Az,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:t.capacity,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},QV=class extends On{_getPcbRotationBeforeLayout(){let e=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+e}get config(){return{componentName:"PinHeader",zodProps:Rz,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,r=this._parsedProps.showSilkscreenPinLabels;if(e>0){let o;if(i)!t&&!n?o=`pinrow${e}_p${i}`:o=`pinrow${e}_p${i}_id${t}_od${n}`;else if(!t&&!n)o=`pinrow${e}`;else return null;return r!==!0&&(o+="_nopinlabels"),o}return null}initPorts(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let t=1;t<=e;t++){let n=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[t-1]:this._parsedProps.pinLabels?.[`pin${t}`];if(n){let i=Array.isArray(n)?n[0]:n,r=Array.isArray(n)?n.slice(1):[];this.add(new Di({pinNumber:t,name:i,aliases:[`pin${t}`,...r]}))}else this.add(new Di({pinNumber:t,name:`pin${t}`}))}}_getSchematicPortArrangement(){let e=this._parsedProps.pinCount??1,t=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",n=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:n?.leftSide?.direction??"top-to-bottom",pins:n?.leftSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}:{rightSide:{direction:n?.rightSide?.direction??"top-to-bottom",pins:n?.rightSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:t.supplierPartNumbers,pin_count:t.pinCount,gender:t.gender,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function o5t(e){switch(e){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var tH=class extends On{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??o5t(this.props.pinVariant),zodProps:wz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:t.frequency,load_capacitance:t.loadCapacitance,supplier_part_numbers:t.supplierPartNumbers,pin_variant:n,are_pins_interchangeable:n==="no_ground"||n==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let e=`${ti(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ti(this._parsedProps.loadCapacitance)}F`:e}},eH=class extends On{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:$z,sourceFtype:na.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${ti(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({name:this.name,ftype:na.simple_inductor,inductance:n.inductance,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function s5t(e){switch(e){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var nH=class extends On{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??s5t(this.props.pinVariant),zodProps:xz,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${ti(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},iH=class extends On{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:Lz,sourceFtype:na.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let e=Qn[this._getSchematicSymbolNameOrThrow()],t=e.ports.find(l=>l.labels.includes("1")),n=e.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),r=i.find(l=>l.props.pinNumber===1),o=i.find(l=>l.props.pinNumber===2),s=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;r.schematicSymbolPortDef=t,(!c||c.length===0)&&(o.schematicSymbolPortDef=n);for(let[l,u]of[[2,o],[3,s],[4,a]]){let h=c?.find(([_,y])=>_===`pin${l}`||y===`pin${l}`);if(!h){u.schematicSymbolPortDef=n;break}(h?.[0]===`pin${l}`?h[1]:h?.[0])!=="pin1"&&(u.schematicSymbolPortDef=n)}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:na.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},rH=class extends On{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:vz,sourceFtype:"simple_crystal"}}initPorts(){let e=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:e})}_getSchematicSymbolDisplayValue(){let e=`${ti(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ti(this._parsedProps.loadCapacitance)}F`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:t.frequency,load_capacitance:t.loadCapacitance,pin_variant:t.pinVariant||"two_pin",are_pins_interchangeable:(t.pinVariant||"two_pin")==="two_pin"});this.source_component_id=n.source_component_id}},oH=class extends On{constructor(){super(...arguments);T(this,"emitter",this.portMap.pin1);T(this,"collector",this.portMap.pin2);T(this,"base",this.portMap.pin3)}get config(){let t=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??t,zodProps:Fz,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let t={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},sH=class extends On{get config(){let e=this.props.mosfetMode==="depletion"?"d":"e",n=`${this.props.channelType}_channel_${e}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??n,zodProps:Dz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}},a5t=e=>e?e.closesAt!==void 0||e.opensAt!==void 0||e.startsClosed!==void 0||e.switchingFrequency!==void 0:!1,c5t=e=>!e||typeof e!="object"?!1:Object.prototype.hasOwnProperty.call(e,"spice"),l5t=e=>{if(!e||typeof e!="object")return null;let t=c5t(e)?e.spice??null:e;return a5t(t)?{...t}:null},aH=class extends On{_getSwitchType(){let e=this._parsedProps;return e?e.dpdt?"dpdt":e.spst?"spst":e.spdt?"spdt":e.dpst?"dpst":e.type??"spst":"spst"}get config(){let e=this._getSwitchType(),t=this._parsedProps?.isNormallyClosed??!1,n={spst:t?"spst_normally_closed_switch":"spst_switch",spdt:t?"spdt_normally_closed_switch":"spdt_switch",dpst:t?"dpst_normally_closed_switch":"dpst_switch",dpdt:t?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??n[e],zodProps:Vz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,t=this._parsedProps??{},n=e.source_component.insert({ftype:"simple_switch",name:this.name,switch_type:t.type,is_normally_closed:t.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=n.source_component_id}doInitialSimulationRender(){let e=this.props,t=l5t(e.simulation);if(!t)return;let{db:n}=this.root,i={type:"simulation_switch"};t.closesAt!==void 0&&(i.closes_at=t.closesAt),t.opensAt!==void 0&&(i.opens_at=t.opensAt),t.startsClosed!==void 0&&(i.starts_closed=t.startsClosed),t.switchingFrequency!==void 0&&(i.switching_frequency=t.switchingFrequency),n.simulation_switch.insert(i)}},LI={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},cH=class extends On{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:Zz,sourceFtype:na.simple_test_point}}_getPropsWithDefaults(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._parsedProps;return!n&&t&&(n="through_hole"),n??(n="through_hole"),e??(e="circle"),n==="pad"?e==="circle"?i??(i=LI.SMT_CIRCLE_DIAMETER):e==="rect"&&(r??(r=LI.SMT_RECT_SIZE),o??(o=r)):n==="through_hole"&&(t??(t=LI.HOLE_DIAMETER)),{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}}_getImpliedFootprintString(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._getPropsWithDefaults();if(n==="through_hole")return`platedhole_d${t}`;if(n==="pad"){if(e==="circle")return`smtpad_circle_d${i}`;if(e==="rect")return`smtpad_rect_w${r}_h${o}`}throw new Error(`Footprint variant "${n}" with pad shape "${e}" not implemented`)}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{padShape:n,holeDiameter:i,footprintVariant:r,padDiameter:o,width:s,height:a}=this._getPropsWithDefaults(),c=e.source_component.insert({ftype:na.simple_test_point,name:this.name,supplier_part_numbers:t.supplierPartNumbers,footprint_variant:r,pad_shape:n,pad_diameter:o,hole_diameter:i,width:s,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},lH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:lF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout();t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:i.x,y:i.y},rotation:n.schRotation??0})}},uH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:cF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_line.insert({schematic_component_id:r,x1:n.x1+i.x,y1:n.y1+i.y,x2:n.x2+i.x,y2:n.y2+i.y,stroke_width:ux,color:lx,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=o.schematic_line_id}},pH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:aF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_rect.insert({center:{x:i.x,y:i.y},width:n.width,height:n.height,stroke_width:ux,color:lx,is_filled:n.isFilled,schematic_component_id:r,is_dashed:n.isDashed,rotation:n.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=o.schematic_rect_id}},hH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:rF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_arc.insert({schematic_component_id:r,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,start_angle_degrees:n.startAngleDegrees,end_angle_degrees:n.endAngleDegrees,direction:n.direction,stroke_width:ux,color:lx,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=o.schematic_arc_id}},dH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:sF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_circle.insert({schematic_component_id:r,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,stroke_width:ux,color:lx,is_filled:n.isFilled,fill_color:n.fillColor,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=o.schematic_circle_id}};function u5t({anchor:e,x:t,y:n,width:i,height:r,isInside:o}){switch(e){case"top_left":return{x:t,y:n+r,textAnchor:o?"top_left":"bottom_left"};case"top_center":return{x:t+i/2,y:n+r,textAnchor:o?"top_center":"bottom_center"};case"top_right":return{x:t+i,y:n+r,textAnchor:o?"top_right":"bottom_right"};case"center_left":return{x:t,y:n+r/2,textAnchor:o?"center_left":"center_right"};case"center":return{x:t+i/2,y:n+r/2,textAnchor:"center"};case"center_right":return{x:t+i,y:n+r/2,textAnchor:o?"center_right":"center_left"};case"bottom_left":return{x:t,y:n,textAnchor:o?"bottom_left":"top_left"};case"bottom_center":return{x:t+i/2,y:n,textAnchor:o?"bottom_center":"top_center"};case"bottom_right":return{x:t+i,y:n,textAnchor:o?"bottom_right":"top_right"};default:return{x:t+i/2,y:n+r,textAnchor:"center"}}}var fH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:oF,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=.6,r=typeof n.padding=="number"?n.padding:0,o=typeof n.paddingTop=="number"?n.paddingTop:r,s=typeof n.paddingBottom=="number"?n.paddingBottom:r,a=typeof n.paddingLeft=="number"?n.paddingLeft:r,c=typeof n.paddingRight=="number"?n.paddingRight:r,l=n.overlay&&n.overlay.length>0,u=typeof n.width=="number"&&typeof n.height=="number",h,d,_,y,g,x;if(l){let S=n.overlay.map(tt=>({selector:tt,port:this.getSubcircuit().selectOne(tt,{type:"port"})})).filter(({port:tt})=>tt!=null).map(({port:tt})=>({position:tt._getGlobalSchematicPositionAfterLayout()}));if(S.length===0)return;let E=S.map(tt=>tt.position.x),M=S.map(tt=>tt.position.y),k=Math.min(...E),I=Math.max(...E),N=Math.min(...M),C=Math.max(...M),A=I-k,O=C-N,B=A===0?i:0,D=O===0?i:0,X=a+B/2,Y=c+B/2,H=o+D/2,K=s+D/2,Z=k-X,ut=I+Y,st=N-K,it=C+H;h=ut-Z,d=it-st,_=Z+(n.schX??0),y=st+(n.schY??0),g=_+h/2,x=y+d/2}else if(u){h=n.width,d=n.height;let w=this._getGlobalSchematicPositionBeforeLayout();g=w.x,x=w.y,_=g-h/2,y=x-d/2}else return;if(t.schematic_box.insert({height:d,width:h,x:_,y,is_dashed:n.strokeStyle==="dashed"}),n.title){let w=n.titleInside,S=.1,E=n.titleAlignment,M=u5t({anchor:E,x:_,y,width:h,height:d,isInside:w}),k,I,N=M.textAnchor;w?(k=E.includes("top")?-S:E.includes("bottom")?S:0,I=E.includes("left")?S:E.includes("right")?-S:0):(k=E.includes("top")?S:E.includes("bottom")?-S:0,I=E.includes("center_left")?-S:E.includes("center_right")?S:0);let C=M.x+I,A=M.y+k;t.schematic_text.insert({anchor:N,text:n.title,font_size:n.titleFontSize??.18,color:n.titleColor??"#000000",position:{x:C,y:A},rotation:0})}}},mH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:uF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.children.filter(d=>d.componentName==="SchematicRow");if(i.length===0)return;let r=[],o=0;for(let d of i){let _=d.children.filter(y=>y.componentName==="SchematicCell");o=Math.max(o,_.length)}for(let d=0;d<i.length;d++)r[d]=[];for(let d=0;d<i.length;d++){let y=i[d].children.filter(x=>x.componentName==="SchematicCell"),g=0;for(let x=0;x<y.length;x++){for(;r[d][g];)g++;let w=y[x],S=w._parsedProps.colSpan??1,E=w._parsedProps.rowSpan??1;for(let M=0;M<E;M++)for(let k=0;k<S;k++)r[d+M]||(r[d+M]=[]),r[d+M][g+k]=w;g+=S}}o=Math.max(0,...r.map(d=>d.length));let s=i.map((d,_)=>d._parsedProps.height??1),a=Array.from({length:o},(d,_)=>{let y=0;for(let g=0;g<i.length;g++){let x=r[g]?.[_];if(x){let w=x._parsedProps.text??x._parsedProps.children,S=x._parsedProps.width??(w?.length??2)*.5;S>y&&(y=S)}}return y||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=t.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:s,cell_padding:n.cellPadding,border_width:n.borderWidth,anchor:n.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=l.schematic_table_id;let u=new Set,h=0;for(let d=0;d<i.length;d++){let _=0;for(let y=0;y<o;y++){let g=r[d]?.[y];if(g&&!u.has(g)){u.add(g);let x=g._parsedProps,w=x.rowSpan??1,S=x.colSpan??1,E=0;for(let k=0;k<S;k++)E+=a[y+k];let M=0;for(let k=0;k<w;k++)M+=s[d+k];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:d,end_row_index:d+w-1,start_column_index:y,end_column_index:y+S-1,text:x.text??x.children,center:{x:c.x+_+E/2,y:c.y-h-M/2},width:E,height:M,horizontal_align:x.horizontalAlign,vertical_align:x.verticalAlign,font_size:x.fontSize??n.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[y]&&(_+=a[y])}h+=s[d]}}},_H=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:pF}}},yH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:hF}}},gH=class extends be{constructor(){super(...arguments);T(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:Nz}}},bH=class extends be{get config(){return{componentName:"AnalogSimulation",zodProps:zz}}doInitialSimulationRender(){let{db:e}=this.root,{duration:t,timePerStep:n}=this._parsedProps,i=t||10,r=n||.01;e.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:i,time_per_step:r})}},xH=class extends be{constructor(){super(...arguments);T(this,"simulation_voltage_probe_id",null)}get config(){return{componentName:"VoltageProbe",zodProps:iF}}doInitialSimulationRender(){let{db:t}=this.root,{connectsTo:n,name:i}=this._parsedProps,r=this.getSubcircuit();if(!r){this.renderError("VoltageProbe must be inside a subcircuit");return}let o=Array.isArray(n)?n:[n];if(o.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let s=o[0],a=r.selectOne(s,{type:"port"}),c=a?null:r.selectOne(s,{type:"net"});if(c&&c.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${s}" resolved to a non-net component "${c.componentName}".`);return}if(!a&&!c){this.renderError(`VoltageProbe could not find connection target "${s}"`);return}let{simulation_voltage_probe_id:l}=t.simulation_voltage_probe.insert({name:i??this.name,source_port_id:a?.source_port_id??void 0,source_net_id:c?.source_net_id??void 0,subcircuit_id:r.subcircuit_id||void 0});this.simulation_voltage_probe_id=l}},p5t={name:"@tscircuit/core",type:"module",version:"0.0.785",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"'},devDependencies:{"@biomejs/biome":"^1.8.3","@tscircuit/capacity-autorouter":"^0.0.132","@tscircuit/checks":"^0.0.85","@tscircuit/circuit-json-util":"^0.0.72","@tscircuit/common":"^0.0.11","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.21","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"0.0.360","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^0.0.41","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.278","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-gltf":"^0.0.7","circuit-json-to-simple-3d":"^0.0.9","circuit-to-svg":"^0.0.238","circuit-json-to-spice":"^0.0.14",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",poppygl:"^0.0.6",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202",spicey:"^0.0.8","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.48","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},Ih=class{constructor({platform:e,projectUrl:t}={}){T(this,"firstChild",null);T(this,"children");T(this,"db");T(this,"root",null);T(this,"isRoot",!0);T(this,"schematicDisabled",!1);T(this,"pcbDisabled",!1);T(this,"pcbRoutingDisabled",!1);T(this,"_featureMspSchematicTraceRouting",!0);T(this,"name");T(this,"platform");T(this,"projectUrl");T(this,"_hasRenderedAtleastOnce",!1);T(this,"_eventListeners",{});this.children=[],this.db=ke([]),this.root=this,this.platform=e,this.projectUrl=t,this.pcbDisabled=e?.pcbDisabled??!1}add(e){let t;(0,vH.isValidElement)(e)?t=eV(e):t=e,this.children.push(t)}_getBoard(){return this.children.find(e=>e.componentName==="Board")}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let e=new Th({subcircuit:!0});e.parent=this,e.addAll(this.children),this.children=[e],this.firstChild=e}render(){this.firstChild||this._guessRootComponent();let{firstChild:e,db:t}=this;if(!e)throw new Error("RootCircuit has no root component");e.parent=this,e.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(t=>setTimeout(t,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(e=>e._hasIncompleteAsyncEffects()?!0:e.children.some(t=>t._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(e){let t=await Promise.resolve().then(()=>(TX(),PX)).catch(n=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
244
+ `),a={x:n.center.x+n.width/2-.25,y:n.center.y-n.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:r,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialSourceRender(){super.doInitialSourceRender();let{db:t}=this.root,n=t.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=n.source_board_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.width??0,r=n.height??0,o={x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)},{boardAnchorPosition:s,boardAnchorAlignment:a}=n;if(s&&(o=l3t({boardAnchorPosition:s,boardAnchorAlignment:a??"center",width:i,height:r})),n.outline){let u=n.outline.map(x=>x.x),h=n.outline.map(x=>x.y),d=Math.min(...u),_=Math.max(...u),y=Math.min(...h),g=Math.max(...h);i=_-d,r=g-y,o={x:(d+_)/2+(n.outlineOffsetX??0),y:(y+g)/2+(n.outlineOffsetY??0)}}let c=n.outline;!c&&n.borderRadius!=null&&i>0&&r>0&&(c=WX(i,r,n.borderRadius));let l=t.pcb_board.insert({center:o,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:r,outline:c?.map(u=>({x:u.x+(n.outlineOffsetX??0),y:u.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=l.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:t}=this.root;this.pcb_board_id&&(t.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return Ai()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let n=pY(t.toArray());for(let l of n)t.pcb_trace_error.insert(l);let i=uY(t.toArray());for(let l of i)t.pcb_port_not_connected_error.insert(l);let r=fY(t.toArray());for(let l of r)t.pcb_component_outside_board_error.insert(l);let o=yY(t.toArray());for(let l of o)t.pcb_trace_error.insert(l);let s=_Y(t.toArray());for(let l of s)t.pcb_via_clearance_error.insert(l);let a=mY(t.toArray());for(let l of a)t.pcb_via_clearance_error.insert(l);let c=gY(t.toArray());for(let l of c)t.pcb_footprint_overlap_error.insert(l)}_emitRenderLifecycleEvent(t,n){super._emitRenderLifecycleEvent(t,n),n==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t})}},n5t=new Proxy({},{get:(e,t)=>t}),na=n5t,lx="rgba(132, 0, 0)",ux=.12,PV=class extends On{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:Sz,sourceFtype:na.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let t=this.props.capacitance,n=typeof t=="string"?t:`${ti(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${n}/${ti(this._parsedProps.maxVoltageRating)}V`:n}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new ko({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new ko({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,capacitance:n.capacitance,max_voltage_rating:n.maxVoltageRating,max_decoupling_trace_length:n.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!n.polarized});this.source_component_id=i.source_component_id}},px=class extends On{constructor(t){super(t);T(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:Rp,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);let{_parsedProps:n}=this;if(n.externallyConnectedPins){let i=new Set;for(let[r,o]of n.externallyConnectedPins)i.add(r),i.add(o);for(let r of i)if(!this.children.find(s=>s instanceof Di&&s.isMatchingAnyOf([r]))){let s=r.match(/^pin(\d+)$/);if(s){let a=parseInt(s[1]);this.add(new Di({pinNumber:a,aliases:[r]}))}else this.add(new Di({name:r,aliases:[r]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:t}=this;t?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:t}=this;if(t.externallyConnectedPins)for(let[n,i]of t.externallyConnectedPins)this.add(new ko({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:t}=this.root,{pinAttributes:n}=this.props;if(!n)return;let i=null,r=null,o,s=this.selectAll("port");for(let h of s)for(let d of h.getNameAndAliases())if(n[d]){let _=n[d];_.providesPower&&(i=h,o=_.providesVoltage),_.providesGround&&(r=h)}if(!i||!r||o===void 0)return;let a=t.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=t.source_port.get(r.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=t.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=t.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||t.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:r.source_port_id,negative_source_net_id:u.source_net_id,voltage:o})}},TV=class extends px{constructor(e){super(e)}get config(){return{...super.config,componentName:"Pinout",zodProps:fz}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}},IV=class extends On{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"anode",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"cathode",this.portMap.pin2)}get config(){let t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},n=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"diode",componentName:"Diode",zodProps:Bz,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},MV=class extends On{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:_z,sourceFtype:na.simple_fuse}}_getSchematicSymbolDisplayValue(){let e=this._parsedProps.currentRating,t=this._parsedProps.voltageRating,n=typeof e=="string"?parseFloat(e):e,i=typeof t=="string"?parseFloat(t):t;return`${ti(n)}A / ${ti(i)}V`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=typeof t.currentRating=="string"?parseFloat(t.currentRating):t.currentRating,i=typeof t.voltageRating=="string"?parseFloat(t.voltageRating):t.voltageRating,r=e.source_component.insert({name:this.name,ftype:na.simple_fuse,current_rating_amps:n,voltage_rating_volts:i,display_current_rating:`${ti(n)}A`,display_voltage_rating:`${ti(i)}V`});this.source_component_id=r.source_component_id}},EV=class extends On{constructor(){super(...arguments);T(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:e4,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},CV=class extends On{constructor(){super(...arguments);T(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(t){return this.selectOne(`port.${t}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let t=this.children.filter(n=>n.componentName==="Port").map(n=>n.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){let t=this._parsedProps??this.props,n=t.pinCount;if(t.pinCount==null&&!t.footprint&&(n=2),t.pinCount==null){let o=(t.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),s=o.length>0?Math.max(...o):0,a=t.pinLabels?Object.keys(t.pinLabels).length:0,c=Math.max(s,a);(c===2||c===3)&&(n=c),n==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(n=this.getPortsFromFootprint().length)}let i="";n?i+=`solderjumper${n}`:i="solderjumper";let r=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?r=Array.from(new Set(t.bridgedPins.flat().map(o=>this._getPinNumberFromBridgedPinName(o)).filter(o=>o!==null))).sort((o,s)=>o-s):t.bridged&&n&&(r=Array.from({length:n},(o,s)=>s+1)),r.length>0&&(i+=`_bridged${r.join("")}`),{schematicSymbolName:t.symbolName??i,componentName:"SolderJumper",zodProps:mz,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);n==null&&!this._parsedProps.footprint&&(n=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of r)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=o(a.start_pcb_port_id),a.end_pcb_port_id=o(a.end_pcb_port_id))}},kV=class extends On{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"anode",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"cathode",this.portMap.pin2)}get config(){let t={laser:"laser_diode"},n=this.props.laser?"laser":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"led",componentName:"Led",zodProps:Yz,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}getFootprinterString(){let t=super.getFootprinterString();return t&&this.props.color?`${t}_color(${this.props.color})`:t}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:n.wavelength,color:n.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},NV=class extends On{constructor(){super(...arguments);T(this,"pos",this.portMap.pin1);T(this,"positive",this.portMap.pin1);T(this,"neg",this.portMap.pin2);T(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:nF,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Di({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Di({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},i5t=Fn.extend({voltage:oi.optional(),frequency:fr.optional(),peakToPeakVoltage:oi.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:ze.optional(),dutyCycle:p.number().optional()}),AV=class extends On{constructor(){super(...arguments);T(this,"terminal1",this.portMap.terminal1);T(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:i5t,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.portMap.terminal1,r=this.portMap.terminal2;t.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:r.source_port_id,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle})}},RV=class extends On{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:gz,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${ti(this._parsedProps.resistance)}\u03A9`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,this.props.pulldownFor,this.props.pulldownTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new ko({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new ko({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new ko({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new ko({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,resistance:n.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}},r5t=["leftedge","rightedge","topedge","bottomedge","center"],OV=class extends be{get config(){return{componentName:"Constraint",zodProps:Tz}}constructor(e){if(super(e),("xdist"in e||"ydist"in e)&&!("edgeToEdge"in e)&&!("centerToCenter"in e))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in e&&e.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let e=[],t=this.getPrimitiveContainer();function n(i){let r=i.split(" ").pop(),o=r5t.includes(r)?r:void 0,s=o?i.replace(` ${o}`,""):i,a=t.selectOne(s,{pcbPrimitive:!0});a&&e.push({selector:i,component:a,componentSelector:s,edge:o})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},LV=class extends be{constructor(){super(...arguments);T(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:Gz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for FabricationNoteRect. Must be "top" or "bottom".`);let o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,s=this.getSubcircuit(),a=t.pcb_fabrication_note_rect.insert({pcb_component_id:o,layer:r,color:n.color,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,stroke_width:n.strokeWidth??1,is_filled:n.isFilled??!1,has_stroke:n.hasStroke??!1,is_stroke_dashed:n.isStrokeDashed??!1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.fabrication_note_rect_id=a.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},zV=class extends be{constructor(){super(...arguments);T(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:Uz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this.getSubcircuit(),{_parsedProps:i}=this,r=i.layer??"top";if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_fabrication_note_path.insert({pcb_component_id:s,layer:r,color:i.color,route:i.route.map(c=>{let l=De(o,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:n?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},FV=class extends be{get config(){return{componentName:"FabricationNoteText",zodProps:Hz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this.getSubcircuit();e.pcb_fabrication_note_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:t.pcbX??0,y:t.pcbY??0},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:"top",color:t.color,text:t.text??"",pcb_component_id:n.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},DV=class extends be{constructor(){super(...arguments);T(this,"fabrication_note_dimension_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:qz}}_resolvePoint(t,n){if(typeof t=="string"){let o=this.getSubcircuit().selectOne(t);return o?o._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${t}"`),De(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,r=typeof t.y=="string"?parseFloat(t.y):t.y;return De(n,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(n.from,i),o=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),l=c(n.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for FabricationNoteDimension. Must be "top" or "bottom".`);let u=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,h=t.pcb_fabrication_note_dimension.insert({pcb_component_id:u,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,layer:l,from:r,to:o,text:n.text,offset:n.offset,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.fabrication_note_dimension_id=h.pcb_fabrication_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}},$V=class extends be{constructor(){super(...arguments);T(this,"pcb_note_line_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:vF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),r=this.getGroup(),o=this._computePcbGlobalTransformBeforeLayout(),s=De(o,{x:n.x1,y:n.y1}),a=De(o,{x:n.x2,y:n.y2}),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.pcb_note_line.insert({pcb_component_id:c,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,x1:s.x,y1:s.y,x2:a.x,y2:a.y,stroke_width:n.strokeWidth??.1,color:n.color,is_dashed:n.isDashed});this.pcb_note_line_id=l.pcb_note_line_id}getPcbSize(){let{_parsedProps:t}=this;return{width:Math.abs(t.x2-t.x1),height:Math.abs(t.y2-t.y1)}}},BV=class extends be{constructor(){super(...arguments);T(this,"pcb_note_rect_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:bF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=De(i,{x:0,y:0}),o=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_rect.insert({pcb_component_id:a,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,center:r,width:n.width,height:n.height,stroke_width:n.strokeWidth??.1,is_filled:n.isFilled??!1,has_stroke:n.hasStroke??!0,is_stroke_dashed:n.isStrokeDashed??!1,color:n.color});this.pcb_note_rect_id=c.pcb_note_rect_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.width=="string"?parseFloat(t.width):t.width,i=typeof t.height=="string"?parseFloat(t.height):t.height;return{width:n,height:i}}},jV=class extends be{constructor(){super(...arguments);T(this,"pcb_note_path_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:xF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this.getSubcircuit(),o=this.getGroup(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=n.route.map(l=>{let{x:u,y:h,...d}=l,_=typeof u=="string"?parseFloat(u):u,y=typeof h=="string"?parseFloat(h):h,g=De(i,{x:_,y});return{...d,x:g.x,y:g.y}}),c=t.pcb_note_path.insert({pcb_component_id:s,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,route:a,stroke_width:n.strokeWidth??.1,color:n.color});this.pcb_note_path_id=c.pcb_note_path_id}getPcbSize(){let{_parsedProps:t}=this;if(t.route.length===0)return{width:0,height:0};let n=t.route.map(c=>typeof c.x=="string"?parseFloat(c.x):c.x),i=t.route.map(c=>typeof c.y=="string"?parseFloat(c.y):c.y),r=Math.min(...n),o=Math.max(...n),s=Math.min(...i),a=Math.max(...i);return{width:o-r,height:a-s}}},YV=class extends be{constructor(){super(...arguments);T(this,"pcb_note_dimension_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:wF}}_resolvePoint(t,n){if(typeof t=="string"){let o=this.getSubcircuit().selectOne(t);return o?o._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${t}"`),De(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,r=typeof t.y=="string"?parseFloat(t.y):t.y;return De(n,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(n.from,i),o=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.pcb_note_dimension.insert({pcb_component_id:c,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,from:r,to:o,text:n.text,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.pcb_note_dimension_id=l.pcb_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}},XV=class extends Th{constructor(e){super({...e,subcircuit:!0})}},VV=class extends Th{constructor(e){super({...e,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!this.pcb_group_id)return;let n=e.pcb_group.get(this.pcb_group_id),i=t.paddingLeft??t.padding??0,r=t.paddingRight??t.padding??0,o=t.paddingTop??t.padding??0,s=t.paddingBottom??t.padding??0;e.pcb_group.update(this.pcb_group_id,{width:n.width+i+r,height:n.height+o+s,center:{x:n.center.x+(r-i)/2,y:n.center.y+(o-s)/2}})}},HV=class extends be{constructor(){super(...arguments);T(this,"pcb_breakout_point_id",null);T(this,"matchedPort",null);T(this,"matchedNet",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:Kz}}_matchConnection(){let{connection:t}=this._parsedProps,n=this.getSubcircuit();n&&(this.matchedPort=n.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=n.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}_getSourceTraceIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(r=>r.connected_source_port_ids.includes(t.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;this._matchConnection();let{pcbX:n=0,pcbY:i=0}=this._parsedProps,r=this.parent?.getGroup(),o=this.getSubcircuit();if(!r||!r.pcb_group_id)return;let s=t.pcb_breakout_point.insert({pcb_group_id:r.pcb_group_id,subcircuit_id:o?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:n,y:i});this.pcb_breakout_point_id=s.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:t=0,pcbY:n=0}=this._parsedProps;return{center:{x:t,y:n},bounds:{left:t,top:n,right:t,bottom:n},width:0,height:0}}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_breakout_point_id&&n.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:t.x,y:t.y})}getPcbSize(){return{width:0,height:0}}},GV=class extends be{constructor(){super(...arguments);T(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:Oz}}_getAnchorSide(){let{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getConnectedPorts();if(r.length===0)return"right";let o=r[0]._getGlobalSchematicPositionBeforeLayout(),s=o.x-i.x,a=o.y-i.y;if(Math.abs(s)>Math.abs(a)){if(s>0)return"right";if(s<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let t=this._resolveConnectsTo();if(!t)return[];let n=[];for(let i of t){let r=this.getSubcircuit().selectOne(i);r&&n.push(r)}return n}computeSchematicPropsTransform(){let{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){let n=this._getConnectedPorts();if(n.length>0){let i=n[0]._getGlobalSchematicPositionBeforeLayout(),r=De(this.parent?.computeSchematicGlobalTransform?.()??Ai(),{x:0,y:0});return vn(i.x-r.x,i.y-r.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),o=n.anchorSide??"right",s=bc({anchor_position:i,anchor_side:o,text:n.net}),a=t.schematic_net_label.insert({text:n.net,source_net_id:r.source_net_id,anchor_position:i,center:s,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo??t.connection;if(Array.isArray(n))return n;if(typeof n=="string")return[n]}_getNetName(){let{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;t.net&&GI(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let t=this._resolveConnectsTo();if(t)for(let n of t)this.add(new ko({from:n,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._resolveConnectsTo();if(!n||n.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getAnchorSide(),s={left:"x-",right:"x+",top:"y+",bottom:"y-"}[r],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of n){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id??""));if(w&&(u=t.schematic_trace.list().some(S=>S.source_trace_id===w.source_trace_id)),u)continue}let h=l._getGlobalSchematicPositionAfterLayout(),d=DI(l.facingDirection??"right")??"x+",_=Ja({x:h.x,y:h.y,facingDirection:d},{x:i.x,y:i.y,facingDirection:s});if(!Array.isArray(_)||_.length<2)continue;let y=[];for(let w=0;w<_.length-1;w++)y.push({from:{x:_[w].x,y:_[w].y},to:{x:_[w+1].x,y:_[w+1].y}});let g,x;if(a?.source_net_id&&l.source_port_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id));g=w?.source_trace_id,x=w?.subcircuit_connectivity_map_key||t.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}t.schematic_trace.insert({source_trace_id:g,edges:y,junctions:[],subcircuit_connectivity_map_key:x}),t.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},UV=class extends be{constructor(){super(...arguments);T(this,"pcb_silkscreen_circle_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:yF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenCircle. Must be "top" or "bottom".`);let o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_circle.insert({pcb_component_id:a,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},qV=class extends be{constructor(){super(...arguments);T(this,"pcb_silkscreen_rect_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:_F}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenRect. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_rect.insert({pcb_component_id:s,layer:r,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},WV=class extends be{constructor(){super(...arguments);T(this,"pcb_silkscreen_line_id",null);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:mF}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(n.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenLine. Must be "top" or "bottom".`);let o=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_line.insert({pcb_component_id:s,layer:r,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:o?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},ZV=class extends be{constructor(t){super(t);T(this,"pcb_via_id",null);T(this,"matchedPort",null);T(this,"isPcbPrimitive",!0);T(this,"source_manually_placed_via_id",null);let n=this._getLayers();this._parsedProps.layers=n,this.initPorts()}get config(){return{componentName:"Via",zodProps:Wz}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}_getLayers(){let{fromLayer:t="top",toLayer:n="bottom"}=this._parsedProps;return t===n?[t]:[t,n]}initPorts(){let t=this._parsedProps.layers;for(let i of t){let r=new Di({name:i,layer:i});r.registerMatch(this),this.add(r)}let n=new Di({name:"pin1"});n.registerMatch(this),this.add(n)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_component.insert({center:i,width:n.outerDiameter,height:n.outerDiameter,layer:n.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:r?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=o.pcb_component_id}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getGroup(),r=this.getSubcircuit(),o=t.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:n.net??"",subcircuit_id:r?.subcircuit_id??void 0});this.source_component_id=o.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),o=t.pcb_via.insert({x:i.x,y:i.y,hole_diameter:n.holeDiameter,outer_diameter:n.outerDiameter,layers:["bottom","top"],from_layer:n.fromLayer||"bottom",to_layer:n.toLayer||"top",subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_via_id=o.pcb_via_id}},KV=class extends be{constructor(){super(...arguments);T(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:Qz}}getPcbSize(){return{width:0,height:0}}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit().selectOne(n.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${n.connectsTo}" not found for copper pour`);return}let r=t.pcb_board.list()[0];if(!r){this.renderError("No board found for copper pour");return}let o;r.outline&&r.outline.length>0?o=new z.Polygon(r.outline.map(_=>z.point(_.x,_.y))):o=new z.Polygon(new z.Box(r.center.x-r.width/2,r.center.y-r.height/2,r.center.x+r.width/2,r.center.y+r.height/2).toPoints());let s=si(t.toArray()),a=WI(t.toArray(),s).filter(_=>_.layers.includes(n.layer));for(let _ of t.pcb_trace.list())if(_.route)for(let y=0;y<_.route.length-1;y++){let g=_.route[y],x=_.route[y+1];if(g.route_type!=="wire"||x.route_type!=="wire"||g.layer!==n.layer)continue;let w=g.width;if(w===0)continue;let S=Math.hypot(g.x-x.x,g.y-x.y);if(S===0)continue;let E=(g.x+x.x)/2,M=(g.y+x.y)/2,k=Math.atan2(x.y-g.y,x.x-g.x)*180/Math.PI,N=pV({center:{x:E,y:M},width:S,height:w,rotation:k});for(let C of N)a.push({type:"rect",layers:[g.layer],center:C.center,width:C.width,height:C.height,connectedTo:_.source_trace_id?[_.source_trace_id]:[],obstacle_type:"trace"})}let c=[],l=[],u=n.traceMargin??.2,h=n.padMargin??.2;for(let _ of a){if(_.connectedTo.some(w=>s.areIdsConnected(w,i.source_net_id)))continue;if(_.type==="oval"&&_.width===_.height){let w=_.width/2+h;l.push({center:_.center,radius:w});continue}if(_.type==="rect"&&_.width===_.height&&_.connectedTo.length===0){let w=_.width/2;l.push({center:_.center,radius:w});continue}let g=u,x=new z.Box(_.center.x-_.width/2-g,_.center.y-_.height/2-g,_.center.x+_.width/2+g,_.center.y+_.height/2+g);c.push(new z.Polygon(x.toPoints()))}let d=o;if(c.length>0){let _=c.reduce((y,g)=>z.BooleanOperations.unify(y,g));_&&!_.isEmpty()&&(d=z.BooleanOperations.subtract(o,_))}Array.isArray(d)||(d=[d]);for(let _ of d){let y=_.splitToIslands();for(let g of y){if(g.isEmpty())continue;let x=[...g.faces],w=x.find(I=>I.orientation()===z.ORIENTATION.CCW),S=x.filter(I=>I.orientation()===z.ORIENTATION.CW);if(!w)continue;if(!t.pcb_copper_pour){this.renderError("db.pcb_copper_pour not found. The database schema may be outdated.");return}let E=I=>I.edges.map(N=>{let C={x:N.start.x,y:N.start.y};if(N.isArc){let A=Math.tan(N.shape.sweep/4);Math.abs(A)>1e-9&&(C.bulge=A)}return C});w.reverse();let M=E(w),k=S.map(I=>(I.reverse(),{vertices:E(I)}));for(let I of l){let N=z.point(I.center.x,I.center.y);g.contains(N)&&k.push({vertices:[{x:I.center.x,y:I.center.y-I.radius,bulge:1},{x:I.center.x,y:I.center.y+I.radius,bulge:1}]})}t.pcb_copper_pour.insert({shape:"brep",layer:n.layer,brep_shape:{outer_ring:{vertices:M},inner_rings:k},source_net_id:i.source_net_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0})}}})}},JV=class extends On{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:Az,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:t.capacity,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},QV=class extends On{_getPcbRotationBeforeLayout(){let e=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+e}get config(){return{componentName:"PinHeader",zodProps:Rz,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,r=this._parsedProps.showSilkscreenPinLabels;if(e>0){let o;if(i)!t&&!n?o=`pinrow${e}_p${i}`:o=`pinrow${e}_p${i}_id${t}_od${n}`;else if(!t&&!n)o=`pinrow${e}`;else return null;return r!==!0&&(o+="_nopinlabels"),o}return null}initPorts(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let t=1;t<=e;t++){let n=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[t-1]:this._parsedProps.pinLabels?.[`pin${t}`];if(n){let i=Array.isArray(n)?n[0]:n,r=Array.isArray(n)?n.slice(1):[];this.add(new Di({pinNumber:t,name:i,aliases:[`pin${t}`,...r]}))}else this.add(new Di({pinNumber:t,name:`pin${t}`}))}}_getSchematicPortArrangement(){let e=this._parsedProps.pinCount??1,t=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",n=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:n?.leftSide?.direction??"top-to-bottom",pins:n?.leftSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}:{rightSide:{direction:n?.rightSide?.direction??"top-to-bottom",pins:n?.rightSide?.pins??Array.from({length:e},(i,r)=>`pin${r+1}`)}}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:t.supplierPartNumbers,pin_count:t.pinCount,gender:t.gender,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function o5t(e){switch(e){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var tH=class extends On{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??o5t(this.props.pinVariant),zodProps:wz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:t.frequency,load_capacitance:t.loadCapacitance,supplier_part_numbers:t.supplierPartNumbers,pin_variant:n,are_pins_interchangeable:n==="no_ground"||n==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let e=`${ti(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ti(this._parsedProps.loadCapacitance)}F`:e}},eH=class extends On{constructor(){super(...arguments);T(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:$z,sourceFtype:na.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${ti(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({name:this.name,ftype:na.simple_inductor,inductance:n.inductance,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function s5t(e){switch(e){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var nH=class extends On{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??s5t(this.props.pinVariant),zodProps:xz,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${ti(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},iH=class extends On{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:Lz,sourceFtype:na.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let e=Qn[this._getSchematicSymbolNameOrThrow()],t=e.ports.find(l=>l.labels.includes("1")),n=e.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),r=i.find(l=>l.props.pinNumber===1),o=i.find(l=>l.props.pinNumber===2),s=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;r.schematicSymbolPortDef=t,(!c||c.length===0)&&(o.schematicSymbolPortDef=n);for(let[l,u]of[[2,o],[3,s],[4,a]]){let h=c?.find(([_,y])=>_===`pin${l}`||y===`pin${l}`);if(!h){u.schematicSymbolPortDef=n;break}(h?.[0]===`pin${l}`?h[1]:h?.[0])!=="pin1"&&(u.schematicSymbolPortDef=n)}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:na.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},rH=class extends On{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:vz,sourceFtype:"simple_crystal"}}initPorts(){let e=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:e})}_getSchematicSymbolDisplayValue(){let e=`${ti(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ti(this._parsedProps.loadCapacitance)}F`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:t.frequency,load_capacitance:t.loadCapacitance,pin_variant:t.pinVariant||"two_pin",are_pins_interchangeable:(t.pinVariant||"two_pin")==="two_pin"});this.source_component_id=n.source_component_id}},oH=class extends On{constructor(){super(...arguments);T(this,"emitter",this.portMap.pin1);T(this,"collector",this.portMap.pin2);T(this,"base",this.portMap.pin3)}get config(){let t=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??t,zodProps:Fz,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let t={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},sH=class extends On{get config(){let e=this.props.mosfetMode==="depletion"?"d":"e",n=`${this.props.channelType}_channel_${e}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??n,zodProps:Dz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}},a5t=e=>e?e.closesAt!==void 0||e.opensAt!==void 0||e.startsClosed!==void 0||e.switchingFrequency!==void 0:!1,c5t=e=>!e||typeof e!="object"?!1:Object.prototype.hasOwnProperty.call(e,"spice"),l5t=e=>{if(!e||typeof e!="object")return null;let t=c5t(e)?e.spice??null:e;return a5t(t)?{...t}:null},aH=class extends On{_getSwitchType(){let e=this._parsedProps;return e?e.dpdt?"dpdt":e.spst?"spst":e.spdt?"spdt":e.dpst?"dpst":e.type??"spst":"spst"}get config(){let e=this._getSwitchType(),t=this._parsedProps?.isNormallyClosed??!1,n={spst:t?"spst_normally_closed_switch":"spst_switch",spdt:t?"spdt_normally_closed_switch":"spdt_switch",dpst:t?"dpst_normally_closed_switch":"dpst_switch",dpdt:t?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??n[e],zodProps:Vz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,t=this._parsedProps??{},n=e.source_component.insert({ftype:"simple_switch",name:this.name,switch_type:t.type,is_normally_closed:t.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=n.source_component_id}doInitialSimulationRender(){let e=this.props,t=l5t(e.simulation);if(!t)return;let{db:n}=this.root,i={type:"simulation_switch"};t.closesAt!==void 0&&(i.closes_at=t.closesAt),t.opensAt!==void 0&&(i.opens_at=t.opensAt),t.startsClosed!==void 0&&(i.starts_closed=t.startsClosed),t.switchingFrequency!==void 0&&(i.switching_frequency=t.switchingFrequency),n.simulation_switch.insert(i)}},LI={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},cH=class extends On{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:Zz,sourceFtype:na.simple_test_point}}_getPropsWithDefaults(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._parsedProps;return!n&&t&&(n="through_hole"),n??(n="through_hole"),e??(e="circle"),n==="pad"?e==="circle"?i??(i=LI.SMT_CIRCLE_DIAMETER):e==="rect"&&(r??(r=LI.SMT_RECT_SIZE),o??(o=r)):n==="through_hole"&&(t??(t=LI.HOLE_DIAMETER)),{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}}_getImpliedFootprintString(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:r,height:o}=this._getPropsWithDefaults();if(n==="through_hole")return`platedhole_d${t}`;if(n==="pad"){if(e==="circle")return`smtpad_circle_d${i}`;if(e==="rect")return`smtpad_rect_w${r}_h${o}`}throw new Error(`Footprint variant "${n}" with pad shape "${e}" not implemented`)}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{padShape:n,holeDiameter:i,footprintVariant:r,padDiameter:o,width:s,height:a}=this._getPropsWithDefaults(),c=e.source_component.insert({ftype:na.simple_test_point,name:this.name,supplier_part_numbers:t.supplierPartNumbers,footprint_variant:r,pad_shape:n,pad_diameter:o,hole_diameter:i,width:s,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},lH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:lF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout();t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:i.x,y:i.y},rotation:n.schRotation??0})}},uH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:cF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_line.insert({schematic_component_id:r,x1:n.x1+i.x,y1:n.y1+i.y,x2:n.x2+i.x,y2:n.y2+i.y,stroke_width:n.strokeWidth??ux,color:n.color??lx,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=o.schematic_line_id}},pH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:aF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_rect.insert({center:{x:i.x,y:i.y},width:n.width,height:n.height,stroke_width:n.strokeWidth??ux,color:n.color??lx,is_filled:n.isFilled,schematic_component_id:r,is_dashed:n.isDashed,rotation:n.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=o.schematic_rect_id}},hH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:rF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_arc.insert({schematic_component_id:r,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,start_angle_degrees:n.startAngleDegrees,end_angle_degrees:n.endAngleDegrees,direction:n.direction,stroke_width:n.strokeWidth??ux,color:n.color??lx,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=o.schematic_arc_id}},dH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:sF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,o=t.schematic_circle.insert({schematic_component_id:r,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,stroke_width:n.strokeWidth??ux,color:n.color??lx,is_filled:n.isFilled,fill_color:n.fillColor,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=o.schematic_circle_id}};function u5t({anchor:e,x:t,y:n,width:i,height:r,isInside:o}){switch(e){case"top_left":return{x:t,y:n+r,textAnchor:o?"top_left":"bottom_left"};case"top_center":return{x:t+i/2,y:n+r,textAnchor:o?"top_center":"bottom_center"};case"top_right":return{x:t+i,y:n+r,textAnchor:o?"top_right":"bottom_right"};case"center_left":return{x:t,y:n+r/2,textAnchor:o?"center_left":"center_right"};case"center":return{x:t+i/2,y:n+r/2,textAnchor:"center"};case"center_right":return{x:t+i,y:n+r/2,textAnchor:o?"center_right":"center_left"};case"bottom_left":return{x:t,y:n,textAnchor:o?"bottom_left":"top_left"};case"bottom_center":return{x:t+i/2,y:n,textAnchor:o?"bottom_center":"top_center"};case"bottom_right":return{x:t+i,y:n,textAnchor:o?"bottom_right":"top_right"};default:return{x:t+i/2,y:n+r,textAnchor:"center"}}}var fH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:oF,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=.6,r=typeof n.padding=="number"?n.padding:0,o=typeof n.paddingTop=="number"?n.paddingTop:r,s=typeof n.paddingBottom=="number"?n.paddingBottom:r,a=typeof n.paddingLeft=="number"?n.paddingLeft:r,c=typeof n.paddingRight=="number"?n.paddingRight:r,l=n.overlay&&n.overlay.length>0,u=typeof n.width=="number"&&typeof n.height=="number",h,d,_,y,g,x;if(l){let S=n.overlay.map(tt=>({selector:tt,port:this.getSubcircuit().selectOne(tt,{type:"port"})})).filter(({port:tt})=>tt!=null).map(({port:tt})=>({position:tt._getGlobalSchematicPositionAfterLayout()}));if(S.length===0)return;let E=S.map(tt=>tt.position.x),M=S.map(tt=>tt.position.y),k=Math.min(...E),I=Math.max(...E),N=Math.min(...M),C=Math.max(...M),A=I-k,O=C-N,B=A===0?i:0,D=O===0?i:0,X=a+B/2,Y=c+B/2,H=o+D/2,K=s+D/2,Z=k-X,ut=I+Y,st=N-K,it=C+H;h=ut-Z,d=it-st,_=Z+(n.schX??0),y=st+(n.schY??0),g=_+h/2,x=y+d/2}else if(u){h=n.width,d=n.height;let w=this._getGlobalSchematicPositionBeforeLayout();g=w.x,x=w.y,_=g-h/2,y=x-d/2}else return;if(t.schematic_box.insert({height:d,width:h,x:_,y,is_dashed:n.strokeStyle==="dashed"}),n.title){let w=n.titleInside,S=.1,E=n.titleAlignment,M=u5t({anchor:E,x:_,y,width:h,height:d,isInside:w}),k,I,N=M.textAnchor;w?(k=E.includes("top")?-S:E.includes("bottom")?S:0,I=E.includes("left")?S:E.includes("right")?-S:0):(k=E.includes("top")?S:E.includes("bottom")?-S:0,I=E.includes("center_left")?-S:E.includes("center_right")?S:0);let C=M.x+I,A=M.y+k;t.schematic_text.insert({anchor:N,text:n.title,font_size:n.titleFontSize??.18,color:n.titleColor??"#000000",position:{x:C,y:A},rotation:0})}}},mH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:uF}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.children.filter(d=>d.componentName==="SchematicRow");if(i.length===0)return;let r=[],o=0;for(let d of i){let _=d.children.filter(y=>y.componentName==="SchematicCell");o=Math.max(o,_.length)}for(let d=0;d<i.length;d++)r[d]=[];for(let d=0;d<i.length;d++){let y=i[d].children.filter(x=>x.componentName==="SchematicCell"),g=0;for(let x=0;x<y.length;x++){for(;r[d][g];)g++;let w=y[x],S=w._parsedProps.colSpan??1,E=w._parsedProps.rowSpan??1;for(let M=0;M<E;M++)for(let k=0;k<S;k++)r[d+M]||(r[d+M]=[]),r[d+M][g+k]=w;g+=S}}o=Math.max(0,...r.map(d=>d.length));let s=i.map((d,_)=>d._parsedProps.height??1),a=Array.from({length:o},(d,_)=>{let y=0;for(let g=0;g<i.length;g++){let x=r[g]?.[_];if(x){let w=x._parsedProps.text??x._parsedProps.children,S=x._parsedProps.width??(w?.length??2)*.5;S>y&&(y=S)}}return y||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=t.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:s,cell_padding:n.cellPadding,border_width:n.borderWidth,anchor:n.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=l.schematic_table_id;let u=new Set,h=0;for(let d=0;d<i.length;d++){let _=0;for(let y=0;y<o;y++){let g=r[d]?.[y];if(g&&!u.has(g)){u.add(g);let x=g._parsedProps,w=x.rowSpan??1,S=x.colSpan??1,E=0;for(let k=0;k<S;k++)E+=a[y+k];let M=0;for(let k=0;k<w;k++)M+=s[d+k];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:d,end_row_index:d+w-1,start_column_index:y,end_column_index:y+S-1,text:x.text??x.children,center:{x:c.x+_+E/2,y:c.y-h-M/2},width:E,height:M,horizontal_align:x.horizontalAlign,vertical_align:x.verticalAlign,font_size:x.fontSize??n.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[y]&&(_+=a[y])}h+=s[d]}}},_H=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:pF}}},yH=class extends be{constructor(){super(...arguments);T(this,"isSchematicPrimitive",!0);T(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:hF}}},gH=class extends be{constructor(){super(...arguments);T(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:Nz}}},bH=class extends be{get config(){return{componentName:"AnalogSimulation",zodProps:zz}}doInitialSimulationRender(){let{db:e}=this.root,{duration:t,timePerStep:n}=this._parsedProps,i=t||10,r=n||.01;e.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:i,time_per_step:r})}},xH=class extends be{constructor(){super(...arguments);T(this,"simulation_voltage_probe_id",null)}get config(){return{componentName:"VoltageProbe",zodProps:iF}}doInitialSimulationRender(){let{db:t}=this.root,{connectsTo:n,name:i}=this._parsedProps,r=this.getSubcircuit();if(!r){this.renderError("VoltageProbe must be inside a subcircuit");return}let o=Array.isArray(n)?n:[n];if(o.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let s=o[0],a=r.selectOne(s,{type:"port"}),c=a?null:r.selectOne(s,{type:"net"});if(c&&c.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${s}" resolved to a non-net component "${c.componentName}".`);return}if(!a&&!c){this.renderError(`VoltageProbe could not find connection target "${s}"`);return}let{simulation_voltage_probe_id:l}=t.simulation_voltage_probe.insert({name:i??this.name,source_port_id:a?.source_port_id??void 0,source_net_id:c?.source_net_id??void 0,subcircuit_id:r.subcircuit_id||void 0});this.simulation_voltage_probe_id=l}},p5t={name:"@tscircuit/core",type:"module",version:"0.0.786",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"'},devDependencies:{"@biomejs/biome":"^1.8.3","@tscircuit/capacity-autorouter":"^0.0.132","@tscircuit/checks":"^0.0.85","@tscircuit/circuit-json-util":"^0.0.72","@tscircuit/common":"^0.0.11","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.21","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"0.0.361","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^0.0.41","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.278","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-gltf":"^0.0.7","circuit-json-to-simple-3d":"^0.0.9","circuit-to-svg":"^0.0.238","circuit-json-to-spice":"^0.0.14",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",poppygl:"^0.0.6",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202",spicey:"^0.0.8","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.48","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},Ih=class{constructor({platform:e,projectUrl:t}={}){T(this,"firstChild",null);T(this,"children");T(this,"db");T(this,"root",null);T(this,"isRoot",!0);T(this,"schematicDisabled",!1);T(this,"pcbDisabled",!1);T(this,"pcbRoutingDisabled",!1);T(this,"_featureMspSchematicTraceRouting",!0);T(this,"name");T(this,"platform");T(this,"projectUrl");T(this,"_hasRenderedAtleastOnce",!1);T(this,"_eventListeners",{});this.children=[],this.db=ke([]),this.root=this,this.platform=e,this.projectUrl=t,this.pcbDisabled=e?.pcbDisabled??!1}add(e){let t;(0,vH.isValidElement)(e)?t=eV(e):t=e,this.children.push(t)}_getBoard(){return this.children.find(e=>e.componentName==="Board")}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let e=new Th({subcircuit:!0});e.parent=this,e.addAll(this.children),this.children=[e],this.firstChild=e}render(){this.firstChild||this._guessRootComponent();let{firstChild:e,db:t}=this;if(!e)throw new Error("RootCircuit has no root component");e.parent=this,e.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(t=>setTimeout(t,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(e=>e._hasIncompleteAsyncEffects()?!0:e.children.some(t=>t._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(e){let t=await Promise.resolve().then(()=>(TX(),PX)).catch(n=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
245
245
 
246
246
  "${n.message}"`)});if(e.view==="pcb")return t.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(e.view==="schematic")return t.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${e.view}`)}getCoreVersion(){let[e,t,n]=p5t.version.split(".").map(Number);return`${e}.${t}.${n+1}`}async preview(e){let t=typeof e=="object"?e:{previewName:e};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return Ai()}_computePcbGlobalTransformBeforeLayout(){return Ai()}selectAll(e){return this._guessRootComponent(),this.firstChild?.selectAll(e)??[]}selectOne(e,t){return this._guessRootComponent(),this.firstChild?.selectOne(e,t)??null}emit(e,...t){if(this._eventListeners[e])for(let n of this._eventListeners[e])n(...t)}on(e,t){this._eventListeners[e]||(this._eventListeners[e]=[]),this._eventListeners[e].push(t)}removeListener(e,t){this._eventListeners[e]&&(this._eventListeners[e]=this._eventListeners[e].filter(n=>n!==t))}enableDebug(e){typeof e=="string"?YI.default.enable(e):(e===null||e===!1)&&YI.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},h5t=Ih,d5t=Ih,f5t=e=>{let[t,n]=wh.default.useState(!0),[i,r]=wh.default.useState(null),[o,s]=wh.default.useState(),[a,c]=wh.default.useState();return wh.default.useEffect(()=>{n(!0),r(null),e&&setTimeout(()=>{try{let l=new Ih;l.add(e),s(l),c(l.toJson())}catch(l){r(l)}n(!1)},1)},[e]),{isLoading:t,error:i,circuit:o,circuitJson:a}},Mh=(e,t)=>(n,i)=>{let r=[];Array.isArray(t)?r.push(...t.flat()):typeof t=="object"&&r.push(...Object.values(t).flat(),...Object.keys(t));let o=s=>{if(s?.name&&s.name!==n)throw new Error(`Component name mismatch. Hook name: ${n}, Component prop name: ${s.name}`);let a={...i,...s,name:n},c=[];for(let l of r)if(a[l]){let u=`.${n} > .${l}`,h=a[l];c.push({from:u,to:h}),delete a[l]}return(0,Kl.jsxs)(Kl.Fragment,{children:[(0,Kl.jsx)(e,{...a}),c.map((l,u)=>(0,Kl.jsx)("trace",{...l},u))]})};for(let s of r)o[s]=`.${n} > .${s}`;return o},m5t=Mh(e=>(0,wH.jsx)("capacitor",{...e}),Pz),_5t=e=>Mh(t=>(0,SH.jsx)("chip",{pinLabels:e,...t}),e),y5t=Mh(e=>(0,PH.jsx)("diode",{...e}),jz),g5t=Mh(e=>(0,TH.jsx)("led",{...e}),Xz),b5t=Mh(e=>(0,IH.jsx)("resistor",{...e}),bz),x5t=new Proxy(e=>new Proxy({},{get:(t,n)=>`.${e} > .${n}`}),{get:(e,t)=>{let n=(...i)=>{let r=i[0];return new Proxy({},{get:(o,s)=>`.${t} > .${s}`})};return new Proxy(n,{get:(i,r)=>t==="net"?`net.${r}`:t==="subcircuit"?new Proxy({},{get:(o,s)=>new Proxy({},{get:(a,c)=>`subcircuit.${r} > .${s} > .${c}`})}):`.${t} > .${r}`,apply:(i,r,o)=>t==="net"?new Proxy({},{get:(s,a)=>`net.${a}`}):new Proxy({},{get:(s,a)=>{let c=`.${t} > .${a}`;return["U","J","CN"].some(u=>t.startsWith(u))?c:new Proxy(new String(c),{get:(u,h)=>typeof h=="symbol"||h==="toString"?()=>c:`.${t} > .${a} > .${h}`})}})})}});tV(ZX);tV({Bug:px});var HH=Yt(vo(),1);var EH=e=>{let t=e.match(/:[RC]_(\d{4})_/);if(t||(t=e.match(/:(SOIC-\d+|SOT-\d+|SOD-\d+|SSOP-\d+|TSSOP-\d+|QFP-\d+|QFN-\d+)/),t))return t[1]};var QI=e=>e.includes("cap")?e.replace(/cap/g,""):e;var CH=e=>{if(e){if(e.startsWith("kicad:")){let t=EH(e);return t?QI(t):e}return QI(e)}};var tM=new Map,nr=async(e,t)=>{let n=new URLSearchParams({...t,json:"true"}).toString();if(tM.has(n))return tM.get(n);let r=await(await fetch(`https://jlcsearch.tscircuit.com/${e}/list?${n}`)).json();return tM.set(n,r),r},ir=e=>e?[...e].sort((t,n)=>Number(n.is_basic??!1)-Number(t.is_basic??!1)):[],kH={findPart:async({sourceComponent:e,footprinterString:t})=>{let n=CH(t);if(e.type==="source_component"&&e.ftype==="simple_resistor"){let{resistors:i}=await nr("resistors",{resistance:e.resistance,package:n});return{jlcpcb:ir(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_capacitor"){let{capacitors:i}=await nr("capacitors",{capacitance:e.capacitance,package:n});return{jlcpcb:ir(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_pin_header"){let i;t?.includes("_p")&&(i=Number(t.split("_p")[1]));let{headers:r}=await nr("headers",i?{pitch:i,num_pins:e.pin_count,gender:e.gender}:{num_pins:e.pin_count,gender:e.gender});return{jlcpcb:ir(r).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_potentiometer"){let{potentiometers:i}=await nr("potentiometers",{resistance:e.max_resistance,package:n});return{jlcpcb:ir(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_diode"){let{diodes:i}=await nr("diodes",{package:n});return{jlcpcb:ir(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_chip"){let{chips:i}=await nr("chips",{package:n});return{jlcpcb:ir(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_transistor"){let{transistors:i}=await nr("transistors",{package:n,transistor_type:e.transistor_type});return{jlcpcb:ir(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_power_source"){let{power_sources:i}=await nr("power_sources",{voltage:e.voltage,package:n});return{jlcpcb:ir(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_inductor"){let{inductors:i}=await nr("inductors",{inductance:e.inductance,package:n});return{jlcpcb:ir(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_crystal"){let{crystals:i}=await nr("crystals",{frequency:e.frequency,load_capacitance:e.load_capacitance,package:n});return{jlcpcb:ir(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_mosfet"){let{mosfets:i}=await nr("mosfets",{package:n,mosfet_mode:e.mosfet_mode,channel_type:e.channel_type});return{jlcpcb:ir(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_resonator"){let{resonators:i}=await nr("resonators",{frequency:e.frequency,package:n});return{jlcpcb:ir(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_switch"){let{switches:i}=await nr("switches",{switch_type:e.type,package:n});return{jlcpcb:ir(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_led"){let{leds:i}=await nr("leds",{package:n});return{jlcpcb:ir(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_fuse"){let{fuses:i}=await nr("fuses",{package:n});return{jlcpcb:ir(i).map(r=>`C${r.lcsc}`).slice(0,3)}}return{}}};var OH=Yt(NH(),1);W();var $H=Yt(Mn(),1),BH=Yt(Mn(),1),rr=p.tuple([p.coerce.number(),p.coerce.number()]),k5t=p.tuple([p.number(),p.number(),p.number()]),yx=p.union([rr,k5t]),LH=p.object({at:yx,size:rr,layers:p.array(p.string()),roundrect_rratio:p.number(),uuid:p.string()}).partial(),N5t=p.object({key:p.string(),val:p.string(),attributes:LH}),fx=p.object({oval:p.boolean().default(!1),width:p.number().optional(),height:p.number().optional(),offset:rr.optional()}),zH=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:yx,drill:p.union([p.number(),p.array(p.any()),fx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:rr.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?rr.parse(e[3].slice(1)):void 0}:e).pipe(fx),size:p.union([p.array(p.number()).length(2).transform(([e,t])=>({width:e,height:t})),p.object({width:p.number(),height:p.number()})]),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),uuid:p.string().optional()}),FH=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:yx,size:rr,drill:p.union([p.number(),p.array(p.any()),fx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:rr.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?rr.parse(e[3].slice(1)):void 0}:e).pipe(fx).optional(),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),chamfer_ratio:p.number().optional(),solder_paste_margin:p.number().optional(),solder_paste_margin_ratio:p.number().optional(),clearance:p.number().optional(),zone_connection:p.union([p.literal(0).describe("Pad is not connect to zone"),p.literal(1).describe("Pad is connected to zone using thermal relief"),p.literal(2).describe("Pad is connected to zone using solid fill")]).optional(),thermal_width:p.number().optional(),thermal_gap:p.number().optional(),uuid:p.string().optional()}),DH=p.object({font:p.object({size:rr,thickness:p.number().optional()})}).partial(),A5t=p.object({fp_text_type:p.literal("user"),text:p.string(),at:yx,layer:p.string(),uuid:p.string().optional(),effects:DH.partial()}),R5t=p.object({start:rr,mid:rr,end:rr,stroke:p.object({width:p.number(),type:p.string()}),layer:p.string(),uuid:p.string().optional()}),O5t=p.object({pts:p.array(rr),stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),L5t=p.object({start:rr,end:rr,stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),AH=p.object({footprint_name:p.string(),version:p.string().optional(),generator:p.string().optional(),generator_version:p.string().optional(),layer:p.string(),descr:p.string().default(""),tags:p.array(p.string()).optional(),properties:p.array(N5t),fp_lines:p.array(L5t),fp_texts:p.array(A5t),fp_arcs:p.array(R5t),fp_polys:p.array(O5t).optional(),pads:p.array(FH),holes:p.array(zH).optional()}),mx=(e,t)=>{if(t==="effects"&&Array.isArray(e)){let n={};for(let i of e)if(i[0]==="font"){let r={};for(let o of i.slice(1))o.length===2?r[o[0].valueOf()]=Number.parseFloat(o[1].valueOf()):r[o[0].valueOf()]=o.slice(1).map(s=>Number.parseFloat(s.valueOf()));n.font=r}return DH.parse(n)}if(t==="pts")return e.map(n=>n.slice(1).map(i=>Number.parseFloat(i.valueOf())));if(t==="stroke"){let n={};for(let i of e){let r=i[0].valueOf();n[r]=mx(i.slice(1),r)}return n}return t==="at"||t==="size"||t==="start"||t==="mid"||t==="end"?(Array.isArray(e)?e:[e]).map(i=>i?.valueOf?.()??i).filter(i=>typeof i=="number"||typeof i=="string"&&/^[-+]?\d*\.?\d+(e[-+]?\d+)?$/i.test(i)).map(i=>typeof i=="number"?i:Number.parseFloat(i)):t==="tags"?e.map(n=>n.valueOf()):t==="generator_version"||t==="version"?e[0].valueOf():e.length===2?e.valueOf():t==="uuid"?Array.isArray(e)?e[0].valueOf():e.valueOf():/^[\d\.]+$/.test(e)&&!Number.isNaN(Number.parseFloat(e))?Number.parseFloat(e):Array.isArray(e)&&e.length===1?e[0].valueOf():Array.isArray(e)?e.map(n=>n.valueOf()):e},rn=(e,t)=>{for(let n of e)if(Array.isArray(n)&&n[0]===t)return mx(n.slice(1),t)},eM=(0,$H.default)("kicad-mod-converter"),z5t=e=>{let t=(0,OH.default)(e),n=t[1].valueOf(),i={},r=Object.entries(AH.shape).filter(([w,S])=>S._def.typeName==="ZodString"||w==="tags").map(([w])=>w);for(let w of t.slice(2)){if(!r.includes(w[0]))continue;let S=w[0].valueOf(),E=mx(w.slice(1),S);i[S]=E}let o=t.slice(2).filter(w=>w[0]==="property").map(w=>{let S=w[1].valueOf(),E=w[2].valueOf(),M=LH.parse(w.slice(3).reduce((k,I)=>{let N=I[0].valueOf();return k[N]=mx(I.slice(1),N),k},{}));return{key:S,val:E,attributes:M}}),s=t.slice(2).filter(w=>w[0]==="pad"),a=[];for(let w of s){let S=rn(w,"at"),E=rn(w,"size"),M=rn(w,"drill"),k=rn(w,"layers");if(Array.isArray(k)?k=k.map(A=>A.valueOf()):typeof k=="string"?k=[k]:k||(k=[]),!k.includes("F.Cu")){eM(`Skipping pad without F.Cu layer: layers=${k.join(", ")}`);continue}let I=rn(w,"roundrect_rratio"),N=rn(w,"uuid"),C={name:w[1].valueOf(),pad_type:w[2].valueOf(),pad_shape:w[3].valueOf(),at:S,drill:M,size:E,layers:k,roundrect_rratio:I,uuid:N};eM(`attempting to parse pad: ${JSON.stringify(C,null," ")}`),a.push(FH.parse(C))}let c=t.slice(2).filter(w=>w[0]==="fp_text"),l=[];for(let w of c){let S=w[2].valueOf(),E=rn(w,"at"),M=rn(w,"layer"),k=rn(w,"uuid"),I=rn(w,"effects");l.push({fp_text_type:"user",text:S,at:E,layer:M,uuid:k,effects:I})}let u=[],h=t.slice(2).filter(w=>w[0]==="fp_line");for(let w of h){let S=rn(w,"start"),E=rn(w,"end"),M=rn(w,"stroke"),k=rn(w,"layer"),I=rn(w,"uuid");u.push({start:S,end:E,stroke:M,layer:k,uuid:I})}let d=[],_=t.slice(2).filter(w=>w[0]==="fp_arc");for(let w of _){let S=rn(w,"start"),E=rn(w,"mid"),M=rn(w,"end"),k=rn(w,"stroke"),I=rn(w,"layer"),N=rn(w,"uuid");!S||!M||!E||!k||!I||d.push({start:S,mid:E,end:M,stroke:k,layer:I,uuid:N})}let y=[],g=t.slice(2).filter(w=>w[0]==="fp_poly");for(let w of g){let S=rn(w,"pts"),E=rn(w,"stroke"),M=rn(w,"layer"),k=rn(w,"uuid");y.push({pts:S,stroke:E,layer:M,uuid:k})}let x=[];for(let w of t.slice(2)){if(w[0]!=="pad"||w[2]?.valueOf?.()!=="thru_hole")continue;let S=w[1]?.valueOf?.(),E=w[2]?.valueOf?.(),M=w[3]?.valueOf?.(),k=rn(w,"at"),I=rn(w,"drill"),N=rn(w,"size");Array.isArray(N)&&(N[0]==="size"&&(N=N.slice(1)),N={width:Number(N[0]),height:Number(N[1])});let C=rn(w,"uuid"),A=rn(w,"roundrect_rratio"),O=rn(w,"layers");Array.isArray(O)?O=O.map(D=>D.valueOf()):typeof O=="string"?O=[O]:O||(O=[]);let B={name:S,pad_type:E,pad_shape:M,at:k,drill:I,size:N,layers:O,roundrect_rratio:A,uuid:C};eM(`attempting to parse holes: ${JSON.stringify(B,null,2)}`),x.push(zH.parse(B))}return AH.parse({footprint_name:n,...i,properties:o,fp_lines:u,fp_texts:l,fp_arcs:d,pads:a,holes:x,fp_polys:y})};function jH(e,t,n){let i={x:(e.x+t.x)/2,y:(e.y+t.y)/2},r={x:(t.x+n.x)/2,y:(t.y+n.y)/2},o=-(e.x-t.x)/(e.y-t.y),s=-(t.x-n.x)/(t.y-n.y),a=(i.y-r.y+s*r.x-o*i.x)/(s-o),c=i.y+o*(a-i.x);return{x:a,y:c}}function YH(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function _x(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}var F5t=(e,t,n)=>{let i=jH(e,t,n),r=YH(i,e),o=_x(i,e),a=_x(i,n)-o;return a<0&&(a+=2*Math.PI),r*a};function D5t(e,t,n,i){let r=jH(e,t,n),o=YH(r,e),s=_x(r,e),c=_x(r,n)-s;c<0&&(c+=2*Math.PI);let l=[];for(let u=0;u<=i;u++){let h=s+u/i*c,d=r.x+o*Math.cos(h),_=r.y+o*Math.sin(h);l.push({x:d,y:_})}return l}var nM=e=>Array.isArray(e)?{x:e[0],y:e[1]}:e,$5t=e=>e*Math.PI/180,iM=(e,t,n)=>{let i=$5t(n),r=Math.cos(i),o=Math.sin(i);return{x:e*r-t*o,y:e*o+t*r}},B5t=e=>{let t=[...new Map(e.map(u=>[`${u.x},${u.y}`,u])).values()];if(t.length!==4)return null;let n=t.map(u=>u.x),i=t.map(u=>u.y),r=[...new Set(n)],o=[...new Set(i)];if(r.length!==2||o.length!==2)return null;let[s,a]=r.sort((u,h)=>u-h),[c,l]=o.sort((u,h)=>u-h);return s===void 0||a===void 0||c===void 0||l===void 0?null:{x:(s+a)/2,y:(c+l)/2,width:a-s,height:l-c}},RH=e=>e&&Array.isArray(e)&&e.length>=3&&typeof e[2]=="number"?e[2]:0,uo=e=>{let t=(e%360+360)%360;return t===90||t===270},Eh=(0,BH.default)("kicad-mod-converter"),ss=e=>{switch(e.toLowerCase()){case"f.cu":case"f.fab":case"f.silks":case"edge.cuts":return"top";case"b.cu":case"b.fab":case"b.silks":return"bottom"}},j5t=async e=>{let{fp_lines:t,fp_texts:n,fp_arcs:i,pads:r,properties:o,holes:s,fp_polys:a}=e,c=[];c.push({type:"source_component",source_component_id:"source_component_0",supplier_part_numbers:{}}),c.push({type:"schematic_component",schematic_component_id:"schematic_component_0",source_component_id:"source_component_0",center:{x:0,y:0},rotation:0,size:{width:0,height:0}});let l=new Set;for(let D of r)D.name&&l.add(D.name);if(s)for(let D of s)D.name&&l.add(D.name);let u=0,h=new Map;for(let D of l){let X=`source_port_${u++}`;h.set(D,X),c.push({type:"source_port",source_port_id:X,source_component_id:"source_component_0",name:D,port_hints:[D]}),c.push({type:"schematic_port",schematic_port_id:`schematic_port_${u++}`,source_port_id:X,schematic_component_id:"schematic_component_0",center:{x:0,y:0}})}let d=Number.POSITIVE_INFINITY,_=Number.NEGATIVE_INFINITY,y=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY;for(let D of r){let X=D.at[0],Y=-D.at[1],H=D.size[0],K=D.size[1];d=Math.min(d,X-H/2),_=Math.max(_,X+H/2),y=Math.min(y,Y-K/2),g=Math.max(g,Y+K/2)}let x="pcb_component_0";c.push({type:"pcb_component",source_component_id:"source_component_0",pcb_component_id:x,layer:"top",center:{x:0,y:0},rotation:0,width:Number.isFinite(d)?_-d:0,height:Number.isFinite(y)?g-y:0});let w=0,S=new Map;for(let D of l){let X=`pcb_port_${w++}`,Y=h.get(D);S.set(D,X);let H=0,K=0,Z=["top","bottom"],ut=r.find(st=>st.name===D);if(ut)H=ut.at[0],K=-ut.at[1],Z=ut.layers?ut.layers.map(st=>ss(st)).filter(Boolean):["top","bottom"];else if(s){let st=s.find(it=>it.name===D);st&&(H=st.at[0],K=-st.at[1],Z=st.layers?st.layers.map(it=>ss(it)).filter(Boolean):["top","bottom"])}c.push({type:"pcb_port",pcb_port_id:X,source_port_id:Y,pcb_component_id:x,x:H,y:K,layers:Z})}let E=0,M=0,k=0;for(let D of r)if(D.pad_type==="smd"){let X=D.name?S.get(D.name):void 0;c.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${E++}`,shape:"rect",x:D.at[0],y:-D.at[1],width:D.size[0],height:D.size[1],layer:ss(D.layers?.[0]??"F.Cu"),pcb_component_id:x,port_hints:[D.name],pcb_port_id:X})}else if(D.pad_type==="thru_hole"){if(D.pad_shape==="rect"){let X=RH(D.at),Y=uo(X)?D.size[1]:D.size[0],H=uo(X)?D.size[0]:D.size[1],K=D.drill?.offset?.[0]??0,Z=D.drill?.offset?.[1]??0,ut=iM(K,Z,X),st=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${M++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:D.at[0],y:-D.at[1],hole_offset_x:ut.x,hole_offset_y:-ut.y,hole_diameter:D.drill?.width,rect_pad_width:Y,rect_pad_height:H,layers:["top","bottom"],pcb_component_id:x,port_hints:[D.name],pcb_port_id:st})}else if(D.pad_shape==="circle"){let X=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${M++}`,shape:"circle",x:D.at[0],y:-D.at[1],outer_diameter:D.size[0],hole_diameter:D.drill?.width,layers:["top","bottom"],pcb_component_id:x,port_hints:[D.name],pcb_port_id:X})}else if(D.pad_shape==="oval"){let X=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${M++}`,shape:"pill",x:D.at[0],y:-D.at[1],outer_width:D.size[0],outer_height:D.size[1],hole_width:D.drill?.width,hole_height:D.drill?.height,layers:["top","bottom"],pcb_component_id:x,port_hints:[D.name],pcb_port_id:X})}}else D.pad_type==="np_thru_hole"&&c.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${k++}`,x:D.at[0],y:-D.at[1],hole_diameter:D.drill?.width,pcb_component_id:x});if(s)for(let D of s){let X=D.layers?.some(St=>St.endsWith(".Cu")||St==="*.Cu"),Y=RH(D.at),H=D.drill?.offset?.[0]??0,K=D.drill?.offset?.[1]??0,Z=iM(H,K,Y),ut=D.at[0]+Z.x,st=-(D.at[1]+Z.y),it=D.drill?.width??0,tt=D.size?.width??it,ht=D.roundrect_rratio??0,gt=ht>0?Math.min(uo(Y)?D.size?.height??tt:D.size?.width??tt,uo(Y)?D.size?.width??tt:D.size?.height??tt)/2*ht:0;if(X)if(D.pad_shape==="rect"){let St=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${M++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:D.at[0],y:-D.at[1],hole_offset_x:Z.x,hole_offset_y:-Z.y,hole_diameter:it,rect_pad_width:uo(Y)?D.size?.height??tt:D.size?.width??tt,rect_pad_height:uo(Y)?D.size?.width??tt:D.size?.height??tt,rect_border_radius:gt,port_hints:[D.name],layers:["top","bottom"],pcb_component_id:x,pcb_port_id:St})}else if(D.pad_shape==="oval"){let St=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${M++}`,shape:"pill",x:ut,y:st,outer_width:uo(Y)?D.size?.height??tt:D.size?.width??tt,outer_height:uo(Y)?D.size?.width??tt:D.size?.height??tt,hole_width:uo(Y)?D.drill?.height??it:D.drill?.width??it,hole_height:uo(Y)?D.drill?.width??it:D.drill?.height??it,port_hints:[D.name],layers:["top","bottom"],pcb_component_id:x,pcb_port_id:St})}else if(D.pad_shape==="roundrect"){let St=D.name?S.get(D.name):void 0,Ot=D.drill?.offset?.[0]??0,dt=D.drill?.offset?.[1]??0,j=iM(Ot,dt,Y),U=uo(Y)?D.size?.height??tt:D.size?.width??tt,nt=uo(Y)?D.size?.width??tt:D.size?.height??tt;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${M++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:ut,y:st,hole_offset_x:j.x,hole_offset_y:-j.y,hole_diameter:it,rect_pad_width:U,rect_pad_height:nt,rect_border_radius:gt,port_hints:[D.name],layers:["top","bottom"],pcb_component_id:x,pcb_port_id:St})}else{let St=D.name?S.get(D.name):void 0;c.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${M++}`,shape:"circle",x:ut,y:st,outer_diameter:tt,hole_diameter:it,port_hints:[D.name],layers:["top","bottom"],pcb_component_id:x,pcb_port_id:St})}else c.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${k++}`,x:ut,y:st,hole_diameter:tt,hole_shape:"circle",pcb_component_id:x})}let I=0,N=0,C=0;for(let D of t){let X=[{x:D.start[0],y:-D.start[1]},{x:D.end[0],y:-D.end[1]}],Y=D.layer.toLowerCase();Y==="f.cu"?c.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${I++}`,pcb_component_id:x,layer:ss(D.layer),route:X,thickness:D.stroke.width}):Y==="f.silks"||Y==="edge.cuts"?c.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${N++}`,pcb_component_id:x,layer:"top",route:X,stroke_width:D.stroke.width}):Y==="f.fab"?c.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${C++}`,pcb_component_id:x,layer:"top",route:X,stroke_width:D.stroke.width,port_hints:[]}):Y.startsWith("user.")?Eh("Skipping user layer for fp_line",D.layer):Eh("Unhandled layer for fp_line",D.layer)}if(a)for(let D of a){let X=D.pts.map(Y=>({x:Y[0],y:-Y[1]}));if(D.layer.endsWith(".Cu")){let Y=B5t(X);Y?c.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${E++}`,shape:"rect",x:Y.x,y:Y.y,width:Y.width,height:Y.height,layer:ss(D.layer),pcb_component_id:x}):c.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${I++}`,pcb_component_id:x,layer:ss(D.layer),route:X,thickness:D.stroke.width})}else D.layer.endsWith(".SilkS")?c.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${N++}`,pcb_component_id:x,layer:ss(D.layer),route:X,stroke_width:D.stroke.width}):D.layer.endsWith(".Fab")?c.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${C++}`,pcb_component_id:x,layer:ss(D.layer),route:X,stroke_width:D.stroke.width,port_hints:[]}):Eh("Unhandled layer for fp_poly",D.layer)}for(let D of i){if(D.layer.toLowerCase().startsWith("user.")){Eh("Skipping user layer for fp_arc",D.layer);continue}let Y=nM(D.start),H=nM(D.mid),K=nM(D.end),Z=F5t(Y,H,K),ut=D5t(Y,H,K,Math.ceil(Z)),st=ss(D.layer);if(!st){Eh("Unable to convert layer for fp_arc",D.layer);continue}c.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${N++}`,layer:st,pcb_component_id:x,route:ut.map(it=>({x:it.x,y:-it.y})),stroke_width:D.stroke.width})}for(let D of n){let X=ss(D.layer);D.layer.endsWith(".SilkS")?c.push({type:"pcb_silkscreen_text",layer:X,font:"tscircuit2024",font_size:D.effects?.font?.size[0]??1,pcb_component_id:x,anchor_position:{x:D.at[0],y:-D.at[1]},anchor_alignment:"center",text:D.text}):D.layer.endsWith(".Fab")?c.push({type:"pcb_fabrication_note_text",layer:X,font:"tscircuit2024",font_size:D.effects?.font?.size[0]??1,pcb_component_id:x,anchor_position:{x:D.at[0],y:-D.at[1]},anchor_alignment:"center",text:D.text}):Eh("Unhandled layer for fp_text",D.layer)}let A=o.find(D=>D.key==="Reference"),O=o.find(D=>D.key==="Value"),B=[A,O].filter(D=>D&&!!D.val);for(let D of B){let X=D.attributes.at;X&&c.push({type:"pcb_silkscreen_text",layer:"top",font:"tscircuit2024",font_size:1.27,pcb_component_id:x,anchor_position:{x:X[0],y:-X[1]},anchor_alignment:"center",text:D.val})}return c},XH=async e=>{let t=z5t(e);return await j5t(t)};var Y5t="https://kicad-mod-cache.tscircuit.com",VH=()=>({partsEngine:kH,footprintLibraryMap:{kicad:async e=>{let t=`${Y5t}/${e}`,n=`${t}.circuit.json`,r=await(await fetch(n)).json(),o=Array.isArray(r)?r.filter(a=>a?.type==="pcb_silkscreen_text"?a?.text==="REF**":!0):r,s=`${t}.wrl`;return{footprintCircuitJson:o,cadModel:{wrlUrl:s,modelUnitToMmScale:2.54}}}},footprintFileParserMap:{kicad_mod:{loadFromUrl:async e=>{let t=await fetch(e).then(i=>i.text()),n=await XH(t);return{footprintCircuitJson:Array.isArray(n)?n:[n]}}}}});var rM=Yt(Mn(),1),Yte=(0,rM.default)("tsci:eval:execution-context");function gx(e,t={}){globalThis.React=HH;let n=t.platform||VH(),i=t.projectConfig?{...n,...t.projectConfig}:n,r=new Ih({platform:i});return t.name&&(r.name=t.name),t.debugNamespace&&r.enableDebug(t.debugNamespace),{fsMap:{},entrypoint:"",preSuppliedImports:{"@tscircuit/core":hx,tscircuit:hx,"@tscircuit/math-utils":i4,react:HH,debug:rM.default,"@tscircuit/props":{}},circuit:r,...e}}function Jl(e){let t=e;return t=t.replace(/\\/g,"/"),t=t.trim(),t.startsWith("./")&&(t=t.slice(2)),t.startsWith("/")&&(t=t.slice(1)),t}function GH(e){let t={};for(let[n,i]of Object.entries(e))t[Jl(n)]=i;return t}function No(e){if(!e)return".";let n=e.replace(/\\/g,"/").replace(/\/+$/,"");return n.indexOf("/")===-1?".":n.substring(0,n.lastIndexOf("/"))||"/"}function UH(e){if(Array.isArray(e))return null;let t=e["tsconfig.json"];if(!t)return null;try{let n=JSON.parse(t);return n?.compilerOptions?.paths?{baseUrl:n.compilerOptions.baseUrl||".",paths:n.compilerOptions.paths}:null}catch{return null}}function qH(e){let{importPath:t,normalizedFilePathMap:n,extensions:i,tsConfig:r}=e;if(!r)return null;let{baseUrl:o,paths:s}=r,a=c=>{let l=Jl(c);if(n.has(l))return n.get(l);for(let u of i){let h=`${l}.${u}`;if(n.has(h))return n.get(h)}return null};for(let[c,l]of Object.entries(s))if(c.includes("*")){let[h,d]=c.split("*");if(!t.startsWith(h)||!t.endsWith(d||""))continue;let _=t.slice(h.length,t.length-(d?d.length:0));for(let y of l){let g=y.replace("*",_),x=o&&!g.startsWith("./")&&!g.startsWith("/")?`${o}/${g}`:g,w=a(x);if(w)return w}}else{if(t!==c)continue;for(let h of l){let d=o&&!h.startsWith("./")&&!h.startsWith("/")?`${o}/${h}`:h,_=a(d);if(_)return _}}return null}function bx(e,t){if(e.startsWith("../")){let n=No(t);return bx(e.slice(3),n)}return e.startsWith("./")?bx(e.slice(2),t):e.startsWith("/")?e.slice(1):`${t}/${e}`}var pm=(e,t,n)=>{let i=n?bx(e,n):e,r=new Set(Array.isArray(t)?t:Object.keys(t));if(r.has(i))return i;let o=new Map;for(let l of r)o.set(Jl(l),l);let s=Jl(i);if(o.has(s))return o.get(s);let a=["tsx","ts","json","js","jsx","obj","gltf","glb"];for(let l of a){let u=`${s}.${l}`;if(o.has(u))return o.get(u)}let c=!Array.isArray(t)&&typeof t=="object"?UH(t):null;if(!e.startsWith("./")&&!e.startsWith("../")){let l=qH({importPath:e,normalizedFilePathMap:o,extensions:a,tsConfig:c});if(l)return l}if(!e.startsWith("./")&&!e.startsWith("../")){let l=Jl(e);if(o.has(l))return o.get(l);for(let u of a){let h=`${l}.${u}`;if(o.has(h))return o.get(h)}}return null},xx=(e,t)=>{let n=pm(e,t);if(!n)throw new Error(`File not found "${e}", available paths:
247
247