@tscircuit/eval 0.0.326 → 0.0.327
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.
- package/dist/blob-url.js +1 -1
- package/dist/webworker/entrypoint.js +3 -3
- package/package.json +2 -2
|
@@ -948,7 +948,7 @@ Using plugins:`),be.forEach(function(ke){wbt(ke,Z,ge)}),I||console.log("\nUsing
|
|
|
948
948
|
:is(button, input, select, textarea, optgroup, option)[disabled],
|
|
949
949
|
optgroup[disabled] > option,
|
|
950
950
|
fieldset[disabled]:not(fieldset[disabled] legend:first-of-type *)
|
|
951
|
-
)`,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 Qu=Or(e1(),1);var aY={};function sY(r,e){return r===Qu.default.falseFunc?Qu.default.falseFunc:a=>e.isTag(a)&&r(a)}function iY(r,e){let a=e.getSiblings(r);if(a.length<=1)return[];let s=a.indexOf(r);return s<0||s===a.length-1?[]:a.slice(s+1).filter(e.isTag)}function nY(r){return{xmlMode:!!r.xmlMode,lowerCaseAttributeNames:!!r.lowerCaseAttributeNames,lowerCaseTags:!!r.lowerCaseTags,quirksMode:!!r.quirksMode,cacheResults:!!r.cacheResults,pseudos:r.pseudos,adapter:r.adapter,equals:r.equals}}var rY=(r,e,a,s,l)=>{let d=l(e,nY(a),s);return d===Qu.default.trueFunc?r:d===Qu.default.falseFunc?Qu.default.falseFunc:x=>d(x)&&r(x)},JR={is:rY,matches:rY,where:rY,not(r,e,a,s,l){let d=l(e,nY(a),s);return d===Qu.default.falseFunc?r:d===Qu.default.trueFunc?Qu.default.falseFunc:x=>!d(x)&&r(x)},has(r,e,a,s,l){let{adapter:d}=a,x=nY(a);x.relativeSelector=!0;let f=e.some(b=>b.some(Ib))?[aY]:void 0,m=l(e,x,f);if(m===Qu.default.falseFunc)return Qu.default.falseFunc;let D=sY(m,d);if(f&&m!==Qu.default.trueFunc){let{shouldTestNextSiblings:b=!1}=m;return E=>{if(!r(E))return!1;f[0]=E;let A=d.getChildren(E),B=b?[...A,...iY(E,d)]:A;return d.existsOne(D,B)}}return b=>r(b)&&d.existsOne(D,d.getChildren(b))}};function s_e(r,e,a,s,l){var d;let{name:x,data:f}=e;if(Array.isArray(f)){if(!(x in JR))throw new Error(`Unknown pseudo-class :${x}(${f})`);return JR[x](r,f,a,s,l)}let m=(d=a.pseudos)===null||d===void 0?void 0:d[x],D=typeof m=="string"?m:tY[x];if(typeof D=="string"){if(f!=null)throw new Error(`Pseudo ${x} doesn't have any arguments`);let b=Pb(D);return JR.is(r,b,a,s,l)}if(typeof m=="function")return eY(m,x,f,1),b=>m(b,f)&&r(b);if(x in kb)return kb[x](r,f,a,s);if(x in KR){let b=KR[x];return eY(b,x,f,2),E=>b(E,a,f)&&r(E)}throw new Error(`Unknown pseudo-class :${x}`)}function oY(r,e){let a=e.getParent(r);return a&&e.isTag(a)?a:null}function i_e(r,e,a,s,l){let{adapter:d,equals:x}=a;switch(e.type){case Jr.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case Jr.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case Jr.Attribute:{if(e.namespace!=null)throw new Error("Namespaced attributes are not yet supported by css-select");return(!a.xmlMode||a.lowerCaseAttributeNames)&&(e.name=e.name.toLowerCase()),t_e[e.action](r,e,a)}case Jr.Pseudo:return s_e(r,e,a,s,l);case Jr.Tag:{if(e.namespace!=null)throw new Error("Namespaced tag names are not yet supported by css-select");let{name:f}=e;return(!a.xmlMode||a.lowerCaseTags)&&(f=f.toLowerCase()),function(D){return d.getName(D)===f&&r(D)}}case Jr.Descendant:{if(a.cacheResults===!1||typeof WeakSet>"u")return function(D){let b=D;for(;b=oY(b,d);)if(r(b))return!0;return!1};let f=new WeakSet;return function(D){let b=D;for(;b=oY(b,d);)if(!f.has(b)){if(d.isTag(b)&&r(b))return!0;f.add(b)}return!1}}case"_flexibleDescendant":return function(m){let D=m;do if(r(D))return!0;while(D=oY(D,d));return!1};case Jr.Parent:return function(m){return d.getChildren(m).some(D=>d.isTag(D)&&r(D))};case Jr.Child:return function(m){let D=d.getParent(m);return D!=null&&d.isTag(D)&&r(D)};case Jr.Sibling:return function(m){let D=d.getSiblings(m);for(let b=0;b<D.length;b++){let E=D[b];if(x(m,E))break;if(d.isTag(E)&&r(E))return!0}return!1};case Jr.Adjacent:return d.prevElementSibling?function(m){let D=d.prevElementSibling(m);return D!=null&&r(D)}:function(m){let D=d.getSiblings(m),b;for(let E=0;E<D.length;E++){let A=D[E];if(x(m,A))break;d.isTag(A)&&(b=A)}return!!b&&r(b)};case Jr.Universal:{if(e.namespace!=null&&e.namespace!=="*")throw new Error("Namespaced universal selectors are not yet supported by css-select");return r}}}function o_e(r,e,a){let s=ZR(r,e,a);return sY(s,e.adapter)}function ZR(r,e,a){let s=typeof r=="string"?Pb(r):r;return QR(s,e,a)}function u_e(r){return r.type===Jr.Pseudo&&(r.name==="scope"||Array.isArray(r.data)&&r.data.some(e=>e.some(u_e)))}var _jt={type:Jr.Descendant},Ajt={type:"_flexibleDescendant"},Rjt={type:Jr.Pseudo,name:"scope",data:null};function Sjt(r,{adapter:e},a){let s=!!a?.every(l=>{let d=e.isTag(l)&&e.getParent(l);return l===aY||d&&e.isTag(d)});for(let l of r){if(!(l.length>0&&Ib(l[0])&&l[0].type!==Jr.Descendant))if(s&&!l.some(u_e))l.unshift(_jt);else continue;l.unshift(Rjt)}}function QR(r,e,a){var s;r.forEach(JX),a=(s=e.context)!==null&&s!==void 0?s:a;let l=Array.isArray(a),d=a&&(Array.isArray(a)?a:[a]);if(e.relativeSelector!==!1)Sjt(r,e,d);else if(r.some(m=>m.length>0&&Ib(m[0])))throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");let x=!1,f=r.map(m=>{if(m.length>=2){let[D,b]=m;D.type!==Jr.Pseudo||D.name!=="scope"||(l&&b.type===Jr.Descendant?m[1]=Ajt:(b.type===Jr.Adjacent||b.type===Jr.Sibling)&&(x=!0))}return Bjt(m,e,d)}).reduce(wjt,ed.default.falseFunc);return f.shouldTestNextSiblings=x,f}function Bjt(r,e,a){var s;return r.reduce((l,d)=>l===ed.default.falseFunc?ed.default.falseFunc:i_e(l,d,e,a,QR),(s=e.rootFunc)!==null&&s!==void 0?s:ed.default.trueFunc)}function wjt(r,e){return e===ed.default.falseFunc||r===ed.default.trueFunc?r:r===ed.default.falseFunc||e===ed.default.trueFunc?e:function(s){return r(s)||e(s)}}var c_e=(r,e)=>r===e,Tjt={adapter:HR,equals:c_e};function l_e(r){var e,a,s,l;let d=r??Tjt;return(e=d.adapter)!==null&&e!==void 0||(d.adapter=HR),(a=d.equals)!==null&&a!==void 0||(d.equals=(l=(s=d.adapter)===null||s===void 0?void 0:s.equals)!==null&&l!==void 0?l:c_e),d}function cY(r){return function(a,s,l){let d=l_e(s);return r(a,d,l)}}var Enr=cY(o_e),vnr=cY(ZR),Cnr=cY(QR);function d_e(r){return function(a,s,l){let d=l_e(l);typeof a!="function"&&(a=ZR(a,d,s));let x=Pjt(s,d.adapter,a.shouldTestNextSiblings);return r(a,x,d)}}function Pjt(r,e,a=!1){return a&&(r=Ijt(r,e)),Array.isArray(r)?e.removeSubsets(r):e.getChildren(r)}function Ijt(r,e){let a=Array.isArray(r)?r.slice(0):[r],s=a.length;for(let l=0;l<s;l++){let d=iY(a[l],e);a.push(...d)}return a}var lY=d_e((r,e,a)=>r===uY.default.falseFunc||!e||e.length===0?[]:a.adapter.findAll(r,e)),e5=d_e((r,e,a)=>r===uY.default.falseFunc||!e||e.length===0?null:a.adapter.findOne(r,e));Ue();qt();Ue();var U_e=Or(fs(),1);qt();var X_e=Or(fs(),1),H_e=Or(fs(),1);qt();V0();gY();var DY=(r,e={})=>{let a=r._internal_store;if(!a){a={counts:{}},r._internal_store=a;for(let l of r){let d=l.type,x=l[`${d}_id`];if(!x)continue;let f=Number.parseInt(x.split("_").pop());Number.isNaN(f)||(a.counts[d]=Math.max(a.counts[d]??0,f))}}return new Proxy({},{get:(l,d)=>d==="toArray"?()=>r:{get:x=>r.find(f=>f.type===d&&f[`${d}_id`]===x),getUsing:x=>{let f=Object.keys(x);if(f.length!==1)throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");let m=f[0],D=m.replace("_id",""),b=r.find(E=>E.type===D&&E[m]===x[m]);return b?r.find(E=>E.type===d&&E[`${d}_id`]===b[`${d}_id`]):null},getWhere:x=>{let f=Object.keys(x);return r.find(m=>m.type===d&&f.every(D=>m[D]===x[D]))},list:x=>{let f=x?Object.keys(x):[];return r.filter(m=>m.type===d&&f.every(D=>m[D]===x[D]))},insert:x=>{var D;(D=a.counts)[d]??(D[d]=-1),a.counts[d]++;let f=a.counts[d],m={type:d,[`${d}_id`]:`${d}_${f}`,...x};return e.validateInserts&&(Yf[d]??Xf).parse(m),r.push(m),m},delete:x=>{let f=r.find(m=>m[`${d}_id`]===x);f&&r.splice(r.indexOf(f),1)},update:(x,f)=>{let m=r.find(D=>D[`${d}_id`]===x);if(m)return Object.assign(m,f),m},select:x=>{if(d==="source_component")return r.find(f=>f.type==="source_component"&&f.name===x.replace(/\./g,""));if(d==="pcb_port"||d==="source_port"||d==="schematic_port"){let[f,m]=x.replace(/\./g,"").split(/[\s\>]+/),D=r.find(E=>E.type==="source_component"&&E.name===f);if(!D)return null;let b=r.find(E=>E.type==="source_port"&&E.source_component_id===D.source_component_id&&(E.name===m||(E.port_hints??[]).includes(m)));if(!b)return null;if(d==="source_port")return b;if(d==="pcb_port")return r.find(E=>E.type==="pcb_port"&&E.source_port_id===b.source_port_id);if(d==="schematic_port")return r.find(E=>E.type==="schematic_port"&&E.source_port_id===b.source_port_id)}}}})};DY.unparsed=DY;var __e=DY;var Ssr=Or(R_e(),1);Fo();function td(r){let e=r.width/2,a=r.height/2;return{minX:r.center.x-e,maxX:r.center.x+e,minY:r.center.y-a,maxY:r.center.y+a}}function sg(r,e){let a=td(r),s=td(e),l=Math.max(a.minX-s.maxX,s.minX-a.maxX,0),d=Math.max(a.minY-s.maxY,s.minY-a.maxY,0),x={x:0,y:0},f={x:0,y:0};return l===0&&d===0?{distance:0,pointA:r.center,pointB:e.center}:(x.x=ms(r.center.x,s.minX,s.maxX),x.y=ms(r.center.y,s.minY,s.maxY),f.x=ms(e.center.x,a.minX,a.maxX),f.y=ms(e.center.y,a.minY,a.maxY),{distance:Math.hypot(x.x-f.x,x.y-f.y),pointA:x,pointB:f})}function ms(r,e,a){return Math.max(e,Math.min(a,r))}function zb(r,e){let a=Number.POSITIVE_INFINITY,s={x:0,y:0},l={x:0,y:0};for(let d of r)for(let x of e){let{distance:f,pointA:m,pointB:D}=sg(d,x);f<a&&(a=f,s=m,l=D)}return{pointA:s,pointB:l,distance:a}}Fo();Fo();var j_e="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var k_e=(r=21)=>{let e="",a=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=j_e[a[r]&63];return e};Fo();var u1=(r,e)=>Math.abs(r.x-e.x)+Math.abs(r.y-e.y),N_e=(r,e)=>{let a=e.x-r.x,s=e.y-r.y;return Math.abs(a)>Math.abs(s)?{dx:Math.sign(a),dy:0}:{dx:0,dy:Math.sign(s)}},z_e=(r,e,a)=>Math.abs(r.x-e.x)*Math.abs(a.dx)+Math.abs(r.y-e.y)*Math.abs(a.dy),q_e=(r,e=.1)=>`${Math.round(r.x/e)},${Math.round(r.y/e)}`,M_e=(r,e)=>Math.abs(r-e)<1e-4,V_e=(r,e,{viaDiameter:a=.5}={})=>{let s=[];for(let l=0;l<r.length-1;l++){let[d,x]=[r[l],r[l+1]],f=l-1>=0?r[l-1]:null,m=M_e(d.y,x.y),D=M_e(d.x,x.x);if(!m&&!D)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${d.x}, ${d.y}), end: (${x.x}, ${x.y})`);let b={type:"rect",layers:[d.layer],center:{x:(d.x+x.x)/2,y:(d.y+x.y)/2},width:m?Math.abs(d.x-x.x):.1,height:D?Math.abs(d.y-x.y):.1,connectedTo:[e]};if(s.push(b),f&&f.layer===d.layer&&d.layer!==x.layer){let E={type:"rect",layers:[d.layer,x.layer],center:{x:d.x,y:d.y},connectedTo:[e],width:a,height:a};s.push(E)}}return s},G_e=class{constructor(r){q(this,"obstacles");q(this,"GRID_STEP",.1);this.obstacles=r.map(e=>({...e,left:e.center.x-e.width/2,right:e.center.x+e.width/2,top:e.center.y+e.height/2,bottom:e.center.y-e.height/2}))}getObstacleAt(r,e,a){a??(a=this.GRID_STEP);for(let s of this.obstacles){let l=s.width/2+a,d=s.height/2+a;if(r>=s.center.x-l&&r<=s.center.x+l&&e>=s.center.y-d&&e<=s.center.y+d)return s}return null}isObstacleAt(r,e,a){return this.getObstacleAt(r,e,a)!==null}getDirectionDistancesToNearestObstacle(r,e){let{GRID_STEP:a}=this,s={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let l of this.obstacles)if(l.type==="rect"){let d=l.center.x-l.width/2-a,x=l.center.x+l.width/2+a,f=l.center.y+l.height/2+a,m=l.center.y-l.height/2-a;e>=m&&e<=f&&r>d&&(s.left=Math.min(s.left,r-x)),e>=m&&e<=f&&r<x&&(s.right=Math.min(s.right,d-r)),r>=d&&r<=x&&e<f&&(s.top=Math.min(s.top,m-e)),r>=d&&r<=x&&e>m&&(s.bottom=Math.min(s.bottom,e-f))}return s}getOrthoDirectionCollisionInfo(r,e,{margin:a=0}={}){let{x:s,y:l}=r,{dx:d,dy:x}=e,f=1/0,m=null;for(let D of this.obstacles){let b=D.left-a,E=D.right+a,A=D.top+a,B=D.bottom-a,w=null;d===1&&x===0?l>B&&l<A&&s<D.left&&(w=D.left-s):d===-1&&x===0?l>B&&l<A&&s>D.right&&(w=s-D.right):d===0&&x===1?s>b&&s<E&&l<D.bottom&&(w=D.bottom-l):d===0&&x===-1&&s>b&&s<E&&l>D.top&&(w=l-D.top),w!==null&&w<f&&(f=w,m=D)}return{dx:d,dy:x,wallDistance:f,obstacle:m}}getObstaclesOverlappingRegion(r){let e=[];for(let a of this.obstacles){let{left:s,right:l,top:d,bottom:x}=a;s<=r.maxX&&l>=r.minX&&d<=r.maxY&&x>=r.minY&&e.push(a)}return e}};function Ljt(r){if(r.length<4)return r;let e=[{...r[0]}],a=r[0].layer;for(let s=1;s<r.length;s++){let l={start:r[s-1],end:r[s]},d=r[s].route_type==="via"||r[s-1].route_type==="via";if(r[s].layer!==a||d){e.push({...r[s]}),a=r[s].layer;continue}let x=!1,f=null,m=-1;for(let b=0;b<e.length-1;b++){let E={start:e[b],end:e[b+1]};if(E.start.layer===l.start.layer&&E.start.layer===l.start.layer){let A=$jt(E,l);if(A){x=!0,f={...A,layer:a},m=b;break}}}x&&f&&(e.splice(m+1),e.push(f));let D=e[e.length-1];(D.x!==r[s].x||D.y!==r[s].y)&&e.push(r[s])}return e}function $jt(r,e){if(r.start.x===r.end.x&&e.start.x===e.end.x||r.start.y===r.end.y&&e.start.y===e.end.y)return null;let a;if(r.start.x===r.end.x){let s=r.start.x,l=e.start.y;a={...r.start,x:s,y:l}}else{let s=e.start.x,l=r.start.y;a={...r.start,x:s,y:l}}return O_e(a,r)&&O_e(a,e)?a:null}function O_e(r,e){return r.x>=Math.min(e.start.x,e.end.x)&&r.x<=Math.max(e.start.x,e.end.x)&&r.y>=Math.min(e.start.y,e.end.y)&&r.y<=Math.max(e.start.y,e.end.y)}function zjt(r){let e=[r[0]];for(let a=1;a<r.length-1;a++){let[s,l,d]=[r[a-1],r[a],r[a+1]];e.push(l),!(l.route_type!=="wire"||s.route_type!=="wire"||d.route_type!=="wire")&&s.layer===l.layer&&l.layer!==d.layer&&e.push({route_type:"via",from_layer:l.layer,to_layer:d.layer,x:l.x,y:l.y})}return e.push(r[r.length-1]),e}var Asr=(0,X_e.default)("autorouter:shortenPathWithShortcuts");function qjt(r,e){if(r.length<=2)return r;let a=[r[0]];for(let s=1;s<r.length;s++){let l={start:a[a.length-1],end:r[s]},d=-1,x=l.start.x===l.end.x,f=l.start.y===l.end.y;for(let m=s+1;m<r.length;m++){if(m<=d)continue;let D={start:r[m],end:r[m+1]};if(!D.end)continue;let b=D.start.x===D.end.x,E=D.start.y===D.end.y,A=x&&b,B=f&&E;if(B&&A||!(A||B))continue;let P=!1,j=Math.min(l.start.x,l.end.x),O=Math.max(l.start.x,l.end.x),z=Math.min(D.start.x,D.end.x),ee=Math.max(D.start.x,D.end.x),W=Math.min(l.start.y,l.end.y),re=Math.max(l.start.y,l.end.y),L=Math.min(D.start.y,D.end.y),K=Math.max(D.start.y,D.end.y);if(B?P=j<=ee&&O>=z:A&&(P=W<=K&&re>=L),!P)continue;let U=[],J=a[a.length-1],Q=r[m+2];if(!Q)continue;B&&z<O&&Q.x===z&&U.push({x:z,y:l.start.y,layer:l.start.layer}),B&&ee>j&&Q.x===ee&&U.push({x:ee,y:l.start.y,layer:l.start.layer}),A&&L<re&&Q.y===L&&U.push({x:l.start.x,y:L,layer:l.start.layer}),A&&K>W&&Q.y===K&&U.push({x:l.start.x,y:K,layer:l.start.layer});let de=null;for(let oe of U)if(!(e(J,oe)||e(Q,oe))){de=oe;break}if(de){a.push(de),s=m+1,d=m+1;break}}d===-1&&a.push(r[s])}return a[a.length-1]!==r[r.length-1]&&a.push(r[r.length-1]),a}var o1=(0,U_e.default)("autorouting-dataset:astar"),Y_e=class{constructor(r){q(this,"openSet",[]);q(this,"closedSet",new Set);q(this,"debug",!1);q(this,"debugSolutions");q(this,"debugMessage",null);q(this,"debugTraceCount",0);q(this,"input");q(this,"obstacles");q(this,"allObstacles");q(this,"startNode");q(this,"goalPoint");q(this,"GRID_STEP");q(this,"OBSTACLE_MARGIN");q(this,"MAX_ITERATIONS");q(this,"isRemovePathLoopsEnabled");q(this,"isShortenPathWithShortcutsEnabled");q(this,"GREEDY_MULTIPLIER",1.1);q(this,"iterations",-1);this.input=r.input,this.allObstacles=r.input.obstacles,this.startNode=r.startNode,this.goalPoint=r.goalPoint?{l:0,...r.goalPoint}:void 0,this.GRID_STEP=r.GRID_STEP??.1,this.OBSTACLE_MARGIN=r.OBSTACLE_MARGIN??.15,this.MAX_ITERATIONS=r.MAX_ITERATIONS??100,this.debug=r.debug??o1.enabled,this.isRemovePathLoopsEnabled=r.isRemovePathLoopsEnabled??!1,this.isShortenPathWithShortcutsEnabled=r.isShortenPathWithShortcutsEnabled??!1,this.debug&&(o1.enabled=!0),o1.enabled&&(this.debugSolutions={},this.debugMessage="")}getNeighbors(r){return[]}isSameNode(r,e){return u1(r,e)<this.GRID_STEP}computeG(r,e){return r.g+u1(r,e)}computeH(r){return u1(r,this.goalPoint)}getNodeName(r){return q_e(r,this.GRID_STEP)}solveOneStep(){this.iterations+=1;let{openSet:r,closedSet:e,GRID_STEP:a,goalPoint:s}=this;r.sort((f,m)=>f.f-m.f);let l=r.shift();if(this.computeH(l)<=a*2)return{solved:!0,current:l,newNeighbors:[]};this.closedSet.add(this.getNodeName(l));let x=[];for(let f of this.getNeighbors(l)){if(e.has(this.getNodeName(f)))continue;let m=this.computeG(l,f),D=this.openSet.find(b=>this.isSameNode(b,f));if(!D||m<D.g){let b=this.computeH(f),E=m+b*this.GREEDY_MULTIPLIER,A={...f,g:m,h:b,f:E,obstacleHit:f.obstacleHit??void 0,manDistFromParent:u1(l,f),nodesInPath:l.nodesInPath+1,parent:l,enterMarginCost:f.enterMarginCost,travelMarginCostFactor:f.travelMarginCostFactor};r.push(A),x.push(A)}}return o1.enabled&&(r.sort((f,m)=>f.f-m.f),this.drawDebugSolution({current:l,newNeighbors:x})),{solved:!1,current:l,newNeighbors:x}}getStartNode(r){return{x:r.pointsToConnect[0].x,y:r.pointsToConnect[0].y,manDistFromParent:0,f:0,g:0,h:0,nodesInPath:0,parent:null}}layerToIndex(r){return 0}indexToLayer(r){return"top"}preprocessConnectionBeforeSolving(r){return r}solveConnection(r){if(r.pointsToConnect.length>2)throw new Error("GeneralizedAstarAutorouter doesn't currently support 2+ points in a connection");r=this.preprocessConnectionBeforeSolving(r);let{pointsToConnect:e}=r;for(this.iterations=0,this.closedSet=new Set,this.startNode=this.getStartNode(r),this.goalPoint={...e[e.length-1],l:this.layerToIndex(e[e.length-1].layer)},this.openSet=[this.startNode];this.iterations<this.MAX_ITERATIONS;){let{solved:a,current:s}=this.solveOneStep();if(a){let l=[],d=s;for(;d;){let x=d.l;l.unshift({x:d.x,y:d.y,layer:x!==void 0?this.indexToLayer(x):e[0].layer}),d=d.parent}return o1.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations
|
|
951
|
+
)`,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 Qu=Or(e1(),1);var aY={};function sY(r,e){return r===Qu.default.falseFunc?Qu.default.falseFunc:a=>e.isTag(a)&&r(a)}function iY(r,e){let a=e.getSiblings(r);if(a.length<=1)return[];let s=a.indexOf(r);return s<0||s===a.length-1?[]:a.slice(s+1).filter(e.isTag)}function nY(r){return{xmlMode:!!r.xmlMode,lowerCaseAttributeNames:!!r.lowerCaseAttributeNames,lowerCaseTags:!!r.lowerCaseTags,quirksMode:!!r.quirksMode,cacheResults:!!r.cacheResults,pseudos:r.pseudos,adapter:r.adapter,equals:r.equals}}var rY=(r,e,a,s,l)=>{let d=l(e,nY(a),s);return d===Qu.default.trueFunc?r:d===Qu.default.falseFunc?Qu.default.falseFunc:x=>d(x)&&r(x)},JR={is:rY,matches:rY,where:rY,not(r,e,a,s,l){let d=l(e,nY(a),s);return d===Qu.default.falseFunc?r:d===Qu.default.trueFunc?Qu.default.falseFunc:x=>!d(x)&&r(x)},has(r,e,a,s,l){let{adapter:d}=a,x=nY(a);x.relativeSelector=!0;let f=e.some(b=>b.some(Ib))?[aY]:void 0,m=l(e,x,f);if(m===Qu.default.falseFunc)return Qu.default.falseFunc;let D=sY(m,d);if(f&&m!==Qu.default.trueFunc){let{shouldTestNextSiblings:b=!1}=m;return E=>{if(!r(E))return!1;f[0]=E;let A=d.getChildren(E),B=b?[...A,...iY(E,d)]:A;return d.existsOne(D,B)}}return b=>r(b)&&d.existsOne(D,d.getChildren(b))}};function s_e(r,e,a,s,l){var d;let{name:x,data:f}=e;if(Array.isArray(f)){if(!(x in JR))throw new Error(`Unknown pseudo-class :${x}(${f})`);return JR[x](r,f,a,s,l)}let m=(d=a.pseudos)===null||d===void 0?void 0:d[x],D=typeof m=="string"?m:tY[x];if(typeof D=="string"){if(f!=null)throw new Error(`Pseudo ${x} doesn't have any arguments`);let b=Pb(D);return JR.is(r,b,a,s,l)}if(typeof m=="function")return eY(m,x,f,1),b=>m(b,f)&&r(b);if(x in kb)return kb[x](r,f,a,s);if(x in KR){let b=KR[x];return eY(b,x,f,2),E=>b(E,a,f)&&r(E)}throw new Error(`Unknown pseudo-class :${x}`)}function oY(r,e){let a=e.getParent(r);return a&&e.isTag(a)?a:null}function i_e(r,e,a,s,l){let{adapter:d,equals:x}=a;switch(e.type){case Jr.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case Jr.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case Jr.Attribute:{if(e.namespace!=null)throw new Error("Namespaced attributes are not yet supported by css-select");return(!a.xmlMode||a.lowerCaseAttributeNames)&&(e.name=e.name.toLowerCase()),t_e[e.action](r,e,a)}case Jr.Pseudo:return s_e(r,e,a,s,l);case Jr.Tag:{if(e.namespace!=null)throw new Error("Namespaced tag names are not yet supported by css-select");let{name:f}=e;return(!a.xmlMode||a.lowerCaseTags)&&(f=f.toLowerCase()),function(D){return d.getName(D)===f&&r(D)}}case Jr.Descendant:{if(a.cacheResults===!1||typeof WeakSet>"u")return function(D){let b=D;for(;b=oY(b,d);)if(r(b))return!0;return!1};let f=new WeakSet;return function(D){let b=D;for(;b=oY(b,d);)if(!f.has(b)){if(d.isTag(b)&&r(b))return!0;f.add(b)}return!1}}case"_flexibleDescendant":return function(m){let D=m;do if(r(D))return!0;while(D=oY(D,d));return!1};case Jr.Parent:return function(m){return d.getChildren(m).some(D=>d.isTag(D)&&r(D))};case Jr.Child:return function(m){let D=d.getParent(m);return D!=null&&d.isTag(D)&&r(D)};case Jr.Sibling:return function(m){let D=d.getSiblings(m);for(let b=0;b<D.length;b++){let E=D[b];if(x(m,E))break;if(d.isTag(E)&&r(E))return!0}return!1};case Jr.Adjacent:return d.prevElementSibling?function(m){let D=d.prevElementSibling(m);return D!=null&&r(D)}:function(m){let D=d.getSiblings(m),b;for(let E=0;E<D.length;E++){let A=D[E];if(x(m,A))break;d.isTag(A)&&(b=A)}return!!b&&r(b)};case Jr.Universal:{if(e.namespace!=null&&e.namespace!=="*")throw new Error("Namespaced universal selectors are not yet supported by css-select");return r}}}function o_e(r,e,a){let s=ZR(r,e,a);return sY(s,e.adapter)}function ZR(r,e,a){let s=typeof r=="string"?Pb(r):r;return QR(s,e,a)}function u_e(r){return r.type===Jr.Pseudo&&(r.name==="scope"||Array.isArray(r.data)&&r.data.some(e=>e.some(u_e)))}var _jt={type:Jr.Descendant},Ajt={type:"_flexibleDescendant"},Rjt={type:Jr.Pseudo,name:"scope",data:null};function Sjt(r,{adapter:e},a){let s=!!a?.every(l=>{let d=e.isTag(l)&&e.getParent(l);return l===aY||d&&e.isTag(d)});for(let l of r){if(!(l.length>0&&Ib(l[0])&&l[0].type!==Jr.Descendant))if(s&&!l.some(u_e))l.unshift(_jt);else continue;l.unshift(Rjt)}}function QR(r,e,a){var s;r.forEach(JX),a=(s=e.context)!==null&&s!==void 0?s:a;let l=Array.isArray(a),d=a&&(Array.isArray(a)?a:[a]);if(e.relativeSelector!==!1)Sjt(r,e,d);else if(r.some(m=>m.length>0&&Ib(m[0])))throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");let x=!1,f=r.map(m=>{if(m.length>=2){let[D,b]=m;D.type!==Jr.Pseudo||D.name!=="scope"||(l&&b.type===Jr.Descendant?m[1]=Ajt:(b.type===Jr.Adjacent||b.type===Jr.Sibling)&&(x=!0))}return Bjt(m,e,d)}).reduce(wjt,ed.default.falseFunc);return f.shouldTestNextSiblings=x,f}function Bjt(r,e,a){var s;return r.reduce((l,d)=>l===ed.default.falseFunc?ed.default.falseFunc:i_e(l,d,e,a,QR),(s=e.rootFunc)!==null&&s!==void 0?s:ed.default.trueFunc)}function wjt(r,e){return e===ed.default.falseFunc||r===ed.default.trueFunc?r:r===ed.default.falseFunc||e===ed.default.trueFunc?e:function(s){return r(s)||e(s)}}var c_e=(r,e)=>r===e,Tjt={adapter:HR,equals:c_e};function l_e(r){var e,a,s,l;let d=r??Tjt;return(e=d.adapter)!==null&&e!==void 0||(d.adapter=HR),(a=d.equals)!==null&&a!==void 0||(d.equals=(l=(s=d.adapter)===null||s===void 0?void 0:s.equals)!==null&&l!==void 0?l:c_e),d}function cY(r){return function(a,s,l){let d=l_e(s);return r(a,d,l)}}var Enr=cY(o_e),vnr=cY(ZR),Cnr=cY(QR);function d_e(r){return function(a,s,l){let d=l_e(l);typeof a!="function"&&(a=ZR(a,d,s));let x=Pjt(s,d.adapter,a.shouldTestNextSiblings);return r(a,x,d)}}function Pjt(r,e,a=!1){return a&&(r=Ijt(r,e)),Array.isArray(r)?e.removeSubsets(r):e.getChildren(r)}function Ijt(r,e){let a=Array.isArray(r)?r.slice(0):[r],s=a.length;for(let l=0;l<s;l++){let d=iY(a[l],e);a.push(...d)}return a}var lY=d_e((r,e,a)=>r===uY.default.falseFunc||!e||e.length===0?[]:a.adapter.findAll(r,e)),e5=d_e((r,e,a)=>r===uY.default.falseFunc||!e||e.length===0?null:a.adapter.findOne(r,e));Ue();qt();Ue();var U_e=Or(fs(),1);qt();var X_e=Or(fs(),1),H_e=Or(fs(),1);qt();V0();gY();var DY=(r,e={})=>{let a=r._internal_store;if(!a){a={counts:{}},r._internal_store=a;for(let l of r){let d=l.type,x=l[`${d}_id`];if(!x)continue;let f=Number.parseInt(x.split("_").pop());Number.isNaN(f)||(a.counts[d]=Math.max(a.counts[d]??0,f))}}return new Proxy({},{get:(l,d)=>d==="toArray"?()=>r:{get:x=>r.find(f=>f.type===d&&f[`${d}_id`]===x),getUsing:x=>{let f=Object.keys(x);if(f.length!==1)throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");let m=f[0],D=m.replace("_id",""),b=r.find(E=>E.type===D&&E[m]===x[m]);return b?r.find(E=>E.type===d&&E[`${d}_id`]===b[`${d}_id`]):null},getWhere:x=>{let f=Object.keys(x);return r.find(m=>m.type===d&&f.every(D=>m[D]===x[D]))},list:x=>{let f=x?Object.keys(x):[];return r.filter(m=>m.type===d&&f.every(D=>m[D]===x[D]))},insert:x=>{var D;(D=a.counts)[d]??(D[d]=-1),a.counts[d]++;let f=a.counts[d],m={type:d,[`${d}_id`]:`${d}_${f}`,...x};return e.validateInserts&&(Yf[d]??Xf).parse(m),r.push(m),m},delete:x=>{let f=r.find(m=>m[`${d}_id`]===x);f&&r.splice(r.indexOf(f),1)},update:(x,f)=>{let m=r.find(D=>D.type===d&&D[`${d}_id`]===x);if(m)return Object.assign(m,f),m},select:x=>{if(d==="source_component")return r.find(f=>f.type==="source_component"&&f.name===x.replace(/\./g,""));if(d==="pcb_port"||d==="source_port"||d==="schematic_port"){let[f,m]=x.replace(/\./g,"").split(/[\s\>]+/),D=r.find(E=>E.type==="source_component"&&E.name===f);if(!D)return null;let b=r.find(E=>E.type==="source_port"&&E.source_component_id===D.source_component_id&&(E.name===m||(E.port_hints??[]).includes(m)));if(!b)return null;if(d==="source_port")return b;if(d==="pcb_port")return r.find(E=>E.type==="pcb_port"&&E.source_port_id===b.source_port_id);if(d==="schematic_port")return r.find(E=>E.type==="schematic_port"&&E.source_port_id===b.source_port_id)}}}})};DY.unparsed=DY;var __e=DY;var Ssr=Or(R_e(),1);Fo();function td(r){let e=r.width/2,a=r.height/2;return{minX:r.center.x-e,maxX:r.center.x+e,minY:r.center.y-a,maxY:r.center.y+a}}function sg(r,e){let a=td(r),s=td(e),l=Math.max(a.minX-s.maxX,s.minX-a.maxX,0),d=Math.max(a.minY-s.maxY,s.minY-a.maxY,0),x={x:0,y:0},f={x:0,y:0};return l===0&&d===0?{distance:0,pointA:r.center,pointB:e.center}:(x.x=ms(r.center.x,s.minX,s.maxX),x.y=ms(r.center.y,s.minY,s.maxY),f.x=ms(e.center.x,a.minX,a.maxX),f.y=ms(e.center.y,a.minY,a.maxY),{distance:Math.hypot(x.x-f.x,x.y-f.y),pointA:x,pointB:f})}function ms(r,e,a){return Math.max(e,Math.min(a,r))}function zb(r,e){let a=Number.POSITIVE_INFINITY,s={x:0,y:0},l={x:0,y:0};for(let d of r)for(let x of e){let{distance:f,pointA:m,pointB:D}=sg(d,x);f<a&&(a=f,s=m,l=D)}return{pointA:s,pointB:l,distance:a}}Fo();Fo();var j_e="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var k_e=(r=21)=>{let e="",a=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=j_e[a[r]&63];return e};Fo();var u1=(r,e)=>Math.abs(r.x-e.x)+Math.abs(r.y-e.y),N_e=(r,e)=>{let a=e.x-r.x,s=e.y-r.y;return Math.abs(a)>Math.abs(s)?{dx:Math.sign(a),dy:0}:{dx:0,dy:Math.sign(s)}},z_e=(r,e,a)=>Math.abs(r.x-e.x)*Math.abs(a.dx)+Math.abs(r.y-e.y)*Math.abs(a.dy),q_e=(r,e=.1)=>`${Math.round(r.x/e)},${Math.round(r.y/e)}`,M_e=(r,e)=>Math.abs(r-e)<1e-4,V_e=(r,e,{viaDiameter:a=.5}={})=>{let s=[];for(let l=0;l<r.length-1;l++){let[d,x]=[r[l],r[l+1]],f=l-1>=0?r[l-1]:null,m=M_e(d.y,x.y),D=M_e(d.x,x.x);if(!m&&!D)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${d.x}, ${d.y}), end: (${x.x}, ${x.y})`);let b={type:"rect",layers:[d.layer],center:{x:(d.x+x.x)/2,y:(d.y+x.y)/2},width:m?Math.abs(d.x-x.x):.1,height:D?Math.abs(d.y-x.y):.1,connectedTo:[e]};if(s.push(b),f&&f.layer===d.layer&&d.layer!==x.layer){let E={type:"rect",layers:[d.layer,x.layer],center:{x:d.x,y:d.y},connectedTo:[e],width:a,height:a};s.push(E)}}return s},G_e=class{constructor(r){q(this,"obstacles");q(this,"GRID_STEP",.1);this.obstacles=r.map(e=>({...e,left:e.center.x-e.width/2,right:e.center.x+e.width/2,top:e.center.y+e.height/2,bottom:e.center.y-e.height/2}))}getObstacleAt(r,e,a){a??(a=this.GRID_STEP);for(let s of this.obstacles){let l=s.width/2+a,d=s.height/2+a;if(r>=s.center.x-l&&r<=s.center.x+l&&e>=s.center.y-d&&e<=s.center.y+d)return s}return null}isObstacleAt(r,e,a){return this.getObstacleAt(r,e,a)!==null}getDirectionDistancesToNearestObstacle(r,e){let{GRID_STEP:a}=this,s={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let l of this.obstacles)if(l.type==="rect"){let d=l.center.x-l.width/2-a,x=l.center.x+l.width/2+a,f=l.center.y+l.height/2+a,m=l.center.y-l.height/2-a;e>=m&&e<=f&&r>d&&(s.left=Math.min(s.left,r-x)),e>=m&&e<=f&&r<x&&(s.right=Math.min(s.right,d-r)),r>=d&&r<=x&&e<f&&(s.top=Math.min(s.top,m-e)),r>=d&&r<=x&&e>m&&(s.bottom=Math.min(s.bottom,e-f))}return s}getOrthoDirectionCollisionInfo(r,e,{margin:a=0}={}){let{x:s,y:l}=r,{dx:d,dy:x}=e,f=1/0,m=null;for(let D of this.obstacles){let b=D.left-a,E=D.right+a,A=D.top+a,B=D.bottom-a,w=null;d===1&&x===0?l>B&&l<A&&s<D.left&&(w=D.left-s):d===-1&&x===0?l>B&&l<A&&s>D.right&&(w=s-D.right):d===0&&x===1?s>b&&s<E&&l<D.bottom&&(w=D.bottom-l):d===0&&x===-1&&s>b&&s<E&&l>D.top&&(w=l-D.top),w!==null&&w<f&&(f=w,m=D)}return{dx:d,dy:x,wallDistance:f,obstacle:m}}getObstaclesOverlappingRegion(r){let e=[];for(let a of this.obstacles){let{left:s,right:l,top:d,bottom:x}=a;s<=r.maxX&&l>=r.minX&&d<=r.maxY&&x>=r.minY&&e.push(a)}return e}};function Ljt(r){if(r.length<4)return r;let e=[{...r[0]}],a=r[0].layer;for(let s=1;s<r.length;s++){let l={start:r[s-1],end:r[s]},d=r[s].route_type==="via"||r[s-1].route_type==="via";if(r[s].layer!==a||d){e.push({...r[s]}),a=r[s].layer;continue}let x=!1,f=null,m=-1;for(let b=0;b<e.length-1;b++){let E={start:e[b],end:e[b+1]};if(E.start.layer===l.start.layer&&E.start.layer===l.start.layer){let A=$jt(E,l);if(A){x=!0,f={...A,layer:a},m=b;break}}}x&&f&&(e.splice(m+1),e.push(f));let D=e[e.length-1];(D.x!==r[s].x||D.y!==r[s].y)&&e.push(r[s])}return e}function $jt(r,e){if(r.start.x===r.end.x&&e.start.x===e.end.x||r.start.y===r.end.y&&e.start.y===e.end.y)return null;let a;if(r.start.x===r.end.x){let s=r.start.x,l=e.start.y;a={...r.start,x:s,y:l}}else{let s=e.start.x,l=r.start.y;a={...r.start,x:s,y:l}}return O_e(a,r)&&O_e(a,e)?a:null}function O_e(r,e){return r.x>=Math.min(e.start.x,e.end.x)&&r.x<=Math.max(e.start.x,e.end.x)&&r.y>=Math.min(e.start.y,e.end.y)&&r.y<=Math.max(e.start.y,e.end.y)}function zjt(r){let e=[r[0]];for(let a=1;a<r.length-1;a++){let[s,l,d]=[r[a-1],r[a],r[a+1]];e.push(l),!(l.route_type!=="wire"||s.route_type!=="wire"||d.route_type!=="wire")&&s.layer===l.layer&&l.layer!==d.layer&&e.push({route_type:"via",from_layer:l.layer,to_layer:d.layer,x:l.x,y:l.y})}return e.push(r[r.length-1]),e}var Asr=(0,X_e.default)("autorouter:shortenPathWithShortcuts");function qjt(r,e){if(r.length<=2)return r;let a=[r[0]];for(let s=1;s<r.length;s++){let l={start:a[a.length-1],end:r[s]},d=-1,x=l.start.x===l.end.x,f=l.start.y===l.end.y;for(let m=s+1;m<r.length;m++){if(m<=d)continue;let D={start:r[m],end:r[m+1]};if(!D.end)continue;let b=D.start.x===D.end.x,E=D.start.y===D.end.y,A=x&&b,B=f&&E;if(B&&A||!(A||B))continue;let P=!1,j=Math.min(l.start.x,l.end.x),O=Math.max(l.start.x,l.end.x),z=Math.min(D.start.x,D.end.x),ee=Math.max(D.start.x,D.end.x),W=Math.min(l.start.y,l.end.y),re=Math.max(l.start.y,l.end.y),L=Math.min(D.start.y,D.end.y),K=Math.max(D.start.y,D.end.y);if(B?P=j<=ee&&O>=z:A&&(P=W<=K&&re>=L),!P)continue;let U=[],J=a[a.length-1],Q=r[m+2];if(!Q)continue;B&&z<O&&Q.x===z&&U.push({x:z,y:l.start.y,layer:l.start.layer}),B&&ee>j&&Q.x===ee&&U.push({x:ee,y:l.start.y,layer:l.start.layer}),A&&L<re&&Q.y===L&&U.push({x:l.start.x,y:L,layer:l.start.layer}),A&&K>W&&Q.y===K&&U.push({x:l.start.x,y:K,layer:l.start.layer});let de=null;for(let oe of U)if(!(e(J,oe)||e(Q,oe))){de=oe;break}if(de){a.push(de),s=m+1,d=m+1;break}}d===-1&&a.push(r[s])}return a[a.length-1]!==r[r.length-1]&&a.push(r[r.length-1]),a}var o1=(0,U_e.default)("autorouting-dataset:astar"),Y_e=class{constructor(r){q(this,"openSet",[]);q(this,"closedSet",new Set);q(this,"debug",!1);q(this,"debugSolutions");q(this,"debugMessage",null);q(this,"debugTraceCount",0);q(this,"input");q(this,"obstacles");q(this,"allObstacles");q(this,"startNode");q(this,"goalPoint");q(this,"GRID_STEP");q(this,"OBSTACLE_MARGIN");q(this,"MAX_ITERATIONS");q(this,"isRemovePathLoopsEnabled");q(this,"isShortenPathWithShortcutsEnabled");q(this,"GREEDY_MULTIPLIER",1.1);q(this,"iterations",-1);this.input=r.input,this.allObstacles=r.input.obstacles,this.startNode=r.startNode,this.goalPoint=r.goalPoint?{l:0,...r.goalPoint}:void 0,this.GRID_STEP=r.GRID_STEP??.1,this.OBSTACLE_MARGIN=r.OBSTACLE_MARGIN??.15,this.MAX_ITERATIONS=r.MAX_ITERATIONS??100,this.debug=r.debug??o1.enabled,this.isRemovePathLoopsEnabled=r.isRemovePathLoopsEnabled??!1,this.isShortenPathWithShortcutsEnabled=r.isShortenPathWithShortcutsEnabled??!1,this.debug&&(o1.enabled=!0),o1.enabled&&(this.debugSolutions={},this.debugMessage="")}getNeighbors(r){return[]}isSameNode(r,e){return u1(r,e)<this.GRID_STEP}computeG(r,e){return r.g+u1(r,e)}computeH(r){return u1(r,this.goalPoint)}getNodeName(r){return q_e(r,this.GRID_STEP)}solveOneStep(){this.iterations+=1;let{openSet:r,closedSet:e,GRID_STEP:a,goalPoint:s}=this;r.sort((f,m)=>f.f-m.f);let l=r.shift();if(this.computeH(l)<=a*2)return{solved:!0,current:l,newNeighbors:[]};this.closedSet.add(this.getNodeName(l));let x=[];for(let f of this.getNeighbors(l)){if(e.has(this.getNodeName(f)))continue;let m=this.computeG(l,f),D=this.openSet.find(b=>this.isSameNode(b,f));if(!D||m<D.g){let b=this.computeH(f),E=m+b*this.GREEDY_MULTIPLIER,A={...f,g:m,h:b,f:E,obstacleHit:f.obstacleHit??void 0,manDistFromParent:u1(l,f),nodesInPath:l.nodesInPath+1,parent:l,enterMarginCost:f.enterMarginCost,travelMarginCostFactor:f.travelMarginCostFactor};r.push(A),x.push(A)}}return o1.enabled&&(r.sort((f,m)=>f.f-m.f),this.drawDebugSolution({current:l,newNeighbors:x})),{solved:!1,current:l,newNeighbors:x}}getStartNode(r){return{x:r.pointsToConnect[0].x,y:r.pointsToConnect[0].y,manDistFromParent:0,f:0,g:0,h:0,nodesInPath:0,parent:null}}layerToIndex(r){return 0}indexToLayer(r){return"top"}preprocessConnectionBeforeSolving(r){return r}solveConnection(r){if(r.pointsToConnect.length>2)throw new Error("GeneralizedAstarAutorouter doesn't currently support 2+ points in a connection");r=this.preprocessConnectionBeforeSolving(r);let{pointsToConnect:e}=r;for(this.iterations=0,this.closedSet=new Set,this.startNode=this.getStartNode(r),this.goalPoint={...e[e.length-1],l:this.layerToIndex(e[e.length-1].layer)},this.openSet=[this.startNode];this.iterations<this.MAX_ITERATIONS;){let{solved:a,current:s}=this.solveOneStep();if(a){let l=[],d=s;for(;d;){let x=d.l;l.unshift({x:d.x,y:d.y,layer:x!==void 0?this.indexToLayer(x):e[0].layer}),d=d.parent}return o1.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations
|
|
952
952
|
`),this.isRemovePathLoopsEnabled&&(l=Ljt(l)),this.isShortenPathWithShortcutsEnabled&&(l=qjt(l,(x,f)=>{if(x.x===f.x&&x.y===f.y)return!1;let m=this.obstacles.getOrthoDirectionCollisionInfo({x:x.x,y:x.y,l:this.layerToIndex(x.layer)??0},{dx:Math.sign(f.x-x.x),dy:Math.sign(f.y-x.y),dl:0},{margin:.05}),D=Math.sqrt((x.x-f.x)**2+(x.y-f.y)**2);return m.wallDistance<D})),{solved:!0,route:l,connectionName:r.name}}if(this.openSet.length===0)break}return o1.enabled&&(this.debugMessage+=`t${this.debugTraceCount}: ${this.iterations} iterations (failed)
|
|
953
953
|
`),{solved:!1,connectionName:r.name}}createObstacleList({dominantLayer:r,connection:e,obstaclesFromTraces:a}){return new G_e(this.allObstacles.filter(s=>!s.connectedTo.includes(e.name)).filter(s=>s.layers.includes(r)).concat(a??[]))}postprocessConnectionSolveResult(r,e){return e}solve(){let r=[],e=[];this.debugTraceCount=0;for(let a of this.input.connections){let s=a.pointsToConnect[0].layer??"top";this.debugTraceCount+=1,this.obstacles=this.createObstacleList({dominantLayer:s,connection:a,obstaclesFromTraces:e});let l=this.solveConnection(a);l=this.postprocessConnectionSolveResult(a,l),r.push(l),o1.enabled&&this.drawDebugTraceObstacles(e),l.solved&&e.push(...V_e(l.route.map(d=>({x:d.x,y:d.y,layer:d.layer??s})),a.name))}return r}solveAndMapToTraces(){return this.solve().flatMap(e=>e.solved?[{type:"pcb_trace",pcb_trace_id:`pcb_trace_for_${e.connectionName}`,route:zjt(e.route.map(a=>({route_type:"wire",x:a.x,y:a.y,width:this.input.minTraceWidth,layer:a.layer})))}]:[])}getDebugGroup(){let r=`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?r:null}drawDebugTraceObstacles(r){let{debugTraceCount:e,debugSolutions:a}=this;for(let s in a)s.startsWith(`t${e}_`)&&a[s].push(...r.map((l,d)=>({type:"pcb_smtpad",pcb_component_id:"",layer:l.layers[0],width:l.width,shape:"rect",x:l.center.x,y:l.center.y,pcb_smtpad_id:`trace_obstacle_${d}`,height:l.height})))}drawDebugSolution({current:r,newNeighbors:e}){let a=this.getDebugGroup();if(!a)return;let{openSet:s,debugTraceCount:l,debugSolutions:d}=this;d[a]??(d[a]=[]);let x=d[a];x.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${r.x}_${r.y}`,font:"tscircuit2024",font_size:.25,text:"X"+(r.l!==void 0?r.l:""),pcb_component_id:"",layer:"top",anchor_position:{x:r.x,y:r.y},anchor_alignment:"center"});for(let f=0;f<s.length;f++){let m=s[f];x.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${m.x}_${m.y}`,layer:"top",route:[[0,.05],[.05,0],[0,-.05],[-.05,0],[0,.05]].map(([D,b])=>({x:m.x+D,y:m.y+b})),stroke_width:.01}),x.push({type:"pcb_fabrication_note_text",pcb_fabrication_note_text_id:`debug_note_${m.x}_${m.y}`,font:"tscircuit2024",font_size:.03,text:f.toString(),pcb_component_id:"",layer:"top",anchor_position:{x:m.x,y:m.y},anchor_alignment:"center"})}if(r.parent){let f=[],m=r;for(;m;)f.unshift(m),m=m.parent;x.push({type:"pcb_fabrication_note_path",pcb_component_id:"",pcb_fabrication_note_path_id:`note_path_${r.x}_${r.y}`,layer:"top",route:f,stroke_width:.01})}}},Ujt=(0,H_e.default)("autorouting-dataset:infinite-grid-ijump-astar:get-distance-to-overcome-obstacle");function EY({node:r,travelDir:e,wallDir:a,obstacle:s,obstacles:l,obstaclesInRow:d=0,OBSTACLE_MARGIN:x=.15,SHOULD_DETECT_CONJOINED_OBSTACLES:f=!1,MAX_CONJOINED_OBSTACLES:m=20}){let D;if(e.dx===0?e.dy>0?D=s.center.y+s.height/2-r.y:D=r.y-(s.center.y-s.height/2):e.dx>0?D=s.center.x+s.width/2-r.x:D=r.x-(s.center.x-s.width/2),D+=x,f&&d<m){let b=l.getObstacleAt(r.x+e.dx*D+a.dx*(a.wallDistance+.001),r.y+e.dy*D+a.dy*(a.wallDistance+.001));if(b===s)return D;if(b&&b.type==="rect"){let E=e.dy===0,A=E?s.height:s.width;if((E?b.height:b.width)>A)return Ujt("next obstacle on path is bigger, not trying to overcome it"),D;let w=EY({node:{x:r.x+e.dx*D,y:r.y+e.dy*D},travelDir:e,wallDir:a,obstacle:b,obstacles:l,obstaclesInRow:d+1,SHOULD_DETECT_CONJOINED_OBSTACLES:f,MAX_CONJOINED_OBSTACLES:m,OBSTACLE_MARGIN:x});D+=w}}return D}var Vjt=class extends Y_e{constructor(){super(...arguments);q(this,"MAX_ITERATIONS",200)}getNeighbors(e){let a=this.obstacles,s=this.goalPoint,l;e.parent?l=N_e(e.parent,e):l=N_e(e,s);let d=[{dx:0,dy:1},{dx:1,dy:0},{dx:0,dy:-1},{dx:-1,dy:0}].filter(f=>f.dx===l.dx*-1&&f.dy===l.dy*-1?!1:!(f.dx===l.dx&&f.dy===l.dy&&e.parent?.obstacleHit)).map(f=>a.getOrthoDirectionCollisionInfo(e,f,{margin:this.OBSTACLE_MARGIN})).filter(f=>f.wallDistance>=this.OBSTACLE_MARGIN),x=[];for(let f of d){let m=null;e?.obstacleHit&&(m=EY({node:e,travelDir:f,wallDir:{...l,wallDistance:this.OBSTACLE_MARGIN},obstacle:e.obstacleHit,obstacles:a,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let D=z_e(e,s,f),b=(f.dx===0||Math.sign(s.x-e.x)===f.dx)&&(f.dy===0||Math.sign(s.y-e.y)===f.dy);D<f.wallDistance&&D>0&&b?x.push({...f,travelDistance:D}):m!==null&&m<f.wallDistance?x.push({...f,travelDistance:m}):f.wallDistance!==1/0&&x.push({...f,travelDistance:f.wallDistance-this.OBSTACLE_MARGIN})}return x.filter(f=>!a.isObstacleAt(e.x+f.dx*f.travelDistance,e.y+f.dy*f.travelDistance)).map(f=>({x:e.x+f.dx*f.travelDistance,y:e.y+f.dy*f.travelDistance,obstacleHit:f.obstacle}))}};function Gjt(r,e=4){let{center:a,width:s,height:l,rotation:d}=r,x=[],f=d*Math.PI/180,m=Math.cos(f),D=Math.sin(f),b=(d%360+360)%360;if(l<=s?b>=45&&b<135||b>=225&&b<315:b>=135&&b<225||b>=315||b<45){let A=s/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*m,j=-w*D,O=A*1.1,z=Math.abs(l*m)+Math.abs(A*D);x.push({center:{x:a.x+P,y:a.y+j},width:O,height:z})}}else{let A=l/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*D,j=w*m,O=Math.abs(s*m)+Math.abs(A*D),z=A*1.1;x.push({center:{x:a.x+P,y:a.y+j},width:O,height:z})}}return x}var i5=["top","inner1","inner2","bottom"],W_e=(r,e)=>{let a=l=>e?l.concat(l.map(d=>e?.getNetConnectedToId(d)).filter(Boolean)):l,s=[];for(let l of r)if(l.type==="pcb_smtpad"){if(l.shape==="circle")s.push({type:"oval",layers:[l.layer],center:{x:l.x,y:l.y},width:l.radius*2,height:l.radius*2,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rect")s.push({type:"rect",layers:[l.layer],center:{x:l.x,y:l.y},width:l.width,height:l.height,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rotated_rect"){let d={center:{x:l.x,y:l.y},width:l.width,height:l.height,rotation:l.ccw_rotation},x=Gjt(d);for(let f of x)s.push({type:"rect",layers:[l.layer],center:f.center,width:f.width,height:f.height,connectedTo:a([l.pcb_smtpad_id])})}}else if(l.type==="pcb_keepout")l.shape==="circle"?s.push({type:"oval",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.radius*2,height:l.radius*2,connectedTo:[]}):l.shape==="rect"&&s.push({type:"rect",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.type==="pcb_hole")l.hole_shape==="oval"?s.push({type:"oval",center:{x:l.x,y:l.y},width:l.hole_width,height:l.hole_height,connectedTo:[]}):l.hole_shape==="square"?s.push({type:"rect",layers:i5,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]}):(l.hole_shape==="round"||l.hole_shape==="circle")&&s.push({type:"rect",layers:i5,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]});else if(l.type==="pcb_plated_hole")l.shape==="circle"?s.push({type:"oval",layers:i5,center:{x:l.x,y:l.y},width:l.outer_diameter,height:l.outer_diameter,connectedTo:a([l.pcb_plated_hole_id])}):(l.shape==="oval"||l.shape==="pill")&&s.push({type:"oval",layers:i5,center:{x:l.x,y:l.y},width:l.outer_width,height:l.outer_height,connectedTo:a([l.pcb_plated_hole_id])});else if(l.type==="pcb_trace"){let d=V_e(l.route.map(x=>({x:x.x,y:x.y,layer:"layer"in x?x.layer:x.from_layer})),l.source_trace_id);s.push(...d)}else l.type==="pcb_via"&&s.push({type:"rect",layers:l.layers,center:{x:l.x,y:l.y},connectedTo:[],width:l.outer_diameter,height:l.outer_diameter});return s};function L_e(r){let{pcbConnMap:e,goalElementId:a}=r;if(!a.startsWith("pcb_port_"))throw new Error(`Currently alternative goal boxes must have a goal id with prefix "pcb_port_" (got ${a})`);let s=e.getAllTracesConnectedToPort(a);return W_e(s).map(l=>({...l,connectedTo:[a]}))}var K_e=r=>{let{connection:e,pcbConnMap:a}=r;if(e.pointsToConnect.length!==2)throw new Error(`Connection must have exactly 2 points for alternative goal boxes (got ${e.pointsToConnect.length})`);let[s,l]=e.pointsToConnect;if(!s.pcb_port_id||!l.pcb_port_id)throw new Error(`Connection points must have pcb_port_id for alternative goal box calculation (got ${s.pcb_port_id} and ${l.pcb_port_id})`);let d=L_e({goalElementId:s.pcb_port_id,pcbConnMap:a}).concat([{center:s,width:.01,height:.01,connectedTo:[s.pcb_port_id],layers:[s.layer],type:"rect"}]),x=L_e({goalElementId:l.pcb_port_id,pcbConnMap:a}).concat([{center:l,width:.01,height:.01,connectedTo:[l.pcb_port_id],layers:[l.layer],type:"rect"}]);if(d.length<=1&&x.length<=1)return{...e,startPoint:s,endPoint:l,goalBoxes:[]};let f=zb(d,x),m,D,b;return d.length>=x.length?(m={...l,...f.pointB},D={...s,...f.pointA},b=d):(m={...s,...f.pointA},D={...l,...f.pointB},b=x),{startPoint:m,endPoint:D,goalBoxes:b,name:e.name,pointsToConnect:[m,D]}},Xjt=(r,e={})=>{let a={minTraceWidth:.1};a.layerCount=e.layerCount??1,a.obstacles=W_e(r,e.connMap),a.connections=[];for(let l of r)if(l.type==="source_trace"){let d={name:l.source_trace_id,pointsToConnect:l.connected_source_port_ids.map(x=>{let f=__e(r).pcb_port.getWhere({source_port_id:x});if(!f)throw new Error(`Could not find pcb_port for source_port_id "${x}"`);return{x:f.x,y:f.y,layer:f.layers?.[0]??"top",pcb_port_id:f.pcb_port_id}})};if(e.optimizeWithGoalBoxes){let x=new s5(r);d=K_e({connection:d,pcbConnMap:x})}a.connections.push(d),Yjt(a.obstacles,d.pointsToConnect,d.name)}let s={minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0};for(let l of a.obstacles)s.minX=Math.min(s.minX,l.center.x-l.width/2),s.maxX=Math.max(s.maxX,l.center.x+l.width/2),s.minY=Math.min(s.minY,l.center.y-l.height/2),s.maxY=Math.max(s.maxY,l.center.y+l.height/2);for(let l of a.connections)for(let d of l.pointsToConnect)s.minX=Math.min(s.minX,d.x),s.maxX=Math.max(s.maxX,d.x),s.minY=Math.min(s.minY,d.y),s.maxY=Math.max(s.maxY,d.y);return a.bounds=s,a},Yjt=(r,e,a)=>{for(let s of e)for(let l of r)Hjt(s,l)&&l.connectedTo.push(a)};function Hjt(r,e){let a=e.width/2,s=e.height/2;if(e.type==="rect")return r.x>=e.center.x-a&&r.x<=e.center.x+a&&r.y>=e.center.y-s&&r.y<=e.center.y+s;if(e.type==="oval"){let l=(r.x-e.center.x)/a,d=(r.y-e.center.y)/s;return l*l+d*d<=1}return!1}function $_e(r,e){let a=e.x>r.x?1:e.x<r.x?-1:0,s=e.y>r.y?1:e.y<r.y?-1:0,l=e.l>r.l?1:e.l<r.l?-1:0;return{dx:a,dy:s,dl:l}}var vY={1:["top"],2:["top","bottom"],4:["top","inner1","inner2","bottom"]},Wjt=r=>vY[r];function J_e(r,e){let s=vY[r].indexOf(e);if(s===-1)throw new Error(`Invalid layer for getLayerIndex (for layerCount === ${r}): "${e}"`);return s}function Kjt(r,e){let s=vY[r][e];if(!s)throw new Error(`Invalid index for indexToLayer (for layerCount === ${r}): "${e}"`);return s}var Jjt=class extends G_e{constructor(e,a){super([]);q(this,"obstacles");q(this,"GRID_STEP",.1);q(this,"layerCount");this.layerCount=e;let s=Wjt(e);this.obstacles=a.flatMap(l=>l.layers.filter(d=>s.includes(d)).map(d=>({...l,left:l.center.x-l.width/2,right:l.center.x+l.width/2,top:l.center.y+l.height/2,bottom:l.center.y-l.height/2,l:J_e(e,d)})))}getObstacleAt(e,a,s,l){l??(l=this.GRID_STEP);for(let d of this.obstacles){if(d.l!==s)continue;let x=d.width/2+l,f=d.height/2+l;if(e>=d.center.x-x&&e<=d.center.x+x&&a>=d.center.y-f&&a<=d.center.y+f)return d}return null}isObstacleAt(e,a,s,l){return this.getObstacleAt(e,a,s,l)!==null}getDirectionDistancesToNearestObstacle3d(e,a,s){let{GRID_STEP:l}=this,d={left:1/0,top:1/0,bottom:1/0,right:1/0};for(let x of this.obstacles)if(x.l===s&&x.type==="rect"){let f=x.center.x-x.width/2-l,m=x.center.x+x.width/2+l,D=x.center.y+x.height/2+l,b=x.center.y-x.height/2-l;a>=b&&a<=D&&e>f&&(d.left=Math.min(d.left,e-m)),a>=b&&a<=D&&e<m&&(d.right=Math.min(d.right,f-e)),e>=f&&e<=m&&a<D&&(d.top=Math.min(d.top,b-a)),e>=f&&e<=m&&a>b&&(d.bottom=Math.min(d.bottom,a-D))}return d}getOrthoDirectionCollisionInfo(e,a,{margin:s=0}={}){let{x:l,y:d,l:x}=e,{dx:f,dy:m,dl:D}=a,b=1/0,E=null;if(D!==0){let A=x+D;return this.isObstacleAt(l,d,A,s)?(b=1,E=this.getObstacleAt(l,d,A,s)):b=1,{dx:f,dy:m,dl:D,wallDistance:b,obstacle:E}}else{for(let A of this.obstacles){if(A.l!==x)continue;let B=A.left-s,w=A.right+s,P=A.top+s,j=A.bottom-s,O=null;f===1&&m===0?d>j&&d<P&&l<A.left&&(O=A.left-l):f===-1&&m===0?d>j&&d<P&&l>A.right&&(O=l-A.right):f===0&&m===1?l>B&&l<w&&d<A.bottom&&(O=A.bottom-d):f===0&&m===-1&&l>B&&l<w&&d>A.top&&(O=d-A.top),O!==null&&O<b&&(b=O,E=A)}return{dx:f,dy:m,dl:0,wallDistance:b,obstacle:E}}}getObstaclesOverlappingRegion(e){let a=[];for(let s of this.obstacles){if(s.l!==e.l)continue;let{left:l,right:d,top:x,bottom:f}=s;l<=e.maxX&&d>=e.minX&&x>=e.minY&&f<=e.maxY&&a.push(s)}return a}},o5=class extends Y_e{constructor(e){super(e);q(this,"MAX_ITERATIONS",500);q(this,"VIA_COST",4);q(this,"VIA_DIAMETER",.5);q(this,"allowLayerChange",!0);q(this,"layerCount");q(this,"obstacles");q(this,"optimizeWithGoalBoxes");q(this,"connMap");q(this,"pcbConnMap");q(this,"GOAL_RUSH_FACTOR",1.1);q(this,"defaultGoalViaMargin",.5);q(this,"marginsWithCosts");this.layerCount=e.input.layerCount??2,this.MAX_ITERATIONS=e.MAX_ITERATIONS??this.MAX_ITERATIONS,this.VIA_COST=e.VIA_COST??this.VIA_COST,this.connMap=e.connMap,this.pcbConnMap=e.pcbConnMap??new s5,this.optimizeWithGoalBoxes=e.optimizeWithGoalBoxes??!1,this.obstacles=null,this.marginsWithCosts=e.marginsWithCosts??[{margin:1,enterCost:0,travelCostFactor:1},{margin:this.OBSTACLE_MARGIN,enterCost:10,travelCostFactor:2}]}get largestMargin(){return this.marginsWithCosts[0].margin}preprocessConnectionBeforeSolving(e){return this.optimizeWithGoalBoxes?K_e({connection:e,pcbConnMap:this.pcbConnMap}):e}postprocessConnectionSolveResult(e,a){if(!a.solved)return a;if(this.optimizeWithGoalBoxes){let s=a.route.map(l=>({x:l.x,y:l.y,route_type:"wire",layer:l.layer,width:this.input.minTraceWidth}));s[0].start_pcb_port_id=e.pointsToConnect[0].pcb_port_id,s[s.length-1].end_pcb_port_id=e.pointsToConnect[1].pcb_port_id,this.pcbConnMap.addTrace({type:"pcb_trace",pcb_trace_id:`postprocess_trace_${k_e(8)}`,route:s})}return a}createObstacleList({dominantLayer:e,connection:a,obstaclesFromTraces:s}){let l=this.connMap?this.connMap.getNetConnectedToId(a.name):a.name;if(!l)throw new Error(`The connection.name "${a.name}" wasn't present in the full connectivity map`);return new Jjt(this.layerCount,this.allObstacles.filter(d=>!d.connectedTo.includes(l)).concat(s??[]))}computeG(e,a){let s=e.g+u1(e,a)*(e.travelMarginCostFactor??1)+(a.enterMarginCost??0);return(a.l??e.l!==-1??-1)&&(s+=this.VIA_COST),s}computeH(e){let a=Math.abs(e.x-this.goalPoint.x),s=Math.abs(e.y-this.goalPoint.y),l=Math.abs(e.l-this.goalPoint.l);return(a+s)**this.GOAL_RUSH_FACTOR+l*this.VIA_COST}getStartNode(e){return{...super.getStartNode(e),l:this.layerToIndex(e.pointsToConnect[0].layer)}}layerToIndex(e){return J_e(this.layerCount,e)}indexToLayer(e){return Kjt(this.layerCount,e)}getNodeName(e){return`${q_e(e,this.GRID_STEP)}-${e.l??0}`}hasSpaceForVia(e,a){return e.every(s=>this.obstacles.getObstaclesOverlappingRegion({minX:a.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:a.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:a.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:a.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:s}).length===0)}getNeighborsSurroundingGoal(e){let a=this.obstacles,s=this.goalPoint,l=[],d=[{dx:1,dy:0,dl:0},{dx:-1,dy:0,dl:0},{dx:0,dy:1,dl:0},{dx:0,dy:-1,dl:0}],x=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin;for(let f of d){let m={x:e.x+f.dx*x,y:e.y+f.dy*x,l:e.l+f.dl,obstacleHit:null};this.hasSpaceForVia([e.l,s.l],m)&&l.push(m)}return l}getNeighbors(e){let a=this.obstacles,s=this.goalPoint,l=u1(e,s);if(l<=this.OBSTACLE_MARGIN)return this.getNeighborsSurroundingGoal(e);let d;e.parent?d=$_e(e.parent,e):d=$_e(e,s);let x=[{dx:0,dy:1,dl:0},{dx:1,dy:0,dl:0},{dx:0,dy:-1,dl:0},{dx:-1,dy:0,dl:0}],f=l>this.VIA_DIAMETER+this.OBSTACLE_MARGIN,m=u1(e,this.startNode)>this.VIA_DIAMETER+this.OBSTACLE_MARGIN;this.allowLayerChange&&f&&m&&(e.l<this.layerCount-1&&x.push({dx:0,dy:0,dl:1}),e.l>0&&x.push({dx:0,dy:0,dl:-1}));let D=x.filter(E=>E.dx===d.dx*-1&&E.dy===d.dy*-1&&E.dl===d.dl*-1?!1:!(E.dx===d.dx&&E.dy===d.dy&&E.dl===d.dl&&e.parent?.obstacleHit)).map(E=>a.getOrthoDirectionCollisionInfo(e,E,{margin:this.OBSTACLE_MARGIN})).filter(E=>!(E.wallDistance<this.OBSTACLE_MARGIN)),b=[];for(let E of D){let A=E.dx===0&&E.dy===0&&E.dl===1,B=E.dx===0&&E.dy===0&&E.dl===-1;if((A||B)&&![e.l,e.l+E.dl].every(z=>a.getObstaclesOverlappingRegion({minX:e.x-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,minY:e.y-this.VIA_DIAMETER/2-this.OBSTACLE_MARGIN,maxX:e.x+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,maxY:e.y+this.VIA_DIAMETER/2+this.OBSTACLE_MARGIN,l:z}).length===0))continue;if(A){e.l<this.layerCount-1&&b.push({...E,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}if(B){e.l>0&&b.push({...E,travelDistance:0,enterMarginCost:0,travelMarginCostFactor:1});continue}let w=null;e?.obstacleHit&&(w=EY({node:e,travelDir:E,wallDir:{...d,wallDistance:this.OBSTACLE_MARGIN},obstacle:e.obstacleHit,obstacles:a,OBSTACLE_MARGIN:this.OBSTACLE_MARGIN,SHOULD_DETECT_CONJOINED_OBSTACLES:!0}));let P=z_e(e,s,E),j=(E.dx===0||Math.sign(s.x-e.x)===E.dx)&&(E.dy===0||Math.sign(s.y-e.y)===E.dy);if(P<E.wallDistance&&P>0&&j){let O=e.l===s.l,z=0;!O&&Math.abs(P-l)<this.GRID_STEP&&(z=this.VIA_DIAMETER+this.OBSTACLE_MARGIN+this.defaultGoalViaMargin),b.push({...E,travelDistance:P-z,enterMarginCost:0,travelMarginCostFactor:1})}else if(w!==null&&w<E.wallDistance){for(let{margin:O,enterCost:z,travelCostFactor:ee}of this.marginsWithCosts)w-this.OBSTACLE_MARGIN+O*2<E.wallDistance&&b.push({...E,travelDistance:w-this.OBSTACLE_MARGIN+O,enterMarginCost:z,travelMarginCostFactor:ee});if(E.wallDistance===1/0)b.push({...E,travelDistance:P,enterMarginCost:0,travelMarginCostFactor:1});else if(E.wallDistance>this.largestMargin)for(let{margin:O,enterCost:z,travelCostFactor:ee}of this.marginsWithCosts)E.wallDistance>this.largestMargin+O&&b.push({...E,travelDistance:E.wallDistance-O,enterMarginCost:z,travelMarginCostFactor:ee})}else if(E.wallDistance!==1/0)for(let{margin:O,enterCost:z,travelCostFactor:ee}of this.marginsWithCosts)E.wallDistance>O&&b.push({...E,travelDistance:E.wallDistance-O,enterMarginCost:z,travelMarginCostFactor:ee})}return b.map(E=>({x:e.x+E.dx*E.travelDistance,y:e.y+E.dy*E.travelDistance,l:e.l+E.dl,obstacleHit:E.obstacle,travelMarginCostFactor:E.travelMarginCostFactor,enterMarginCost:E.enterMarginCost}))}};function Z_e(r){let e=Xjt(r),a=new Vjt({input:e});return{solution:a.solveAndMapToTraces(),debugSolutions:a.debugSolutions,debugMessage:a.debugMessage}}Ue();Ue();qt();Ue();Ue();qt();qt();Ue();Ue();Ue();Ue();Ue();qt();Ue();Ue();Ue();qt();Ue();Ue();qt();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();qt();Ue();qt();Ue();qt();Ue();qt();qt();Ue();qt();Ue();Ue();qt();Ue();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();Ue();Ue();Ue();Ue();Ue();Ue();Ue();qt();Ue();qt();Ue();Ue();qt();Ue();qt();Ue();Ue();Ue();qt();Ue();qt();Ue();Ue();qt();Ue();Ue();Ue();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();Ue();qt();Ue();Ue();qt();qt();Ue();Ue();qt();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();Ue();qt();qt();Ue();qt();Ue();qt();Ue();Ue();Ue();var cr=r=>{};cr("extra props b");cr("missing props b");cr(!0);cr("property a has mismatched types");var Zjt=v.enum(["up","down","left","right"]),Vsr=v.enum(["top-to-bottom","left-to-right","bottom-to-top","right-to-left"]);cr(!0);cr(!0);var G0=v.array(v.string().or(v.number()));cr(!0);var l5=v.object({x:Be,y:Be,z:Be}),Qjt=v.object({x:v.union([v.number(),v.string()]),y:v.union([v.number(),v.string()]),z:v.union([v.number(),v.string()])}),Mp=v.object({rotationOffset:v.number().or(Qjt).optional(),positionOffset:l5.optional(),size:l5.optional(),modelUnitToMmScale:Be.optional()});cr(!0);var ekt=Mp.extend({stlUrl:v.string()}),tkt=Mp.extend({objUrl:v.string(),mtlUrl:v.string().optional()}),rkt=Mp.extend({gltfUrl:v.string()}),nkt=Mp.extend({glbUrl:v.string()}),akt=Mp.extend({stepUrl:v.string()}),skt=Mp.extend({wrlUrl:v.string()}),ikt=Mp.extend({jscad:v.record(v.any())}),nAe=v.union([v.null(),v.string(),v.custom(r=>r&&typeof r=="object"&&"type"in r&&"props"in r),ekt,tkt,rkt,nkt,akt,skt,ikt]);cr(!0);var okt=v.custom(r=>!0),ukt=v.custom(r=>!0),Ta=v.object({pcbX:Be.optional(),pcbY:Be.optional(),pcbRotation:Vn.optional(),pcbPositionAnchor:v.string().optional(),layer:dn.optional(),pcbMarginTop:Be.optional(),pcbMarginRight:Be.optional(),pcbMarginBottom:Be.optional(),pcbMarginLeft:Be.optional(),pcbMarginX:Be.optional(),pcbMarginY:Be.optional(),pcbRelative:v.boolean().optional(),relative:v.boolean().optional()});cr(!0);var d5=v.object({pcbX:Be.optional(),pcbY:Be.optional(),pcbRotation:Vn.optional(),pcbPositionAnchor:v.string().optional(),pcbMarginTop:Be.optional(),pcbMarginRight:Be.optional(),pcbMarginBottom:Be.optional(),pcbMarginLeft:Be.optional(),pcbMarginX:Be.optional(),pcbMarginY:Be.optional(),schMarginTop:Be.optional(),schMarginRight:Be.optional(),schMarginBottom:Be.optional(),schMarginLeft:Be.optional(),schMarginX:Be.optional(),schMarginY:Be.optional(),schX:Be.optional(),schY:Be.optional(),schRotation:Vn.optional(),layer:dn.optional(),footprint:okt.optional(),symbol:ukt.optional(),relative:v.boolean().optional(),schRelative:v.boolean().optional(),pcbRelative:v.boolean().optional()});cr(!0);var ckt=v.object({supplierPartNumbers:v.record(Lm,v.array(v.string())).optional()});cr(!0);var lkt=v.object({providesPower:v.boolean().optional(),requiresPower:v.boolean().optional(),providesGround:v.boolean().optional(),requiresGround:v.boolean().optional(),providesVoltage:v.union([v.string(),v.number()]).optional(),requiresVoltage:v.union([v.string(),v.number()]).optional(),doNotConnect:v.boolean().optional(),includeInBoardPinout:v.boolean().optional()});cr(!0);var gs=d5.merge(ckt).extend({key:v.any().optional(),name:v.string(),cadModel:nAe.optional(),children:v.any().optional(),symbolName:v.string().optional(),doNotPlace:v.boolean().optional(),pinAttributes:v.record(v.string(),lkt).optional()});cr(!0);var _Y=["pin1","left","pin2","right"],p5=["pin1","left","anode","pos","pin2","right","cathode","neg"],tir=Be.or(v.enum(["2x","3x","4x"])),Op=v.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)");cr(!0);var u5=v.object({pins:v.array(v.union([v.number(),v.string()])),direction:v.union([v.literal("top-to-bottom"),v.literal("left-to-right"),v.literal("bottom-to-top"),v.literal("right-to-left")])}),Ub=v.object({leftSize:v.number().optional().describe("@deprecated, use leftPinCount"),topSize:v.number().optional().describe("@deprecated, use topPinCount"),rightSize:v.number().optional().describe("@deprecated, use rightPinCount"),bottomSize:v.number().optional().describe("@deprecated, use bottomPinCount"),leftPinCount:v.number().optional(),rightPinCount:v.number().optional(),topPinCount:v.number().optional(),bottomPinCount:v.number().optional(),leftSide:u5.optional(),rightSide:u5.optional(),topSide:u5.optional(),bottomSide:u5.optional()}),AY=Ub;cr(!0);var x5=v.record(v.object({marginLeft:Be.optional(),marginRight:Be.optional(),marginTop:Be.optional(),marginBottom:Be.optional(),leftMargin:Be.optional(),rightMargin:Be.optional(),topMargin:Be.optional(),bottomMargin:Be.optional()}));cr(!0);var ec=v.string().regex(/^[A-Za-z0-9_]+$/),Vb=v.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),ig=v.object({x:Be,y:Be}),Gb=v.object({edit_event_id:v.string(),in_progress:v.boolean().optional(),created_at:v.number()});cr(!0);var dkt=Gb.extend({pcb_edit_event_type:v.literal("edit_component_location").describe("deprecated"),edit_event_type:v.literal("edit_pcb_component_location"),pcb_component_id:v.string(),original_center:v.object({x:v.number(),y:v.number()}),new_center:v.object({x:v.number(),y:v.number()})});cr(!0);var pkt=Gb.extend({pcb_edit_event_type:v.literal("edit_trace_hint").describe("deprecated"),edit_event_type:v.literal("edit_pcb_trace_hint").optional(),pcb_port_id:v.string(),pcb_trace_hint_id:v.string().optional(),route:v.array(v.object({x:v.number(),y:v.number(),via:v.boolean().optional()}))});cr(!0);var xkt=Gb.extend({edit_event_type:v.literal("edit_schematic_component_location"),schematic_component_id:v.string(),original_center:v.object({x:v.number(),y:v.number()}),new_center:v.object({x:v.number(),y:v.number()})});cr(!0);var Dir=Gb.extend({edit_event_type:v.literal("edit_pcb_group_location"),pcb_group_id:v.string(),original_center:v.object({x:v.number(),y:v.number()}),new_center:v.object({x:v.number(),y:v.number()})});cr(!0);var bir=Gb.extend({edit_event_type:v.literal("edit_schematic_group_location"),schematic_group_id:v.string(),original_center:v.object({x:v.number(),y:v.number()}),new_center:v.object({x:v.number(),y:v.number()})});cr(!0);var Eir=v.union([dkt,pkt,xkt]);cr(!0);var fkt=v.object({selector:v.string(),relative_to:v.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Yr});cr(!0);var hkt=v.object({pcb_port_selector:v.string(),offsets:v.array(bo)});cr(!0);var mkt=v.object({selector:v.string(),relative_to:v.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:Yr});cr(!0);var gkt=v.object({pcb_placements:v.array(fkt).optional(),manual_trace_hints:v.array(hkt).optional(),schematic_placements:v.array(mkt).optional()});cr(!0);var f5=v.string().or(v.array(v.string()).readonly()).or(v.array(v.string())),c1=r=>v.record(v.enum(r),f5),qb=v.object({layoutMode:v.enum(["grid","flex","match-adapt","relative","none"]).optional(),position:v.enum(["absolute","relative"]).optional(),grid:v.boolean().optional(),gridCols:v.number().or(v.string()).optional(),gridRows:v.number().or(v.string()).optional(),gridTemplateRows:v.string().optional(),gridTemplateColumns:v.string().optional(),gridTemplate:v.string().optional(),gridGap:v.number().or(v.string()).optional(),gridRowGap:v.number().or(v.string()).optional(),gridColumnGap:v.number().or(v.string()).optional(),flex:v.boolean().or(v.string()).optional(),flexDirection:v.enum(["row","column"]).optional(),alignItems:v.enum(["start","center","end","stretch"]).optional(),justifyContent:v.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),flexRow:v.boolean().optional(),flexColumn:v.boolean().optional(),gap:v.number().or(v.string()).optional(),pack:v.boolean().optional().describe("Pack the contents of this group using a packing strategy"),packOrderStrategy:v.enum(["largest_to_smallest","first_to_last","highest_to_lowest_pin_count"]).optional(),packPlacementStrategy:v.enum(["shortest_connection_along_outline"]).optional(),padding:pe.optional(),paddingLeft:pe.optional(),paddingRight:pe.optional(),paddingTop:pe.optional(),paddingBottom:pe.optional(),paddingX:pe.optional(),paddingY:pe.optional(),width:pe.optional(),height:pe.optional(),matchAdapt:v.boolean().optional(),matchAdaptTemplate:v.any().optional()});cr(!0);var Q_e=v.object({strokeWidth:pe.optional(),dashed:v.boolean().optional(),solid:v.boolean().optional()}),Dkt=v.object({serverUrl:v.string().optional(),inputFormat:v.enum(["simplified","circuit-json"]).optional(),serverMode:v.enum(["job","solve-endpoint"]).optional(),serverCacheEnabled:v.boolean().optional(),cache:v.custom(r=>!0).optional(),traceClearance:pe.optional(),groupMode:v.enum(["sequential_trace","subcircuit","sequential-trace"]).optional(),algorithmFn:v.custom(r=>typeof r=="function"||r===void 0).optional(),preset:v.enum(["sequential_trace","subcircuit","auto","auto_local","auto_cloud","freerouting","sequential-trace","auto-local","auto-cloud"]).optional(),local:v.boolean().optional()}),aAe=v.union([Dkt,v.literal("sequential_trace"),v.literal("subcircuit"),v.literal("auto"),v.literal("auto_local"),v.literal("auto_cloud"),v.literal("freerouting"),v.literal("sequential-trace"),v.literal("auto-local"),v.literal("auto-cloud")]),sAe=d5.extend({name:v.string().optional(),children:v.any().optional(),schTitle:v.string().optional(),key:v.any().optional(),showAsSchematicBox:v.boolean().optional(),connections:v.record(v.string(),f5.optional()).optional(),schPinArrangement:AY.optional(),...qb.shape,grid:qb.shape.grid.describe("@deprecated use pcbGrid"),flex:qb.shape.flex.describe("@deprecated use pcbFlex"),pcbGrid:v.boolean().optional(),pcbGridCols:v.number().or(v.string()).optional(),pcbGridRows:v.number().or(v.string()).optional(),pcbGridTemplateRows:v.string().optional(),pcbGridTemplateColumns:v.string().optional(),pcbGridTemplate:v.string().optional(),pcbGridGap:v.number().or(v.string()).optional(),pcbGridRowGap:v.number().or(v.string()).optional(),pcbGridColumnGap:v.number().or(v.string()).optional(),pcbFlex:v.boolean().or(v.string()).optional(),pcbFlexGap:v.number().or(v.string()).optional(),pcbFlexDirection:v.enum(["row","column"]).optional(),pcbAlignItems:v.enum(["start","center","end","stretch"]).optional(),pcbJustifyContent:v.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),pcbFlexRow:v.boolean().optional(),pcbFlexColumn:v.boolean().optional(),pcbGap:v.number().or(v.string()).optional(),pcbPack:v.boolean().optional(),pcbPackGap:v.number().or(v.string()).optional(),schGrid:v.boolean().optional(),schGridCols:v.number().or(v.string()).optional(),schGridRows:v.number().or(v.string()).optional(),schGridTemplateRows:v.string().optional(),schGridTemplateColumns:v.string().optional(),schGridTemplate:v.string().optional(),schGridGap:v.number().or(v.string()).optional(),schGridRowGap:v.number().or(v.string()).optional(),schGridColumnGap:v.number().or(v.string()).optional(),schFlex:v.boolean().or(v.string()).optional(),schFlexGap:v.number().or(v.string()).optional(),schFlexDirection:v.enum(["row","column"]).optional(),schAlignItems:v.enum(["start","center","end","stretch"]).optional(),schJustifyContent:v.enum(["start","center","end","stretch","space-between","space-around","space-evenly"]).optional(),schFlexRow:v.boolean().optional(),schFlexColumn:v.boolean().optional(),schGap:v.number().or(v.string()).optional(),schPack:v.boolean().optional(),schMatchAdapt:v.boolean().optional(),pcbWidth:pe.optional(),pcbHeight:pe.optional(),schWidth:pe.optional(),schHeight:pe.optional(),pcbLayout:qb.optional(),schLayout:qb.optional(),cellBorder:Q_e.nullable().optional(),border:Q_e.nullable().optional(),schPadding:pe.optional(),schPaddingLeft:pe.optional(),schPaddingRight:pe.optional(),schPaddingTop:pe.optional(),schPaddingBottom:pe.optional(),pcbPadding:pe.optional(),pcbPaddingLeft:pe.optional(),pcbPaddingRight:pe.optional(),pcbPaddingTop:pe.optional(),pcbPaddingBottom:pe.optional()}),iAe=v.custom(r=>"findPart"in r),RY=sAe.extend({manualEdits:gkt.optional(),schAutoLayoutEnabled:v.boolean().optional(),schTraceAutoLabelEnabled:v.boolean().optional(),schMaxTraceDistance:Be.optional(),routingDisabled:v.boolean().optional(),defaultTraceWidth:pe.optional(),minTraceWidth:pe.optional(),partsEngine:iAe.optional(),pcbRouteCache:v.custom(r=>!0).optional(),autorouter:aAe.optional(),square:v.boolean().optional(),emptyArea:v.string().optional(),filledArea:v.string().optional(),width:Be.optional(),height:Be.optional(),outline:v.array(ig).optional(),outlineOffsetX:Be.optional(),outlineOffsetY:Be.optional()}),ykt=RY.extend({subcircuit:v.literal(!0)}),oAe=v.discriminatedUnion("subcircuit",[sAe.extend({subcircuit:v.literal(!1).optional()}),ykt]);cr(!0);cr(!0);cr(!0);var SY=RY.extend({material:v.enum(["fr4","fr1"]).default("fr4"),layers:v.union([v.literal(2),v.literal(4)]).default(2),borderRadius:Be.optional(),boardAnchorPosition:ig.optional(),boardAnchorAlignment:Vb.optional()});cr(!0);var Pir=RY.extend({padding:Be.optional(),paddingLeft:Be.optional(),paddingRight:Be.optional(),paddingTop:Be.optional(),paddingBottom:Be.optional()});cr(!0);var bkt=v.string().or(v.array(v.string()).readonly()).or(v.array(v.string())),Fkt=v.custom().pipe(v.record(v.string(),bkt)),Ekt=v.record(ec,ec.or(v.array(ec).readonly()).or(v.array(ec)));cr(!0);var vkt=v.object({manufacturerPartNumber:v.string().optional(),supplierPartNumber:v.record(Lm,v.array(v.string())).optional()}),og=gs.extend({manufacturerPartNumber:v.string().optional(),pinLabels:Ekt.optional(),showPinAliases:v.boolean().optional(),pcbPinLabels:v.record(v.string(),v.string()).optional(),internallyConnectedPins:v.array(v.array(v.union([v.string(),v.number()]))).optional(),externallyConnectedPins:v.array(v.array(v.string())).optional(),schPinArrangement:Ub.optional(),schPortArrangement:Ub.optional(),pinCompatibleVariants:v.array(vkt).optional(),schPinStyle:x5.optional(),schPinSpacing:Be.optional(),schWidth:Be.optional(),schHeight:Be.optional(),noSchematicRepresentation:v.boolean().optional(),connections:Fkt.optional()});cr(!0);var uAe=og;cr(!0);var BY=gs.extend({manufacturerPartNumber:v.string().optional(),pinLabels:v.record(v.number().or(ec),ec.or(v.array(ec))).optional(),schPinStyle:x5.optional(),schPinSpacing:Be.optional(),schWidth:Be.optional(),schHeight:Be.optional(),schDirection:v.enum(["left","right"]).optional(),schPinArrangement:AY.optional(),schPortArrangement:Ub.optional(),pcbPinLabels:v.record(v.string(),v.string()).optional(),pinCount:v.union([v.literal(2),v.literal(3)]).optional(),internallyConnectedPins:v.array(v.array(v.union([v.string(),v.number()]))).optional(),connections:v.custom().pipe(v.record(v.string(),f5)).optional()});cr(!0);var cAe=BY.extend({bridgedPins:v.array(v.array(v.string())).optional(),bridged:v.boolean().optional()});cr(!0);var $ir=gs.extend({manufacturerPartNumber:v.string().optional(),pinLabels:v.record(v.number().or(ec),ec.or(v.array(ec))).optional(),schPinStyle:x5.optional(),schPinSpacing:Be.optional(),schWidth:Be.optional(),schHeight:Be.optional(),schDirection:v.enum(["left","right"]).optional(),schPortArrangement:Ub.optional(),internallyConnectedPins:v.array(v.array(v.union([v.string(),v.number()]))).optional(),standard:v.enum(["usb_c","m2"]).optional()});cr(!0);var lAe=gs.extend({currentRating:v.union([v.number(),v.string()]),voltageRating:v.union([v.number(),v.string()]).optional(),schShowRatings:v.boolean().optional(),schOrientation:Op.optional(),connections:v.record(v.string(),v.union([v.string(),v.array(v.string()).readonly(),v.array(v.string())])).optional()}),c5=v.custom().transform(r=>{if(r!==void 0)return Be.parse(r)}),dAe=v.discriminatedUnion("shape",[Ta.omit({pcbRotation:!0,layer:!0}).extend({name:v.string().optional(),connectsTo:v.string().or(v.array(v.string())).optional(),shape:v.literal("circle"),holeDiameter:Be,outerDiameter:Be,portHints:G0.optional()}),Ta.omit({layer:!0}).extend({name:v.string().optional(),connectsTo:v.string().or(v.array(v.string())).optional(),shape:v.literal("oval"),outerWidth:Be,outerHeight:Be,holeWidth:c5,holeHeight:c5,innerWidth:Be.optional().describe("DEPRECATED use holeWidth"),innerHeight:Be.optional().describe("DEPRECATED use holeHeight"),portHints:G0.optional()}),Ta.omit({layer:!0}).extend({name:v.string().optional(),connectsTo:v.string().or(v.array(v.string())).optional(),shape:v.literal("pill"),rectPad:v.boolean().optional(),outerWidth:Be,outerHeight:Be,holeWidth:c5,holeHeight:c5,innerWidth:Be.optional().describe("DEPRECATED use holeWidth"),innerHeight:Be.optional().describe("DEPRECATED use holeHeight"),portHints:G0.optional(),holeOffsetX:Be.optional(),holeOffsetY:Be.optional()}),Ta.omit({pcbRotation:!0,layer:!0}).extend({name:v.string().optional(),connectsTo:v.string().or(v.array(v.string())).optional(),shape:v.literal("circular_hole_with_rect_pad"),holeDiameter:Be,rectPadWidth:Be,rectPadHeight:Be,rectBorderRadius:Be.optional(),holeShape:v.literal("circle").optional(),padShape:v.literal("rect").optional(),portHints:G0.optional(),holeOffsetX:Be.optional(),holeOffsetY:Be.optional()}),Ta.omit({pcbRotation:!0,layer:!0}).extend({name:v.string().optional(),connectsTo:v.string().or(v.array(v.string())).optional(),shape:v.literal("pill_hole_with_rect_pad"),holeShape:v.literal("pill"),padShape:v.literal("rect"),holeWidth:Be,holeHeight:Be,rectPadWidth:Be,rectPadHeight:Be,portHints:G0.optional(),holeOffsetX:Be.optional(),holeOffsetY:Be.optional()})]).refine(r=>("innerWidth"in r&&r.innerWidth!==void 0&&(r.holeWidth??(r.holeWidth=r.innerWidth)),"innerHeight"in r&&r.innerHeight!==void 0&&(r.holeHeight??(r.holeHeight=r.innerHeight)),r));cr(!0);var Ckt=["pin1","pin2","pos","neg"],pAe=gs.extend({resistance:Bp,pullupFor:v.string().optional(),pullupTo:v.string().optional(),pulldownFor:v.string().optional(),pulldownTo:v.string().optional(),schOrientation:Op.optional(),connections:c1(Ckt).optional()}),xAe=_Y;cr(!0);var fAe=gs.extend({maxResistance:Bp,pinVariant:v.enum(["two_pin","three_pin"]).optional()});cr(!0);var _kt=_Y,hAe=gs.extend({frequency:Oc,loadCapacitance:Xl,manufacturerPartNumber:v.string().optional(),mpn:v.string().optional(),pinVariant:v.enum(["two_pin","four_pin"]).optional(),schOrientation:Op.optional(),connections:c1(_kt).optional()});cr(!0);var mAe=gs.extend({frequency:Oc,loadCapacitance:Xl,pinVariant:v.enum(["no_ground","ground_pin","two_ground_pins"]).optional()});cr(!0);var eor=SY.extend({leftPinCount:v.number().optional(),rightPinCount:v.number().optional(),topPinCount:v.number().optional(),bottomPinCount:v.number().optional(),leftPins:v.array(v.string()).optional(),rightPins:v.array(v.string()).optional(),topPins:v.array(v.string()).optional(),bottomPins:v.array(v.string()).optional(),pinPitch:Be.optional(),innerHoles:v.boolean().optional()});cr(!0);var Akt=["pin1","pin2","pos","neg","anode","cathode"],gAe=gs.extend({capacitance:Xl,maxVoltageRating:Us.optional(),schShowRatings:v.boolean().optional().default(!1),polarized:v.boolean().optional().default(!1),decouplingFor:v.string().optional(),decouplingTo:v.string().optional(),bypassFor:v.string().optional(),bypassTo:v.string().optional(),maxDecouplingTraceLength:v.number().optional(),schOrientation:Op.optional(),connections:c1(Akt).optional()}),DAe=p5;cr(!0);var aor=v.object({name:v.string(),connectsTo:v.string().or(v.array(v.string())).optional()});cr(!0);var ior=v.object({name:v.string().optional(),pcbOnly:v.boolean().optional(),schOnly:v.boolean().optional()});cr(!0);var Rkt=v.object({pcb:v.literal(!0).optional(),xDist:Be,left:v.string(),right:v.string(),edgeToEdge:v.literal(!0).optional(),centerToCenter:v.literal(!0).optional()});cr(!0);var Skt=v.object({pcb:v.literal(!0).optional(),yDist:Be,top:v.string(),bottom:v.string(),edgeToEdge:v.literal(!0).optional(),centerToCenter:v.literal(!0).optional()});cr(!0);var Bkt=v.object({pcb:v.literal(!0).optional(),sameY:v.literal(!0).optional(),for:v.array(v.string())});cr(!0);var wkt=v.object({pcb:v.literal(!0).optional(),sameX:v.literal(!0).optional(),for:v.array(v.string())});cr(!0);var yAe=v.union([Rkt,Skt,Bkt,wkt]);cr(!0);var Tkt=Ta.omit({layer:!0,pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("rect"),width:Be,height:Be});cr(!0);var Pkt=Ta.omit({layer:!0,pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("circle"),radius:Be});cr(!0);var Ikt=Ta.omit({layer:!0,pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("polygon"),points:v.array(ig)});cr(!0);var bAe=v.discriminatedUnion("shape",[Tkt,Pkt,Ikt]),jkt=Ta.omit({pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("rect"),width:Be,height:Be,rectBorderRadius:Be.optional(),portHints:G0.optional(),coveredWithSolderMask:v.boolean().optional()});cr(!0);var kkt=Ta.omit({pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("rotated_rect"),width:Be,height:Be,ccwRotation:v.number(),portHints:G0.optional(),coveredWithSolderMask:v.boolean().optional()});cr(!0);var Nkt=Ta.omit({pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("circle"),radius:Be,portHints:G0.optional(),coveredWithSolderMask:v.boolean().optional()});cr(!0);var Mkt=Ta.omit({pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("pill"),width:Be,height:Be,radius:Be,portHints:G0.optional(),coveredWithSolderMask:v.boolean().optional()});cr(!0);var Okt=Ta.omit({pcbRotation:!0}).extend({name:v.string().optional(),shape:v.literal("polygon"),points:v.array(ig),portHints:G0.optional(),coveredWithSolderMask:v.boolean().optional()});cr(!0);var FAe=v.discriminatedUnion("shape",[Nkt,jkt,kkt,Mkt,Okt]);cr(!0);var Lkt=Ta.omit({pcbRotation:!0}).extend({shape:v.literal("rect"),width:Be,height:Be});cr(!0);var $kt=Ta.omit({pcbRotation:!0}).extend({shape:v.literal("circle"),radius:Be});cr(!0);var dor=v.union([$kt,Lkt]);cr(!0);var zkt=Ta.extend({name:v.string().optional(),shape:v.literal("circle").optional(),diameter:Be.optional(),radius:Be.optional()}).transform(r=>({...r,diameter:r.diameter??2*r.radius,radius:r.radius??r.diameter/2})),qkt=Ta.extend({name:v.string().optional(),shape:v.literal("pill"),width:Be,height:Be}),EAe=v.union([zkt,qkt]);cr(!0);var CY=v.union([v.string(),v.custom(r=>!!r.getPortSelector)]),eAe=v.object({key:v.string().optional(),thickness:Be.optional(),schematicRouteHints:v.array(ig).optional(),pcbRouteHints:v.array(bo).optional(),pcbPathRelativeTo:v.string().optional(),pcbPath:v.array(ig).optional(),schDisplayLabel:v.string().optional(),schStroke:v.string().optional(),maxLength:Be.optional()}),vAe=v.union([eAe.extend({path:v.array(CY)}),eAe.extend({from:CY,to:CY})]),CAe=v.object({originalLayer:dn.default("top").optional()});cr(!0);var yor=v.object({originalFacingDirection:v.enum(["up","down","left","right"]).default("right").optional()});cr(!0);var Ukt=v.number().or(v.string().endsWith("mAh")).transform(r=>{if(typeof r=="string"){let e=r.replace("mAh",""),a=Number.parseFloat(e);if(Number.isNaN(a))throw new Error("Invalid capacity");return a}return r}).describe("Battery capacity in mAh"),_Ae=gs.extend({capacity:Ukt.optional(),voltage:Us.optional(),standard:v.enum(["AA","AAA","9V","CR2032","18650","C"]).optional(),schOrientation:Op.optional()});cr(!0);var Vkt=v.enum(["vertical","horizontal"]).describe("vertical means pins go 1->2 downward and horizontal means pins go 1->2 rightward");cr(!0);var AAe=gs.extend({pinCount:v.number(),pitch:Be.optional(),schFacingDirection:v.enum(["up","down","left","right"]).optional(),gender:v.enum(["male","female","unpopulated"]).optional().default("male"),showSilkscreenPinLabels:v.boolean().optional(),pcbPinLabels:v.record(v.string(),v.string()).optional(),doubleRow:v.boolean().optional(),rightAngle:v.boolean().optional(),pcbOrientation:Vkt.optional(),holeDiameter:Be.optional(),platedDiameter:Be.optional(),pinLabels:v.record(v.string(),ec).or(v.array(ec)).optional(),connections:v.custom().pipe(v.record(v.string(),f5)).optional(),facingDirection:v.enum(["left","right"]).optional(),schPinArrangement:AY.optional(),schPinStyle:x5.optional(),schPinSpacing:Be.optional(),schWidth:Be.optional(),schHeight:Be.optional()});cr(!0);var Ror=v.object({net:v.string().optional(),connection:v.string().optional(),schX:Be.optional(),schY:Be.optional(),schRotation:Vn.optional(),anchorSide:v.enum(["left","top","right","bottom"]).optional()});cr(!0);var RAe=v.object({net:v.string().optional(),connection:v.string().optional(),connectsTo:v.string().or(v.array(v.string())).optional(),schX:Be.optional(),schY:Be.optional(),schRotation:Vn.optional(),anchorSide:v.enum(["left","top","right","bottom"]).optional()});cr(!0);var SAe=og.extend({});cr(!0);cr(!0);var Gkt=["pin1","pin2","pin3","emitter","collector","base","gate","source","drain"],BAe=gs.extend({type:v.enum(["npn","pnp","bjt","jfet","mosfet","igbt"]),connections:c1(Gkt).optional()});cr(!0);var wAe=gs.extend({channelType:v.enum(["n","p"]),mosfetMode:v.enum(["enhancement","depletion"])});cr(!0);var Xkt=_Y,TAe=gs.extend({inductance:OA,maxCurrentRating:v.union([v.string(),v.number()]).optional(),schOrientation:Op.optional(),connections:c1(Xkt).optional()});cr(!0);var Ykt=v.enum(["anode","cathode","pin1","pin2","pos","neg"]),Hkt=v.string().or(v.array(v.string()).readonly()).or(v.array(v.string())),Wkt=v.record(Ykt,Hkt),Kkt=v.enum(["standard","schottky","zener","avalanche","photo","tvs"]),PAe=gs.extend({connections:Wkt.optional(),variant:Kkt.optional().default("standard"),standard:v.boolean().optional(),schottky:v.boolean().optional(),zener:v.boolean().optional(),avalanche:v.boolean().optional(),photo:v.boolean().optional(),tvs:v.boolean().optional(),schOrientation:Op.optional()}).superRefine((r,e)=>{if([r.standard,r.schottky,r.zener,r.avalanche,r.photo,r.tvs].filter(Boolean).length>1)return e.addIssue({code:v.ZodIssueCode.custom,message:"Exactly one diode variant must be enabled",path:[]}),v.INVALID}).transform(r=>{let e={...r,standard:!1,schottky:!1,zener:!1,avalanche:!1,photo:!1,tvs:!1};if(r.standard)e.standard=!0;else if(r.schottky)e.schottky=!0;else if(r.zener)e.zener=!0;else if(r.photo)e.photo=!0;else if(r.tvs)e.tvs=!0;else switch(r.variant){case"standard":e.standard=!0;break;case"schottky":e.schottky=!0;break;case"zener":e.zener=!0;break;case"avalanche":e.avalanche=!0;break;case"photo":e.photo=!0;break;case"tvs":e.tvs=!0;break;default:e.standard=!0}return e}),IAe=p5;cr(!0);var jAe=gs.extend({color:v.string().optional(),wavelength:v.string().optional(),schDisplayValue:v.string().optional(),schOrientation:Op.optional(),connections:c1(p5).optional(),laser:v.boolean().optional()}),kAe=p5,NAe=gs.extend({type:v.enum(["spst","spdt","dpst","dpdt"]).optional(),isNormallyClosed:v.boolean().optional().default(!1),spst:v.boolean().optional(),spdt:v.boolean().optional(),dpst:v.boolean().optional(),dpdt:v.boolean().optional()}).transform(r=>{let e={...r};switch(e.dpdt?e.type="dpdt":e.spst?e.type="spst":e.spdt?e.type="spdt":e.dpst&&(e.type="dpst"),e.type){case"spdt":e.spdt=!0;break;case"spst":e.spst=!0;break;case"dpst":e.dpst=!0;break;case"dpdt":e.dpdt=!0;break}return e});cr(!0);var MAe=Ta.extend({text:v.string(),anchorAlignment:v.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:v.enum(["tscircuit2024"]).optional(),fontSize:pe.optional(),color:v.string().optional()}),OAe=Ta.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:v.array(bo),strokeWidth:pe.optional(),color:v.string().optional()}),Uor=v.object({layer:v.string().optional(),thickness:Be.optional(),route:v.array(bo)}),LAe=d5.extend({name:v.string().optional(),fromLayer:dn,toLayer:dn,holeDiameter:Be,outerDiameter:Be,connectsTo:v.string().or(v.array(v.string())).optional()});cr(!0);var $Ae=gs.extend({footprintVariant:v.enum(["pad","through_hole"]).optional(),padShape:v.enum(["rect","circle"]).optional().default("circle"),padDiameter:Be.optional(),holeDiameter:Be.optional(),width:Be.optional(),height:Be.optional()}).refine(r=>r.footprintVariant!=="through_hole"||r.holeDiameter!==void 0,{message:"holeDiameter is required for through_hole testpoints"});cr(!0);var zAe=Ta.omit({pcbRotation:!0,layer:!0}).extend({connection:v.string()});cr(!0);var qAe=v.union([Ta.omit({pcbRotation:!0}).extend({shape:v.literal("circle"),radius:Be}),Ta.extend({shape:v.literal("rect"),width:Be,height:Be})]),UAe=v.object({name:v.string().optional(),layer:dn,connectsTo:v.string(),padMargin:Be.optional(),traceMargin:Be.optional()});cr(!0);var VAe=v.object({originalLayer:dn.default("top").optional(),children:v.any().optional()});cr(!0);var Jkt=v.object({pcbX:Be.optional(),pcbY:Be.optional(),pcbZ:Be.optional()}),Zkt=Mp.extend({modelUrl:v.string()}),Qkt=Zkt.merge(Jkt);cr(!0);var GAe=v.union([v.null(),v.string(),Qkt]),XAe=gs.extend({voltage:Us}),eNt=["pin1","pin2","pos","neg"],tNt=v.union([v.string(),v.number()]).transform(r=>typeof r=="string"?r.endsWith("%")?parseFloat(r.slice(0,-1))/100:parseFloat(r):r).pipe(v.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),sur=gs.extend({voltage:Us.optional(),frequency:Oc.optional(),peakToPeakVoltage:Us.optional(),waveShape:v.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Vn.optional(),dutyCycle:tNt.optional(),connections:c1(eNt).optional()});cr(!0);var uur=v.object({center:Yr,radius:Be,startAngleDegrees:Vn,endAngleDegrees:Vn,direction:v.enum(["clockwise","counterclockwise"]).default("counterclockwise"),strokeWidth:Be.optional(),color:v.string().optional().default("#000000"),isDashed:v.boolean().optional().default(!1)}),YAe=v.object({schX:Be.optional(),schY:Be.optional(),width:Be.optional(),height:Be.optional(),overlay:v.array(v.string()).optional(),padding:Be.optional(),paddingLeft:Be.optional(),paddingRight:Be.optional(),paddingTop:Be.optional(),paddingBottom:Be.optional(),title:v.string().optional(),titleAlignment:Vb.default("top_left"),titleColor:v.string().optional(),titleFontSize:Be.optional(),titleInside:v.boolean().default(!1),strokeStyle:v.enum(["solid","dashed"]).default("solid")}).refine(r=>r.width!==void 0&&r.height!==void 0||Array.isArray(r.overlay)&&r.overlay.length>0,{message:"Must provide either both `width` and `height`, or a non-empty `overlay` array."}).refine(r=>!(r.width!==void 0&&r.height!==void 0&&Array.isArray(r.overlay)&&r.overlay.length>0),{message:"Cannot provide both `width`/`height` and `overlay` at the same time."}),xur=v.object({center:Yr,radius:Be,strokeWidth:Be.optional(),color:v.string().optional().default("#000000"),isFilled:v.boolean().optional().default(!1),fillColor:v.string().optional(),isDashed:v.boolean().optional().default(!1)}),mur=v.object({center:Yr,width:Be,height:Be,rotation:Vn.default(0),strokeWidth:Be.optional(),color:v.string().optional().default("#000000"),isFilled:v.boolean().optional().default(!1),fillColor:v.string().optional(),isDashed:v.boolean().optional().default(!1)}),yur=v.object({x1:Be,y1:Be,x2:Be,y2:Be,strokeWidth:Be.optional(),color:v.string().optional().default("#000000"),isDashed:v.boolean().optional().default(!1)}),rNt=v.enum(["center","left","right","top","bottom"]),HAe=v.object({schX:Be.optional(),schY:Be.optional(),text:v.string(),fontSize:v.number().default(1),anchor:v.union([rNt.describe("legacy"),Vb]).default("center"),color:v.string().default("#000000"),schRotation:Vn.default(0)}),_ur=v.object({points:v.array(Yr),isFilled:v.boolean().optional().default(!1),fillColor:v.enum(["red","blue"]).optional()}),WAe=v.object({schX:Be.optional(),schY:Be.optional(),children:v.any().optional(),cellPadding:Be.optional(),borderWidth:Be.optional(),anchor:Vb.optional(),fontSize:Be.optional()});cr(!0);var KAe=v.object({children:v.any().optional(),height:Be.optional()});cr(!0);var JAe=v.object({children:v.string().optional(),horizontalAlign:v.enum(["left","center","right"]).optional(),verticalAlign:v.enum(["top","middle","bottom"]).optional(),fontSize:Be.optional(),rowSpan:v.number().optional(),colSpan:v.number().optional(),width:Be.optional(),text:v.string().optional()});cr(!0);var ZAe=Ta.extend({text:v.string(),anchorAlignment:Vb.default("center"),font:v.enum(["tscircuit2024"]).optional(),fontSize:pe.optional(),isKnockout:v.boolean().optional(),knockoutPadding:pe.optional(),knockoutPaddingLeft:pe.optional(),knockoutPaddingRight:pe.optional(),knockoutPaddingTop:pe.optional(),knockoutPaddingBottom:pe.optional(),layers:v.array(dn).optional()}),QAe=Ta.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:v.array(bo),strokeWidth:pe.optional()}),e4e=Ta.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({strokeWidth:Be,x1:Be,y1:Be,x2:Be,y2:Be}),t4e=Ta.omit({pcbRotation:!0}).extend({filled:v.boolean().default(!0).optional(),stroke:v.enum(["dashed","solid","none"]).optional(),strokeWidth:Be.optional(),width:Be,height:Be}),r4e=Ta.omit({pcbRotation:!0}).extend({isFilled:v.boolean().optional(),isOutline:v.boolean().optional(),strokeWidth:Be.optional(),radius:Be}),tAe=v.object({x:Be,y:Be,via:v.boolean().optional(),toLayer:dn.optional()}),n4e=v.object({for:v.string().optional().describe("Selector for the port you're targeting, not required if you're inside a trace"),order:v.number().optional(),offset:bo.or(tAe).optional(),offsets:v.array(bo).or(v.array(tAe)).optional(),traceWidth:v.number().optional()}),Vur=d5.extend({name:v.string(),pinNumber:v.number().optional(),aliases:v.array(v.string()).optional(),direction:Zjt}),nNt=v.array(v.any()).describe("Circuit JSON"),a4e=v.object({footprintCircuitJson:v.array(v.any()),cadModel:nAe.optional()}),rAe=v.function().args(v.string()).returns(v.promise(a4e)).describe("A function that takes a path and returns Circuit JSON"),aNt=v.object({loadFromUrl:v.function().args(v.string()).returns(v.promise(a4e)).describe("A function that takes a footprint file URL and returns Circuit JSON")}),sNt=v.object({partsEngine:iAe.optional(),autorouter:aAe.optional(),registryApiUrl:v.string().optional(),cloudAutorouterUrl:v.string().optional(),projectName:v.string().optional(),projectBaseUrl:v.string().optional(),version:v.string().optional(),url:v.string().optional(),printBoardInformationToSilkscreen:v.boolean().optional(),localCacheEngine:v.any().optional(),pcbDisabled:v.boolean().optional(),schematicDisabled:v.boolean().optional(),partsEngineDisabled:v.boolean().optional(),footprintLibraryMap:v.record(v.string(),v.union([rAe,v.record(v.string(),v.union([nNt,rAe]))])).optional(),footprintFileParserMap:v.record(v.string(),aNt).optional()});cr(!0);var iNt=sNt,Xur=iNt.pick({projectName:!0,projectBaseUrl:!0,version:!0,url:!0,printBoardInformationToSilkscreen:!0});cr(!0);Ue();qt();Jl();Ue();var B1=Or(kc(),1);Jl();Ue();function Lp(){return new wY}var wY=class r{constructor(){q(this,"index",{});q(this,"array",[])}size(){return this.array.length}empty(){return this.array.length===0}itemAt(e){return this.array[e]}contains(e){return this.index[e.id()]!==void 0}find(e){let a=this.index[e.id()];return a===void 0?void 0:this.array[a]}setDefault(e,a){let s=this.index[e.id()];if(s===void 0){let l=new h5(e,a());return this.index[e.id()]=this.array.length,this.array.push(l),l}else return this.array[s]}insert(e,a){let s=new h5(e,a),l=this.index[e.id()];return l===void 0?(this.index[e.id()]=this.array.length,this.array.push(s)):this.array[l]=s,s}erase(e){let a=this.index[e.id()];if(a===void 0)return;this.index[e.id()]=void 0;let s=this.array[a],l=this.array.pop();return s!==l&&(this.array[a]=l,this.index[l.first.id()]=a),s}copy(){let e=new r;for(let a=0;a<this.array.length;a++){let s=this.array[a].copy();e.array[a]=s,e.index[s.first.id()]=a}return e}},h5=class r{constructor(e,a){q(this,"first");q(this,"second");this.first=e,this.second=a}copy(){return new r(this.first,this.second)}};var rd=class{constructor(e=""){q(this,"_name");q(this,"_value",0);q(this,"_context",null);q(this,"_id",oNt++);this._name=e}id(){return this._id}name(){return this._name}setName(e){this._name=e}context(){return this._context}setContext(e){this._context=e}value(){return this._value}setValue(e){this._value=e}plus(e){return new Xa(this,e)}minus(e){return new Xa(this,typeof e=="number"?-e:[-1,e])}multiply(e){return new Xa([e,this])}divide(e){return new Xa([1/e,this])}toJSON(){return{name:this._name,value:this._value}}toString(){return this._context+"["+this._name+":"+this._value+"]"}},oNt=0;var Xa=class r{constructor(){q(this,"_terms");q(this,"_constant");let e=uNt(arguments);this._terms=e.terms,this._constant=e.constant}terms(){return this._terms}constant(){return this._constant}value(){let e=this._constant;for(let a=0,s=this._terms.size();a<s;a++){let l=this._terms.itemAt(a);e+=l.first.value()*l.second}return e}plus(e){return new r(this,e)}minus(e){return new r(this,typeof e=="number"?-e:[-1,e])}multiply(e){return new r([e,this])}divide(e){return new r([1/e,this])}isConstant(){return this._terms.size()==0}toString(){let e=this._terms.array.map(function(a){return a.second+"*"+a.first.toString()}).join(" + ");return!this.isConstant()&&this._constant!==0&&(e+=" + "),e+=this._constant,e}};function uNt(r){let e=0,a=()=>0,s=Lp();for(let l=0,d=r.length;l<d;++l){let x=r[l];if(typeof x=="number")e+=x;else if(x instanceof rd)s.setDefault(x,a).second+=1;else if(x instanceof Xa){e+=x.constant();let f=x.terms();for(let m=0,D=f.size();m<D;m++){let b=f.itemAt(m);s.setDefault(b.first,a).second+=b.second}}else if(x instanceof Array){if(x.length!==2)throw new Error("array must have length 2");let f=x[0],m=x[1];if(typeof f!="number")throw new Error("array item 0 must be a number");if(m instanceof rd)s.setDefault(m,a).second+=f;else if(m instanceof Xa){e+=m.constant()*f;let D=m.terms();for(let b=0,E=D.size();b<E;b++){let A=D.itemAt(b);s.setDefault(A.first,a).second+=A.second*f}}else throw new Error("array item 1 must be a variable or expression")}else throw new Error("invalid Expression argument: "+x)}return{terms:s,constant:e}}var $c=class $c{static create(e,a,s,l=1){let d=0;return d+=Math.max(0,Math.min(1e3,e*l))*1e6,d+=Math.max(0,Math.min(1e3,a*l))*1e3,d+=Math.max(0,Math.min(1e3,s*l)),d}static clip(e){return Math.max(0,Math.min($c.required,e))}};q($c,"required",$c.create(1e3,1e3,1e3)),q($c,"strong",$c.create(1,0,0)),q($c,"medium",$c.create(0,1,0)),q($c,"weak",$c.create(0,0,1));var Oa=$c;var Ds;(function(r){r[r.Le=0]="Le",r[r.Ge=1]="Ge",r[r.Eq=2]="Eq"})(Ds||(Ds={}));var Vs=class{constructor(e,a,s,l=Oa.required){q(this,"_expression");q(this,"_operator");q(this,"_strength");q(this,"_id",cNt++);this._operator=a,this._strength=Oa.clip(l),s===void 0&&e instanceof Xa?this._expression=e:this._expression=e.minus(s)}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()+")"}},cNt=0;var ug=class{constructor(){q(this,"maxIterations",1e3);q(this,"_cnMap",lNt());q(this,"_rowMap",dNt());q(this,"_varMap",pNt());q(this,"_editMap",xNt());q(this,"_infeasibleRows",[]);q(this,"_objective",new D5);q(this,"_artificial",null);q(this,"_idTick",0)}createConstraint(e,a,s,l=Oa.required){let d=new Vs(e,a,s,l);return this.addConstraint(d),d}addConstraint(e){if(this._cnMap.find(e)!==void 0)throw new Error("duplicate constraint");let s=this._createRow(e),l=s.row,d=s.tag,x=this._chooseSubject(l,d);if(x.type()===ta.Invalid&&l.allDummies())if(m5(l.constant()))x=d.marker;else throw new Error("unsatisfiable constraint");if(x.type()===ta.Invalid){if(!this._addWithArtificialVariable(l))throw new Error("unsatisfiable constraint")}else l.solveFor(x),this._substitute(x,l),this._rowMap.insert(x,l);this._cnMap.insert(e,d),this._optimize(this._objective)}removeConstraint(e){let a=this._cnMap.erase(e);if(a===void 0)throw new Error("unknown constraint");this._removeConstraintEffects(e,a.second);let s=a.second.marker,l=this._rowMap.erase(s);if(l===void 0){let d=this._getMarkerLeavingSymbol(s);if(d.type()===ta.Invalid)throw new Error("failed to find leaving row");l=this._rowMap.erase(d),l.second.solveForEx(d,s),this._substitute(s,l.second)}this._optimize(this._objective)}hasConstraint(e){return this._cnMap.contains(e)}getConstraints(){return this._cnMap.array.map(({first:e})=>e)}addEditVariable(e,a){if(this._editMap.find(e)!==void 0)throw new Error("duplicate edit variable");if(a=Oa.clip(a),a===Oa.required)throw new Error("bad required strength");let l=new Xa(e),d=new Vs(l,Ds.Eq,void 0,a);this.addConstraint(d);let f={tag:this._cnMap.find(d).second,constraint:d,constant:0};this._editMap.insert(e,f)}removeEditVariable(e){let a=this._editMap.erase(e);if(a===void 0)throw new Error("unknown edit variable");this.removeConstraint(a.second.constraint)}hasEditVariable(e){return this._editMap.contains(e)}suggestValue(e,a){let s=this._editMap.find(e);if(s===void 0)throw new Error("unknown edit variable");let l=this._rowMap,d=s.second,x=a-d.constant;d.constant=a;let f=d.tag.marker,m=l.find(f);if(m!==void 0){m.second.add(-x)<0&&this._infeasibleRows.push(f),this._dualOptimize();return}let D=d.tag.other;if(m=l.find(D),m!==void 0){m.second.add(x)<0&&this._infeasibleRows.push(D),this._dualOptimize();return}for(let b=0,E=l.size();b<E;++b){let A=l.itemAt(b),B=A.second,w=B.coefficientFor(f);w!==0&&B.add(x*w)<0&&A.first.type()!==ta.External&&this._infeasibleRows.push(A.first)}this._dualOptimize()}updateVariables(){let e=this._varMap,a=this._rowMap;for(let s=0,l=e.size();s<l;++s){let d=e.itemAt(s),x=a.find(d.second);x!==void 0?d.first.setValue(x.second.constant()):d.first.setValue(0)}}_getVarSymbol(e){let a=()=>this._makeSymbol(ta.External);return this._varMap.setDefault(e,a).second}_createRow(e){let a=e.expression(),s=new D5(a.constant()),l=a.terms();for(let m=0,D=l.size();m<D;++m){let b=l.itemAt(m);if(!m5(b.second)){let E=this._getVarSymbol(b.first),A=this._rowMap.find(E);A!==void 0?s.insertRow(A.second,b.second):s.insertSymbol(E,b.second)}}let d=this._objective,x=e.strength(),f={marker:$p,other:$p};switch(e.op()){case Ds.Le:case Ds.Ge:{let m=e.op()===Ds.Le?1:-1,D=this._makeSymbol(ta.Slack);if(f.marker=D,s.insertSymbol(D,m),x<Oa.required){let b=this._makeSymbol(ta.Error);f.other=b,s.insertSymbol(b,-m),d.insertSymbol(b,x)}break}case Ds.Eq:{if(x<Oa.required){let m=this._makeSymbol(ta.Error),D=this._makeSymbol(ta.Error);f.marker=m,f.other=D,s.insertSymbol(m,-1),s.insertSymbol(D,1),d.insertSymbol(m,x),d.insertSymbol(D,x)}else{let m=this._makeSymbol(ta.Dummy);f.marker=m,s.insertSymbol(m)}break}}return s.constant()<0&&s.reverseSign(),{row:s,tag:f}}_chooseSubject(e,a){let s=e.cells();for(let d=0,x=s.size();d<x;++d){let f=s.itemAt(d);if(f.first.type()===ta.External)return f.first}let l=a.marker.type();return(l===ta.Slack||l===ta.Error)&&e.coefficientFor(a.marker)<0?a.marker:(l=a.other.type(),(l===ta.Slack||l===ta.Error)&&e.coefficientFor(a.other)<0?a.other:$p)}_addWithArtificialVariable(e){let a=this._makeSymbol(ta.Slack);this._rowMap.insert(a,e.copy()),this._artificial=e.copy(),this._optimize(this._artificial);let s=m5(this._artificial.constant());this._artificial=null;let l=this._rowMap.erase(a);if(l!==void 0){let x=l.second;if(x.isConstant())return s;let f=this._anyPivotableSymbol(x);if(f.type()===ta.Invalid)return!1;x.solveForEx(a,f),this._substitute(f,x),this._rowMap.insert(f,x)}let d=this._rowMap;for(let x=0,f=d.size();x<f;++x)d.itemAt(x).second.removeSymbol(a);return this._objective.removeSymbol(a),s}_substitute(e,a){let s=this._rowMap;for(let l=0,d=s.size();l<d;++l){let x=s.itemAt(l);x.second.substitute(e,a),x.second.constant()<0&&x.first.type()!==ta.External&&this._infeasibleRows.push(x.first)}this._objective.substitute(e,a),this._artificial&&this._artificial.substitute(e,a)}_optimize(e){let a=0;for(;a<this.maxIterations;){let s=this._getEnteringSymbol(e);if(s.type()===ta.Invalid)return;let l=this._getLeavingSymbol(s);if(l.type()===ta.Invalid)throw new Error("the objective is unbounded");let d=this._rowMap.erase(l).second;d.solveForEx(l,s),this._substitute(s,d),this._rowMap.insert(s,d),a++}throw new Error("solver iterations exceeded")}_dualOptimize(){let e=this._rowMap,a=this._infeasibleRows;for(;a.length!==0;){let s=a.pop(),l=e.find(s);if(l!==void 0&&l.second.constant()<0){let d=this._getDualEnteringSymbol(l.second);if(d.type()===ta.Invalid)throw new Error("dual optimize failed");let x=l.second;e.erase(s),x.solveForEx(s,d),this._substitute(d,x),e.insert(d,x)}}}_getEnteringSymbol(e){let a=e.cells();for(let s=0,l=a.size();s<l;++s){let d=a.itemAt(s),x=d.first;if(d.second<0&&x.type()!==ta.Dummy)return x}return $p}_getDualEnteringSymbol(e){let a=Number.MAX_VALUE,s=$p,l=e.cells();for(let d=0,x=l.size();d<x;++d){let f=l.itemAt(d),m=f.first,D=f.second;if(D>0&&m.type()!==ta.Dummy){let E=this._objective.coefficientFor(m)/D;E<a&&(a=E,s=m)}}return s}_getLeavingSymbol(e){let a=Number.MAX_VALUE,s=$p,l=this._rowMap;for(let d=0,x=l.size();d<x;++d){let f=l.itemAt(d),m=f.first;if(m.type()!==ta.External){let D=f.second,b=D.coefficientFor(e);if(b<0){let E=-D.constant()/b;E<a&&(a=E,s=m)}}}return s}_getMarkerLeavingSymbol(e){let a=Number.MAX_VALUE,s=a,l=a,d=$p,x=d,f=d,m=d,D=this._rowMap;for(let b=0,E=D.size();b<E;++b){let A=D.itemAt(b),B=A.second,w=B.coefficientFor(e);if(w===0)continue;let P=A.first;if(P.type()===ta.External)m=P;else if(w<0){let j=-B.constant()/w;j<s&&(s=j,x=P)}else{let j=B.constant()/w;j<l&&(l=j,f=P)}}return x!==d?x:f!==d?f:m}_removeConstraintEffects(e,a){a.marker.type()===ta.Error&&this._removeMarkerEffects(a.marker,e.strength()),a.other.type()===ta.Error&&this._removeMarkerEffects(a.other,e.strength())}_removeMarkerEffects(e,a){let s=this._rowMap.find(e);s!==void 0?this._objective.insertRow(s.second,-a):this._objective.insertSymbol(e,-a)}_anyPivotableSymbol(e){let a=e.cells();for(let s=0,l=a.size();s<l;++s){let d=a.itemAt(s),x=d.first.type();if(x===ta.Slack||x===ta.Error)return d.first}return $p}_makeSymbol(e){return new g5(e,this._idTick++)}};function m5(r){let e=1e-8;return r<0?-r<e:r<e}function lNt(){return Lp()}function dNt(){return Lp()}function pNt(){return Lp()}function xNt(){return Lp()}var ta;(function(r){r[r.Invalid=0]="Invalid",r[r.External=1]="External",r[r.Slack=2]="Slack",r[r.Error=3]="Error",r[r.Dummy=4]="Dummy"})(ta||(ta={}));var g5=class{constructor(e,a){q(this,"_id");q(this,"_type");this._id=a,this._type=e}id(){return this._id}type(){return this._type}},$p=new g5(ta.Invalid,-1),D5=class r{constructor(e=0){q(this,"_cellMap",Lp());q(this,"_constant");this._constant=e}cells(){return this._cellMap}constant(){return this._constant}isConstant(){return this._cellMap.empty()}allDummies(){let e=this._cellMap;for(let a=0,s=e.size();a<s;++a)if(e.itemAt(a).first.type()!==ta.Dummy)return!1;return!0}copy(){let e=new r(this._constant);return e._cellMap=this._cellMap.copy(),e}add(e){return this._constant+=e}insertSymbol(e,a=1){let s=this._cellMap.setDefault(e,()=>0);m5(s.second+=a)&&this._cellMap.erase(e)}insertRow(e,a=1){this._constant+=e._constant*a;let s=e._cellMap;for(let l=0,d=s.size();l<d;++l){let x=s.itemAt(l);this.insertSymbol(x.first,x.second*a)}}removeSymbol(e){this._cellMap.erase(e)}reverseSign(){this._constant=-this._constant;let e=this._cellMap;for(let a=0,s=e.size();a<s;++a){let l=e.itemAt(a);l.second=-l.second}}solveFor(e){let a=this._cellMap,l=-1/a.erase(e).second;this._constant*=l;for(let d=0,x=a.size();d<x;++d)a.itemAt(d).second*=l}solveForEx(e,a){this.insertSymbol(e,-1),this.solveFor(a)}coefficientFor(e){let a=this._cellMap.find(e);return a!==void 0?a.second:0}substitute(e,a){let s=this._cellMap.erase(e);s!==void 0&&this.insertRow(a,s.second)}};var JBe=Or(fs(),1);Ue();qt();Fo();var TY={};Am(TY,{boundsAreaOverlap:()=>h4e,boundsDistance:()=>m4e,clamp:()=>ms,computeDistanceBetweenBoxes:()=>sg,distSq:()=>d4e,distance:()=>wi,doBoundsOverlap:()=>Yb,doSegmentsIntersect:()=>tu,doesLineIntersectLine:()=>zp,doesSegmentIntersectRect:()=>o4e,findNearestPointsBetweenBoxSets:()=>zb,getBoundingBox:()=>td,getSegmentIntersection:()=>i4e,getUnitVectorFromDirection:()=>E5,getUnitVectorFromPointAToB:()=>F5,grid:()=>g4e,midpoint:()=>l4e,onSegment:()=>lg,orientation:()=>cg,pointToBoundsDistance:()=>c4e,pointToBoxDistance:()=>u4e,pointToSegmentClosestPoint:()=>f4e,pointToSegmentDistance:()=>Gs,range:()=>p4e,segmentToBoundsMinDistance:()=>Xb,segmentToBoxMinDistance:()=>x4e,segmentToCircleMinDistance:()=>b5,segmentToSegmentMinDistance:()=>y5});function zp([r,e],[a,s],{lineThickness:l=0}={}){return l===0?tu(r,e,a,s):fNt(r,e,a,s)<=l}function tu(r,e,a,s){let l=cg(r,e,a),d=cg(r,e,s),x=cg(a,s,r),f=cg(a,s,e);return!!(l!==d&&x!==f||l===0&&lg(r,a,e)||d===0&&lg(r,s,e)||x===0&&lg(a,r,s)||f===0&&lg(a,e,s))}function cg(r,e,a){let s=(e.y-r.y)*(a.x-e.x)-(e.x-r.x)*(a.y-e.y);return s===0?0:s>0?1:2}function lg(r,e,a){return e.x<=Math.max(r.x,a.x)&&e.x>=Math.min(r.x,a.x)&&e.y<=Math.max(r.y,a.y)&&e.y>=Math.min(r.y,a.y)}function fNt(r,e,a,s){if(r.x===e.x&&r.y===e.y)return Gs(r,a,s);if(a.x===s.x&&a.y===s.y)return Gs(a,r,e);if(tu(r,e,a,s))return 0;let l=[Gs(r,a,s),Gs(e,a,s),Gs(a,r,e),Gs(s,r,e)];return Math.min(...l)}function Gs(r,e,a){let s=(a.x-e.x)**2+(a.y-e.y)**2;if(s===0)return wi(r,e);let l=((r.x-e.x)*(a.x-e.x)+(r.y-e.y)*(a.y-e.y))/s;l=Math.max(0,Math.min(1,l));let d={x:e.x+l*(a.x-e.x),y:e.y+l*(a.y-e.y)};return wi(r,d)}function wi(r,e){let a=r.x-e.x,s=r.y-e.y;return Math.sqrt(a*a+s*s)}function i4e(r,e,a,s){let l=e.x-r.x,d=e.y-r.y,x=s.x-a.x,f=s.y-a.y,m=r.x-a.x,D=r.y-a.y,b=l*f-d*x;if(Math.abs(b)<1e-10)return null;let E=(D*x-m*f)/b,A=(l*D-d*m)/b,B=1e-9;if(E>=-B&&E<=1+B&&A>=-B&&A<=1+B){let w=r.x+E*l,P=r.y+E*d;return{x:w,y:P}}return null}function o4e(r,e,a){let s=m=>m.x>=a.minX&&m.x<=a.maxX&&m.y>=a.minY&&m.y<=a.maxY;if(s(r)||s(e))return!0;let l={x:a.minX,y:a.minY},d={x:a.maxX,y:a.minY},x={x:a.minX,y:a.maxY},f={x:a.maxX,y:a.maxY};return tu(r,e,l,d)||tu(r,e,d,f)||tu(r,e,f,x)||tu(r,e,x,l)}function u4e(r,e){let a=e.width/2,s=e.height/2,l=e.center.x-a,d=e.center.x+a,x=e.center.y-s,f=e.center.y+s;if(r.x>=l&&r.x<=d&&r.y>=x&&r.y<=f)return 0;let m=ms(r.x,l,d),D=ms(r.y,x,f);return wi(r,{x:m,y:D})}function c4e(r,e){if(r.x>=e.minX&&r.x<=e.maxX&&r.y>=e.minY&&r.y<=e.maxY)return 0;let a=ms(r.x,e.minX,e.maxX),s=ms(r.y,e.minY,e.maxY);return wi(r,{x:a,y:s})}function l4e(r,e){return{x:(r.x+e.x)/2,y:(r.y+e.y)/2}}function d4e(r,e){let a=r.x-e.x,s=r.y-e.y;return a*a+s*s}function p4e(r,e,a=1){if(a===0)throw new Error("step cannot be 0");let s,l;e===void 0?(s=0,l=r):(s=r,l=e);let d=[];if(a>0)for(let x=s;x<l;x+=a)d.push(x);else for(let x=s;x>l;x+=a)d.push(x);return d}function y5(r,e,a,s){if(r.x===e.x&&r.y===e.y)return Gs(r,a,s);if(a.x===s.x&&a.y===s.y)return Gs(a,r,e);if(tu(r,e,a,s))return 0;let l=[Gs(r,a,s),Gs(e,a,s),Gs(a,r,e),Gs(s,r,e)];return Math.min(...l)}function Xb(r,e,a){let s={x:a.minX,y:a.minY},l={x:a.maxX,y:a.minY},d={x:a.minX,y:a.maxY},x={x:a.maxX,y:a.maxY};if(tu(r,e,s,l)||tu(r,e,l,x)||tu(r,e,x,d)||tu(r,e,d,s)||r.x>=a.minX&&r.x<=a.maxX&&r.y>=a.minY&&r.y<=a.maxY&&e.x>=a.minX&&e.x<=a.maxX&&e.y>=a.minY&&e.y<=a.maxY)return 0;let f=[Gs(s,r,e),Gs(l,r,e),Gs(d,r,e),Gs(x,r,e)];if(r.x>=a.minX&&r.x<=a.maxX&&r.y>=a.minY&&r.y<=a.maxY||e.x>=a.minX&&e.x<=a.maxX&&e.y>=a.minY&&e.y<=a.maxY)return 0;if(r.x<a.minX||r.x>a.maxX||r.y<a.minY||r.y>a.maxY){let m=ms(r.x,a.minX,a.maxX),D=ms(r.y,a.minY,a.maxY);f.push(wi(r,{x:m,y:D}))}if(e.x<a.minX||e.x>a.maxX||e.y<a.minY||e.y>a.maxY){let m=ms(e.x,a.minX,a.maxX),D=ms(e.y,a.minY,a.maxY);f.push(wi(e,{x:m,y:D}))}return Math.min(...f)}function x4e(r,e,a){let s=a.width/2,l=a.height/2,d={minX:a.center.x-s,maxX:a.center.x+s,minY:a.center.y-l,maxY:a.center.y+l};return Xb(r,e,d)}function b5(r,e,a){let s={x:a.x,y:a.y};if(r.x===e.x&&r.y===e.y)return Math.max(0,wi(r,s)-a.radius);let l={x:e.x-r.x,y:e.y-r.y},d={x:s.x-r.x,y:s.y-r.y},x=l.x*l.x+l.y*l.y,f=Math.max(0,Math.min(1,(l.x*d.x+l.y*d.y)/x)),m={x:r.x+f*l.x,y:r.y+f*l.y},D=wi(m,s);return Math.max(0,D-a.radius)}function f4e(r,e,a){let s=a.x-e.x,l=a.y-e.y,d=s*s+l*l;if(d===0)return{x:e.x,y:e.y};let x=((r.x-e.x)*s+(r.y-e.y)*l)/d;return x=Math.max(0,Math.min(1,x)),{x:e.x+x*s,y:e.y+x*l}}var h4e=(r,e)=>{let a=Math.max(0,Math.min(r.maxX,e.maxX)-Math.max(r.minX,e.minX)),s=Math.max(0,Math.min(r.maxY,e.maxY)-Math.max(r.minY,e.minY));return a*s};var m4e=(r,e)=>{let a=r.maxX<e.minX?e.minX-r.maxX:e.maxX<r.minX?r.minX-e.maxX:0,s=r.maxY<e.minY?e.minY-r.maxY:e.maxY<r.minY?r.minY-e.maxY:0;return Math.sqrt(a*a+s*s)};var Yb=(r,e)=>!(r.maxX<e.minX||e.maxX<r.minX||r.maxY<e.minY||e.maxY<r.minY);var F5=(r,e)=>{let a={x:e.x-r.x,y:e.y-r.y},s=Math.sqrt(a.x**2+a.y**2);return{x:a.x/s,y:a.y/s}},E5=r=>{switch(r){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 g4e({rows:r,cols:e,xSpacing:a,ySpacing:s,width:l,height:d,offsetX:x=0,offsetY:f=0,yDirection:m="cartesian",centered:D=!0}){let b=a??1,E=s??1,A=l??e*b,B=d??r*E,w=D?-A/2:0,P=D?-B/2:0,j=l?l/e:b,O=d?d/r:E,z=[];for(let ee=0;ee<r;ee++)for(let W=0;W<e;W++){let re=ee*e+W,L=x+w+W*j+j/2,K=f+ee*O+O/2,U=m==="cartesian"?f+P+(r-1-ee)*O+O/2:f+P+ee*O+O/2;z.push({index:re,center:{x:L,y:U},topLeft:{x:L-j/2,y:U+O/2},bottomRight:{x:L+j/2,y:U-O/2},row:ee,col:W})}return z}qt();var hNt=(r,e,a)=>{let s=[{x:r.x,y:r.y}],l=(r.x+e.x)/2,d=(r.y+e.y)/2,x={x:e.x,y:e.y};switch(e.facingDirection){case"x+":x.x+=a;break;case"x-":x.x-=a;break;case"y+":x.y+=a;break;case"y-":x.y-=a;break}let f=r.facingDirection??"none",m=e.facingDirection??"none",D=A=>{let B=s[s.length-1];(B.x!==A.x||B.y!==A.y)&&s.push(A)},b=Math.abs(r.y-e.y)<=Math.max(1e-6,a*.1),E=Math.abs(r.x-e.x)<=Math.max(1e-6,a*.1);if(f==="none"&&m==="none")D({x:l,y:r.y}),D({x:l,y:e.y});else if(f==="x+"&&m==="y+")r.x>e.x&&r.y<e.y?(D({x:r.x+a,y:r.y}),D({x:r.x+a,y:e.y+a}),D({x:e.x,y:e.y+a})):!E&&!b&&r.x<e.x&&r.y>e.y?D({x:e.x,y:r.y}):E?(D({x:r.x+a,y:r.y}),D({x:r.x+a,y:e.y+a}),D({x:e.x,y:e.y+a})):r.x<e.x?(D({x:l,y:r.y}),D({x:l,y:x.y}),D({x:e.x,y:x.y})):r.y<=e.y+a?(D({x:r.x+a,y:r.y}),D({x:r.x+a,y:r.y+a}),D({x:e.x,y:r.y+a}),D({x:e.x,y:e.y})):(D({x:r.x+a,y:r.y}),D({x:r.x+a,y:(r.y+e.y)/2}),D({x:e.x,y:(r.y+e.y)/2}));else if(f==="x+"&&m==="x+"&&!b){let A=Math.max(r.x+a,x.x);D({x:A,y:r.y}),D({x:A,y:e.y})}else if(f==="x+"&&m==="x+"&&b)D({x:r.x+a,y:r.y}),D({x:r.x+a,y:r.y+a}),D({x:e.x+a,y:r.y+a}),D({x:e.x+a,y:e.y});else if(f==="x+"&&m==="y-")if(E&&r.y<=e.y)D({x:r.x+a,y:r.y}),D({x:r.x+a,y:d}),D({x:e.x,y:d});else if(E&&r.y>e.y)D({x:r.x+a,y:r.y}),D({x:r.x+a,y:e.y-a}),D({x:e.x,y:e.y-a});else if(r.x<e.x&&r.y<e.y)D({x:e.x,y:r.y});else if(r.x>e.x&&r.y<e.y){let A=r.x+a;D({x:A,y:r.y}),D({x:A,y:d}),D({x:e.x,y:d})}else if(r.x>e.x&&r.y>e.y){let A=r.x+a;D({x:A,y:r.y}),D({x:A,y:x.y}),D({x:e.x,y:x.y})}else r.y===e.y?(D({x:r.x+a,y:r.y}),D({x:r.x+a,y:r.y-a}),D({x:e.x,y:r.y-a})):(D({x:l,y:r.y}),D({x:l,y:x.y}),D({x:e.x,y:x.y}));else if(f==="x+"&&m==="x-"&&r.x+a>=e.x-a&&!b){let A=r.x+a;D({x:A,y:r.y}),D({x:A,y:d}),D({x:x.x,y:d}),D({x:x.x,y:x.y})}else f==="x+"&&m==="x-"&&b&&e.x>r.x||(f==="x+"&&m==="x-"&&b?(D({x:r.x+a,y:r.y}),D({x:r.x+a,y:r.y+a}),D({x:e.x-a,y:r.y+a}),D({x:e.x-a,y:r.y})):(f==="x+"&&D({x:r.x+a,y:r.y}),D({x:l,y:s[s.length-1].y}),D({x:l,y:x.y}),D({x:x.x,y:x.y})));return D({x:e.x,y:e.y}),s},dg=(r,e,a={})=>{let s=r,l=e,d=!1;(s.x>l.x||s.x===l.x&&s.y>l.y)&&(d=!0,[s,l]=[l,s]);let x=s.facingDirection==="x-",f=s.facingDirection==="y-",m=z=>{let ee=x?s.x-(z.x-s.x):z.x,W=f?s.y-(z.y-s.y):z.y,re=z.facingDirection;return x&&(re==="x+"?re="x-":re==="x-"&&(re="x+")),f&&(re==="y+"?re="y-":re==="y-"&&(re="y+")),{x:ee,y:W,facingDirection:re}},D=(z,ee)=>{let W=z.x-ee.x,re=z.y-ee.y,L=ee.x+re,K=ee.y-W,U=z.facingDirection;switch(U){case"x+":U="y-";break;case"y-":U="x-";break;case"x-":U="y+";break;case"y+":U="x+";break}return{x:L,y:K,facingDirection:U}},b=(z,ee)=>{let W=z.x-ee.x,re=z.y-ee.y;return{x:ee.x-re,y:ee.y+W}},E=x||f?m(s):s,A=x||f?m(l):l,B=E,w=A,P=!1;E.facingDirection==="y+"&&(P=!0,B={...E,facingDirection:"x+"},w=D(A,E));let j=a?.overshoot??.1*Math.max(Math.abs(B.x-w.x),Math.abs(B.y-w.y)),O=hNt(B,w,j);return P&&(O=O.map(z=>b(z,B))),(x||f)&&(O=O.map(({x:z,y:ee})=>({x:x?s.x-(z-s.x):z,y:f?s.y-(ee-s.y):ee}))),d?O.reverse():O};var D4e={name:"@tscircuit/capacity-autorouter",main:"./dist/index.js",version:"0.0.107",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"},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","@tscircuit/checks":"^0.0.36","@tscircuit/circuit-json-util":"^0.0.46","@tscircuit/core":"^0.0.337","@tscircuit/math-utils":"^0.0.18","@types/bun":"^1.2.16","@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","bun-match-svg":"^0.0.9","circuit-json-to-connectivity-map":"^0.0.19","circuit-to-svg":"^0.0.110",clsx:"^2.1.1",flatbush:"^4.4.0","graphics-debug":"^0.0.44",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","use-mouse-matrix-transform":"^1.3.0",vite:"^6.0.11","vite-tsconfig-paths":"^5.1.4"},peerDependencies:{typescript:"^5.7.3"},dependencies:{"fast-json-stable-stringify":"^2.1.0","object-hash":"^3.0.0"}};qt();Fo();ra();var tK=Or(kc(),1);qt();var v6e=Or(kY(),1),A6e=Or(kY(),1);var L5=(...r)=>{let e={points:[],lines:[],circles:[],rects:[]};return r.forEach((a,s)=>{a&&(a.lines&&(e.lines=[...e.lines||[],...a.lines.map(l=>({...l,step:s}))]),a.points&&(e.points=[...e.points||[],...a.points.map(l=>({...l,step:s}))]),a.circles&&(e.circles=[...e.circles||[],...a.circles.map(l=>({...l,step:s}))]),a.rects&&(e.rects=[...e.rects||[],...a.rects.map(l=>({...l,step:s}))]))}),e},Aa=class{constructor(){q(this,"MAX_ITERATIONS",1e3);q(this,"solved",!1);q(this,"failed",!1);q(this,"iterations",0);q(this,"progress",0);q(this,"error",null);q(this,"activeSubSolver");q(this,"failedSubSolvers");q(this,"timeToSolve");q(this,"stats",{});q(this,"cacheHit");q(this,"cacheKey");q(this,"cacheToSolveSpaceTransform")}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(r){throw this.error=`${this.constructor.name} error: ${r}`,console.error(this.error),this.failed=!0,r}!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 r=Date.now();for(;!this.solved&&!this.failed;)this.step();let e=Date.now();this.timeToSolve=e-r}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function nu(){return nu=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var a=arguments[e];for(var s in a)({}).hasOwnProperty.call(a,s)&&(r[s]=a[s])}return r},nu.apply(null,arguments)}function U5(r,e){return(U5=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(a,s){return a.__proto__=s,a})(r,e)}function u6e(r){return(u6e=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(r)}function c6e(){try{var r=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(c6e=function(){return!!r})()}function YY(r){var e=typeof Map=="function"?new Map:void 0;return YY=function(a){if(a===null||!(function(l){try{return Function.toString.call(l).indexOf("[native code]")!==-1}catch{return typeof l=="function"}})(a))return a;if(typeof a!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(a))return e.get(a);e.set(a,s)}function s(){return(function(l,d,x){if(c6e())return Reflect.construct.apply(null,arguments);var f=[null];f.push.apply(f,d);var m=new(l.bind.apply(l,f));return x&&U5(m,x.prototype),m})(a,arguments,u6e(this).constructor)}return s.prototype=Object.create(a.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),U5(s,a)},YY(r)}var ru=(function(r){var e,a;function s(l){var d;if(1)d=r.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+l+" for more information.")||this;else for(var x,f,m;m<x;m++);return(function(D){if(D===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return D})(d)}return a=r,(e=s).prototype=Object.create(a.prototype),e.prototype.constructor=e,U5(e,a),s})(YY(Error));function I4e(r,e){return r.substr(-e.length)===e}var RNt=/^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;function j4e(r){return typeof r!="string"?r:r.match(RNt)?parseFloat(r):r}var k4e=function(r){return function(e,a){a===void 0&&(a="16px");var s=e,l=a;if(typeof e=="string"){if(!I4e(e,"px"))throw new ru(69,r,e);s=j4e(e)}if(typeof a=="string"){if(!I4e(a,"px"))throw new ru(70,r,a);l=j4e(a)}if(typeof s=="string")throw new ru(71,e,r);if(typeof l=="string")throw new ru(72,a,r);return""+s/l+r}};k4e("em"),k4e("rem");function NY(r){return Math.round(255*r)}function SNt(r,e,a){return NY(r)+","+NY(e)+","+NY(a)}function rF(r,e,a,s){if(s===void 0&&(s=SNt),e===0)return s(a,a,a);var l=(r%360+360)%360/60,d=(1-Math.abs(2*a-1))*e,x=d*(1-Math.abs(l%2-1)),f=0,m=0,D=0;l>=0&&l<1?(f=d,m=x):l>=1&&l<2?(f=x,m=d):l>=2&&l<3?(m=d,D=x):l>=3&&l<4?(m=x,D=d):l>=4&&l<5?(f=x,D=d):l>=5&&l<6&&(f=d,D=x);var b=a-d/2;return s(f+b,m+b,D+b)}var N4e={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"},BNt=/^#[a-fA-F0-9]{6}$/,wNt=/^#[a-fA-F0-9]{8}$/,TNt=/^#[a-fA-F0-9]{3}$/,PNt=/^#[a-fA-F0-9]{4}$/,MY=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,INt=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,jNt=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,kNt=/^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 Dg(r){if(typeof r!="string")throw new ru(3);var e=(function(A){if(typeof A!="string")return A;var B=A.toLowerCase();return N4e[B]?"#"+N4e[B]:A})(r);if(e.match(BNt))return{red:parseInt(""+e[1]+e[2],16),green:parseInt(""+e[3]+e[4],16),blue:parseInt(""+e[5]+e[6],16)};if(e.match(wNt)){var a=parseFloat((parseInt(""+e[7]+e[8],16)/255).toFixed(2));return{red:parseInt(""+e[1]+e[2],16),green:parseInt(""+e[3]+e[4],16),blue:parseInt(""+e[5]+e[6],16),alpha:a}}if(e.match(TNt))return{red:parseInt(""+e[1]+e[1],16),green:parseInt(""+e[2]+e[2],16),blue:parseInt(""+e[3]+e[3],16)};if(e.match(PNt)){var s=parseFloat((parseInt(""+e[4]+e[4],16)/255).toFixed(2));return{red:parseInt(""+e[1]+e[1],16),green:parseInt(""+e[2]+e[2],16),blue:parseInt(""+e[3]+e[3],16),alpha:s}}var l=MY.exec(e);if(l)return{red:parseInt(""+l[1],10),green:parseInt(""+l[2],10),blue:parseInt(""+l[3],10)};var d=INt.exec(e.substring(0,50));if(d)return{red:parseInt(""+d[1],10),green:parseInt(""+d[2],10),blue:parseInt(""+d[3],10),alpha:parseFloat(""+d[4])>1?parseFloat(""+d[4])/100:parseFloat(""+d[4])};var x=jNt.exec(e);if(x){var f="rgb("+rF(parseInt(""+x[1],10),parseInt(""+x[2],10)/100,parseInt(""+x[3],10)/100)+")",m=MY.exec(f);if(!m)throw new ru(4,e,f);return{red:parseInt(""+m[1],10),green:parseInt(""+m[2],10),blue:parseInt(""+m[3],10)}}var D=kNt.exec(e.substring(0,50));if(D){var b="rgb("+rF(parseInt(""+D[1],10),parseInt(""+D[2],10)/100,parseInt(""+D[3],10)/100)+")",E=MY.exec(b);if(!E)throw new ru(4,e,b);return{red:parseInt(""+E[1],10),green:parseInt(""+E[2],10),blue:parseInt(""+E[3],10),alpha:parseFloat(""+D[4])>1?parseFloat(""+D[4])/100:parseFloat(""+D[4])}}throw new ru(5)}function Up(r){return(function(e){var a,s=e.red/255,l=e.green/255,d=e.blue/255,x=Math.max(s,l,d),f=Math.min(s,l,d),m=(x+f)/2;if(x===f)return e.alpha!==void 0?{hue:0,saturation:0,lightness:m,alpha:e.alpha}:{hue:0,saturation:0,lightness:m};var D=x-f,b=m>.5?D/(2-x-f):D/(x+f);switch(x){case s:a=(l-d)/D+(l<d?6:0);break;case l:a=(d-s)/D+2;break;default:a=(s-l)/D+4}return a*=60,e.alpha!==void 0?{hue:a,saturation:b,lightness:m,alpha:e.alpha}:{hue:a,saturation:b,lightness:m}})(Dg(r))}var HY=function(r){return r.length===7&&r[1]===r[2]&&r[3]===r[4]&&r[5]===r[6]?"#"+r[1]+r[3]+r[5]:r};function p1(r){var e=r.toString(16);return e.length===1?"0"+e:e}function OY(r){return p1(Math.round(255*r))}function NNt(r,e,a){return HY("#"+OY(r)+OY(e)+OY(a))}function R5(r,e,a){return rF(r,e,a,NNt)}function WY(r,e,a){if(typeof r=="number"&&typeof e=="number"&&typeof a=="number")return HY("#"+p1(r)+p1(e)+p1(a));if(typeof r=="object"&&e===void 0&&a===void 0)return HY("#"+p1(r.red)+p1(r.green)+p1(r.blue));throw new ru(6)}function H5(r,e,a,s){if(typeof r=="string"&&typeof e=="number"){var l=Dg(r);return"rgba("+l.red+","+l.green+","+l.blue+","+e+")"}if(typeof r=="number"&&typeof e=="number"&&typeof a=="number"&&typeof s=="number")return s>=1?WY(r,e,a):"rgba("+r+","+e+","+a+","+s+")";if(typeof r=="object"&&e===void 0&&a===void 0&&s===void 0)return r.alpha>=1?WY(r.red,r.green,r.blue):"rgba("+r.red+","+r.green+","+r.blue+","+r.alpha+")";throw new ru(7)}function Vp(r){if(typeof r!="object")throw new ru(8);if((function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&typeof e.alpha=="number"})(r))return H5(r);if((function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&(typeof e.alpha!="number"||e.alpha===void 0)})(r))return WY(r);if((function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&typeof e.alpha=="number"})(r))return(function(e,a,s,l){if(typeof e=="number"&&typeof a=="number"&&typeof s=="number"&&typeof l=="number")return l>=1?R5(e,a,s):"rgba("+rF(e,a,s)+","+l+")";if(typeof e=="object"&&a===void 0&&s===void 0&&l===void 0)return e.alpha>=1?R5(e.hue,e.saturation,e.lightness):"rgba("+rF(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new ru(2)})(r);if((function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&(typeof e.alpha!="number"||e.alpha===void 0)})(r))return(function(e,a,s){if(typeof e=="number"&&typeof a=="number"&&typeof s=="number")return R5(e,a,s);if(typeof e=="object"&&a===void 0&&s===void 0)return R5(e.hue,e.saturation,e.lightness);throw new ru(1)})(r);throw new ru(8)}function l6e(r,e,a){return function(){var s=a.concat(Array.prototype.slice.call(arguments));return s.length>=e?r.apply(this,s):l6e(r,e,s)}}function mu(r){return l6e(r,r.length,[])}mu(function(r,e){if(e==="transparent")return e;var a=Up(e);return Vp(nu({},a,{hue:a.hue+parseFloat(r)}))});function bg(r,e,a){return Math.max(r,Math.min(e,a))}mu(function(r,e){if(e==="transparent")return e;var a=Up(e);return Vp(nu({},a,{lightness:bg(0,1,a.lightness-parseFloat(r))}))});mu(function(r,e){if(e==="transparent")return e;var a=Up(e);return Vp(nu({},a,{saturation:bg(0,1,a.saturation-parseFloat(r))}))});mu(function(r,e){if(e==="transparent")return e;var a=Up(e);return Vp(nu({},a,{lightness:bg(0,1,a.lightness+parseFloat(r))}))});var d6e=mu(function(r,e,a){if(e==="transparent")return a;if(a==="transparent")return e;if(r===0)return a;var s=Dg(e),l=nu({},s,{alpha:typeof s.alpha=="number"?s.alpha:1}),d=Dg(a),x=nu({},d,{alpha:typeof d.alpha=="number"?d.alpha:1}),f=l.alpha-x.alpha,m=2*parseFloat(r)-1,D=((m*f===-1?m:m+f)/(1+m*f)+1)/2,b=1-D;return H5({red:Math.floor(l.red*D+x.red*b),green:Math.floor(l.green*D+x.green*b),blue:Math.floor(l.blue*D+x.blue*b),alpha:l.alpha*parseFloat(r)+x.alpha*(1-parseFloat(r))})});mu(function(r,e){if(e==="transparent")return e;var a=Dg(e);return H5(nu({},a,{alpha:bg(0,1,(100*(typeof a.alpha=="number"?a.alpha:1)+100*parseFloat(r))/100)}))});mu(function(r,e){if(e==="transparent")return e;var a=Up(e);return Vp(nu({},a,{saturation:bg(0,1,a.saturation+parseFloat(r))}))});mu(function(r,e){return e==="transparent"?e:Vp(nu({},Up(e),{hue:parseFloat(r)}))});mu(function(r,e){return e==="transparent"?e:Vp(nu({},Up(e),{lightness:parseFloat(r)}))});mu(function(r,e){return e==="transparent"?e:Vp(nu({},Up(e),{saturation:parseFloat(r)}))});mu(function(r,e){return e==="transparent"?e:d6e(parseFloat(r),"rgb(0, 0, 0)",e)});mu(function(r,e){return e==="transparent"?e:d6e(parseFloat(r),"rgb(255, 255, 255)",e)});var MNt=mu(function(r,e){if(e==="transparent")return e;var a=Dg(e);return H5(nu({},a,{alpha:bg(0,1,+(100*(typeof a.alpha=="number"?a.alpha:1)-100*parseFloat(r)).toFixed(2)/100)}))}),M4e=["blue","orange","purple","cyan","magenta","yellowgreen","darkgoldenrod","deeppink"],KY=(r,e)=>{let a={};for(let s=0;s<r.connections.length;s++){let l=r.connections[s],d=e?.getNetConnectedToId(l.name);d&&!a[d]&&(a[d]=`hsl(${300*s/r.connections.length}, 100%, 50%)`),a[l.name]=(d?a[d]:null)??`hsl(${340*s/r.connections.length}, 100%, 50%)`}return a},ys=(r,e)=>{try{return MNt(e,r)}catch(a){return console.error(a),r}},nF=(r,e)=>r==="top"?0:r==="bottom"?e-1:parseInt(r.slice(5)),X0=(r,e=1)=>{let a=(("width"in r?r.width:r)/.5/2)**1.1*e;return r.availableZ?.length===1&&a>1?1:a},ONt=(r,e=.5,a=16)=>{let s=0,l=r;for(;s<a&&!(X0({width:l})<=e);)l/=2,s++;return Math.max(1,s)};function p6e(r,e,a=0,s=r.length-1,l=LNt){for(;s>a;){if(s-a>600){let m=s-a+1,D=e-a+1,b=Math.log(m),E=.5*Math.exp(2*b/3),A=.5*Math.sqrt(b*E*(m-E)/m)*(D-m/2<0?-1:1);p6e(r,e,Math.max(a,Math.floor(e-D*E/m+A)),Math.min(s,Math.floor(e+(m-D)*E/m+A)),l)}let d=r[e],x=a,f=s;for(Wb(r,a,e),l(r[s],d)>0&&Wb(r,a,s);x<f;){for(Wb(r,x,f),x++,f--;l(r[x],d)<0;)x++;for(;l(r[f],d)>0;)f--}l(r[a],d)===0?Wb(r,a,f):(f++,Wb(r,f,s)),f<=e&&(a=f+1),e<=f&&(s=f-1)}}function Wb(r,e,a){let s=r[e];r[e]=r[a],r[a]=s}function LNt(r,e){return r<e?-1:r>e?1:0}var $Nt=class{constructor(r=9){this._maxEntries=Math.max(4,r),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(r){let e=this.data,a=[];if(!B5(r,e))return a;let s=this.toBBox,l=[];for(;e;){for(let d=0;d<e.children.length;d++){let x=e.children[d],f=e.leaf?s(x):x;B5(r,f)&&(e.leaf?a.push(x):$Y(r,f)?this._all(x,a):l.push(x))}e=l.pop()}return a}collides(r){let e=this.data;if(!B5(r,e))return!1;let a=[];for(;e;){for(let s=0;s<e.children.length;s++){let l=e.children[s],d=e.leaf?this.toBBox(l):l;if(B5(r,d)){if(e.leaf||$Y(r,d))return!0;a.push(l)}}e=a.pop()}return!1}load(r){if(!r||!r.length)return this;if(r.length<this._minEntries){for(let a=0;a<r.length;a++)this.insert(r[a]);return this}let e=this._build(r.slice(),0,r.length-1,0);if(this.data.children.length)if(this.data.height===e.height)this._splitRoot(this.data,e);else{if(this.data.height<e.height){let a=this.data;this.data=e,e=a}this._insert(e,this.data.height-e.height-1,!0)}else this.data=e;return this}insert(r){return r&&this._insert(r,this.data.height-1),this}clear(){return this.data=hg([]),this}remove(r,e){if(!r)return this;let a=this.data,s=this.toBBox(r),l=[],d=[],x,f,m;for(;a||l.length;){if(a||(a=l.pop(),f=l[l.length-1],x=d.pop(),m=!0),a.leaf){let D=zNt(r,a.children,e);if(D!==-1)return a.children.splice(D,1),l.push(a),this._condense(l),this}m||a.leaf||!$Y(a,s)?f?(x++,a=f.children[x],m=!1):a=null:(l.push(a),d.push(x),x=0,f=a,a=a.children[0])}return this}toBBox(r){return r}compareMinX(r,e){return r.minX-e.minX}compareMinY(r,e){return r.minY-e.minY}toJSON(){return this.data}fromJSON(r){return this.data=r,this}_all(r,e){let a=[];for(;r;)r.leaf?e.push(...r.children):a.push(...r.children),r=a.pop();return e}_build(r,e,a,s){let l=a-e+1,d,x=this._maxEntries;if(l<=x)return d=hg(r.slice(e,a+1)),fg(d,this.toBBox),d;s||(s=Math.ceil(Math.log(l)/Math.log(x)),x=Math.ceil(l/Math.pow(x,s-1))),d=hg([]),d.leaf=!1,d.height=s;let f=Math.ceil(l/x),m=f*Math.ceil(Math.sqrt(x));O4e(r,e,a,m,this.compareMinX);for(let D=e;D<=a;D+=m){let b=Math.min(D+m-1,a);O4e(r,D,b,f,this.compareMinY);for(let E=D;E<=b;E+=f){let A=Math.min(E+f-1,b);d.children.push(this._build(r,E,A,s-1))}}return fg(d,this.toBBox),d}_chooseSubtree(r,e,a,s){for(;s.push(e),!e.leaf&&s.length-1!==a;){let l,d=1/0,x=1/0;for(let f=0;f<e.children.length;f++){let m=e.children[f],D=LY(m),b=VNt(r,m)-D;b<x?(x=b,d=D<d?D:d,l=m):b===x&&D<d&&(d=D,l=m)}e=l||e.children[0]}return e}_insert(r,e,a){let s=a?r:this.toBBox(r),l=[],d=this._chooseSubtree(s,this.data,e,l);for(d.children.push(r),Jb(d,s);e>=0&&l[e].children.length>this._maxEntries;)this._split(l,e),e--;this._adjustParentBBoxes(s,l,e)}_split(r,e){let a=r[e],s=a.children.length,l=this._minEntries;this._chooseSplitAxis(a,l,s);let d=this._chooseSplitIndex(a,l,s),x=hg(a.children.splice(d,a.children.length-d));x.height=a.height,x.leaf=a.leaf,fg(a,this.toBBox),fg(x,this.toBBox),e?r[e-1].children.push(x):this._splitRoot(a,x)}_splitRoot(r,e){this.data=hg([r,e]),this.data.height=r.height+1,this.data.leaf=!1,fg(this.data,this.toBBox)}_chooseSplitIndex(r,e,a){let s,l=1/0,d=1/0;for(let x=e;x<=a-e;x++){let f=Kb(r,0,x,this.toBBox),m=Kb(r,x,a,this.toBBox),D=GNt(f,m),b=LY(f)+LY(m);D<l?(l=D,s=x,d=b<d?b:d):D===l&&b<d&&(d=b,s=x)}return s||a-e}_chooseSplitAxis(r,e,a){let s=r.leaf?this.compareMinX:qNt,l=r.leaf?this.compareMinY:UNt;this._allDistMargin(r,e,a,s)<this._allDistMargin(r,e,a,l)&&r.children.sort(s)}_allDistMargin(r,e,a,s){r.children.sort(s);let l=this.toBBox,d=Kb(r,0,e,l),x=Kb(r,a-e,a,l),f=S5(d)+S5(x);for(let m=e;m<a-e;m++){let D=r.children[m];Jb(d,r.leaf?l(D):D),f+=S5(d)}for(let m=a-e-1;m>=e;m--){let D=r.children[m];Jb(x,r.leaf?l(D):D),f+=S5(x)}return f}_adjustParentBBoxes(r,e,a){for(let s=a;s>=0;s--)Jb(e[s],r)}_condense(r){for(let e,a=r.length-1;a>=0;a--)r[a].children.length===0?a>0?(e=r[a-1].children,e.splice(e.indexOf(r[a]),1)):this.clear():fg(r[a],this.toBBox)}};function zNt(r,e,a){if(!a)return e.indexOf(r);for(let s=0;s<e.length;s++)if(a(r,e[s]))return s;return-1}function fg(r,e){Kb(r,0,r.children.length,e,r)}function Kb(r,e,a,s,l){l||(l=hg(null)),l.minX=1/0,l.minY=1/0,l.maxX=-1/0,l.maxY=-1/0;for(let d=e;d<a;d++){let x=r.children[d];Jb(l,r.leaf?s(x):x)}return l}function Jb(r,e){return r.minX=Math.min(r.minX,e.minX),r.minY=Math.min(r.minY,e.minY),r.maxX=Math.max(r.maxX,e.maxX),r.maxY=Math.max(r.maxY,e.maxY),r}function qNt(r,e){return r.minX-e.minX}function UNt(r,e){return r.minY-e.minY}function LY(r){return(r.maxX-r.minX)*(r.maxY-r.minY)}function S5(r){return r.maxX-r.minX+(r.maxY-r.minY)}function VNt(r,e){return(Math.max(e.maxX,r.maxX)-Math.min(e.minX,r.minX))*(Math.max(e.maxY,r.maxY)-Math.min(e.minY,r.minY))}function GNt(r,e){let a=Math.max(r.minX,e.minX),s=Math.max(r.minY,e.minY),l=Math.min(r.maxX,e.maxX),d=Math.min(r.maxY,e.maxY);return Math.max(0,l-a)*Math.max(0,d-s)}function $Y(r,e){return r.minX<=e.minX&&r.minY<=e.minY&&e.maxX<=r.maxX&&e.maxY<=r.maxY}function B5(r,e){return e.minX<=r.maxX&&e.minY<=r.maxY&&e.maxX>=r.minX&&e.maxY>=r.minY}function hg(r){return{children:r,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function O4e(r,e,a,s,l){let d=[e,a];for(;d.length;){if((a=d.pop())-(e=d.pop())<=s)continue;let x=e+Math.ceil((a-e)/s/2)*s;p6e(r,x,e,a,l),d.push(e,x,x,a)}}var L4e=class{constructor(r=9){q(this,"tree");this.tree=new $Nt(r)}insert(r,e,a,s,l){this.tree.insert({minX:e,minY:a,maxX:s,maxY:l,data:r})}bulkLoad(r){let e=r.map(({item:a,minX:s,minY:l,maxX:d,maxY:x})=>({minX:s,minY:l,maxX:d,maxY:x,data:a}));this.tree.load(e)}search(r,e,a,s){return this.tree.search({minX:r,minY:e,maxX:a,maxY:s}).map(l=>l.data)}clear(){this.tree.clear()}},XNt=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(r,e){let a=this.length++;for(;a>0;){let s=a-1>>1,l=this.values[s];if(e>=l)break;this.ids[a]=this.ids[s],this.values[a]=l,a=s}this.ids[a]=r,this.values[a]=e}pop(){if(this.length===0)return;let r=this.ids[0];if(this.length--,this.length>0){let e=this.ids[0]=this.ids[this.length],a=this.values[0]=this.values[this.length],s=this.length>>1,l=0;for(;l<s;){let d=1+(l<<1),x=d+1,f=this.ids[d],m=this.values[d],D=this.values[x];if(x<this.length&&D<m&&(d=x,f=this.ids[x],m=D),m>=a)break;this.ids[l]=f,this.values[l]=m,l=d}this.ids[l]=e,this.values[l]=a}return r}peek(){if(this.length!==0)return this.ids[0]}peekValue(){if(this.length!==0)return this.values[0]}shrink(){this.ids.length=this.values.length=this.length}},$4e=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],z4e=class x6e{static from(e,a=0){if(a%8!=0)throw new Error("byteOffset must be 8-byte aligned.");if(!e||e.byteLength===void 0||e.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[s,l]=new Uint8Array(e,a+0,2);if(s!==251)throw new Error("Data does not appear to be in a Flatbush format.");let d=l>>4;if(d!==3)throw new Error(`Got v${d} data when expected v3.`);let x=$4e[15&l];if(!x)throw new Error("Unrecognized array type.");let[f]=new Uint16Array(e,a+2,1),[m]=new Uint32Array(e,a+4,1);return new x6e(m,f,x,void 0,e,a)}constructor(e,a=16,s=Float64Array,l=ArrayBuffer,d,x=0){if(e===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(e)||e<=0)throw new Error(`Unexpected numItems value: ${e}.`);this.numItems=+e,this.nodeSize=Math.min(Math.max(+a,2),65535),this.byteOffset=x;let f=e,m=f;this._levelBounds=[4*f];do f=Math.ceil(f/this.nodeSize),m+=f,this._levelBounds.push(4*m);while(f!==1);this.ArrayType=s,this.IndexArrayType=m<16384?Uint16Array:Uint32Array;let D=$4e.indexOf(this.ArrayType),b=4*m*this.ArrayType.BYTES_PER_ELEMENT;if(D<0)throw new Error(`Unexpected typed array class: ${s}.`);d&&d.byteLength!==void 0&&!d.buffer?(this.data=d,this._boxes=new this.ArrayType(this.data,x+8,4*m),this._indices=new this.IndexArrayType(this.data,x+8+b,m),this._pos=4*m,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]):(this.data=new l(8+b+m*this.IndexArrayType.BYTES_PER_ELEMENT),this._boxes=new this.ArrayType(this.data,8,4*m),this._indices=new this.IndexArrayType(this.data,8+b,m),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(this.data,0,2).set([251,48+D]),new Uint16Array(this.data,2,1)[0]=a,new Uint32Array(this.data,4,1)[0]=e),this._queue=new XNt}add(e,a,s=e,l=a){let d=this._pos>>2,x=this._boxes;return this._indices[d]=d,x[this._pos++]=e,x[this._pos++]=a,x[this._pos++]=s,x[this._pos++]=l,e<this.minX&&(this.minX=e),a<this.minY&&(this.minY=a),s>this.maxX&&(this.maxX=s),l>this.maxY&&(this.maxY=l),d}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let e=this._boxes;if(this.numItems<=this.nodeSize)return e[this._pos++]=this.minX,e[this._pos++]=this.minY,e[this._pos++]=this.maxX,void(e[this._pos++]=this.maxY);let a=this.maxX-this.minX||1,s=this.maxY-this.minY||1,l=new Uint32Array(this.numItems);for(let d=0,x=0;d<this.numItems;d++){let f=e[x++],m=e[x++],D=e[x++],b=e[x++],E=Math.floor(65535*((f+D)/2-this.minX)/a),A=Math.floor(65535*((m+b)/2-this.minY)/s);l[d]=HNt(E,A)}JY(l,e,this._indices,0,this.numItems-1,this.nodeSize);for(let d=0,x=0;d<this._levelBounds.length-1;d++){let f=this._levelBounds[d];for(;x<f;){let m=x,D=e[x++],b=e[x++],E=e[x++],A=e[x++];for(let B=1;B<this.nodeSize&&x<f;B++)D=Math.min(D,e[x++]),b=Math.min(b,e[x++]),E=Math.max(E,e[x++]),A=Math.max(A,e[x++]);this._indices[this._pos>>2]=m,e[this._pos++]=D,e[this._pos++]=b,e[this._pos++]=E,e[this._pos++]=A}}}search(e,a,s,l,d){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let x=this._boxes.length-4,f=[],m=[];for(;x!==void 0;){let D=Math.min(x+4*this.nodeSize,U4e(x,this._levelBounds));for(let b=x;b<D;b+=4){if(s<this._boxes[b]||l<this._boxes[b+1]||e>this._boxes[b+2]||a>this._boxes[b+3])continue;let E=0|this._indices[b>>2];x>=4*this.numItems?f.push(E):(d===void 0||d(E))&&m.push(E)}x=f.pop()}return m}neighbors(e,a,s=1/0,l=1/0,d){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let x=this._boxes.length-4,f=this._queue,m=[],D=l*l;e:for(;x!==void 0;){let b=Math.min(x+4*this.nodeSize,U4e(x,this._levelBounds));for(let E=x;E<b;E+=4){let A=0|this._indices[E>>2],B=q4e(e,this._boxes[E],this._boxes[E+2]),w=q4e(a,this._boxes[E+1],this._boxes[E+3]),P=B*B+w*w;P>D||(x>=4*this.numItems?f.push(A<<1,P):(d===void 0||d(A))&&f.push(1+(A<<1),P))}for(;f.length&&1&f.peek();)if(f.peekValue()>D||(m.push(f.pop()>>1),m.length===s))break e;x=f.length?f.pop()>>1:void 0}return f.clear(),m}};function q4e(r,e,a){return r<e?e-r:r<=a?0:r-a}function U4e(r,e){let a=0,s=e.length-1;for(;a<s;){let l=a+s>>1;e[l]>r?s=l:a=l+1}return e[a]}function JY(r,e,a,s,l,d){if(Math.floor(s/d)>=Math.floor(l/d))return;let x=r[s+l>>1],f=s-1,m=l+1;for(;;){do f++;while(r[f]<x);do m--;while(r[m]>x);if(f>=m)break;YNt(r,e,a,f,m)}JY(r,e,a,s,m,d),JY(r,e,a,m+1,l,d)}function YNt(r,e,a,s,l){let d=r[s];r[s]=r[l],r[l]=d;let x=4*s,f=4*l,m=e[x],D=e[x+1],b=e[x+2],E=e[x+3];e[x]=e[f],e[x+1]=e[f+1],e[x+2]=e[f+2],e[x+3]=e[f+3],e[f]=m,e[f+1]=D,e[f+2]=b,e[f+3]=E;let A=a[s];a[s]=a[l],a[l]=A}function HNt(r,e){let a=r^e,s=65535^a,l=65535^(r|e),d=r&(65535^e),x=a|s>>1,f=a>>1^a,m=l>>1^s&d>>1^l,D=a&l>>1^d>>1^d;a=x,s=f,l=m,d=D,x=a&a>>2^s&s>>2,f=a&s>>2^s&(a^s)>>2,m^=a&l>>2^s&d>>2,D^=s&l>>2^(a^s)&d>>2,a=x,s=f,l=m,d=D,x=a&a>>4^s&s>>4,f=a&s>>4^s&(a^s)>>4,m^=a&l>>4^s&d>>4,D^=s&l>>4^(a^s)&d>>4,a=x,s=f,l=m,d=D,m^=a&l>>8^s&d>>8,D^=s&l>>8^(a^s)&d>>8,a=m^m>>1,s=D^D>>1;let b=r^e,E=s|65535^(b|a);return b=16711935&(b|b<<8),b=252645135&(b|b<<4),b=858993459&(b|b<<2),b=1431655765&(b|b<<1),E=16711935&(E|E<<8),E=252645135&(E|E<<4),E=858993459&(E|E<<2),E=1431655765&(E|E<<1),(E<<1|b)>>>0}var WNt=class{constructor(r){q(this,"index");q(this,"items",[]);q(this,"currentIndex",0);q(this,"capacity");this.capacity=Math.max(1,r),this.index=new z4e(this.capacity)}insert(r,e,a,s,l){if(this.currentIndex>=this.index.numItems)throw new Error("Exceeded initial capacity");this.items[this.currentIndex]=r,this.index.add(e,a,s,l),this.currentIndex++}finish(){this.index.finish()}search(r,e,a,s){return this.index.search(r,e,a,s).map(l=>this.items[l]||null).filter(Boolean)}clear(){this.items=[],this.currentIndex=0,this.index=new z4e(this.capacity)}},f6e=class{constructor(r="native",e=[]){q(this,"idx");q(this,"storage",[]);r==="flatbush"?e.length===0?(this.idx=new L4e,r="rbush"):this.idx=new WNt(e.length):this.idx=r==="rbush"?new L4e:new class{constructor(){q(this,"shi",new KNt(e))}insert(a){}search(a,s,l,d){let x=(a+l)/2,f=(s+d)/2,m=l-a,D=d-s;return this.shi.getNodesInArea(x,f,m,D)}clear(){}},e.forEach(a=>this.insert(a)),r==="flatbush"&&e.length>0&&this.idx.finish?.()}insert(r){this.storage.push(r),this.idx.insert(r,r.center.x-r.width/2,r.center.y-r.height/2,r.center.x+r.width/2,r.center.y+r.height/2)}search(r){return this.idx.search(r.minX,r.minY,r.maxX,r.maxY)}searchArea(r,e,a,s){return this.search({minX:r-a/2,minY:e-s/2,maxX:r+a/2,maxY:e+s/2})}},KNt=class{constructor(r){q(this,"buckets");q(this,"CELL_SIZE",.4);this.obstacles=r,this.buckets=new Map;for(let e=0;e<r.length;e++){let a=r[e],s=a.center.x-a.width/2,l=a.center.y-a.height/2,d=a.center.x+a.width/2,x=a.center.y+a.height/2;for(let f=s;f<=d;f+=this.CELL_SIZE)for(let m=l;m<=x;m+=this.CELL_SIZE){let D=this.getBucketKey(f,m),b=this.buckets.get(D);b?b.push([a,e]):this.buckets.set(D,[[a,e]])}}}getBucketKey(r,e){return`${Math.floor(r/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getNodesInArea(r,e,a,s){let l=[],d=new Set,x=e-s/2,f=r+a/2,m=e+s/2;for(let D=r-a/2;D<=f;D+=this.CELL_SIZE)for(let b=x;b<=m;b+=this.CELL_SIZE){let E=this.getBucketKey(D,b),A=this.buckets.get(E)||[];for(let B of A)d.has(B[1])||(d.add(B[1]),l.push(B[0]))}return l}},JNt=class{constructor(r){q(this,"buckets");q(this,"CELL_SIZE",5);this.targets=r,this.buckets=new Map;for(let e=0;e<r.length;e++){let a=r[e],s=Math.floor(a.bounds.minX/this.CELL_SIZE)*this.CELL_SIZE,l=Math.floor(a.bounds.minY/this.CELL_SIZE)*this.CELL_SIZE,d=a.bounds.maxX,x=a.bounds.maxY;for(let f=s;f<=d;f+=this.CELL_SIZE)for(let m=l;m<=x;m+=this.CELL_SIZE){let D=this.getBucketKey(f,m),b=this.buckets.get(D);b?b.push([a,e]):this.buckets.set(D,[[a,e]])}}}getBucketKey(r,e){return`${Math.floor(r/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getTargetsInArea(r,e,a,s){let l=[],d=new Set,x=Math.floor((r-a/2)/this.CELL_SIZE)*this.CELL_SIZE,f=Math.floor((e-s/2)/this.CELL_SIZE)*this.CELL_SIZE,m=r+a/2,D=e+s/2;for(let b=x;b<=m;b+=this.CELL_SIZE)for(let E=f;E<=D;E+=this.CELL_SIZE){let A=this.getBucketKey(b,E),B=this.buckets.get(A)||[];for(let w of B)d.has(w[1])||(d.add(w[1]),l.push(w[0]))}return l}},ZNt=class extends Aa{constructor(e,a={}){super();q(this,"unfinishedNodes");q(this,"finishedNodes");q(this,"nodeToXYOverlappingObstaclesMap");q(this,"layerCount");q(this,"MAX_DEPTH",4);q(this,"targets");q(this,"targetTree");q(this,"obstacleTree");q(this,"_nextNodeCounter",0);this.srj=e,this.opts=a,this.MAX_DEPTH=a?.capacityDepth??this.MAX_DEPTH,this.MAX_ITERATIONS=1e5,this.layerCount=e.layerCount??2;for(let x of e.obstacles)if(!x.zLayers){let f=[];for(let m of x.layers)f.push(nF(m,e.layerCount));x.zLayers=f}let s={x:(e.bounds.minX+e.bounds.maxX)/2,y:(e.bounds.minY+e.bounds.maxY)/2},l={width:e.bounds.maxX-e.bounds.minX,height:e.bounds.maxY-e.bounds.minY},d=Math.max(l.width,l.height);this.unfinishedNodes=[{capacityMeshNodeId:this.getNextNodeId(),center:s,width:d,height:d,layer:"top",availableZ:[0,1],_depth:0,_containsTarget:!0,_containsObstacle:!0,_completelyInsideObstacle:!1}],this.finishedNodes=[],this.nodeToXYOverlappingObstaclesMap=new Map,this.obstacleTree=new f6e("flatbush",this.srj.obstacles),this.targets=this.computeTargets(),this.targetTree=new JNt(this.targets)}computeTargets(){let e=[];for(let a of this.srj.connections)for(let s of a.pointsToConnect){let l=this.obstacleTree.searchArea(s.x,s.y,.01,.01).filter(f=>f.zLayers.some(m=>s.layer==="top"?m===0:m===1)),d={minX:s.x-.005,minY:s.y-.005,maxX:s.x+.005,maxY:s.y+.005};l.length>0&&(d={minX:Math.min(...l.map(f=>f.center.x-f.width/2)),minY:Math.min(...l.map(f=>f.center.y-f.height/2)),maxX:Math.max(...l.map(f=>f.center.x+f.width/2)),maxY:Math.max(...l.map(f=>f.center.y+f.height/2))});let x={...s,connectionName:a.name,availableZ:s.layer==="top"?[0]:[1],bounds:d};e.push(x)}return e}getNextNodeId(){return"cn"+this._nextNodeCounter++}getCapacityFromDepth(e){return(this.MAX_DEPTH-e+1)**2}getTargetIfNodeContainsTarget(e){let a=e.width>4*this.targetTree.CELL_SIZE?this.targets:this.targetTree.getTargetsInArea(e.center.x,e.center.y,e.width,e.height);for(let s of a)if(s.bounds.minX<=e.center.x+e.width/2&&s.bounds.maxX>=e.center.x-e.width/2&&s.bounds.minY<=e.center.y+e.height/2&&s.bounds.maxY>=e.center.y-e.height/2&&s.availableZ.some(l=>e.availableZ.includes(l)))return s;return null}getXYOverlappingObstacles(e){let a=this.nodeToXYOverlappingObstaclesMap.get(e.capacityMeshNodeId);if(a)return a;let s=[],l=e.center.x-e.width/2,d=e.center.x+e.width/2,x=e.center.y-e.height/2,f=e.center.y+e.height/2,m=e._parent?this.getXYOverlappingObstacles(e._parent):this.srj.obstacles;for(let D of m){let b=D.center.x-D.width/2,E=D.center.x+D.width/2,A=D.center.y-D.height/2,B=D.center.y+D.height/2;(d>=b&&l<=E&&f>=A&&x<=B||l>=b&&d<=E&&x>=A&&f<=B||b>=l&&E<=d&&A>=x&&B<=f)&&s.push(D)}return this.nodeToXYOverlappingObstaclesMap.set(e.capacityMeshNodeId,s),s}getXYZOverlappingObstacles(e){let a=this.getXYOverlappingObstacles(e),s=[];for(let l of a)e.availableZ.some(d=>l.zLayers.includes(d))&&s.push(l);return s}doesNodeOverlapObstacle(e){if(this.getXYZOverlappingObstacles(e).length>0)return!0;let a=e.center.x-e.width/2,s=e.center.x+e.width/2,l=e.center.y-e.height/2,d=e.center.y+e.height/2;return a<this.srj.bounds.minX||s>this.srj.bounds.maxX||l<this.srj.bounds.minY||d>this.srj.bounds.maxY}isNodeCompletelyInsideObstacle(e){let a=this.getXYZOverlappingObstacles(e),s=e.center.x-e.width/2,l=e.center.x+e.width/2,d=e.center.y-e.height/2,x=e.center.y+e.height/2;for(let f of a){let m=f.center.x-f.width/2,D=f.center.x+f.width/2,b=f.center.y-f.height/2,E=f.center.y+f.height/2;if(s>=m&&l<=D&&d>=b&&x<=E)return!0}return!1}getChildNodes(e){if(e._depth===this.MAX_DEPTH)return[];let a=[],s={width:e.width/2,height:e.height/2},l=[{x:e.center.x-s.width/2,y:e.center.y-s.height/2},{x:e.center.x+s.width/2,y:e.center.y-s.height/2},{x:e.center.x-s.width/2,y:e.center.y+s.height/2},{x:e.center.x+s.width/2,y:e.center.y+s.height/2}];for(let d of l){let x={capacityMeshNodeId:this.getNextNodeId(),center:d,width:s.width,height:s.height,layer:e.layer,availableZ:[0,1],_depth:(e._depth??0)+1,_parent:e};x._containsObstacle=this.doesNodeOverlapObstacle(x);let f=this.getTargetIfNodeContainsTarget(x);f&&(x._targetConnectionName=f.connectionName,x.availableZ=f.availableZ,x._containsTarget=!0),x._containsObstacle&&(x._completelyInsideObstacle=this.isNodeCompletelyInsideObstacle(x)),x._completelyInsideObstacle&&!x._containsTarget||a.push(x)}return a}shouldNodeBeXYSubdivided(e){return!(e._depth>=this.MAX_DEPTH)&&(!!e._containsTarget||!(!e._containsObstacle||e._completelyInsideObstacle))}_step(){let e=this.unfinishedNodes.pop();if(!e)return void(this.solved=!0);let a=this.getChildNodes(e),s=[],l=[];for(let d of a){let x=this.shouldNodeBeXYSubdivided(d);x?l.push(d):x||d._containsObstacle?!x&&d._containsTarget&&s.push(d):s.push(d)}this.unfinishedNodes.push(...l),this.finishedNodes.push(...s)}visualize(){let e={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Capacity Mesh Visualization"};for(let s of this.srj.obstacles)e.rects.push({center:s.center,width:s.width,height:s.height,fill:s.zLayers?.length===1&&s.zLayers?.includes(1)?"rgba(0,0,255,0.3)":"rgba(255,0,0,0.3)",stroke:"red",label:["obstacle",`z: ${s.zLayers.join(",")}`].join(`
|
|
954
954
|
`)});let a=[...this.finishedNodes,...this.unfinishedNodes];for(let s of a){let l=Math.min(...s.availableZ),d=this.unfinishedNodes.length>0&&s===this.unfinishedNodes[this.unfinishedNodes.length-1];e.rects.push({center:{x:s.center.x+l*s.width*.05,y:s.center.y-l*s.width*.05},width:Math.max(s.width-2,.8*s.width),height:Math.max(s.height-2,.8*s.height),fill:s._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)"}[s.availableZ.join(",")]??"rgba(0,200,200,0.1)",stroke:d?"rgba(255,165,0,0.5)":void 0,label:[s.capacityMeshNodeId,`availableZ: ${s.availableZ.join(",")}`,`target? ${s._containsTarget??!1}`,`obs? ${s._containsObstacle??!1}`,`${s.width.toFixed(2)}x${s.height.toFixed(2)}`,`capacity: ${X0(s).toFixed(2)}`].join(`
|
|
@@ -1034,8 +1034,8 @@ ${B.join(`
|
|
|
1034
1034
|
`)}
|
|
1035
1035
|
</div>`},uqt=r=>{let e=r.layout(),a={title:"CssGrid",coordinateSystem:"screen",lines:[],circles:[],points:[],rects:[],texts:[]},{cells:s}=e;for(let l of s){let{x:d,y:x,width:f,height:m,key:D}=l;a.rects.push({center:{x:d+f/2,y:x+m/2},width:f,height:m,fill:xSe(D),label:D})}return a};function AS(r){return r.replace(/repeat\((\d+),\s*([^)]+)\)/g,(e,a,s)=>Array(Number(a)).fill(s.trim()).join(" "))}function RS(r){return r.trim().split(/\s+/).filter(Boolean)}function lSe(r){return r?RS(AS(r)).length:0}function dSe(r,e){if(r==="auto")return{fr:1};if(r.endsWith("%")){let s=parseFloat(r);return e!=null?e*s/100:0}if(r.endsWith("px"))return parseFloat(r);if(r.endsWith("em"))return parseFloat(r)*16;if(r.endsWith("fr"))return{fr:parseFloat(r)};let a=parseFloat(r);return Number.isNaN(a)?0:a}function pSe(r,e){return r>0?r:e+2+r}var cqt=r=>{let e=r.opts,a=e.children,s,l;if("gridTemplate"in e&&typeof e.gridTemplate=="string"){let[L,K]=e.gridTemplate.split("/");s=L?.trim(),l=K?.trim()}else s=typeof e.gridTemplateRows=="string"?e.gridTemplateRows:void 0,l=typeof e.gridTemplateColumns=="string"?e.gridTemplateColumns:void 0;let d=lSe(l),x=lSe(s);function f(L,K,U,J){if(!L)return 0;let Q=AS(L),de=RS(Q),oe=de.length,Te=0,Me=!1;for(let et=0;et<de.length;et++){let dt=de[et];if(dt.endsWith("px"))Te+=parseFloat(dt);else if(dt.endsWith("em"))Te+=parseFloat(dt)*16;else if(dt.endsWith("fr")||dt==="auto"){Me=!0;let $t=0;for(let bt of K){let ut=U?bt.columnStart||bt.column:bt.rowStart||bt.row,it=U?bt.columnSpan||1:bt.rowSpan||1,Ut=U?bt.contentWidth:bt.contentHeight,It=(typeof ut=="number"?ut:parseInt(ut||"1"))-1,tr=typeof it=="number"?it:parseInt(it.toString());if(It<=et&&et<It+tr&&Ut){let Dr=typeof Ut=="string"&&Ut.endsWith("px")?parseFloat(Ut):typeof Ut=="number"?Ut:0;$t=Math.max($t,Dr/tr)}}Te+=$t}}let Ge=J*(oe-1);return Te+Ge}function m(L,K,U,J=!0,Q=1){if(!L)return[];if(K==null){let it=AS(L),Ut=RS(it),It=Ut.length,tr=Fe=>Fe===void 0?0:typeof Fe=="number"?Fe:(Fe.endsWith("px"),parseFloat(Fe)),Dr=new Array(It).fill(0),vt=0;for(let Fe of a){let Ie=J?typeof Fe.columnSpan=="number"?Fe.columnSpan:Fe.columnSpan?parseInt(Fe.columnSpan.toString()):1:typeof Fe.rowSpan=="number"?Fe.rowSpan:Fe.rowSpan?parseInt(Fe.rowSpan.toString()):1,_e=J?Fe.contentWidth:Fe.contentHeight,Ze=tr(_e)/Ie,Ft;J?(Fe.columnStart!==void 0||Fe.column!==void 0)&&(Ft=parseInt(Fe.columnStart??Fe.column)-1):(Fe.rowStart!==void 0||Fe.row!==void 0)&&(Ft=parseInt(Fe.rowStart??Fe.row)-1),(Ft===void 0||Number.isNaN(Ft))&&(J?Ft=vt%It:Ft=Math.floor(vt/Q),vt+=Ie);for(let St=0;St<Ie&&Ft+St<It;St++)Dr[Ft+St]=Math.max(Dr[Ft+St],Ze)}return Ut.forEach((Fe,Ie)=>{let _e=dSe(Fe,void 0);typeof _e=="number"&&(Dr[Ie]=_e)}),Dr}let de=AS(L),oe=RS(de),Te=oe.length,Me=K;Me==null&&(Me=f(L,a,J,U));let Ge=Me-U*(Te-1),et=0,dt=0,$t=[],bt=[];oe.forEach((it,Ut)=>{let It=dSe(it,Ge);typeof It=="number"?(bt.push(It),et+=It):It&&typeof It=="object"&&"fr"in It?(bt.push(It),dt+=It.fr,$t.push({idx:Ut,fr:It.fr})):(bt.push(0),et+=0)});let ut=Math.max(Ge-et,0);return bt.map(it=>typeof it=="number"?it:dt>0?ut/dt*it.fr:0)}let D=typeof e.gap=="number"?e.gap:Array.isArray(e.gap)?e.gap[0]:0,b=typeof e.gap=="number"?e.gap:Array.isArray(e.gap)?e.gap[1]:0,E=m(s,e.containerHeight,D,!1,d||1),A=m(l,e.containerWidth,b,!0,x||1),B=E.length,w=A.length;w===0&&a.length>0&&(w=1);let P=[],j=0;for(let L of a){let K=L.rowStart!==void 0?L.rowStart:L.row,U=L.columnStart!==void 0?L.columnStart:L.column,J=L.rowSpan!==void 0?typeof L.rowSpan=="string"?parseInt(L.rowSpan):L.rowSpan:1,Q=L.columnSpan!==void 0?typeof L.columnSpan=="string"?parseInt(L.columnSpan):L.columnSpan:1;if(L.rowEnd!==void 0){let Te=typeof L.rowEnd=="string"?parseInt(L.rowEnd):L.rowEnd;K!==void 0?J=Te-(typeof K=="string"?parseInt(K):K):K=Te-J}if(L.columnEnd!==void 0){let Te=typeof L.columnEnd=="string"?parseInt(L.columnEnd):L.columnEnd;U!==void 0?Q=Te-(typeof U=="string"?parseInt(U):U):U=Te-Q}if(typeof K=="string"&&(K=parseInt(K)),typeof U=="string"&&(U=parseInt(U)),typeof K=="number"&&K<0&&(K=pSe(K,B)),typeof U=="number"&&U<0&&(U=pSe(U,w)),K===void 0&&U!==void 0)K=1;else if(U===void 0&&K!==void 0)U=1;else if(K===void 0&&U===void 0){let Te=j;K=Math.floor(Te/w)+1,U=Te%w+1}let de=K-1,oe=U-1;J=Math.max(1,J),Q=Math.max(1,Q),P.push({key:L.key,row:de,column:oe,rowSpan:J,columnSpan:Q,x:0,y:0,width:0,height:0}),j+=Q}let O=E.length,z=A.length;for(let L of P)L.row+L.rowSpan>O&&(O=L.row+L.rowSpan),L.column+L.columnSpan>z&&(z=L.column+L.columnSpan);if(E.length===0&&O>0&&e.containerHeight){let L=O,U=(e.containerHeight-D*(L-1))/L;for(let J=0;J<L;J++)E.push(U)}else for(;E.length<O;)E.push(0);if(A.length===0&&z>0&&e.containerWidth){let L=z,U=(e.containerWidth-b*(L-1))/L;for(let J=0;J<L;J++)A.push(U)}else if(A.length===0&&a.length>0&&e.containerWidth)A.push(e.containerWidth);else for(;A.length<z;)A.push(0);let ee=(L,K,U)=>{let J=0;for(let Q=0;Q<L;Q++)J+=K[Q]||0,J+=U;return J},W=(L,K,U,J)=>{let Q=0;for(let de=L;de<L+K;de++)Q+=U[de]||0,de>L&&(Q+=J);return Q},re={};for(let L of P){let K=a.find(bt=>bt.key===L.key),U=ee(L.column,A,b),J=ee(L.row,E,D),Q=W(L.column,L.columnSpan,A,b),de=W(L.row,L.rowSpan,E,D),oe=bt=>bt===void 0?0:typeof bt=="string"?bt.endsWith("px")?parseFloat(bt):bt.endsWith("%")?0:parseFloat(bt):bt,Te=oe(K?.contentWidth),Me=oe(K?.contentHeight),Ge=Q,et=de,dt=U,$t=J;if(Te>0)switch(Ge=Te,e.justifyItems||"stretch"){case"start":dt=U;break;case"end":dt=U+Q-Ge;break;case"center":dt=U+(Q-Ge)/2;break;case"stretch":Ge=Q,dt=U;break}if(Me>0)switch(et=Me,e.alignItems||"stretch"){case"start":$t=J;break;case"end":$t=J+de-et;break;case"center":$t=J+(de-et)/2;break;case"stretch":et=de,$t=J;break}L.x=dt,L.y=$t,L.width=Ge,L.height=et,re[L.key]={x:dt,y:$t,width:Ge,height:et}}return{cells:P,rowSizes:E,columnSizes:A,rowGap:D,columnGap:b,itemCoordinates:re}},fSe=class{constructor(r){q(this,"opts");this.opts=r}layout(){return cqt(this)}convertToHtml(){return oqt(this)}visualize(){return uqt(this)}};qt();var u9e=Or(fs(),1);ra();ra();qt();var vW=class{constructor(r){q(this,"netMap");q(this,"idToNetMap");this.netMap=r,this.idToNetMap={};for(let[e,a]of Object.entries(r))for(let s of a)this.idToNetMap[s]=e}addConnections(r){for(let e of r){let a=new Set;for(let l of e){let d=this.idToNetMap[l];d&&a.add(d)}let s;if(a.size===0)s=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[s]=[];else if(a.size===1)s=a.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{s=a.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(let l of a)if(l!==s){let d=this.netMap[s],x=this.netMap[l];if(d&&x){d.push(...x),this.netMap[l]=d;for(let f of d)this.idToNetMap[f]=s}}}for(let l of e){let d=this.netMap[s];d&&!d.includes(l)&&d.push(l),this.idToNetMap[l]=s}}}getIdsConnectedToNet(r){return this.netMap[r]||[]}getNetConnectedToId(r){return this.idToNetMap[r]}areIdsConnected(r,e){if(r===e)return!0;let a=this.getNetConnectedToId(r);if(!a)return!1;let s=this.getNetConnectedToId(e);return s?a===s||s===r||s===r:!1}areAllIdsConnected(r){if(r.length===0)return!0;let e=this.getNetConnectedToId(r[0]);if(!e)return!1;for(let a of r){let s=this.getNetConnectedToId(a);if(s===void 0||s!==e)return!1}return!0}};var TF=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(e,a){let s=this.length++;for(;s>0;){let l=s-1>>1,d=this.values[l];if(a>=d)break;this.ids[s]=this.ids[l],this.values[s]=d,s=l}this.ids[s]=e,this.values[s]=a}pop(){if(this.length===0)return;let e=this.ids,a=this.values,s=e[0],l=--this.length;if(l>0){let d=e[l],x=a[l],f=0,m=l>>1;for(;f<m;){let D=(f<<1)+1,b=D+1,E=D+(+(b<l)&+(a[b]<a[D]));if(a[E]>=x)break;e[f]=e[E],a[f]=a[E],f=E}e[f]=d,a[f]=x}return s}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){this.ids.length=this.values.length=this.length}};var hSe=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],CW=3,PF=class r{static from(e,a=0){if(a%8!==0)throw new Error("byteOffset must be 8-byte aligned.");if(!e||e.byteLength===void 0||e.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[s,l]=new Uint8Array(e,a+0,2);if(s!==251)throw new Error("Data does not appear to be in a Flatbush format.");let d=l>>4;if(d!==CW)throw new Error(`Got v${d} data when expected v${CW}.`);let x=hSe[l&15];if(!x)throw new Error("Unrecognized array type.");let[f]=new Uint16Array(e,a+2,1),[m]=new Uint32Array(e,a+4,1);return new r(m,f,x,void 0,e,a)}constructor(e,a=16,s=Float64Array,l=ArrayBuffer,d,x=0){if(e===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(e)||e<=0)throw new Error(`Unexpected numItems value: ${e}.`);this.numItems=+e,this.nodeSize=Math.min(Math.max(+a,2),65535),this.byteOffset=x;let f=e,m=f;this._levelBounds=[f*4];do f=Math.ceil(f/this.nodeSize),m+=f,this._levelBounds.push(m*4);while(f!==1);this.ArrayType=s,this.IndexArrayType=m<16384?Uint16Array:Uint32Array;let D=hSe.indexOf(s),b=m*4*s.BYTES_PER_ELEMENT;if(D<0)throw new Error(`Unexpected typed array class: ${s}.`);if(d)this.data=d,this._boxes=new s(d,x+8,m*4),this._indices=new this.IndexArrayType(d,x+8+b,m),this._pos=m*4,this.minX=this._boxes[this._pos-4],this.minY=this._boxes[this._pos-3],this.maxX=this._boxes[this._pos-2],this.maxY=this._boxes[this._pos-1];else{let E=this.data=new l(8+b+m*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new s(E,8,m*4),this._indices=new this.IndexArrayType(E,8+b,m),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(E,0,2).set([251,(CW<<4)+D]),new Uint16Array(E,2,1)[0]=a,new Uint32Array(E,4,1)[0]=e}this._queue=new TF}add(e,a,s=e,l=a){let d=this._pos>>2,x=this._boxes;return this._indices[d]=d,x[this._pos++]=e,x[this._pos++]=a,x[this._pos++]=s,x[this._pos++]=l,e<this.minX&&(this.minX=e),a<this.minY&&(this.minY=a),s>this.maxX&&(this.maxX=s),l>this.maxY&&(this.maxY=l),d}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let e=this._boxes;if(this.numItems<=this.nodeSize){e[this._pos++]=this.minX,e[this._pos++]=this.minY,e[this._pos++]=this.maxX,e[this._pos++]=this.maxY;return}let a=this.maxX-this.minX||1,s=this.maxY-this.minY||1,l=new Uint32Array(this.numItems),d=65535;for(let x=0,f=0;x<this.numItems;x++){let m=e[f++],D=e[f++],b=e[f++],E=e[f++],A=Math.floor(d*((m+b)/2-this.minX)/a),B=Math.floor(d*((D+E)/2-this.minY)/s);l[x]=dqt(A,B)}_W(l,e,this._indices,0,this.numItems-1,this.nodeSize);for(let x=0,f=0;x<this._levelBounds.length-1;x++){let m=this._levelBounds[x];for(;f<m;){let D=f,b=e[f++],E=e[f++],A=e[f++],B=e[f++];for(let w=1;w<this.nodeSize&&f<m;w++)b=Math.min(b,e[f++]),E=Math.min(E,e[f++]),A=Math.max(A,e[f++]),B=Math.max(B,e[f++]);this._indices[this._pos>>2]=D,e[this._pos++]=b,e[this._pos++]=E,e[this._pos++]=A,e[this._pos++]=B}}}search(e,a,s,l,d){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let x=this._boxes.length-4,f=[],m=[];for(;x!==void 0;){let D=Math.min(x+this.nodeSize*4,mSe(x,this._levelBounds));for(let b=x;b<D;b+=4){let E=this._boxes[b];if(s<E)continue;let A=this._boxes[b+1];if(l<A)continue;let B=this._boxes[b+2];if(e>B)continue;let w=this._boxes[b+3];if(a>w)continue;let P=this._indices[b>>2]|0;x>=this.numItems*4?f.push(P):(d===void 0||d(P,E,A,B,w))&&m.push(P)}x=f.pop()}return m}neighbors(e,a,s=1/0,l=1/0,d){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let x=this._boxes.length-4,f=this._queue,m=[],D=l*l;e:for(;x!==void 0;){let b=Math.min(x+this.nodeSize*4,mSe(x,this._levelBounds));for(let E=x;E<b;E+=4){let A=this._indices[E>>2]|0,B=this._boxes[E],w=this._boxes[E+1],P=this._boxes[E+2],j=this._boxes[E+3],O=e<B?B-e:e>P?e-P:0,z=a<w?w-a:a>j?a-j:0,ee=O*O+z*z;ee>D||(x>=this.numItems*4?f.push(A<<1,ee):(d===void 0||d(A))&&f.push((A<<1)+1,ee))}for(;f.length&&f.peek()&1;)if(f.peekValue()>D||(m.push(f.pop()>>1),m.length===s))break e;x=f.length?f.pop()>>1:void 0}return f.clear(),m}};function mSe(r,e){let a=0,s=e.length-1;for(;a<s;){let l=a+s>>1;e[l]>r?s=l:a=l+1}return e[a]}function _W(r,e,a,s,l,d){if(Math.floor(s/d)>=Math.floor(l/d))return;let x=r[s],f=r[s+l>>1],m=r[l],D=m,b=Math.max(x,f);m>b?D=b:b===x?D=Math.max(f,m):b===f&&(D=Math.max(x,m));let E=s-1,A=l+1;for(;;){do E++;while(r[E]<D);do A--;while(r[A]>D);if(E>=A)break;lqt(r,e,a,E,A)}_W(r,e,a,s,A,d),_W(r,e,a,A+1,l,d)}function lqt(r,e,a,s,l){let d=r[s];r[s]=r[l],r[l]=d;let x=4*s,f=4*l,m=e[x],D=e[x+1],b=e[x+2],E=e[x+3];e[x]=e[f],e[x+1]=e[f+1],e[x+2]=e[f+2],e[x+3]=e[f+3],e[f]=m,e[f+1]=D,e[f+2]=b,e[f+3]=E;let A=a[s];a[s]=a[l],a[l]=A}function dqt(r,e){let a=r^e,s=65535^a,l=65535^(r|e),d=r&(e^65535),x=a|s>>1,f=a>>1^a,m=l>>1^s&d>>1^l,D=a&l>>1^d>>1^d;a=x,s=f,l=m,d=D,x=a&a>>2^s&s>>2,f=a&s>>2^s&(a^s)>>2,m^=a&l>>2^s&d>>2,D^=s&l>>2^(a^s)&d>>2,a=x,s=f,l=m,d=D,x=a&a>>4^s&s>>4,f=a&s>>4^s&(a^s)>>4,m^=a&l>>4^s&d>>4,D^=s&l>>4^(a^s)&d>>4,a=x,s=f,l=m,d=D,m^=a&l>>8^s&d>>8,D^=s&l>>8^(a^s)&d>>8,a=m^m>>1,s=D^D>>1;let b=r^e,E=s|65535^(b|a);return b=(b|b<<8)&16711935,b=(b|b<<4)&252645135,b=(b|b<<2)&858993459,b=(b|b<<1)&1431655765,E=(E|E<<8)&16711935,E=(E|E<<4)&252645135,E=(E|E<<2)&858993459,E=(E|E<<1)&1431655765,(E<<1|b)>>>0}var ex=class{constructor(){q(this,"MAX_ITERATIONS",1e5);q(this,"solved",!1);q(this,"failed",!1);q(this,"iterations",0);q(this,"progress",0);q(this,"error",null);q(this,"activeSubSolver");q(this,"failedSubSolvers");q(this,"timeToSolve");q(this,"stats",{})}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(r){throw this.error=`${this.constructor.name} error: ${r}`,this.failed=!0,r}!this.solved&&this.iterations>this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}solve(){let r=Date.now();for(;!this.solved&&!this.failed;)this.step();let e=Date.now();this.timeToSolve=e-r}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}},ESe=r=>{let e=new vW({});for(let s of r.directConnections)e.addConnections([s.netId?[s.netId,...s.pinIds]:s.pinIds]);let a=new vW(e.netMap);for(let s of r.netConnections)a.addConnections([[s.netId,...s.pinIds]]);return{directConnMap:e,netConnMap:a}};function pqt(r,e={}){let a=r.length,s=e?.maxDistance??Number.POSITIVE_INFINITY;if(a<=1)return[];{let b=new Set;for(let E of r){if(b.has(E.pinId))throw new Error(`Duplicate pinId detected: "${E.pinId}"`);b.add(E.pinId)}}let l=(b,E)=>Math.abs(b.x-E.x)+Math.abs(b.y-E.y),d=new Array(a).fill(!1),x=new Array(a).fill(Number.POSITIVE_INFINITY),f=new Array(a).fill(-1),m=0;for(let b=1;b<a;b++)r[b].pinId<r[m].pinId&&(m=b);x[m]=0;let D=[];for(let b=0;b<a;b++){let E=-1,A=Number.POSITIVE_INFINITY,B="";for(let w=0;w<a;w++)if(!d[w]){let P=x[w];(P<A||P===A&&(B===""||r[w].pinId<B))&&(A=P,B=r[w].pinId,E=w)}d[E]=!0,f[E]!==-1&&D.push([r[E].pinId,r[f[E]].pinId]);for(let w=0;w<a;w++)if(!d[w]){let P=l(r[E],r[w]),j=e?.forbidEdge?.(r[E],r[w])??!1,O=P>s||j?Number.POSITIVE_INFINITY:P;(O<x[w]||O===x[w]&&r[E].pinId<r[f[w]]?.pinId)&&(x[w]=O,f[w]=E)}}return D}var IF=(r,e)=>{let{x:a,y:s}=r,{center:l,width:d,height:x}=e,f=l.y+x/2,m=l.y-x/2,D=l.x+d/2,b=l.x-d/2,E=f-s,A=s-m,B=D-a,w=a-b,P=Math.min(E,A,B,w);return P===E?"y+":P===A?"y-":P===B?"x+":"x-"},xqt=r=>{let{pins:e,inputProblem:a,pinIdMap:s,chipMap:l}=r,d=A=>{let B=new Set,w=[A];B.add(A);let P=a.directConnections||[];for(;w.length;){let j=w.shift();for(let O of P)if(O.pinIds.includes(j))for(let z of O.pinIds)B.has(z)||(B.add(z),w.push(z))}return B},x=e[0].pinId,f=e[1].pinId,m=new Set([...d(x),...d(f)]),D=new Map,b=new Map,E=new Set(e.map(A=>A.chipId));for(let A of m){let B=s.get(A);if(!B)continue;let w=l[B.chipId];if(!w)continue;let P=B._facingDirection??IF(B,w),j=b.get(w.chipId);if(!j){j={center:w.center};let O={xPos:0,xNeg:0,yPos:0,yNeg:0};for(let z of w.pins){let ee=z._facingDirection??IF(z,w);ee==="x+"&&O.xPos++,ee==="x-"&&O.xNeg++,ee==="y+"&&O.yPos++,ee==="y-"&&O.yNeg++}j.counts=O,b.set(w.chipId,j)}P==="x+"&&(j.hasXPos=!0),P==="x-"&&(j.hasXNeg=!0),P==="y+"&&(j.hasYPos=!0),P==="y-"&&(j.hasYNeg=!0)}for(let[A,B]of b){let w=new Set,P={axes:w},j=B.counts;!!!(j&&(j.xPos>1||j.xNeg>1||j.yPos>1||j.yNeg>1))&&E.has(A)||(B.hasXPos&&B.hasXNeg&&(P.x=B.center.x,w.add("x")),B.hasYPos&&B.hasYNeg&&(P.y=B.center.y,w.add("y"))),w.size>0&&D.set(A,P)}return D},AW=r=>{let{inputProblem:e,chipMap:a,pinIdMap:s,p1:l,p2:d}=r,x=xqt({pins:[l,d],inputProblem:e,pinIdMap:s,chipMap:a});if(x.size===0)return!1;let f=1e-9,m=(B,w)=>{for(let[,P]of x)if(P.axes.has("x")&&typeof P.x=="number"&&(B.x-P.x)*(w.x-P.x)<-f||P.axes.has("y")&&typeof P.y=="number"&&(B.y-P.y)*(w.y-P.y)<-f)return!0;return!1};if(Math.abs(l.x-d.x)<f||Math.abs(l.y-d.y)<f)return m({x:l.x,y:l.y},{x:d.x,y:d.y});let D={x:d.x,y:l.y},b={x:l.x,y:d.y},E=m({x:l.x,y:l.y},D)||m(D,{x:d.x,y:d.y}),A=m({x:l.x,y:l.y},b)||m(b,{x:d.x,y:d.y});return E&&A},tl=(r,e=1)=>`hsl(${r.split("").reduce((s,l)=>s*31+l.charCodeAt(0),0)%360}, 100%, 50%, ${e})`,C1=(r,e={})=>{let{connectionAlpha:a=.8,chipAlpha:s=.8}=e,l={lines:[],points:[],rects:[]},d=new Map;for(let x of r.chips)for(let f of x.pins)d.set(f.pinId,f);for(let x of r.chips){l.rects.push({label:x.chipId,center:x.center,width:x.width,height:x.height,fill:tl(x.chipId,s)});for(let f of x.pins)l.points.push({label:`${f.pinId}
|
|
1036
1036
|
${f._facingDirection??IF(f,x)}`,x:f.x,y:f.y,color:tl(f.pinId,.8)})}for(let x of r.directConnections){let[f,m]=x.pinIds,D=d.get(f),b=d.get(m);l.lines.push({points:[{x:D.x,y:D.y},{x:b.x,y:b.y}],strokeColor:tl(x.netId??`${f}-${m}`,a)})}for(let x of r.netConnections){let f=x.pinIds.map(m=>d.get(m));for(let m=0;m<f.length-1;m++)for(let D=m+1;D<f.length;D++){let b=f[m],E=f[D];l.lines.push({points:[{x:b.x,y:b.y},{x:E.x,y:E.y}],strokeColor:tl(x.netId,a),strokeDash:"4 2"})}}return l},fqt=class extends ex{constructor({inputProblem:e}){super();q(this,"inputProblem");q(this,"mspConnectionPairs",[]);q(this,"dcConnMap");q(this,"globalConnMap");q(this,"queuedDcNetIds");q(this,"chipMap");q(this,"maxMspPairDistance");q(this,"pinMap");q(this,"userNetIdByPinId");this.inputProblem=e,this.maxMspPairDistance=e.maxMspPairDistance??1;let{directConnMap:a,netConnMap:s}=ESe(e);this.dcConnMap=a,this.globalConnMap=s,this.pinMap={};for(let l of e.chips)for(let d of l.pins)this.pinMap[d.pinId]={...d,chipId:l.chipId};this.chipMap={};for(let l of e.chips)this.chipMap[l.chipId]=l;this.userNetIdByPinId={};for(let l of e.directConnections)if(l.netId){let[d,x]=l.pinIds;this.userNetIdByPinId[d]=l.netId,this.userNetIdByPinId[x]=l.netId}for(let l of e.netConnections)for(let d of l.pinIds)this.userNetIdByPinId[d]=l.netId;this.queuedDcNetIds=Object.keys(s.netMap)}getConstructorParams(){return{inputProblem:this.inputProblem}}_step(){if(this.queuedDcNetIds.length===0){this.solved=!0;return}let e=this.queuedDcNetIds.shift(),s=this.globalConnMap.getIdsConnectedToNet(e).filter(x=>!!this.pinMap[x]);if(s.length<=1)return;if(s.length===2){let[x,f]=s,m=this.pinMap[x],D=this.pinMap[f];if(Math.abs(m.x-D.x)+Math.abs(m.y-D.y)>this.maxMspPairDistance)return;let E=new Map(Object.entries(this.pinMap));if(AW({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:E,p1:m,p2:D}))return;let A=this.globalConnMap.getNetConnectedToId(x),B=this.userNetIdByPinId[x]??this.userNetIdByPinId[f];this.mspConnectionPairs.push({mspPairId:`${x}-${f}`,dcConnNetId:e,globalConnNetId:A,userNetId:B,pins:[m,D]});return}let l=new Map(Object.entries(this.pinMap)),d=pqt(s.map(x=>this.pinMap[x]).filter(Boolean),{maxDistance:this.maxMspPairDistance,forbidEdge:(x,f)=>AW({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:l,p1:x,p2:f})});for(let[x,f]of d){let m=this.pinMap[x],D=this.pinMap[f];if(AW({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:l,p1:m,p2:D}))continue;let b=this.globalConnMap.getNetConnectedToId(x),E=this.userNetIdByPinId[x]??this.userNetIdByPinId[f];this.mspConnectionPairs.push({mspPairId:`${x}-${f}`,dcConnNetId:e,globalConnNetId:b,userNetId:E,pins:[m,D]})}}visualize(){let e=C1(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let a of this.mspConnectionPairs)e.lines.push({points:[{x:a.pins[0].x,y:a.pins[0].y},{x:a.pins[1].x,y:a.pins[1].y}],strokeColor:tl(a.mspPairId,.75)});return e}};function BW(r){let e=r.width/2,a=r.height/2;return{minX:r.center.x-e,maxX:r.center.x+e,minY:r.center.y-a,maxY:r.center.y+a}}var hqt=r=>{let e=BW(r);return{chipId:r.chipId,...e}},mqt=r=>r.chips.map(hqt),wW=1e-9,BS=(r,e,a=wW)=>Math.abs(r.x-e.x)<a,wS=(r,e,a=wW)=>Math.abs(r.y-e.y)<a,gqt=(r,e,a,s=wW)=>{let l=BS(r,e,s),d=wS(r,e,s);if(!l&&!d)return!1;if(l){let x=r.x;if(x<a.minX-s||x>a.maxX+s)return!1;let f=Math.min(r.y,e.y),m=Math.max(r.y,e.y);return Math.min(m,a.maxY)-Math.max(f,a.minY)>s}else{let x=r.y;if(x<a.minY-s||x>a.maxY+s)return!1;let f=Math.min(r.x,e.x),m=Math.max(r.x,e.x);return Math.min(m,a.maxX)-Math.max(f,a.minX)>s}},Dqt=(r,e,a={})=>{for(let s=0;s<r.length-1;s++){let l=r[s],d=r[s+1],x=a.excludeRectIdsForSegment?.(s)??new Set;for(let f of e)if(!x.has(f.chipId)&&gqt(l,d,f))return{segIndex:s,rect:f}}return null},vSe=1e-9,yqt=(r,e)=>({minX:Math.min(r.x,e.x),maxX:Math.max(r.x,e.x),minY:Math.min(r.y,e.y),maxY:Math.max(r.y,e.y)}),gSe=(r,e,a,s=vSe)=>r==="x"?e.x<a.minX-s?[(e.x+a.minX)/2]:e.x>a.maxX+s?[(e.x+a.maxX)/2]:[a.minX-.2,a.maxX+.2]:e.y<a.minY-s?[(e.y+a.minY)/2]:e.y>a.maxY+s?[(e.y+a.maxY)/2]:[a.minY-.2,a.maxY+.2],bqt=(r,e,a,s,l,d=vSe)=>{let x=[...s].map(f=>a.get(f)).filter(f=>!!f);if(r==="x"){let f=[l.minX,...x.map(A=>A.maxX)].filter(A=>A<e.minX-d),m=[l.maxX,...x.map(A=>A.minX)].filter(A=>A>e.maxX+d),D=f.length>0?Math.max(...f):void 0,b=m.length>0?Math.min(...m):void 0,E=[];return D!==void 0&&E.push((D+e.minX)/2),b!==void 0&&E.push((e.maxX+b)/2),E}else{let f=[l.minY,...x.map(A=>A.maxY)].filter(A=>A<e.minY-d),m=[l.maxY,...x.map(A=>A.minY)].filter(A=>A>e.maxY+d),D=f.length>0?Math.max(...f):void 0,b=m.length>0?Math.min(...m):void 0,E=[];return D!==void 0&&E.push((D+e.minY)/2),b!==void 0&&E.push((e.maxY+b)/2),E}},Fqt=1e-9,Eqt=(r,e,a,s,l=Fqt)=>{if(e<0||e>=r.length-1)return null;let d=r[e],x=r[e+1],f=BS(d,x,l),m=wS(d,x,l);if(!f&&!m||f&&a!=="x"||m&&a!=="y")return null;let D=r.map(b=>({...b}));if(a==="x"){if(Math.abs(d.x-s)<l&&Math.abs(x.x-s)<l)return null;D[e]={...D[e],x:s},D[e+1]={...D[e+1],x:s}}else{if(Math.abs(d.y-s)<l&&Math.abs(x.y-s)<l)return null;D[e]={...D[e],y:s},D[e+1]={...D[e+1],y:s}}if(e-1>=0){let b=D[e-1],E=D[e];if(Math.abs(b.x-E.x)+Math.abs(b.y-E.y)<l)return null}if(e+2<=D.length-1){let b=D[e+1],E=D[e+2];if(Math.abs(b.x-E.x)+Math.abs(b.y-E.y)<l)return null}for(let b=0;b<D.length-1;b++){let E=D[b],A=D[b+1];if(!wS(E,A,l)&&!BS(E,A,l))return null}return D},DSe=(r,e=6)=>r.map(a=>`${a.x.toFixed(e)},${a.y.toFixed(e)}`).join("|"),vqt=class extends ex{constructor(e){super();q(this,"pins");q(this,"inputProblem");q(this,"chipMap");q(this,"obstacles");q(this,"rectById");q(this,"aabb");q(this,"baseElbow");q(this,"solvedTracePath",null);q(this,"queue",[]);q(this,"visited",new Set);this.pins=e.pins,this.inputProblem=e.inputProblem,this.chipMap=e.chipMap;for(let l of this.pins)if(!l._facingDirection){let d=this.chipMap[l.chipId];l._facingDirection=IF(l,d)}this.obstacles=mqt(this.inputProblem),this.rectById=new Map(this.obstacles.map(l=>[l.chipId,l]));let[a,s]=this.pins;this.baseElbow=dg({x:a.x,y:a.y,facingDirection:a._facingDirection},{x:s.x,y:s.y,facingDirection:s._facingDirection},{overshoot:.2}),this.aabb=yqt({x:a.x,y:a.y},{x:s.x,y:s.y}),this.queue.push({path:this.baseElbow,collisionChipIds:new Set}),this.visited.add(DSe(this.baseElbow))}getConstructorParams(){return{chipMap:this.chipMap,pins:this.pins,inputProblem:this.inputProblem}}axisOfSegment(e,a){return BS(e,a)?"x":wS(e,a)?"y":null}pathLength(e){let a=0;for(let s=0;s<e.length-1;s++)a+=Math.abs(e[s+1].x-e[s].x)+Math.abs(e[s+1].y-e[s].y);return a}_step(){if(this.solvedTracePath){this.solved=!0;return}let e=this.queue.shift();if(!e){this.failed=!0,this.error="No collision-free path found";return}let{path:a,collisionChipIds:s}=e,[l,d]=this.pins,x=Dqt(a,this.obstacles);if(!x){let j=a[0],O=a[a.length-1],z=1e-9,ee=(W,re)=>Math.abs(W.x-re.x)<z&&Math.abs(W.y-re.y)<z;ee(j,{x:l.x,y:l.y})&&ee(O,{x:d.x,y:d.y})&&(this.solvedTracePath=a,this.solved=!0);return}let{segIndex:f,rect:m}=x,D=f===0,b=f===a.length-2;if(D){if(a.length<3)return;f=1}else if(b){if(a.length<3)return;f=a.length-3}let E=a[f],A=a[f+1],B=this.axisOfSegment(E,A);if(!B)return;let w=[];if(s.size===0){let j=gSe(B,{x:l.x,y:l.y},m),O=gSe(B,{x:d.x,y:d.y},m),z=[...j,...O],ee=[...new Set(z)];w.push(...ee)}else{let j=bqt(B,m,this.rectById,s,this.aabb);w.push(...j)}let P=[];for(let j of w){let O=Eqt(a,f,B,j);if(!O)continue;let z=DSe(O);if(this.visited.has(z))continue;this.visited.add(z);let ee=new Set(s);ee.add(m.chipId);let W=this.pathLength(O);P.push({path:O,collisionRectIds:ee,len:W})}P.sort((j,O)=>j.len-O.len);for(let j of P)this.queue.push({path:j.path,collisionChipIds:j.collisionRectIds})}visualize(){let e=C1(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});e.lines.push({points:this.baseElbow,strokeColor:"red",strokeDash:"4 4"});let[a,s]=this.pins;e.lines.push({points:[{x:a.x,y:a.y},{x:s.x,y:s.y}],strokeColor:"blue",strokeDash:"5 5"});for(let{path:l,collisionChipIds:d}of this.queue)e.lines.push({points:l,strokeColor:"teal",strokeDash:"2 2"});return this.solvedTracePath?e.lines.push({points:this.solvedTracePath,strokeColor:"green"}):this.queue.length>0&&e.lines.push({points:this.queue[0].path,strokeColor:"orange"}),e}},Cqt=class extends ex{constructor(e){super();q(this,"inputProblem");q(this,"mspConnectionPairs");q(this,"dcConnMap");q(this,"globalConnMap");q(this,"queuedConnectionPairs");q(this,"chipMap");q(this,"currentConnectionPair",null);q(this,"solvedTracePaths",[]);q(this,"failedConnectionPairs",[]);this.inputProblem=e.inputProblem,this.mspConnectionPairs=e.mspConnectionPairs,this.dcConnMap=e.dcConnMap,this.globalConnMap=e.globalConnMap,this.chipMap=e.chipMap,this.queuedConnectionPairs=[...this.mspConnectionPairs]}getConstructorParams(){return{inputProblem:this.inputProblem,chipMap:this.chipMap,mspConnectionPairs:this.mspConnectionPairs,dcConnMap:this.dcConnMap,globalConnMap:this.globalConnMap}}_step(){if(this.activeSubSolver?.solved&&(this.solvedTracePaths.push({...this.currentConnectionPair,tracePath:this.activeSubSolver.solvedTracePath,mspConnectionPairIds:[this.currentConnectionPair.mspPairId],pinIds:[this.currentConnectionPair.pins[0].pinId,this.currentConnectionPair.pins[1].pinId]}),this.activeSubSolver=null,this.currentConnectionPair=null),this.activeSubSolver?.failed&&(this.currentConnectionPair&&this.failedConnectionPairs.push({...this.currentConnectionPair,error:this.activeSubSolver.error||void 0}),this.activeSubSolver=null,this.currentConnectionPair=null),this.activeSubSolver){this.activeSubSolver.step();return}let e=this.queuedConnectionPairs.shift();if(!e){this.solved=!0;return}this.currentConnectionPair=e;let{pins:a}=e;this.activeSubSolver=new vqt({inputProblem:this.inputProblem,pins:a,chipMap:this.chipMap})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=C1(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let{mspPairId:a,tracePath:s}of this.solvedTracePaths)e.lines.push({points:s,strokeColor:"green"});for(let a of this.failedConnectionPairs)e.lines.push({points:[{x:a.pins[0].x,y:a.pins[0].y},{x:a.pins[1].x,y:a.pins[1].y}],strokeColor:"red",strokeDash:"4 2"});return e}},_qt=({pts:r,segmentIndex:e,offset:a,JOG_SIZE:s,EPS:l=1e-6})=>{if(e!==0&&e!==r.length-2)return;let d=r[e],x=r[e+1],f=Math.abs(d.x-x.x)<l,m=Math.abs(d.y-x.y)<l;if(!f&&!m)return;let D=f?x.y>d.y?1:-1:x.x>d.x?1:-1;if(e===0)if(f){let b=d.y+D*s;r.splice(1,1,{x:d.x,y:b},{x:d.x+a,y:b},{x:x.x+a,y:x.y})}else{let b=d.x+D*s;r.splice(1,1,{x:b,y:d.y},{x:b,y:d.y+a},{x:x.x,y:x.y+a})}else if(f){let b=x.y-D*s;r.splice(e,1,{x:d.x+a,y:d.y},{x:x.x+a,y:b},{x:x.x,y:b})}else{let b=x.x-D*s;r.splice(e,1,{x:d.x,y:d.y+a},{x:b,y:x.y+a},{x:b,y:x.y})}},Aqt=class extends ex{constructor(e){super();q(this,"overlappingTraceSegments");q(this,"traceNetIslands");q(this,"SHIFT_DISTANCE",.1);q(this,"correctedTraceMap",{});this.overlappingTraceSegments=e.overlappingTraceSegments,this.traceNetIslands=e.traceNetIslands;for(let{connNetId:a,pathsWithOverlap:s}of this.overlappingTraceSegments)for(let{solvedTracePathIndex:l,traceSegmentIndex:d}of s){let x=this.traceNetIslands[a][l].mspPairId;this.correctedTraceMap[x]=this.traceNetIslands[a][l]}}_step(){let a=this.overlappingTraceSegments.map((d,x)=>{let f=Math.floor(x/2)+1;return(x%2===0?-f:f)*this.SHIFT_DISTANCE}),s=(d,x)=>Math.abs(d-x)<1e-6,l=(d,x)=>!!d&&!!x&&s(d.x,x.x)&&s(d.y,x.y);this.overlappingTraceSegments.forEach((d,x)=>{let f=a[x],m=new Map;for(let D of d.pathsWithOverlap)m.has(D.solvedTracePathIndex)||m.set(D.solvedTracePathIndex,new Set),m.get(D.solvedTracePathIndex).add(D.traceSegmentIndex);for(let[D,b]of m){let E=this.traceNetIslands[d.connNetId][D],A=this.correctedTraceMap[E.mspPairId]??E,B=A.tracePath.map(z=>({...z})),w=Array.from(b).sort((z,ee)=>z-ee),P=Array.from(b).sort((z,ee)=>z-ee).reverse(),j=this.SHIFT_DISTANCE;for(let z of P)if(!(z<0||z>=B.length-1))if(z===0||z===B.length-2)_qt({pts:B,segmentIndex:z,offset:f,JOG_SIZE:j,EPS:1e-6});else{let ee=B[z],W=B[z+1],re=Math.abs(ee.x-W.x)<1e-6,L=Math.abs(ee.y-W.y)<1e-6;if(!re&&!L)continue;re?(ee.x+=f,W.x+=f):(ee.y+=f,W.y+=f)}let O=[];for(let z of B)(O.length===0||!l(O[O.length-1],z))&&O.push(z);this.correctedTraceMap[E.mspPairId]={...A,tracePath:O}}}),this.solved=!0}visualize(){let e={lines:[],points:[],rects:[],circles:[]};for(let a of this.overlappingTraceSegments)for(let{solvedTracePathIndex:s,traceSegmentIndex:l}of a.pathsWithOverlap){let d=this.traceNetIslands[a.connNetId][s],x=d.tracePath[l],f=d.tracePath[l+1];e.lines.push({points:[x,f],strokeColor:"red"})}for(let a of Object.values(this.correctedTraceMap))e.lines.push({points:a.tracePath,strokeColor:"blue",strokeDash:"4 2"});return e}},Rqt=class extends ex{constructor(e){super();q(this,"inputProblem");q(this,"inputTracePaths");q(this,"globalConnMap");q(this,"traceNetIslands",{});q(this,"correctedTraceMap",{});this.inputProblem=e.inputProblem,this.inputTracePaths=e.inputTracePaths,this.globalConnMap=e.globalConnMap;for(let a of this.inputTracePaths){let{mspPairId:s}=a;this.correctedTraceMap[s]=a}this.traceNetIslands=this.computeTraceNetIslands()}getConstructorParams(){return{inputProblem:this.inputProblem,inputTracePaths:this.inputTracePaths,globalConnMap:this.globalConnMap}}computeTraceNetIslands(){let e={};for(let a of this.inputTracePaths){let s=this.correctedTraceMap[a.mspPairId]??a,l=s.globalConnNetId;e[l]||(e[l]=[]),e[l].push(s)}return e}findNextOverlapIssue(){let a=Object.keys(this.traceNetIslands);for(let s=0;s<a.length;s++)for(let l=s+1;l<a.length;l++){let d=a[s],x=a[l],f=this.traceNetIslands[d]||[],m=this.traceNetIslands[x]||[],D=[],b=[],E=new Set,A=new Set,B=(w,P,j,O)=>{let z=Math.min(w,P),ee=Math.max(w,P),W=Math.min(j,O),re=Math.max(j,O);return Math.min(ee,re)-Math.max(z,W)>.002};for(let w=0;w<f.length;w++){let j=f[w].tracePath;for(let O=0;O<j.length-1;O++){let z=j[O],ee=j[O+1],W=Math.abs(z.x-ee.x)<.002,re=Math.abs(z.y-ee.y)<.002;if(!(!W&&!re))for(let L=0;L<m.length;L++){let U=m[L].tracePath;for(let J=0;J<U.length-1;J++){let Q=U[J],de=U[J+1],oe=Math.abs(Q.x-de.x)<.002,Te=Math.abs(Q.y-de.y)<.002;if(!(!oe&&!Te)){if(W&&oe){if(Math.abs(z.x-Q.x)<.002&&B(z.y,ee.y,Q.y,de.y)){let Me=`${w}:${O}`,Ge=`${L}:${J}`;E.has(Me)||(D.push({solvedTracePathIndex:w,traceSegmentIndex:O}),E.add(Me)),A.has(Ge)||(b.push({solvedTracePathIndex:L,traceSegmentIndex:J}),A.add(Ge))}}else if(re&&Te&&Math.abs(z.y-Q.y)<.002&&B(z.x,ee.x,Q.x,de.x)){let Me=`${w}:${O}`,Ge=`${L}:${J}`;E.has(Me)||(D.push({solvedTracePathIndex:w,traceSegmentIndex:O}),E.add(Me)),A.has(Ge)||(b.push({solvedTracePathIndex:L,traceSegmentIndex:J}),A.add(Ge))}}}}}}if(D.length>0&&b.length>0)return{overlappingTraceSegments:[{connNetId:d,pathsWithOverlap:D},{connNetId:x,pathsWithOverlap:b}]}}return null}_step(){if(this.activeSubSolver?.solved){for(let[s,l]of Object.entries(this.activeSubSolver.correctedTraceMap))this.correctedTraceMap[s]=l;this.activeSubSolver=null,this.traceNetIslands=this.computeTraceNetIslands()}if(this.activeSubSolver){this.activeSubSolver.step();return}let e=this.findNextOverlapIssue();if(e===null){this.solved=!0;return}let{overlappingTraceSegments:a}=e;this.activeSubSolver=new Aqt({overlappingTraceSegments:a,traceNetIslands:this.traceNetIslands})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=C1(this.inputProblem);for(let a of Object.values(this.correctedTraceMap))e.lines.push({points:a.tracePath,strokeColor:"purple"});return e}},Sqt=class{constructor(r){q(this,"chips");q(this,"spatialIndex");q(this,"spatialIndexIdToChip");this.chips=r.map(e=>({...e,bounds:BW(e),spatialIndexId:null})),this.spatialIndexIdToChip=new Map,this.spatialIndex=new PF(r.length);for(let e of this.chips)e.spatialIndexId=this.spatialIndex.add(e.bounds.minX,e.bounds.minY,e.bounds.maxX,e.bounds.maxY),this.spatialIndexIdToChip.set(e.spatialIndexId,e);this.spatialIndex.finish()}getChipsInBounds(r){return this.spatialIndex.search(r.minX,r.minY,r.maxX,r.maxY).map(a=>this.spatialIndexIdToChip.get(a))}doesOrthogonalLineIntersectChip(r,e={}){let a=e.excludeChipIds??[],[s,l]=r,{x:d,y:x}=s,{x:f,y:m}=l;return this.getChipsInBounds({minX:Math.min(d,f),minY:Math.min(x,m),maxX:Math.max(d,f),maxY:Math.max(x,m)}).filter(b=>!a.includes(b.chipId)).length>0}},Bqt=.45,ySe=.2;function RW(r){let{orientation:e,netLabelWidth:a}=r,s=typeof a=="number"?a:Bqt;return e==="y+"||e==="y-"?{width:ySe,height:s}:{width:s,height:ySe}}function SW(r,e,a,s){switch(e){case"x+":return{x:r.x+a/2,y:r.y};case"x-":return{x:r.x-a/2,y:r.y};case"y+":return{x:r.x,y:r.y+s/2};case"y-":return{x:r.x,y:r.y-s/2}}}function CSe(r,e,a){return{minX:r.x-e/2,minY:r.y-a/2,maxX:r.x+e/2,maxY:r.y+a/2}}function wqt(r,e,a,s=1e-9){let l=Math.abs(r.x-e.x)<s,d=Math.abs(r.y-e.y)<s;if(!l&&!d)return!1;if(l){let x=r.x;if(x<a.minX-s||x>a.maxX+s)return!1;let f=Math.min(r.y,e.y),m=Math.max(r.y,e.y);return Math.min(m,a.maxY)-Math.max(f,a.minY)>s}else{let x=r.y;if(x<a.minY-s||x>a.maxY+s)return!1;let f=Math.min(r.x,e.x),m=Math.max(r.x,e.x);return Math.min(m,a.maxX)-Math.max(f,a.minX)>s}}function _Se(r,e,a,s){for(let[l,d]of Object.entries(e)){let x=d.tracePath;for(let f=0;f<x.length-1;f++)if(!(l===a&&f===s)&&wqt(x[f],x[f+1],r))return{hasIntersection:!0,mspPairId:l,segIndex:f}}return{hasIntersection:!1}}function bSe(r){let e=0,a=r.tracePath;for(let s=0;s<a.length-1;s++)e+=Math.abs(a[s+1].x-a[s].x)+Math.abs(a[s+1].y-a[s].y);return e}function ASe(r){let{inputProblem:e,inputTraceMap:a,globalConnNetId:s,fallbackTrace:l,mspConnectionPairIds:d}=r,x=Object.fromEntries(e.chips.map(A=>[A.chipId,A])),f=Object.values(a).filter(A=>A.globalConnNetId===s);if(d&&d.length>0){let A=new Set(d);f=f.filter(B=>B.mspConnectionPairIds.some(w=>A.has(w)))}let m=new Set;for(let A of f)m.add(A.pins[0].chipId),m.add(A.pins[1].chipId);let D=null,b=-1;for(let A of m){let w=x[A]?.pins?.length??0;w>b&&(b=w,D=A)}let E=D==null?[]:f.filter(A=>A.pins[0].chipId===D||A.pins[1].chipId===D);return E.length>0?E.reduce((A,B)=>bSe(A)>=bSe(B)?A:B):l}function Tqt(r,e){return[{x:r.x,y:r.y},{x:(r.x+e.x)/2,y:(r.y+e.y)/2},{x:e.x,y:e.y}]}function Pqt(r){let{inputProblem:e,inputTraceMap:a,chipObstacleSpatialIndex:s,overlappingSameNetTraceGroup:l,availableOrientations:d,netLabelWidth:x}=r,f=l.portOnlyPinId;if(!f)return{placement:null,testedCandidates:[],error:"No portOnlyPinId provided"};let m=null,D=null;for(let L of e.chips){let K=L.pins.find(U=>U.pinId===f);if(K){m={x:K.x,y:K.y},D=K._facingDirection||IF(K,L);break}}if(!m||!D)return{placement:null,testedCandidates:[],error:`Port-only pin not found: ${f}`};let b=d.length>0?d:["x+","x-","y+","y-"],E={x:m.x,y:m.y},A=L=>L==="x+"?{x:1,y:0}:L==="x-"?{x:-1,y:0}:L==="y+"?{x:0,y:1}:{x:0,y:-1},B=[];for(let L of b){let{width:K,height:U}=RW({orientation:L,netLabelWidth:x}),J=SW(E,L,K,U),Q=A(L),de=.001,oe={x:J.x+Q.x*de,y:J.y+Q.y*de},Te=CSe(oe,K,U);if(s.getChipsInBounds(Te).length>0){B.push({center:oe,width:K,height:U,bounds:Te,anchor:E,orientation:L,status:"chip-collision",hostSegIndex:-1});continue}if(_Se(Te,a,"",-1).hasIntersection){B.push({center:oe,width:K,height:U,bounds:Te,anchor:E,orientation:L,status:"trace-collision",hostSegIndex:-1});continue}return B.push({center:oe,width:K,height:U,bounds:Te,anchor:E,orientation:L,status:"ok",hostSegIndex:-1}),{placement:{globalConnNetId:l.globalConnNetId,dcConnNetId:void 0,netId:l.netId,mspConnectionPairIds:[],pinIds:[f],orientation:L,anchorPoint:E,width:K,height:U,center:oe},testedCandidates:B}}let w=D,{width:P,height:j}=RW({orientation:w,netLabelWidth:x}),O=SW(E,w,P,j),z=A(w),ee=.001,W={x:O.x+z.x*ee,y:O.y+z.y*ee};return{placement:{globalConnNetId:l.globalConnNetId,dcConnNetId:void 0,netId:l.netId,mspConnectionPairIds:[],pinIds:[f],orientation:w,anchorPoint:E,width:P,height:j,center:W},testedCandidates:B}}function Iqt(r){let e=C1(r.inputProblem),a=r.overlappingSameNetTraceGroup.globalConnNetId,s=ASe({inputProblem:r.inputProblem,inputTraceMap:r.inputTraceMap,globalConnNetId:a,fallbackTrace:r.overlappingSameNetTraceGroup.overlappingTraces}),l=tl(a,.9),d=tl(a,.5);for(let x of Object.values(r.inputTraceMap)){let f=s?x.mspPairId===s.mspPairId:!1;e.lines.push({points:x.tracePath})}for(let x of r.testedCandidates){let f=x.status==="ok"?"rgba(0, 180, 0, 0.25)":x.status==="chip-collision"?"rgba(220, 0, 0, 0.25)":x.status==="trace-collision"?"rgba(220, 140, 0, 0.25)":"rgba(120, 120, 120, 0.15)",m=x.status==="ok"?"green":x.status==="chip-collision"?"red":x.status==="trace-collision"?"orange":"gray";e.rects.push({center:{x:(x.bounds.minX+x.bounds.maxX)/2,y:(x.bounds.minY+x.bounds.maxY)/2},width:x.width,height:x.height,fill:f,strokeColor:m}),e.points.push({x:x.anchor.x,y:x.anchor.y,color:m})}if(r.netLabelPlacement){let x=r.netLabelPlacement;e.rects.push({center:x.center,width:x.width,height:x.height,fill:"rgba(0, 128, 255, 0.35)",strokeColor:"blue"}),e.points.push({x:x.anchorPoint.x,y:x.anchorPoint.y,color:"blue"})}return e}var FSe=class extends ex{constructor(e){super();q(this,"inputProblem");q(this,"inputTraceMap");q(this,"overlappingSameNetTraceGroup");q(this,"availableOrientations");q(this,"chipObstacleSpatialIndex");q(this,"netLabelWidth");q(this,"netLabelPlacement",null);q(this,"testedCandidates",[]);this.inputProblem=e.inputProblem,this.inputTraceMap=e.inputTraceMap,this.overlappingSameNetTraceGroup=e.overlappingSameNetTraceGroup,this.availableOrientations=e.availableOrientations,this.netLabelWidth=e.netLabelWidth,this.chipObstacleSpatialIndex=e.inputProblem._chipObstacleSpatialIndex??new Sqt(e.inputProblem.chips)}getConstructorParams(){return{inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth}}_step(){if(this.netLabelPlacement){this.solved=!0;return}if(this.overlappingSameNetTraceGroup.portOnlyPinId){let A=Pqt({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,chipObstacleSpatialIndex:this.chipObstacleSpatialIndex,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth});if(this.testedCandidates.push(...A.testedCandidates),A.placement){this.netLabelPlacement=A.placement,this.solved=!0;return}this.failed=!0,this.error=A.error??"Could not place net label at port without collisions";return}let e=this.overlappingSameNetTraceGroup.globalConnNetId,a=ASe({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,globalConnNetId:e,fallbackTrace:this.overlappingSameNetTraceGroup.overlappingTraces,mspConnectionPairIds:this.overlappingSameNetTraceGroup.mspConnectionPairIds});if(!a){this.failed=!0,this.error="No host trace found for net label placement";return}let s=new Set(this.overlappingSameNetTraceGroup.mspConnectionPairIds??[]),l=Object.values(this.inputTraceMap).filter(A=>A.globalConnNetId===e&&(s.size===0||A.mspConnectionPairIds.some(B=>s.has(B)))),d=this.availableOrientations.length===1?[a,...l.filter(A=>A.mspPairId!==a.mspPairId)]:[a],x=this.availableOrientations.length>0?this.availableOrientations:["x+","x-","y+","y-"],f=this.availableOrientations.length===1,m=(A,B)=>{switch(A){case"y+":return B.y;case"y-":return-B.y;case"x+":return B.x;case"x-":return-B.x}},D=null,b=-1/0,E=1e-6;for(let A of d){let B=A.tracePath.slice();for(let w=0;w<B.length-1;w++){let P=B[w],j=B[w+1],O=Math.abs(P.y-j.y)<E,z=Math.abs(P.x-j.x)<E;if(!O&&!z)continue;let ee=O?["y+","y-"]:["x+","x-"],W=x.filter(L=>ee.includes(L));if(W.length===0)continue;let re=Tqt(P,j);for(let L of re)for(let K of W){let{width:U,height:J}=RW({orientation:K,netLabelWidth:this.netLabelWidth}),Q=SW(L,K,U,J),de=K==="x+"?{x:1,y:0}:K==="x-"?{x:-1,y:0}:K==="y+"?{x:0,y:1}:{x:0,y:-1},oe=1e-4,Te={x:Q.x+de.x*oe,y:Q.y+de.y*oe},Me=CSe(Te,U,J);if(this.chipObstacleSpatialIndex.getChipsInBounds(Me).length>0){this.testedCandidates.push({center:Te,width:U,height:J,bounds:Me,anchor:L,orientation:K,status:"chip-collision",hostSegIndex:w});continue}if(_Se(Me,this.inputTraceMap,A.mspPairId,w).hasIntersection){this.testedCandidates.push({center:Te,width:U,height:J,bounds:Me,anchor:L,orientation:K,status:"trace-collision",hostSegIndex:w});continue}if(this.testedCandidates.push({center:Te,width:U,height:J,bounds:Me,anchor:L,orientation:K,status:"ok",hostSegIndex:w}),f){let dt=m(K,L);dt>b+1e-9&&(b=dt,D={anchor:L,orientation:K,width:U,height:J,center:Q,hostSegIndex:w,dcConnNetId:A.dcConnNetId,mspPairId:A.mspPairId,pinIds:[A.pins[0].pinId,A.pins[1].pinId]});continue}this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:A.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[A.mspPairId],pinIds:[A.pins[0].pinId,A.pins[1].pinId],orientation:K,anchorPoint:L,width:U,height:J,center:Q},this.solved=!0;return}}}if(f&&D){this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:D.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[D.mspPairId],pinIds:D.pinIds,orientation:D.orientation,anchorPoint:D.anchor,width:D.width,height:D.height,center:D.center},this.solved=!0;return}this.failed=!0,this.error="Could not place net label without collisions"}visualize(){return Iqt(this)}},jqt=class extends ex{constructor(e){super();q(this,"inputProblem");q(this,"inputTraceMap");q(this,"overlappingSameNetTraceGroups");q(this,"queuedOverlappingSameNetTraceGroups");q(this,"netLabelPlacements",[]);q(this,"currentGroup",null);q(this,"triedAnyOrientationFallbackForCurrentGroup",!1);this.inputProblem=e.inputProblem,this.inputTraceMap=e.inputTraceMap,this.overlappingSameNetTraceGroups=this.computeOverlappingSameNetTraceGroups(),this.queuedOverlappingSameNetTraceGroups=[...this.overlappingSameNetTraceGroups]}computeOverlappingSameNetTraceGroups(){let e={};for(let m of Object.values(this.inputTraceMap)){let D=m.globalConnNetId;e[D]||(e[D]=[]),e[D].push(m)}let{netConnMap:a}=ESe(this.inputProblem),s=new Map;for(let m of this.inputProblem.chips)for(let D of m.pins)s.set(D.pinId,D);let l={};for(let m of this.inputProblem.directConnections)if(m.netId){let[D,b]=m.pinIds;l[D]=m.netId,l[b]=m.netId}for(let m of this.inputProblem.netConnections)for(let D of m.pinIds)l[D]=m.netId;let d=[],x=this.inputProblem.chips.flatMap(m=>m.pins.map(D=>D.pinId)),f=new Set;for(let m of x){let D=a.getNetConnectedToId(m);D&&f.add(D)}for(let m of f){let b=a.getIdsConnectedToNet(m).filter(B=>s.has(B)),E={};for(let B of b)E[B]=new Set;for(let B of e[m]??[]){let w=B.pins[0].pinId,P=B.pins[1].pinId;E[w]&&E[P]&&(E[w].add(P),E[P].add(w))}let A=new Set;for(let B of b){if(A.has(B))continue;let w=[B],P=new Set;for(A.add(B);w.length>0;){let O=w.pop();P.add(O);for(let z of E[O]??[])A.has(z)||(A.add(z),w.push(z))}let j=(e[m]??[]).filter(O=>P.has(O.pins[0].pinId)&&P.has(O.pins[1].pinId));if(j.length>0){let O=K=>{let U=0,J=K.tracePath;for(let Q=0;Q<J.length-1;Q++)U+=Math.abs(J[Q+1].x-J[Q].x)+Math.abs(J[Q+1].y-J[Q].y);return U},z=j[0],ee=O(z);for(let K=1;K<j.length;K++){let U=O(j[K]);U>ee&&(z=j[K],ee=U)}let W=j.find(K=>K.userNetId!=null)?.userNetId;if(!W){for(let K of P)if(l[K]){W=l[K];break}}let re=Array.from(new Set(j.flatMap(K=>K.mspConnectionPairIds??[K.mspPairId]))),L={globalConnNetId:m,netId:W,overlappingTraces:z,mspConnectionPairIds:re};d.push(L)}else for(let O of P){let z=l[O];z&&d.push({globalConnNetId:m,netId:z,portOnlyPinId:O})}}}return d}_step(){if(this.activeSubSolver?.solved){this.netLabelPlacements.push(this.activeSubSolver.netLabelPlacement),this.activeSubSolver=null,this.currentGroup=null,this.triedAnyOrientationFallbackForCurrentGroup=!1;return}if(this.activeSubSolver?.failed){let l=["x+","x-","y+","y-"],d=this.activeSubSolver.availableOrientations,x=d.length===4&&l.every(f=>d.includes(f));if(!this.triedAnyOrientationFallbackForCurrentGroup&&!x&&this.currentGroup){this.triedAnyOrientationFallbackForCurrentGroup=!0;let f=this.currentGroup.netId?this.inputProblem.netConnections.find(m=>m.netId===this.currentGroup.netId)?.netLabelWidth:void 0;this.activeSubSolver=new FSe({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.currentGroup,availableOrientations:l,netLabelWidth:f});return}this.failed=!0,this.error=this.activeSubSolver.error;return}if(this.activeSubSolver){this.activeSubSolver.step();return}let e=this.queuedOverlappingSameNetTraceGroups.shift();if(!e){this.solved=!0;return}let a=e.netId??e.globalConnNetId;this.currentGroup=e,this.triedAnyOrientationFallbackForCurrentGroup=!1;let s=this.currentGroup.netId?this.inputProblem.netConnections.find(l=>l.netId===this.currentGroup.netId)?.netLabelWidth:void 0;this.activeSubSolver=new FSe({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:e,availableOrientations:this.inputProblem.availableNetLabelOrientations[a]??["x+","x-","y+","y-"],netLabelWidth:s})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=C1(this.inputProblem);for(let a of Object.values(this.inputTraceMap))e.lines.push({points:a.tracePath,strokeColor:"purple"});for(let a of this.netLabelPlacements)e.rects.push({center:a.center,width:a.width,height:a.height,fill:tl(a.globalConnNetId,.35),strokeColor:tl(a.globalConnNetId,.9)}),e.points.push({x:a.anchorPoint.x,y:a.anchorPoint.y,color:tl(a.globalConnNetId,.9)});return e}},kqt=r=>{for(let e of r.chips){let a=BW(e);for(let s of e.pins){if(!(s.x>a.minX&&s.x<a.maxX&&s.y>a.minY&&s.y<a.maxY))continue;let d=s.x-a.minX,x=a.maxX-s.x,f=s.y-a.minY,m=a.maxY-s.y,D=Math.min(d,x,f,m);D===d?s.x=a.minX:D===x?s.x=a.maxX:D===f?s.y=a.minY:s.y=a.maxY,s._facingDirection=void 0}}},Nqt=r=>{for(let e of r.chips){let a=e.width/2,s=e.height/2,l=0,d=0;for(let m of e.pins){let D=Math.abs(m.x-e.center.x),b=Math.abs(m.y-e.center.y);D>l&&(l=D),b>d&&(d=b)}let x=Math.max(a,l),f=Math.max(s,d);if(x>a||f>s){e.width=x*2,e.height=f*2;for(let m of e.pins)m._facingDirection=void 0}}};function SS(r,e,a,s={}){return{solverName:r,solverClass:e,getConstructorParams:a,onSolved:s.onSolved}}var RSe=class extends ex{constructor(e){super();q(this,"mspConnectionPairSolver");q(this,"schematicTraceLinesSolver");q(this,"traceOverlapShiftSolver");q(this,"netLabelPlacementSolver");q(this,"startTimeOfPhase");q(this,"endTimeOfPhase");q(this,"timeSpentOnPhase");q(this,"firstIterationOfPhase");q(this,"inputProblem");q(this,"pipelineDef",[SS("mspConnectionPairSolver",fqt,()=>[{inputProblem:this.inputProblem}],{onSolved:e=>{}}),SS("schematicTraceLinesSolver",Cqt,()=>[{mspConnectionPairs:this.mspConnectionPairSolver.mspConnectionPairs,dcConnMap:this.mspConnectionPairSolver.dcConnMap,globalConnMap:this.mspConnectionPairSolver.globalConnMap,inputProblem:this.inputProblem,chipMap:this.mspConnectionPairSolver.chipMap}],{onSolved:e=>{}}),SS("traceOverlapShiftSolver",Rqt,()=>[{inputProblem:this.inputProblem,inputTracePaths:this.schematicTraceLinesSolver.solvedTracePaths,globalConnMap:this.mspConnectionPairSolver.globalConnMap}],{onSolved:e=>{}}),SS("netLabelPlacementSolver",jqt,()=>[{inputProblem:this.inputProblem,inputTraceMap:this.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(this.schematicTraceLinesSolver.solvedTracePaths.map(e=>[e.mspPairId,e]))}],{onSolved:e=>{}})]);q(this,"currentPipelineStepIndex",0);this.inputProblem=this.cloneAndCorrectInputProblem(e),this.MAX_ITERATIONS=1e6,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={},this.firstIterationOfPhase={}}getConstructorParams(){return this.inputProblem}cloneAndCorrectInputProblem(e){let a=structuredClone({...e,_chipObstacleSpatialIndex:void 0});return Nqt(a),kqt(a),a}_step(){let e=this.pipelineDef[this.currentPipelineStepIndex];if(!e){this.solved=!0;return}if(this.activeSubSolver){this.activeSubSolver.step(),this.activeSubSolver.solved?(this.endTimeOfPhase[e.solverName]=performance.now(),this.timeSpentOnPhase[e.solverName]=this.endTimeOfPhase[e.solverName]-this.startTimeOfPhase[e.solverName],e.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++):this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let a=e.getConstructorParams(this);this.activeSubSolver=new e.solverClass(...a),this[e.solverName]=this.activeSubSolver,this.timeSpentOnPhase[e.solverName]=0,this.startTimeOfPhase[e.solverName]=performance.now(),this.firstIterationOfPhase[e.solverName]=this.iterations}solveUntilPhase(e){for(;this.getCurrentPhase().toLowerCase()!==e.toLowerCase();)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let e=[C1(this.inputProblem),...this.pipelineDef.map(a=>this[a.solverName]?.visualize()).filter(Boolean).map((a,s)=>{for(let l of a.rects??[])l.step=s;for(let l of a.points??[])l.step=s;for(let l of a.circles??[])l.step=s;for(let l of a.texts??[])l.step=s;for(let l of a.lines??[])l.step=s;return a})];return e.length===1?e[0]:{points:e.flatMap(a=>a.points||[]),rects:e.flatMap(a=>a.rects||[]),lines:e.flatMap(a=>a.lines||[]),circles:e.flatMap(a=>a.circles||[]),texts:e.flatMap(a=>a.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}};var c9e=Or(fs(),1);var l9e=Or(fs(),1);var d9e=Or(fs(),1);Fo();ra();Fo();ra();ra();qt();ra();ra();V0();ra();Fo();ra();function SSe(r,e,a,s){return Math.sqrt((a-r)**2+(s-e)**2)}var Mqt=r=>{let e=r.filter(d=>d.type==="pcb_port"),a=r.filter(d=>d.type==="pcb_smtpad"),s=r.filter(d=>d.type==="pcb_trace");function l(d,x={}){let f=x.traceWidth||0,m=e.find(D=>SSe(D.x,D.y,d.x,d.y)<.01);if(m)return m.pcb_port_id;if(x.isFirstOrLastPoint){let D=a.find(b=>{if(b.shape==="rect")return Math.abs(d.x-b.x)<b.width/2+f/2&&Math.abs(d.y-b.y)<b.height/2+f/2;if(b.shape==="circle")return SSe(d.x,d.y,b.x,b.y)<b.radius});if(D)return D.pcb_port_id??null}return null}for(let d of s)for(let x=0;x<d.route.length;x++){let f=d.route[x],m=x===0||x===d.route.length-1;if(f.route_type==="wire"){if(!f.start_pcb_port_id&&x===0){let D=l(f,{isFirstOrLastPoint:m,traceWidth:f.width});D&&(f.start_pcb_port_id=D)}if(!f.end_pcb_port_id&&x===d.route.length-1){let D=l(f,{isFirstOrLastPoint:m,traceWidth:f.width});D&&(f.end_pcb_port_id=D)}}}};function wSe(r){Mqt(r);let e=r.filter(x=>x.type==="source_trace"),a=r.filter(x=>x.type==="pcb_port"),s=[],l=eu(r),d=new Map;for(let x of a)d.set(x.source_port_id,x);for(let x of e){let f=x.connected_source_port_ids;if(f.length<2)continue;let m=[],D=[];for(let w of f){let P=d.get(w);P?m.push(P):D.push(w)}if(m.length<2)continue;let b=m[0],E=l.getNetConnectedToId(b.pcb_port_id);l.getIdsConnectedToNet(E).filter(w=>r.some(P=>P.type==="pcb_trace"&&("pcb_trace_id"in P&&P.pcb_trace_id===w||"route_id"in P&&P.route_id===w))).length===0&&new Set(m.map(P=>P.pcb_component_id)).size>1&&s.push({type:"pcb_port_not_connected_error",message:`pcb_port_not_connected_error: Pcb ports [${m.map(P=>P.pcb_port_id).join(", ")}] are not connected together through the same net.`,error_type:"pcb_port_not_connected_error",pcb_port_ids:m.map(P=>P.pcb_port_id),pcb_component_ids:m.map(P=>P.pcb_component_id),pcb_port_not_connected_error_id:`pcb_port_not_connected_error_trace_${x.source_trace_id}`})}return s}var Oqt=class{constructor({objects:r,getBounds:e,getId:a,CELL_SIZE:s}){q(this,"buckets");q(this,"objectsById");q(this,"getBounds");q(this,"getId");q(this,"CELL_SIZE",.4);q(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=e,this.getId=a??(()=>this._getNextId()),this.CELL_SIZE=s??this.CELL_SIZE;for(let l of r)this.addObject(l)}_getNextId(){return`${this._idCounter++}`}addObject(r){let e=this.getBounds(r),a=this.getId(r),s={...r,spatialIndexId:a};this.objectsById.set(a,s);let l=Math.floor(e.minX/this.CELL_SIZE),d=Math.floor(e.minY/this.CELL_SIZE),x=Math.floor(e.maxX/this.CELL_SIZE),f=Math.floor(e.maxY/this.CELL_SIZE);for(let m=l;m<=x;m++)for(let D=d;D<=f;D++){let b=`${m}x${D}`,E=this.buckets.get(b);E?E.push(s):this.buckets.set(b,[s])}}removeObject(r){let e=this.objectsById.get(r);if(!e)return!1;this.objectsById.delete(r);let a=this.getBounds(e),s=Math.floor(a.minX/this.CELL_SIZE),l=Math.floor(a.minY/this.CELL_SIZE),d=Math.floor(a.maxX/this.CELL_SIZE),x=Math.floor(a.maxY/this.CELL_SIZE);for(let f=s;f<=d;f++)for(let m=l;m<=x;m++){let D=`${f}x${m}`,b=this.buckets.get(D);if(b){let E=b.findIndex(A=>A.spatialIndexId===r);E!==-1&&(b.splice(E,1),b.length===0&&this.buckets.delete(D))}}return!0}getBucketKey(r,e){return`${Math.floor(r/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getObjectsInBounds(r,e=0){let a=[],s=new Set,l=Math.floor((r.minX-e)/this.CELL_SIZE),d=Math.floor((r.minY-e)/this.CELL_SIZE),x=Math.floor((r.maxX+e)/this.CELL_SIZE),f=Math.floor((r.maxY+e)/this.CELL_SIZE);for(let m=l;m<=x;m++)for(let D=d;D<=f;D++){let b=`${m}x${D}`,E=this.buckets.get(b)||[];for(let A of E){let B=A.spatialIndexId;s.has(B)||(s.add(B),a.push(A))}}return a}},jF=r=>r.type==="pcb_trace_segment"?{minX:Math.min(r.x1,r.x2),minY:Math.min(r.y1,r.y2),maxX:Math.max(r.x1,r.x2),maxY:Math.max(r.y1,r.y2)}:_4e([r]),TW=.1,Lqt=.15;var PW=.005;function $qt(r){let e=new Set;for(let a of r.route)a.route_type==="wire"&&(a.start_pcb_port_id&&e.add(a.start_pcb_port_id),a.end_pcb_port_id&&e.add(a.end_pcb_port_id));return Array.from(e)}function IW(r){let e=new Set;for(let a of r)for(let s of $qt(a))e.add(s);return Array.from(e)}var zqt=(r,e)=>{let a={x:r.x1,y:r.y1},s={x:r.x2,y:r.y2},l={x:e.x1,y:e.y1},d={x:e.x2,y:e.y2},x={x:s.x-a.x,y:s.y-a.y},f={x:d.x-l.x,y:d.y-l.y},m=x.x*x.x+x.y*x.y,D=f.x*f.x+f.y*f.y;if(m===0||D===0){if(m===0&&D===0)return{x:(a.x+l.x)/2,y:(a.y+l.y)/2};if(m===0){let de=rl(((a.x-l.x)*f.x+(a.y-l.y)*f.y)/D,0,1),oe={x:l.x+de*f.x,y:l.y+de*f.y};return{x:(a.x+oe.x)/2,y:(a.y+oe.y)/2}}let J=rl(((l.x-a.x)*x.x+(l.y-a.y)*x.y)/m,0,1),Q={x:a.x+J*x.x,y:a.y+J*x.y};return{x:(Q.x+l.x)/2,y:(Q.y+l.y)/2}}let b={x:a.x-l.x,y:a.y-l.y},E=x.x*x.x+x.y*x.y,A=x.x*f.x+x.y*f.y,B=x.x*b.x+x.y*b.y,w=f.x*f.x+f.y*f.y,P=f.x*b.x+f.y*b.y,j=E*w-A*A;if(j<1e-10)return qqt(a,s,l,d,x,f,m,D);let O=(A*P-w*B)/j,z=(E*P-A*B)/j;O=rl(O,0,1),z=rl(z,0,1),z=(O*A+P)/w,z=rl(z,0,1),O=(z*A-B)/E,O=rl(O,0,1);let ee={x:a.x+O*x.x,y:a.y+O*x.y},W={x:l.x+z*f.x,y:l.y+z*f.y},re=ee.x-W.x,L=ee.y-W.y,K=Math.sqrt(re*re+L*L);return{x:(ee.x+W.x)/2,y:(ee.y+W.y)/2}},qqt=(r,e,a,s,l,d,x,f)=>{let m=((a.x-r.x)*l.x+(a.y-r.y)*l.y)/x;m=rl(m,0,1);let D={x:r.x+m*l.x,y:r.y+m*l.y},b=((s.x-r.x)*l.x+(s.y-r.y)*l.y)/x;b=rl(b,0,1);let E={x:r.x+b*l.x,y:r.y+b*l.y},A=((r.x-a.x)*d.x+(r.y-a.y)*d.y)/f;A=rl(A,0,1);let B={x:a.x+A*d.x,y:a.y+A*d.y},w=((e.x-a.x)*d.x+(e.y-a.y)*d.y)/f;w=rl(w,0,1);let P={x:a.x+w*d.x,y:a.y+w*d.y},O=[{pointA:D,pointB:a,distance:Math.sqrt((D.x-a.x)**2+(D.y-a.y)**2)},{pointA:E,pointB:s,distance:Math.sqrt((E.x-s.x)**2+(E.y-s.y)**2)},{pointA:r,pointB:B,distance:Math.sqrt((r.x-B.x)**2+(r.y-B.y)**2)},{pointA:e,pointB:P,distance:Math.sqrt((e.x-P.x)**2+(e.y-P.y)**2)}].reduce((z,ee)=>ee.distance<z.distance?ee:z);return{x:(O.pointA.x+O.pointB.x)/2,y:(O.pointA.y+O.pointB.y)/2}},rl=(r,e,a)=>Math.max(e,Math.min(a,r)),Uqt=r=>{if(r.type==="pcb_via"||r.type==="pcb_plated_hole"&&r.shape==="circle")return r.outer_diameter/2;if(r.type==="pcb_hole"&&r.hole_shape==="circle")return r.hole_diameter/2;if(r.type==="pcb_smtpad"&&r.shape==="circle")return r.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(r)}`)},BSe=(r,e)=>{let a={x:r.x1,y:r.y1},s={x:r.x2,y:r.y2},l=e.minX,d=e.minY,x=e.maxX,f=e.maxY;if(a.x===s.x&&a.y===s.y){let U=Math.max(l,Math.min(x,a.x)),J=Math.max(d,Math.min(f,a.y));return U===a.x&&J===a.y?{x:a.x,y:a.y}:{x:U,y:J}}let m=s.x-a.x,D=s.y-a.y,b=m!==0?(l-a.x)/m:Number.NEGATIVE_INFINITY,E=m!==0?(x-a.x)/m:Number.POSITIVE_INFINITY,A=D!==0?(d-a.y)/D:Number.NEGATIVE_INFINITY,B=D!==0?(f-a.y)/D:Number.POSITIVE_INFINITY,w=Math.max(Math.min(b,E),Math.min(A,B)),P=Math.min(Math.max(b,E),Math.max(A,B));if(w<=P&&P>=0&&w<=1){let U=Math.max(0,Math.min(1,w));return{x:a.x+U*m,y:a.y+U*D}}let j={x:Math.max(l,Math.min(x,a.x)),y:Math.max(d,Math.min(f,a.y))},O={x:Math.max(l,Math.min(x,s.x)),y:Math.max(d,Math.min(f,s.y))},z=(j.x-a.x)**2+(j.y-a.y)**2,ee=(O.x-s.x)**2+(O.y-s.y)**2,W=[{start:{x:l,y:d},end:{x,y:d}},{start:{x,y:d},end:{x,y:f}},{start:{x,y:f},end:{x:l,y:f}},{start:{x:l,y:f},end:{x:l,y:d}}],re=Math.min(z,ee),L=z<=ee?j:O,K=(U,J,Q)=>Math.max(J,Math.min(Q,U));for(let U of W){let J={x:s.x-a.x,y:s.y-a.y},Q={x:U.end.x-U.start.x,y:U.end.y-U.start.y},de={x:a.x-U.start.x,y:a.y-U.start.y},oe=J.x*J.x+J.y*J.y,Te=J.x*Q.x+J.y*Q.y,Me=J.x*de.x+J.y*de.y,Ge=Q.x*Q.x+Q.y*Q.y,et=Q.x*de.x+Q.y*de.y,dt=oe*Ge-Te*Te;if(Math.abs(dt)<1e-10)continue;let $t=(Te*et-Ge*Me)/dt,bt=(oe*et-Te*Me)/dt;$t=K($t,0,1),bt=K(bt,0,1);let ut={x:a.x+$t*J.x,y:a.y+$t*J.y},it={x:U.start.x+bt*Q.x,y:U.start.y+bt*Q.y},Ut=ut.x-it.x,It=ut.y-it.y,tr=Ut*Ut+It*It;tr<re&&(re=tr,L={x:(ut.x+it.x)/2,y:(ut.y+it.y)/2})}return L};function Vqt(r){return r.type==="pcb_trace_segment"?[r.layer]:r.type==="pcb_smtpad"?[r.layer]:r.type==="pcb_plated_hole"?Array.isArray(r.layers)?r.layers:[...$m]:r.type==="pcb_hole"?[...$m]:r.type==="pcb_via"?Array.isArray(r.layers)?r.layers:[...$m]:r.type==="pcb_keepout"?Array.isArray(r.layers)?r.layers:[]:[]}function TSe(r,{connMap:e}={}){let a=[];e??(e=eu(r));let l=La(r).pcb_trace.list().flatMap(w=>{let P=[];for(let j=0;j<w.route.length-1;j++){let O=w.route[j],z=w.route[j+1];O.route_type==="wire"&&z.route_type==="wire"&&O.layer===z.layer&&P.push({type:"pcb_trace_segment",pcb_trace_id:w.pcb_trace_id,_pcbTrace:w,thickness:"width"in O?O.width:"width"in z?z.width:Lqt,layer:O.layer,x1:O.x,y1:O.y,x2:z.x,y2:z.y})}return P}),d=La(r).pcb_smtpad.list(),x=La(r).pcb_plated_hole.list(),f=La(r).pcb_hole.list(),m=La(r).pcb_via.list(),D=La(r).pcb_keepout.list(),b=[...l,...d,...x,...f,...m,...D],E=new Oqt({objects:b,getBounds:jF}),A=w=>l1(r,w),B=new Set;for(let w of l){let P=TW,j=jF(w),O=E.getObjectsInBounds(j,P+w.thickness/2);if(!(w.x1===w.x2&&w.y1===w.y2))for(let z of O){if(!Vqt(z).includes(w.layer))continue;if(z.type==="pcb_trace_segment"){let L=z;if(w.layer!==L.layer||e.areIdsConnected(w.pcb_trace_id,L.pcb_trace_id))continue;let K=y5({x:w.x1,y:w.y1},{x:w.x2,y:w.y2},{x:L.x1,y:L.y1},{x:L.x2,y:L.y2})-w.thickness/2-L.thickness/2;if(K>TW-PW)continue;let U=`overlap_${w.pcb_trace_id}_${L.pcb_trace_id}`,J=`overlap_${L.pcb_trace_id}_${w.pcb_trace_id}`;if(B.has(U)||B.has(J))continue;B.add(U),a.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${A(w.pcb_trace_id)} overlaps with ${A(L.pcb_trace_id)} ${K<0?"(accidental contact)":`(gap: ${K.toFixed(3)}mm)`}`,pcb_trace_id:w.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:U,pcb_component_ids:[],center:zqt(w,L),pcb_port_ids:IW([w._pcbTrace,L._pcbTrace])});continue}let ee=v5(z);if(e.areIdsConnected(w.pcb_trace_id,"pcb_trace_id"in z?z.pcb_trace_id:ee))continue;if(z.type==="pcb_via"||z.type==="pcb_plated_hole"&&z.shape==="circle"||z.type==="pcb_hole"||z.type==="pcb_smtpad"&&z.shape==="circle"){let L=Uqt(z),U=b5({x:w.x1,y:w.y1},{x:w.x2,y:w.y2},{x:z.x,y:z.y,radius:L})-w.thickness/2;if(U>TW-PW)continue;let J=`overlap_${w.pcb_trace_id}_${ee}`;if(B.has(J))continue;B.add(J),a.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${A(w.pcb_trace_id)} overlaps with ${z.type} "${A(v5(z))}" ${U<0?"(accidental contact)":`(gap: ${U.toFixed(3)}mm)`}`,pcb_trace_id:w.pcb_trace_id,center:BSe(w,jF(z)),source_trace_id:"",pcb_trace_error_id:J,pcb_component_ids:["pcb_component_id"in z?z.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...IW([w._pcbTrace]),"pcb_port_id"in z?z.pcb_port_id:void 0].filter(Boolean)})}let re=Xb({x:w.x1,y:w.y1},{x:w.x2,y:w.y2},jF(z))-w.thickness/2;if(re+PW<P){let L=`overlap_${w.pcb_trace_id}_${ee}`;if(B.has(L))continue;B.add(L),a.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${A(w.pcb_trace_id)} overlaps with ${z.type} "${A(v5(z))}" ${re<0?"(accidental contact)":`(gap: ${re.toFixed(3)}mm)`}`,pcb_trace_id:w.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:L,pcb_component_ids:["pcb_component_id"in z?z.pcb_component_id:void 0].filter(Boolean),center:BSe(w,jF(z)),pcb_port_ids:[...IW([w._pcbTrace]),"pcb_port_id"in z?z.pcb_port_id:void 0].filter(Boolean)})}}}return a}function PSe(r){return r.area()>=0}function ISe({center:r,size:e,rotationDeg:a=0}){let s=r.x,l=r.y,d=e.width/2,x=e.height/2,f=[new el(s-d,l-x),new el(s+d,l-x),new el(s+d,l+x),new el(s-d,l+x)],m=new BF(f);if(a){let D=r5(a,s,l),b=f.map(E=>{let A=wa(D,{x:E.x,y:E.y});return new el(A.x,A.y)});m=new BF(b)}return PSe(m)||m.reverse(),m}function Gqt({board:r}){if(r.outline&&r.outline.length>0){let e=r.outline.map(s=>new el(s.x,s.y)),a=new BF(e);return PSe(a)||a.reverse(),a}return r.center&&typeof r.width=="number"&&typeof r.height=="number"?ISe({center:r.center,size:{width:r.width,height:r.height},rotationDeg:0}):null}function Xqt({circuitJson:r,component:e}){if(e.source_component_id){let a=r.find(s=>s.type==="source_component"&&s.source_component_id===e.source_component_id);if(a&&"name"in a&&a.name)return a.name}return l1(r,e.pcb_component_id)||"Unknown"}function Yqt(r,e,a,s,l,d){let x=new el(a.x,a.y);if(!e.contains(x)){let P=e.distanceTo(x);return Array.isArray(P)?P[0]:Number(P)||0}let f=s/2,m=l/2,D=[{x:a.x-f,y:a.y-m},{x:a.x+f,y:a.y-m},{x:a.x+f,y:a.y+m},{x:a.x-f,y:a.y+m}],b=[];for(let P=0;P<4;P++){let j=(P+1)%4;b.push({x:(D[P].x+D[j].x)/2,y:(D[P].y+D[j].y)/2})}let E=r5(d,a.x,a.y),A=P=>{let j=wa(E,P);return new el(j.x,j.y)},B=D.concat(b).map(A),w=0;for(let P of B)if(!e.contains(P)){let j=e.distanceTo(P),O=Array.isArray(j)?j[0]:Number(j)||0;O>w&&(w=O)}if(w>0)return w;try{let P=dW.intersect(r,e),j=0;P?Array.isArray(P)?j=P.reduce((z,ee)=>z+(typeof ee.area=="function"?ee.area():0),0):typeof P.area=="function"?j=P.area():j=0:j=0;let O=r.area();if(j>0&&j<O){let z=1-j/O,ee=Math.abs(s),W=Math.abs(l);return Math.min(ee,W)*z}else return .1}catch{return .1}}function jSe(r){let e=r.find(d=>d.type==="pcb_board");if(!e)return[];let a=Gqt({board:e});if(!a)return[];let s=r.filter(d=>d.type==="pcb_component");if(s.length===0)return[];let l=[];for(let d of s){if(!d.center||typeof d.width!="number"||typeof d.height!="number"||d.width<=0||d.height<=0)continue;let x=ISe({center:d.center,size:{width:d.width,height:d.height},rotationDeg:d.rotation||0});if(x.area()===0||a.contains(x))continue;let m=Yqt(x,a,d.center,d.width,d.height,d.rotation||0),D=Xqt({circuitJson:r,component:d}),b=Math.round(m*100)/100;l.push({type:"pcb_component_outside_board_error",error_type:"pcb_component_outside_board_error",pcb_component_outside_board_error_id:`pcb_component_outside_board_${d.pcb_component_id}`,message:`Component ${D} (${d.pcb_component_id}) extends outside board boundaries by ${b}mm`,pcb_component_id:d.pcb_component_id,pcb_board_id:e.pcb_board_id,component_center:d.center,component_bounds:{min_x:x.box.xmin,max_x:x.box.xmax,min_y:x.box.ymin,max_y:x.box.ymax},subcircuit_id:d.subcircuit_id,source_component_id:d.source_component_id})}return l}var jW=[{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 Ns(r){if(r==null)return"";if(r===0)return"0";let e=Math.abs(r),a=jW.find(d=>{let x=e/d.value;return x>=1&&x<1e3})||jW[jW.length-1],l=(r/a.value).toPrecision(3);return l.includes(".")&&!/\.0+$/.test(l)&&(l=l.replace(/0+$/,"")),l=l.replace(/\.0+$/,""),`${l}${a.symbol}`}qt();Ue();Fo();Jl();ra();var J9e=Or(kc(),1);var aK=Or(fs(),1),Xg=Or(kc(),1),zgr=Or(kc(),1);var w1=Or(_1(),1);var Z9e=Or(_1(),1),Q9e=Or(_1(),1);var e7e=Or(_1(),1);var t7e=Or(_1(),1);var r7e=Or(_1(),1),n7e=Or(kc(),1);var gVt=Object.defineProperty,DVt=(r,e)=>{for(var a in e)gVt(r,a,{get:e[a],enumerable:!0})},qBe={};DVt(qBe,{Battery:()=>k9e,Board:()=>p9e,Breakout:()=>R9e,BreakoutPoint:()=>S9e,CadAssembly:()=>e9e,CadModel:()=>QBe,Capacitor:()=>x9e,Chip:()=>QS,Constraint:()=>v9e,CopperPour:()=>j9e,Crystal:()=>z9e,Cutout:()=>XF,Diode:()=>h9e,FabricationNotePath:()=>C9e,FabricationNoteText:()=>_9e,Footprint:()=>ZBe,Fuse:()=>m9e,Group:()=>Wg,Hole:()=>dK,Inductor:()=>O9e,Jumper:()=>g9e,Keepout:()=>XS,Led:()=>y9e,Mosfet:()=>U9e,Net:()=>oK,NetLabel:()=>B9e,NormalComponent:()=>es,PcbTrace:()=>lK,PinHeader:()=>N9e,Pinout:()=>f9e,PlatedHole:()=>Yg,Port:()=>Ni,Potentiometer:()=>L9e,PowerSource:()=>b9e,PrimitiveComponent:()=>Qn,PushButton:()=>$9e,Renderable:()=>sK,Resistor:()=>E9e,Resonator:()=>M9e,SchematicBox:()=>Y9e,SchematicCell:()=>K9e,SchematicRow:()=>W9e,SchematicTable:()=>H9e,SchematicText:()=>X9e,SilkscreenCircle:()=>w9e,SilkscreenLine:()=>P9e,SilkscreenPath:()=>cK,SilkscreenRect:()=>T9e,SilkscreenText:()=>JS,SmtPad:()=>GS,SolderJumper:()=>D9e,Subcircuit:()=>A9e,Switch:()=>V9e,TestPoint:()=>G9e,Trace:()=>qc,TraceHint:()=>fK,Transistor:()=>q9e,Via:()=>I9e,VoltageSource:()=>F9e});var yVt=(0,GBe.default)("tscircuit:renderable"),ld=["ReactSubtreesRender","SourceNameDuplicateComponentRemoval","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","AssignFallbackProps","CreateTracesFromProps","CreateTracesFromNetLabels","CreateTraceHintsFromProps","SourceGroupRender","AssignNameToUnnamedComponents","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SourceDesignRuleChecks","SimulationRender","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicLayout","SchematicTraceRender","SchematicReplaceNetLabelsWithSymbols","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbComponentSizeCalculation","PcbComponentAnchorAlignment","PcbLayout","PcbBoardAutoSize","PcbTraceHintRender","PcbManualTraceRender","PcbTraceRender","PcbRouteNetIslands","PcbCopperPourRender","PcbDesignRuleChecks","SilkscreenOverlapAdjustment","CadModelRender","PartsEngineRender"],bVt={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"]},FVt=0,sK=class{constructor(r){q(this,"renderPhaseStates");q(this,"shouldBeRemoved",!1);q(this,"children");q(this,"isPcbPrimitive",!1);q(this,"isSchematicPrimitive",!1);q(this,"_renderId");q(this,"_currentRenderPhase",null);q(this,"_asyncEffects",[]);q(this,"parent",null);this._renderId=`${FVt++}`,this.children=[],this.renderPhaseStates={};for(let e of ld)this.renderPhaseStates[e]={initialized:!1,dirty:!1}}_markDirty(r){this.renderPhaseStates[r].dirty=!0;let e=ld.indexOf(r);for(let a=e+1;a<ld.length;a++)this.renderPhaseStates[ld[a]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(r)}_queueAsyncEffect(r,e){let a={promise:e(),phase:this._currentRenderPhase,effectName:r,complete:!1};this._asyncEffects.push(a),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:r,componentDisplayName:this.getString(),phase:a.phase}),a.promise.then(()=>{a.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:r,componentDisplayName:this.getString(),phase:a.phase})}).catch(s=>{console.error(`Async effect error in ${a.phase} "${r}":
|
|
1037
|
-
${s.stack}`),a.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:r,componentDisplayName:this.getString(),phase:a.phase,error:s.toString()})})}_emitRenderLifecycleEvent(r,e){yVt(`${r}:${e} ${this.getString()}`);let a=`renderable:renderLifecycle:${r}:${e}`,s={renderId:this._renderId,componentDisplayName:this.getString(),type:a};"root"in this&&this.root&&(this.root.emit(a,s),this.root.emit("renderable:renderLifecycle:anyEvent",{...s,type:a}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(r=>!r.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(r){for(let e of this._asyncEffects)if(!e.complete&&e.phase===r)return!0;for(let e of this.children)if(e._hasIncompleteAsyncEffectsInSubtreeForPhase(r))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(r=>r.getRenderGraph())}}runRenderCycle(){for(let r of ld)this.runRenderPhaseForChildren(r),this.runRenderPhase(r)}runRenderPhase(r){this._currentRenderPhase=r;let e=this.renderPhaseStates[r],a=e.initialized,s=e.dirty;if(!a&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&a){this._emitRenderLifecycleEvent(r,"start"),this?.[`remove${r}`]?.(),e.initialized=!1,e.dirty=!1,this._emitRenderLifecycleEvent(r,"end");return}let l=ld.indexOf(r)-1;if(l>=0){let x=ld[l];if(this._asyncEffects.filter(m=>m.phase===x).some(m=>!m.complete))return}let d=bVt[r]||[];for(let x of d)if(this._hasIncompleteAsyncEffectsInSubtreeForPhase(x))return;if(this._emitRenderLifecycleEvent(r,"start"),a){s&&(this?.[`update${r}`]?.(),e.dirty=!1),this._emitRenderLifecycleEvent(r,"end");return}e.dirty=!1,this?.[`doInitial${r}`]?.(),e.initialized=!0,this._emitRenderLifecycleEvent(r,"end")}runRenderPhaseForChildren(r){for(let e of this.children)e.runRenderPhaseForChildren(r),e.runRenderPhase(r)}renderError(r){throw typeof r=="string"?new Error(r):new Error(JSON.stringify(r,null,2))}},VS={},XBe=r=>{let e=Object.fromEntries(Object.entries(r).map(([a,s])=>[a.toLowerCase(),s]));Object.assign(VS,r),Object.assign(VS,e)},EVt=class extends Error{constructor(r,e,a){let s,l=Object.keys(a).filter(m=>m!=="_errors"),d=[],x=e.pinLabels;if(x)for(let[m,D]of Object.entries(x)){let b=Array.isArray(D)?D:[D];for(let E of b)typeof E=="string"&&(E.startsWith(" ")||E.endsWith(" "))&&d.push(`pinLabels.${m} ("${E}" has leading or trailing spaces)`)}let f=l.map(m=>m==="pinLabels"&&d.length>0?d.join(", "):a[m]._errors[0]?`${m} (${a[m]._errors[0]})`:`${m} (${JSON.stringify(a[m])})`).join(", ");"name"in e?s=`Invalid props for ${r} "${e.name}": ${f}`:"footprint"in e&&typeof e.footprint=="string"?s=`Invalid props for ${r} (unnamed ${e.footprint} component): ${f}`:s=`Invalid props for ${r} (unnamed): ${f}`,super(s),this.componentName=r,this.originalProps=e,this.formattedError=a}};function VW(r,e){let a=e.match(/^#(\w+)/);if(a)return r.props.id===a[1];let s=e.match(/^\.(\w+)/);if(s)return r.isMatchingNameOrAlias(s[1]);let[l,...d]=e.split(/(?=[#.[])/);return l==="pin"&&(l="port"),l&&l!=="*"&&r.lowercaseComponentName!==l.toLowerCase()?!1:d.every(x=>{if(x.startsWith("#"))return r.props.id===x.slice(1);if(x.startsWith("."))return r.isMatchingNameOrAlias(x.slice(1));let f=x.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!f)return!0;let[,m,D]=f;return r.props[m].toString()===D})}var iK={isTag:r=>!0,getParent:r=>r.parent,getChildren:r=>r.children,getName:r=>r.lowercaseComponentName,getAttributeValue:(r,e)=>{if(e==="class"&&"getNameAndAliases"in r)return r.getNameAndAliases().join(" ");if(e==="name"&&r._parsedProps?.name)return r._parsedProps.name;if(r._parsedProps&&e in r._parsedProps){let s=r._parsedProps[e];return typeof s=="string"?s:s!=null?String(s):null}if(e in r){let s=r[e];return typeof s=="string"?s:s!=null?String(s):null}let a=r._attributeLowerToCamelNameMap;if(a){let s=a[e];if(s&&s in r){let l=r[s];return typeof l=="string"?l:l!=null?String(l):null}}return null},hasAttrib:(r,e)=>{if(e==="class")return!!r._parsedProps?.name;if(r._parsedProps&&e in r._parsedProps||e in r)return!0;let a=r._attributeLowerToCamelNameMap;if(a){let s=a[e];if(s&&s in r)return!0}return!1},getSiblings:r=>r.parent?r.parent.children:[],prevElementSibling:r=>{if(!r.parent)return null;let e=r.parent.children,a=e.indexOf(r);return a>0?e[a-1]:null},getText:()=>"",removeSubsets:r=>r.filter((e,a)=>!r.some((s,l)=>a!==l&&s!==e&&s.getDescendants().includes(e))),existsOne:(r,e)=>e.some(r),findAll:(r,e)=>{let a=[],s=l=>{r(l)&&a.push(l);for(let d of l.children)s(d)};for(let l of e)s(l);return a},findOne:(r,e)=>{for(let a of e){if(r(a))return a;let s=a.children;if(s.length>0){let l=iK.findOne(r,s);if(l)return l}}return null},equals:(r,e)=>r._renderId===e._renderId,isHovered:r=>!1,isVisited:r=>!1,isActive:r=>!1},vVt={...iK,getChildren:r=>r.children.filter(e=>!e.isSubcircuit)},yBe={...iK,getChildren:r=>r.children.filter(e=>e.isSubcircuit)},bBe=r=>{if(/net\.[^\s>]*\./.test(r))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(r))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(r)){let e=r.match(/net\.([^ >]+)/),a=e?e[1]:"";throw new Error(`Net name "${a}" cannot start with a number, try using a prefix like "VBUS1"`)}return r.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,(e,a,s,l)=>{let d=/^\d+$/.test(l)?`pin${l}`:l;return`${a}.${s} > .${d}`}).trim()},GW={adapter:vVt,cacheResults:!0},Qn=class extends sK{constructor(e){super(e);q(this,"parent",null);q(this,"children");q(this,"childrenPendingRemoval");q(this,"props");q(this,"_parsedProps");q(this,"externallyAddedAliases");q(this,"isPrimitiveContainer",!1);q(this,"canHaveTextChildren",!1);q(this,"source_group_id",null);q(this,"source_component_id",null);q(this,"schematic_component_id",null);q(this,"pcb_component_id",null);q(this,"cad_component_id",null);q(this,"fallbackUnassignedName");q(this,"_cachedSelectAllQueries",new Map);q(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=e??{},this.externallyAddedAliases=[];let s=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(e??{});if(s.success)this._parsedProps=s.data;else throw new EVt(this.lowercaseComponentName,this.props,s.error.format())}get config(){return{componentName:"",zodProps:v.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(e){let a=this;for(;a;){if(a._parsedProps&&e in a._parsedProps)return a._parsedProps[e];a=a.parent}if(this.root?.platform&&e in this.root.platform)return this.root.platform[e]}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(e){let a=this.config.zodProps.parse({...this.props,...e}),s=this.props;this.props=a,this._parsedProps=this.config.zodProps.parse(e),this.onPropsChange({oldProps:s,newProps:a,changedProps:Object.keys(e)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation:e}=this.props;return typeof e=="string"?parseFloat(e):e??null}computePcbPropsTransform(){let{_parsedProps:e}=this,a=this._getPcbRotationBeforeLayout()??0;return js(Ma(e.pcbX??0,e.pcbY??0),Ip(a*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let e=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(e&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let a=this._getPcbRotationBeforeLayout()??0;return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),js(Ma(e.x,e.y),Ip(a*Math.PI/180)))}if(this.isPcbPrimitive){let a=this.getPrimitiveContainer();if(a&&a._parsedProps.layer==="bottom")return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),P3e(),this.computePcbPropsTransform())}return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let e=this.getPrimitiveContainer(),a=e?e._parsedProps.layer==="bottom":!1;return{isFlipped:a,maybeFlipLayer:l=>a?l==="top"?"bottom":"top":l}}_setPositionFromLayout(e){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:e}=this;return js(Ma(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){let e=this._getSchematicGlobalManualPlacementTransform(this);return e||js(this.parent?.computeSchematicGlobalTransform?.()??Si(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:e}=this,a=this.config.schematicSymbolName,s={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},l=e.schOrientation!==void 0?s[e.schOrientation]:e.schRotation;if(l===void 0&&(l=0),l=l%360,l<0&&(l+=360),e.schRotation!==void 0&&l%90!==0)throw new Error(`Schematic rotation ${e.schRotation} is not supported for ${this.componentName}`);let d=`${a}_horz`,x=`${a}_vert`,f=`${a}_up`,m=`${a}_down`,D=`${a}_left`,b=`${a}_right`;if(b in ks&&l===0)return b;if(f in ks&&l===90)return f;if(D in ks&&l===180)return D;if(m in ks&&l===270)return m;if(d in ks&&(l===0||l===180))return d;if(x in ks&&(l===90||l===270))return x;if(a in ks)return a}_getSchematicSymbolNameOrThrow(){let e=this._getSchematicSymbolName();if(!e)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return e}getSchematicSymbol(){let e=this._getSchematicSymbolName();return e?ks[e]??null:null}_getPcbManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let a=this.props.manualEdits;if(!a)return null;let s=a?.pcb_placements;if(!s)return null;for(let l of s)if(VW(e,l.selector)||e.props.name===l.selector)return as(this._computePcbGlobalTransformBeforeLayout(),l.center);return null}_getSchematicManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let a=this.props.manualEdits;if(!a)return null;let s=a.schematic_placements;if(!s)return null;for(let l of s)if(VW(e,l.selector)||e.props.name===l.selector)return as(this.computeSchematicGlobalTransform(),l.center);return null}_getSchematicGlobalManualPlacementTransform(e){let a=this.getSubcircuit()?._parsedProps.manualEdits;if(!a)return null;for(let s of a.schematic_placements??[])if((VW(e,s.selector)||e.props.name===s.selector)&&s.relative_to==="group_center")return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),Ma(s.center.x,s.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return as(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return as(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(e){this.parent=e}onPropsChange(e){}onChildChanged(e){this.parent?.onChildChanged?.(e)}add(e){let a=e.__text;if(typeof a=="string"){if(this.canHaveTextChildren||a.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${a}"`)}if(Object.keys(e).length!==0){if(this.lowercaseComponentName==="board"&&e.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(!e.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(e)}"`);e.onAddToParent(this),e.parent=this,this.children.push(e)}}addAll(e){for(let a of e)this.add(a)}remove(e){this.children=this.children.filter(a=>a!==e),this.childrenPendingRemoval.push(e),e.shouldBeRemoved=!0}getSubcircuitSelector(){let e=this.name,a=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?a:`${this.parent.getSubcircuitSelector()} > ${a}`}getFullPathSelector(){let e=this.name,a=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName,s=this.parent?.getFullPathSelector?.();return s?`${s} > ${a}`:a}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(e){return this.getNameAndAliases().includes(e)}isMatchingAnyOf(e){return this.getNameAndAliases().some(a=>e.map(s=>s.toString()).includes(a))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(e){let a=[this.componentName,this.lowercaseComponentName],s=[this.name].filter(Boolean),l=e.trim().split(/\> /)[0],d=l[0];return l.length>1?!1:!!(e==="*"||e[0]==="#"&&e.slice(1)===this.props.id||e[0]==="."&&s.includes(e.slice(1))||/^[a-zA-Z0-9_]/.test(d)&&a.includes(d))}getSubcircuit(){if(this.isSubcircuit)return this;let e=this.parent?.getSubcircuit?.();if(!e)throw new Error("Component is not inside an opaque group (no board?)");return e}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let e=this.selectAll("port");for(let a of e){let s=a.parent?.getNameAndAliases(),l=a.getNameAndAliases();if(s)for(let d of s)for(let x of l){let f=[`.${d} > .${x}`,`.${d} .${x}`];for(let m of f){let D=this._cachedSelectAllQueries.get(m);D?D.push(a):this._cachedSelectAllQueries.set(m,[a])}}}for(let[a,s]of this._cachedSelectAllQueries.entries())s.length===1&&this._cachedSelectOneQueries.set(a,s[0])}selectAll(e){if(this._cachedSelectAllQueries.has(e))return this._cachedSelectAllQueries.get(e);let a=bBe(e),s=lY(a,this,GW);if(s.length>0)return this._cachedSelectAllQueries.set(e,s),s;let[l,...d]=a.split(" "),x=e5(l,this,{adapter:yBe});if(!x)return[];let f=x.selectAll(d.join(" "));return this._cachedSelectAllQueries.set(e,f),f}selectOne(e,a){if(this._cachedSelectOneQueries.has(e))return this._cachedSelectOneQueries.get(e);let s=bBe(e);a?.port&&(a.type="port");let l=null;if(a?.type&&(l=lY(s,this,GW).find(D=>D.lowercaseComponentName===a.type)),l??(l=e5(s,this,GW)),l)return this._cachedSelectOneQueries.set(e,l),l;let[d,...x]=s.split(" "),f=e5(d,this,{adapter:yBe});return f?(l=f.selectOne(x.join(" "),a),this._cachedSelectOneQueries.set(e,l),l):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:e}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[e(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?this.root?._getBoard()?.allLayers??["top","bottom"]:[]}return[]}getDescendants(){let e=[];for(let a of this.children)e.push(a),e.push(...a.getDescendants());return e}getSelectableDescendants(){let e=[];for(let a of this.children)a.isSubcircuit?e.push(a):(e.push(a),e.push(...a.getSelectableDescendants()));return e}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this;return{schWidth:e.schWidth,schHeight:e.schHeight}}renderError(e){if(typeof e=="string")return super.renderError(e);this.root?.db.pcb_placement_error.insert(e)}getString(){let{lowercaseComponentName:e,_parsedProps:a,parent:s}=this;return a?.pinNumber!==void 0&&s?.props?.name&&a?.name?`<${e}#${this._renderId}(pin:${a.pinNumber} .${s?.props.name}>.${a.name}) />`:s?.props?.name&&a?.name?`<${e}#${this._renderId}(.${s?.props.name}>.${a?.name}) />`:a?.from&&a?.to?`<${e}#${this._renderId}(from:${a.from} to:${a?.to}) />`:a?.name?`<${e}#${this._renderId} name=".${a?.name}" />`:a?.portHints?`<${e}#${this._renderId}(${a.portHints.map(l=>`.${l}`).join(", ")}) />`:`<${e}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},CVt=class extends Qn{constructor(r,e){super(r),this._parsedProps={...r,error:e,type:r.type||"unknown",component_name:r.name,error_type:"source_failed_to_create_component_error",message:e instanceof Error?e.message:String(e),pcbX:r.pcbX,pcbY:r.pcbY,schX:r.schX,schY:r.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:v.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let r=this._getGlobalPcbPositionBeforeLayout(),e=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:r,schematic_center:e})}}};function _Vt(r,e){return new CVt(r,e)}function AVt(r,e){let a=r;return a.__tsci={...e},r}var RVt={supportsMutation:!0,createInstance(r,e){let a=VS[r];if(!a)throw Object.keys(VS).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 "${r}". 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 AVt(new a(e),{})}catch(s){return _Vt({...e,componentType:r},s)}},createTextInstance(r){return{__text:r}},appendInitialChild(r,e){r.add(e)},appendChild(r,e){r.add(e)},appendChildToContainer(r,e){r.add(e)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(r){return r},preparePortalMount(r){throw new Error("Function not implemented.")},scheduleTimeout(r,e){throw new Error("Function not implemented.")},cancelTimeout(r){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(r){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(r,e)=>{throw new Error("Function not implemented.")},getInstanceFromScope:r=>{throw new Error("Function not implemented.")},detachDeletedInstance:r=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>zS.DefaultEventPriority,getCurrentUpdatePriority:()=>zS.DefaultEventPriority,resolveUpdatePriority:()=>zS.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},OS=(0,VBe.default)(RVt),YBe=r=>{let e={children:[],props:{name:"$root"},add(d){d.parent=this,this.children.push(d)},computePcbGlobalTransform(){return Si()}},a=[],s=OS.createContainer(e,0,null,!1,null,"tsci",d=>{console.log("Error in createContainer"),console.error(d),a.push(d)},null);if(OS.updateContainerSync(r,s,null,()=>{}),OS.flushSyncWork(),a.length>0)throw a[0];let l=OS.getPublicRootInstance(s);return l||e.children[0]},YF=(r,e)=>{if(typeof r=="number")return r;if(r.startsWith("pin"))return Number(r.slice(3));if(!e)throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`);for(let a in e)if((Array.isArray(e[a])?e[a]:[e[a]]).includes(r))return Number(a.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`)},SVt=(r,e)=>{if(!r)return;let a={},s={};for(let[l,d]of Object.entries(r)){let x=YF(l,e);s[x]={...s[x],...d}}for(let[l,d]of Object.entries(s)){let x=`pin${l}`;a[x]={bottom_margin:d.bottomMargin,left_margin:d.leftMargin,right_margin:d.rightMargin,top_margin:d.topMargin}}return a},BVt=r=>{if(r){if("leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r)return{left_side:r.leftSide,right_side:r.rightSide,top_side:r.topSide,bottom_side:r.bottomSide};if("leftPinCount"in r||"rightPinCount"in r||"topPinCount"in r||"bottomPinCount"in r)return{left_size:r.leftPinCount,right_size:r.rightPinCount,top_size:r.topPinCount,bottom_size:r.bottomPinCount};if("leftSize"in r||"rightSize"in r||"topSize"in r||"bottomSize"in r)return{left_size:r.leftSize,right_size:r.rightSize,top_size:r.topSize,bottom_size:r.bottomSize}}};function HBe(r){let e=[];for(let a=0;a<r.length-1;a++)e.push([r[a],r[a+1]]);return e}var wVt=v.object({name:v.string().refine(r=>!/[+-]/.test(r),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),oK=class extends Qn{constructor(){super(...arguments);q(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:wVt}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=a.name.startsWith("GND"),l=a.name.startsWith("V"),d=e.source_net.insert({name:a.name,member_source_group_ids:[],is_ground:s,is_power:l,is_positive_voltage_source:l});this.source_net_id=d.source_net_id}doInitialSourceParentAttachment(){let e=this.getSubcircuit();if(!e)return;let{db:a}=this.root;a.source_net.update(this.source_net_id,{subcircuit_id:e.subcircuit_id})}getAllConnectedPorts(){let e=this.getSubcircuit().selectAll("port"),a=[];for(let s of e){let l=s._getDirectlyConnectedTraces();for(let d of l)if(d._isExplicitlyConnectedToNet(this)){a.push(s);break}}return a}_getAllDirectlyConnectedTraces(){let e=this.getSubcircuit().selectAll("trace"),a=[];for(let s of e)s._isExplicitlyConnectedToNet(this)&&a.push(s);return a}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getAllDirectlyConnectedTraces().filter(x=>(x._portsRoutedOnPcb?.length??0)>0),l=[];for(let x of s){let f=x._portsRoutedOnPcb,m=l.find(D=>f.some(b=>D.ports.includes(b)));if(!m){l.push({ports:[...f],traces:[x]});continue}m.traces.push(x),m.ports.push(...f)}if(l.length===0)return;let d=HBe(l);for(let[x,f]of d){let m=x.ports.map(O=>O._getGlobalPcbPositionBeforeLayout()),D=f.ports.map(O=>O._getGlobalPcbPositionBeforeLayout()),b=1/0,E=[-1,-1];for(let O=0;O<m.length;O++){let z=m[O];for(let ee=0;ee<D.length;ee++){let W=D[ee],re=Math.sqrt((z.x-W.x)**2+(z.y-W.y)**2);re<b&&(b=re,E=[O,ee])}}let A=x.ports[E[0]],B=f.ports[E[1]],w=e.toArray().filter(O=>O.type==="pcb_smtpad"||O.type==="pcb_trace"||O.type==="pcb_plated_hole"||O.type==="pcb_hole"||O.type==="source_port"||O.type==="pcb_port"),{solution:P}=Z_e(w.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[A.source_port_id,B.source_port_id]}])),j=P[0];if(!j){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[A.pcb_component_id,B.pcb_component_id].filter(Boolean),pcb_port_ids:[A.pcb_port_id,B.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}e.pcb_trace.insert(j)}}renderError(e){if(typeof e=="string")return super.renderError(e);this.root?.db.pcb_trace_error.insert(e)}},uK=(r,e)=>{for(let a of e)if(typeof a=="string"&&a.startsWith("net.")){if(/net\.[^\s>]*\./.test(a))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(a))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(a)){let l=a.split("net.")[1];throw new Error(`Net name "${l}" cannot start with a number, try using a prefix like "VBUS1"`)}let s=r.getSubcircuit();if(!s.selectOne(a)){let l=new oK({name:a.split("net.")[1]});s.add(l)}}},GS=class extends Qn{constructor(){super(...arguments);q(this,"pcb_smtpad_id",null);q(this,"matchedPort",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:FAe}}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="polygon"){let a=e.points,s=a.map(D=>D.x),l=a.map(D=>D.y),d=Math.min(...s),x=Math.max(...s),f=Math.min(...l),m=Math.max(...l);return{width:x-d,height:m-f}}if(e.shape==="pill")return{width:e.width,height:e.height};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let a of e)if(a.isMatchingAnyOf(this.props.portHints)){this.matchedPort=a,a.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this;if(!a.portHints)return;let s=this.getPrimitiveContainer(),l=this.getSubcircuit(),d=this._getGlobalPcbPositionBeforeLayout(),x=s?._getGlobalPcbPositionBeforeLayout(),f=i4(this._computePcbGlobalTransformBeforeLayout()),m=Math.abs(f.rotation.angle*(180/Math.PI)-90)%180<.01,{maybeFlipLayer:D}=this._getPcbPrimitiveFlippedHelpers(),b=s?._parsedProps.pcbRotation??0,E=null,A=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;a.shape==="circle"?(E=e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"circle",radius:a.radius,port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,x:d.x,y:d.y,subcircuit_id:l?.subcircuit_id??void 0}),e.pcb_solder_paste.insert({layer:E.layer,shape:"circle",radius:E.radius*.7,x:E.x,y:E.y,pcb_component_id:E.pcb_component_id,pcb_smtpad_id:E.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):a.shape==="rect"?(E=b===0||m?e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"rect",width:m?a.height:a.width,height:m?a.width:a.height,port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,x:d.x,y:d.y,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):e.pcb_smtpad.insert({pcb_component_id:A,layer:D(a.layer??"top"),shape:"rotated_rect",width:a.width,height:a.height,x:d.x,y:d.y,ccw_rotation:b,port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),E.shape==="rect"&&e.pcb_solder_paste.insert({layer:D(a.layer??"top"),shape:"rect",width:E.width*.7,height:E.height*.7,x:E.x,y:E.y,pcb_component_id:E.pcb_component_id,pcb_smtpad_id:E.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),E.shape==="rotated_rect"&&e.pcb_solder_paste.insert({layer:D(a.layer??"top"),shape:"rotated_rect",width:E.width*.7,height:E.height*.7,x:E.x,y:E.y,ccw_rotation:b,pcb_component_id:E.pcb_component_id,pcb_smtpad_id:E.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):a.shape==="polygon"?E=e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"polygon",points:a.points.map(B=>({x:B.x+d.x,y:B.y+d.y})),port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):a.shape==="pill"&&(E=e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"pill",x:d.x,y:d.y,radius:a.radius,height:a.height,width:a.width,port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})),E&&(this.pcb_smtpad_id=E.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_smtpad.get(this.pcb_smtpad_id);if(a.shape==="rect")return{center:{x:a.x,y:a.y},bounds:{left:a.x-a.width/2,top:a.y+a.height/2,right:a.x+a.width/2,bottom:a.y-a.height/2},width:a.width,height:a.height};if(a.shape==="rotated_rect"){let s=a.ccw_rotation*Math.PI/180,l=Math.cos(s),d=Math.sin(s),x=a.width/2,f=a.height/2,m=Math.abs(x*l)+Math.abs(f*d),D=Math.abs(x*d)+Math.abs(f*l);return{center:{x:a.x,y:a.y},bounds:{left:a.x-m,right:a.x+m,top:a.y-D,bottom:a.y+D},width:m*2,height:D*2}}if(a.shape==="circle")return{center:{x:a.x,y:a.y},bounds:{left:a.x-a.radius,top:a.y-a.radius,right:a.x+a.radius,bottom:a.y+a.radius},width:a.radius*2,height:a.radius*2};if(a.shape==="polygon"){let s=a.points,l=s.map(b=>b.x),d=s.map(b=>b.y),x=Math.min(...l),f=Math.max(...l),m=Math.min(...d),D=Math.max(...d);return{center:{x:(x+f)/2,y:(m+D)/2},bounds:{left:x,top:D,right:f,bottom:m},width:f-x,height:D-m}}if(a.shape==="pill"){let s=a.width/2,l=a.height/2;return{center:{x:a.x,y:a.y},bounds:{left:a.x-s,top:a.y-l,right:a.x+s,bottom:a.y+l},width:a.width,height:a.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${a.shape}"`)}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_smtpad.update(this.pcb_smtpad_id,{x:e.x,y:e.y});let s=a.pcb_solder_paste.list().find(l=>l.pcb_smtpad_id===this.pcb_smtpad_id);a.pcb_solder_paste.update(s?.pcb_solder_paste_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}},cK=class extends Qn{constructor(){super(...arguments);q(this,"pcb_silkscreen_path_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:QAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenPath. Must be "top" or "bottom".`);let d=this._computePcbGlobalTransformBeforeLayout(),x=this.getSubcircuit(),f=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=e.pcb_silkscreen_path.insert({pcb_component_id:f,layer:l,route:a.route.map(D=>{let b=as(d,{x:D.x,y:D.y});return{...D,x:b.x,y:b.y}}),stroke_width:a.strokeWidth??.1,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=m.pcb_silkscreen_path_id}_setPositionFromLayout(e){let{db:a}=this.root,{_parsedProps:s}=this,l=a.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!l)return;let d=0,x=0;for(let b of l.route)d+=b.x,x+=b.y;d/=l.route.length,x/=l.route.length;let f=e.x-d,m=e.y-x,D=l.route.map(b=>({...b,x:b.x+f,y:b.y+m}));a.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:D})}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let a=1/0,s=-1/0,l=1/0,d=-1/0;for(let x of e.route)a=Math.min(a,x.x),s=Math.max(s,x.x),l=Math.min(l,x.y),d=Math.max(d,x.y);return{width:s-a,height:d-l}}},TVt=v.object({route:v.array(UA),source_trace_id:v.string().optional()}),lK=class extends Qn{constructor(){super(...arguments);q(this,"pcb_trace_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:TVt}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer(),l=this.getSubcircuit(),{maybeFlipLayer:d}=this._getPcbPrimitiveFlippedHelpers(),x=this._computePcbGlobalTransformBeforeLayout(),f=a.route.map(D=>{let{x:b,y:E,...A}=D,B=as(x,{x:b,y:E});return D.route_type==="wire"&&D.layer?{...B,...A,layer:d(D.layer)}:{...B,...A}}),m=e.pcb_trace.insert({pcb_component_id:s.pcb_component_id,source_trace_id:a.source_trace_id,route:f,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=m.pcb_trace_id}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let a=1/0,s=-1/0,l=1/0,d=-1/0;for(let x of e.route)a=Math.min(a,x.x),s=Math.max(s,x.x),l=Math.min(l,x.y),d=Math.max(d,x.y),x.route_type==="wire"&&(a=Math.min(a,x.x-x.width/2),s=Math.max(s,x.x+x.width/2),l=Math.min(l,x.y-x.width/2),d=Math.max(d,x.y+x.width/2));return a===1/0||s===-1/0||l===1/0||d===-1/0?{width:0,height:0}:{width:s-a,height:d-l}}},Yg=class extends Qn{constructor(){super(...arguments);q(this,"pcb_plated_hole_id",null);q(this,"matchedPort",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:dAe}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.outerDiameter,height:e.outerDiameter};if(e.shape==="oval"||e.shape==="pill")return{width:e.outerWidth,height:e.outerHeight};if(e.shape==="circular_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};if(e.shape==="pill_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_plated_hole.get(this.pcb_plated_hole_id),s=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-s.width/2,top:a.y+s.height/2,right:a.x+s.width/2,bottom:a.y-s.height/2},width:s.width,height:s.height}}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let a of e)if(a.isMatchingAnyOf(this.props.portHints)){this.matchedPort=a,a.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalPcbPositionBeforeLayout(),l=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,d=this.getSubcircuit();if(a.shape==="circle"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:a.outerDiameter,hole_diameter:a.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:a.outerDiameter/2,x:s.x,y:s.y,subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:a.outerDiameter/2,x:s.x,y:s.y,subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(a.shape==="pill"&&a.rectPad){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:a.outerWidth,outer_height:a.outerHeight,hole_width:a.holeWidth,hole_height:a.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:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:a.pcbRotation??0,rect_ccw_rotation:a.pcbRotation??0,rect_pad_width:a.outerWidth,rect_pad_height:a.outerHeight,hole_offset_x:a.holeOffsetX,hole_offset_y:a.holeOffsetY});this.pcb_plated_hole_id=x.pcb_plated_hole_id}else if(a.shape==="pill"||a.shape==="oval"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:a.outerWidth,outer_height:a.outerHeight,hole_width:a.holeWidth,hole_height:a.holeHeight,shape:a.shape,port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:a.pcbRotation??0});this.pcb_plated_hole_id=x.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:a.shape,width:a.outerWidth,height:a.outerHeight,x:s.x,y:s.y,subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:a.shape,width:a.outerWidth,height:a.outerHeight,x:s.x,y:s.y,subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(a.shape==="circular_hole_with_rect_pad"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:a.holeDiameter,rect_pad_width:a.rectPadWidth,rect_pad_height:a.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:a.holeOffsetX,hole_offset_y:a.holeOffsetY,rect_border_radius:a.rectBorderRadius??0});this.pcb_plated_hole_id=x.pcb_plated_hole_id}else if(a.shape==="pill_hole_with_rect_pad"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:a.holeWidth,hole_height:a.holeHeight,rect_pad_width:a.rectPadWidth,rect_pad_height:a.rectPadHeight,hole_offset_x:a.holeOffsetX,hole_offset_y:a.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},XS=class extends Qn{constructor(){super(...arguments);q(this,"pcb_keepout_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:qAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let e=this.getSubcircuit(),{db:a}=this.root,{_parsedProps:s}=this,l=this._getGlobalPcbPositionBeforeLayout(),d=i4(this._computePcbGlobalTransformBeforeLayout()),x=Math.abs(d.rotation.angle*(180/Math.PI)-90)%180<.01,f=null;s.shape==="circle"?f=a.pcb_keepout.insert({layers:["top"],shape:"circle",radius:s.radius,center:{x:l.x,y:l.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0}):s.shape==="rect"&&(f=a.pcb_keepout.insert({layers:["top"],shape:"rect",...x?{width:s.height,height:s.width}:{width:s.width,height:s.height},center:{x:l.x,y:l.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0})),f&&(this.pcb_keepout_id=f.pcb_keepout_id)}},dK=class extends Qn{constructor(){super(...arguments);q(this,"pcb_hole_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:EAe}}getPcbSize(){let{_parsedProps:e}=this,a=e.shape==="pill";return{width:a?e.width:e.diameter,height:a?e.height:e.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=this._getGlobalPcbPositionBeforeLayout(),d=e.pcb_hole.insert({hole_shape:"circle",hole_diameter:a.diameter,x:l.x,y:l.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:s?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=d.pcb_hole_id}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_hole.get(this.pcb_hole_id),s=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-s.width/2,top:a.y-s.height/2,right:a.x+s.width/2,bottom:a.y+s.height/2},width:s.width,height:s.height}}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_hole.update(this.pcb_hole_id,{x:e.x,y:e.y})}},JS=class extends Qn{constructor(){super(...arguments);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:ZAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer(),l=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:d}=this._getPcbPrimitiveFlippedHelpers(),x=this.getSubcircuit(),f=new Set(a.layers);a.layer&&f.add(a.layer);let m=f.size>0?Array.from(f):["top"];for(let D of m)e.pcb_silkscreen_text.insert({anchor_alignment:a.anchorAlignment,anchor_position:{x:l.x,y:l.y},font:a.font??"tscircuit2024",font_size:a.fontSize??1,layer:d(D),text:a.text??"",ccw_rotation:a.pcbRotation,pcb_component_id:s.pcb_component_id,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:e}=this,a=e.fontSize??1,l=(e.text??"").length*a,d=a;return{width:l*a,height:d*a}}},XF=class extends Qn{constructor(){super(...arguments);q(this,"pcb_cutout_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:bAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=this.getGroup()?.pcb_group_id??void 0,d=this._getGlobalPcbPositionBeforeLayout(),f=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,m;if(a.shape==="rect"){let D=typeof f=="string"?parseInt(f.replace("deg",""),10):f,b=Math.abs(D%180)===90,E={shape:"rect",center:d,width:b?a.height:a.width,height:b?a.width:a.height,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:l};m=e.pcb_cutout.insert(E)}else if(a.shape==="circle"){let D={shape:"circle",center:d,radius:a.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:l};m=e.pcb_cutout.insert(D)}else if(a.shape==="polygon"){let D=this._computePcbGlobalTransformBeforeLayout(),E={shape:"polygon",points:a.points.map(A=>as(D,A)),subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:l};m=e.pcb_cutout.insert(E)}m&&(this.pcb_cutout_id=m.pcb_cutout_id)}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="polygon"){if(e.points.length===0)return{width:0,height:0};let a=1/0,s=-1/0,l=1/0,d=-1/0;for(let x of e.points)a=Math.min(a,x.x),s=Math.max(s,x.x),l=Math.min(l,x.y),d=Math.max(d,x.y);return{width:s-a,height:d-l}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,a=e.pcb_cutout.get(this.pcb_cutout_id);if(!a)return super._getPcbCircuitJsonBounds();if(a.shape==="rect")return{center:a.center,bounds:{left:a.center.x-a.width/2,top:a.center.y+a.height/2,right:a.center.x+a.width/2,bottom:a.center.y-a.height/2},width:a.width,height:a.height};if(a.shape==="circle")return{center:a.center,bounds:{left:a.center.x-a.radius,top:a.center.y+a.radius,right:a.center.x+a.radius,bottom:a.center.y-a.radius},width:a.radius*2,height:a.radius*2};if(a.shape==="polygon"){if(a.points.length===0)return super._getPcbCircuitJsonBounds();let s=1/0,l=-1/0,d=1/0,x=-1/0;for(let f of a.points)s=Math.min(s,f.x),l=Math.max(l,f.x),d=Math.min(d,f.y),x=Math.max(x,f.y);return{center:{x:(s+l)/2,y:(d+x)/2},bounds:{left:s,top:x,right:l,bottom:d},width:l-s,height:x-d}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(e){if(!this.pcb_cutout_id)return;let{db:a}=this.root,s=a.pcb_cutout.get(this.pcb_cutout_id);if(s){if(s.shape==="rect"||s.shape==="circle")a.pcb_cutout.update(this.pcb_cutout_id,{...s,center:e});else if(s.shape==="polygon"){let l=this._getPcbCircuitJsonBounds().center,d=e.x-l.x,x=e.y-l.y,f=s.points.map(m=>({x:m.x+d,y:m.y+x}));a.pcb_cutout.update(this.pcb_cutout_id,{...s,points:f})}}}},PVt=({elm:r,pinLabels:e,layer:a,readableRotation:s,anchorAlignment:l})=>{let d=r.text.replace(/[{}]/g,"").toLowerCase(),x=d;if(Array.isArray(e)){let f=parseInt(d.replace(/[^\d]/g,""),10)-1;x=String(e[f]??d)}else typeof e=="object"&&(x=String(e[d]??d));return new JS({anchorAlignment:l||"center",text:x??d,layer:a||"top",fontSize:r.font_size+.2,pcbX:isNaN(r.anchor_position.x)?0:r.anchor_position.x,pcbY:r.anchor_position.y,pcbRotation:s??0})},IVt=(r,e)=>((-parseInt(r||"0",10)+(e??0))%360+360)%360,qS=({componentName:r,componentRotation:e,footprint:a,pinLabels:s,pcbPinLabels:l},d)=>{let x=[];for(let f of d)if(f.type==="pcb_smtpad"&&f.shape==="rect")x.push(new GS({pcbX:f.x,pcbY:f.y,layer:f.layer,shape:"rect",height:f.height,width:f.width,portHints:f.port_hints,rectBorderRadius:f.rect_border_radius}));else if(f.type==="pcb_smtpad"&&f.shape==="circle")x.push(new GS({pcbX:f.x,pcbY:f.y,layer:f.layer,shape:"circle",radius:f.radius,portHints:f.port_hints}));else if(f.type==="pcb_silkscreen_path")x.push(new cK({layer:f.layer,route:f.route,strokeWidth:f.stroke_width}));else if(f.type==="pcb_plated_hole")f.shape==="circle"?x.push(new Yg({pcbX:f.x,pcbY:f.y,shape:"circle",holeDiameter:f.hole_diameter,outerDiameter:f.outer_diameter,portHints:f.port_hints})):f.shape==="circular_hole_with_rect_pad"?x.push(new Yg({pcbX:f.x,pcbY:f.y,shape:"circular_hole_with_rect_pad",holeDiameter:f.hole_diameter,rectPadHeight:f.rect_pad_height,rectPadWidth:f.rect_pad_width,portHints:f.port_hints,rectBorderRadius:f.rect_border_radius,holeOffsetX:f.hole_offset_x,holeOffsetY:f.hole_offset_y})):f.shape==="pill"||f.shape==="oval"?x.push(new Yg({pcbX:f.x,pcbY:f.y,shape:f.shape,holeWidth:f.hole_width,holeHeight:f.hole_height,outerWidth:f.outer_width,outerHeight:f.outer_height,portHints:f.port_hints})):f.shape==="pill_hole_with_rect_pad"&&x.push(new Yg({pcbX:f.x,pcbY:f.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:f.hole_width,holeHeight:f.hole_height,rectPadWidth:f.rect_pad_width,rectPadHeight:f.rect_pad_height,portHints:f.port_hints,holeOffsetX:f.hole_offset_x,holeOffsetY:f.hole_offset_y}));else if(f.type==="pcb_keepout"&&f.shape==="circle")x.push(new XS({pcbX:f.center.x,pcbY:f.center.y,shape:"circle",radius:f.radius}));else if(f.type==="pcb_keepout"&&f.shape==="rect")x.push(new XS({pcbX:f.center.x,pcbY:f.center.y,shape:"rect",width:f.width,height:f.height}));else if(f.type==="pcb_hole"&&f.hole_shape==="circle")x.push(new dK({pcbX:f.x,pcbY:f.y,diameter:f.hole_diameter}));else if(f.type==="pcb_cutout")f.shape==="rect"?x.push(new XF({pcbX:f.center.x,pcbY:f.center.y,shape:"rect",width:f.width,height:f.height})):f.shape==="circle"?x.push(new XF({pcbX:f.center.x,pcbY:f.center.y,shape:"circle",radius:f.radius})):f.shape==="polygon"&&x.push(new XF({shape:"polygon",points:f.points}));else if(f.type==="pcb_silkscreen_text"){let m=IVt(e,f.ccw_rotation);a.includes("pinrow")&&f.text.includes("PIN")?x.push(PVt({elm:f,pinLabels:l??s,layer:f.layer,readableRotation:m,anchorAlignment:f.anchor_alignment})):x.push(new JS({anchorAlignment:f.anchor_alignment||"center",text:r,fontSize:f.font_size+.2,pcbX:Number.isNaN(f.anchor_position.x)?0:f.anchor_position.x,pcbY:f.anchor_position.y,pcbRotation:m??0}))}else f.type==="pcb_trace"&&x.push(new lK({route:f.route}));return x};function ZS(r){let e=1/0,a=1/0,s=-1/0,l=-1/0,d=!1;for(let m of r)if(m.isPcbPrimitive&&!m.componentName.startsWith("Silkscreen")){let{x:D,y:b}=m._getGlobalPcbPositionBeforeLayout(),{width:E,height:A}=m.getPcbSize();e=Math.min(e,D-E/2),a=Math.min(a,b-A/2),s=Math.max(s,D+E/2),l=Math.max(l,b+A/2),d=!0}else if(m.children.length>0){let D=ZS(m.children);(D.width>0||D.height>0)&&(e=Math.min(e,D.minX),a=Math.min(a,D.minY),s=Math.max(s,D.maxX),l=Math.max(l,D.maxY),d=!0)}if(!d)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let x=s-e,f=l-a;return x<0&&(x=0),f<0&&(f=0),{minX:e,minY:a,maxX:s,maxY:l,width:x,height:f}}function jVt(r,e){let a=e.x-r.x,s=e.y-r.y;return Math.abs(a)>Math.abs(s)?a>=0?"right":"left":s>=0?"up":"down"}var FBe=r=>{if(r.length<=1)return!0;let e=r.map(d=>{let x=d._getPcbCircuitJsonBounds();return{left:x.bounds.left,right:x.bounds.right,top:x.bounds.top,bottom:x.bounds.bottom}}),a=Array(e.length).fill(!1).map(()=>Array(e.length).fill(!1));for(let d=0;d<e.length;d++)for(let x=d+1;x<e.length;x++){let f=e[d],m=e[x];a[d][x]=a[x][d]=!(f.right<m.left||f.left>m.right||f.bottom>m.top||f.top<m.bottom)}let s=new Set,l=d=>{s.add(d);for(let x=0;x<e.length;x++)a[d][x]&&!s.has(x)&&l(x)};return l(0),s.size===e.length},EBe=r=>{if(r.length===0)throw new Error("Cannot get center of empty PCB primitives array");let e=r.map(l=>l._getPcbCircuitJsonBounds().center).filter(Boolean),a=e.reduce((l,d)=>l+d.x,0),s=e.reduce((l,d)=>l+d.y,0);return{x:a/e.length,y:s/e.length}},kVt=v.object({name:v.string().optional(),pinNumber:v.number().optional(),aliases:v.array(v.string()).optional(),layer:v.string().optional(),layers:v.array(v.string()).optional()}),Ni=class extends Qn{constructor(e,a={}){if(!e.name&&e.pinNumber!==void 0&&(e.name=`pin${e.pinNumber}`),!e.name)throw new Error("Port must have a name or a pinNumber");super(e);q(this,"source_port_id",null);q(this,"pcb_port_id",null);q(this,"schematic_port_id",null);q(this,"schematicSymbolPortDef",null);q(this,"matchedComponents");q(this,"facingDirection",null);q(this,"originDescription",null);a.originDescription&&(this.originDescription=a.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:kVt}}_getGlobalPcbPositionBeforeLayout(){let e=this.matchedComponents.find(s=>s.isPcbPrimitive),a=this.parent;if(a&&!a.props.footprint)throw new Error(`${a.componentName} "${a.props.name}" does not have a footprint. Add a footprint prop, e.g. <${a.componentName.toLowerCase()} footprint="..." />`);if(!e)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return e?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,a=e.pcb_port.get(this.pcb_port_id);return{center:{x:a.x,y:a.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let e=this.parent;if(!e||!e._getInternallyConnectedPins)return[];let a=e._getInternallyConnectedPins();for(let s of a)if(s.some(l=>l===this))return s;return[]}_hasSchematicPort(){if(this.parent?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(l=>l.schematicSymbolPortDef));let a=this?.parent?._getSchematicBoxDimensions();return!!(a&&this.props.pinNumber!==void 0&&a.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let e=this.parent?.getSchematicSymbol();if(e){let s=this.schematicSymbolPortDef;if(!s&&(s=this._getPortsInternallyConnectedToThisPort().find(d=>d.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 l=js(this.parent.computeSchematicGlobalTransform(),Ma(-e.center.x,-e.center.y));return as(l,s)}let a=this?.parent?._getSchematicBoxDimensions();if(a&&this.props.pinNumber!==void 0){let s=a.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 as(this.parent.computeSchematicGlobalTransform(),s)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:e}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let a=e.schematic_port.get(this.schematic_port_id);if(!a)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return a.center}registerMatch(e){this.matchedComponents.push(e)}getNameAndAliases(){let{_parsedProps:e}=this;return Array.from(new Set([...e.name?[e.name]:[],...e.aliases??[],...typeof e.pinNumber=="number"?[`pin${e.pinNumber}`,e.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let e=this.parent?._parsedProps?.pinAttributes;if(!e)return[];let a=[];for(let s of this.getNameAndAliases()){let l=e[s];l&&a.push(l)}return a}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(e=>e.includeInBoardPinout===!0)}isMatchingPort(e){return this.isMatchingAnyOf(e.getNameAndAliases())}getPortSelector(){return`.${this.parent?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:e,layers:a}=this._parsedProps;return a||(e?[e]:Array.from(new Set(this.matchedComponents.flatMap(s=>s.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(s=>!s._couldNotFindPort).filter(s=>s._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getNameAndAliases(),l=e.source_port.insert({name:a.name,pin_number:a.pinNumber,port_hints:s,source_component_id:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=l.source_port_id}doInitialSourceParentAttachment(){let{db:e}=this.root;if(!this.parent?.source_component_id)throw new Error(`${this.getString()} has no parent source component (parent: ${this.parent?.getString()})`);e.source_port.update(this.source_port_id,{source_component_id:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=this.parent?.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{matchedComponents:a}=this;if(!this.parent?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()})`);let s=a.filter(d=>d.isPcbPrimitive);if(s.length===0)return;let l=null;if(s.length===1&&(l=s[0]._getPcbCircuitJsonBounds().center),s.length>1){if(!FBe(s))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${s.map(d=>d.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)`);l=EBe(s)}if(l){let d=this.getSubcircuit(),x=this._shouldIncludeInBoardPinout(),f=e.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...x?{is_board_pinout:!0}:{},...l,source_port_id:this.source_port_id});this.pcb_port_id=f.pcb_port_id}else{let d=s[0];throw new Error(`${d.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;if(this.pcb_port_id)return;let a=this.matchedComponents.filter(f=>f.isPcbPrimitive);if(a.length===0)return;let s=null;if(a.length===1&&(s=a[0]._getPcbCircuitJsonBounds().center),a.length>1)try{FBe(a)&&(s=EBe(a))}catch{}if(!s)return;let l=this.getSubcircuit(),d=this._shouldIncludeInBoardPinout(),x=e.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...d?{is_board_pinout:!0}:{},...s,source_port_id:this.source_port_id});this.pcb_port_id=x.pcb_port_id}doInitialSchematicPortRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer();if(!s||!this._hasSchematicPort())return;let l=s._getGlobalSchematicPositionBeforeLayout(),d=this._getGlobalSchematicPositionBeforeLayout(),x=null,f=s._getSchematicBoxDimensions();f&&a.pinNumber!==void 0&&(x=f.getPortPositionByPinNumber(a.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&e.schematic_debug_object.insert({shape:"rect",center:d,size:{width:.1,height:.1},label:"obstacle"}),x?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[x.side]:this.facingDirection=jVt(l,d);let m=e.source_port.get(this.source_port_id),D=[];for(let w of m?.port_hints??[])w.match(/^(pin)?\d+$/)||w.match(/^(left|right)/)&&!m?.name.match(/^(left|right)/)||D.push(w);let b;this.parent?.props?.showPinAliases&&D.length>0?b=D.join("/"):D.length>0&&(b=D[0]);let A={type:"schematic_port",schematic_component_id:this.parent?.schematic_component_id,center:d,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:x?.side,pin_number:a.pinNumber,true_ccw_index:x?.trueIndex,display_pin_label:b,is_connected:!1};for(let w of this._getMatchingPinAttributes())w.requiresPower&&(A.has_input_arrow=!0),w.providesPower&&(A.has_output_arrow=!0);let B=e.schematic_port.insert(A);this.schematic_port_id=B.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(e){let{db:a}=this.root;this.pcb_port_id&&a.pcb_port.update(this.pcb_port_id,{x:e.x,y:e.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(e=>e.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},WBe=r=>{let e=r.find(a=>/^(pin)?\d+$/.test(a));return e?Number.parseInt(e.replace(/^pin/,"")):null};function qF(r,e){let a=WBe(r);if(!a)return null;let l=[...r.filter(d=>d.toString()!==a.toString()&&d!==`pin${a}`),...e?.additionalAliases?.[`pin${a}`]??[]];return new Ni({pinNumber:a,aliases:l})}var NVt=r=>{for(let e of["leftSide","rightSide","topSide","bottomSide"])if(e in r&&typeof r[e]=="number")throw new Error(`A number was specified for "${e}", you probably meant to use "size" not "side"`);return"leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r},MVt=r=>{if(NVt(r))return{leftSize:r.leftSide?.pins.length??0,rightSize:r.rightSide?.pins.length??0,topSize:r.topSide?.pins.length??0,bottomSize:r.bottomSide?.pins.length??0};let{leftSize:e=0,rightSize:a=0,topSize:s=0,bottomSize:l=0}=r;return{leftSize:e,rightSize:a,topSize:s,bottomSize:l}};function KBe(r){let e=r;return e.leftSide!==void 0||e.rightSide!==void 0||e.topSide!==void 0||e.bottomSide!==void 0}var OVt=r=>{let e=r.portDistanceFromEdge??.4,a=r.schPortArrangement?MVt(r.schPortArrangement):null,s={left:0,right:0,top:0,bottom:0},l=r.pinCount??null;if(l===null)if(a)l=a.leftSize+a.rightSize+a.topSize;else throw new Error("Could not determine pin count for the schematic box");if(l&&!a){let w=Math.floor(l/2);a={leftSize:l-w,rightSize:w,topSize:0,bottomSize:0}}a||(a={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let d=({side:w,sideIndex:P,truePinIndex:j})=>{if(!r.schPortArrangement||!KBe(r.schPortArrangement))return j+1;let O={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[w],z=r.schPortArrangement?.[`${w}Side`]?.direction??O,ee=r.schPortArrangement?.[`${w}Side`]?.pins,W=P;return z!==O&&(W=ee.length-P-1),YF(ee[W],r.pinLabels)},x=[],f=0,m=0;for(let w=0;w<a.leftSize;w++){let P=d({side:"left",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.topMargin&&(f+=j.topMargin),x.push({trueIndex:m,pinNumber:P,side:"left",distanceFromOrthogonalEdge:f}),j?.bottomMargin&&(f+=j.bottomMargin),w===a.leftSize-1?s.left=f:f+=r.schPinSpacing,m++}f=0;for(let w=0;w<a.bottomSize;w++){let P=d({side:"bottom",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.leftMargin&&(f+=j.leftMargin),x.push({trueIndex:m,pinNumber:P,side:"bottom",distanceFromOrthogonalEdge:f}),j?.rightMargin&&(f+=j.rightMargin),w===a.bottomSize-1?s.bottom=f:f+=r.schPinSpacing,m++}f=0;for(let w=0;w<a.rightSize;w++){let P=d({side:"right",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.bottomMargin&&(f+=j.bottomMargin),x.push({trueIndex:m,pinNumber:P,side:"right",distanceFromOrthogonalEdge:f}),j?.topMargin&&(f+=j.topMargin),w===a.rightSize-1?s.right=f:f+=r.schPinSpacing,m++}f=0;for(let w=0;w<a.topSize;w++){let P=d({side:"top",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.rightMargin&&(f+=j.rightMargin),x.push({trueIndex:m,pinNumber:P,side:"top",distanceFromOrthogonalEdge:f}),j?.leftMargin&&(f+=j.leftMargin),w===a.topSize-1?s.top=f:f+=r.schPinSpacing,m++}let D=r.schWidth;if(D===void 0){D=Math.max(s.top+r.schPinSpacing*2,s.bottom+r.schPinSpacing*2);let w=r.pinLabels?Math.max(...Object.values(r.pinLabels).map(j=>j.length*.1)):0,P=w>0?1.1:0;D=Math.max(D,w+P)}let b=r.schHeight;b||(b=Math.max(s.left+r.schPinSpacing*2,s.right+r.schPinSpacing*2));let E={left:{x:-D/2-e,y:s.left/2},bottom:{x:-s.bottom/2,y:-b/2-e},right:{x:D/2+e,y:-s.right/2},top:{x:s.top/2,y:b/2+e}},A={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},B=x.map(w=>{let{distanceFromOrthogonalEdge:P,side:j}=w,O=E[j],z=A[j];return{x:O.x+P*z.x,y:O.y+P*z.y,...w}});return{getPortPositionByPinNumber(w){let P=B.find(j=>j.pinNumber.toString()===w.toString());return P||null},getSize(){return{width:D,height:b}},getSizeIncludingPins(){return{width:D+(a.leftSize||a.rightSize?.4:0),height:b+(a.topSize||a.bottomSize?.4:0)}},pinCount:l}},LVt=(0,JBe.default)("tscircuit:core:footprint"),ZBe=class extends Qn{get config(){return{componentName:"Footprint",zodProps:CAe}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let r=this.children.filter(E=>E.componentName==="Constraint");if(r.length===0)return;let{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers(),a=E=>e&&"left"in E&&"right"in E?{...E,left:E.right,right:E.left}:E,s=r.flatMap(E=>E._getAllReferencedComponents().componentsWithSelectors).map(({component:E,selector:A,componentSelector:B,edge:w})=>({component:E,selector:A,componentSelector:B,edge:w,bounds:E._getPcbCircuitJsonBounds()}));if(s.some(E=>E.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function l(E){return s.find(({selector:A})=>A===E)}let d=new ug,x={};function f(E){return E in x||(x[E]=new rd(E),d.addEditVariable(x[E],Oa.weak)),x[E]}for(let{selector:E,bounds:A}of s){let B=f(`${E}_x`),w=f(`${E}_y`);d.suggestValue(B,A.center.x),d.suggestValue(w,A.center.y)}for(let E of r){let A=E._parsedProps;if("xDist"in A){let{xDist:B,left:w,right:P,edgeToEdge:j,centerToCenter:O}=a(A),z=f(`${w}_x`),ee=f(`${P}_x`),W=l(w)?.bounds,re=l(P)?.bounds;if(O){let L=new Xa(ee,[-1,z]);d.addConstraint(new Vs(L,Ds.Eq,A.xDist,Oa.required))}else if(j){let L=new Xa(ee,-re.width/2,[-1,z],-W.width/2);d.addConstraint(new Vs(L,Ds.Eq,A.xDist,Oa.required))}}else if("yDist"in A){let{yDist:B,top:w,bottom:P,edgeToEdge:j,centerToCenter:O}=A,z=f(`${w}_y`),ee=f(`${P}_y`),W=l(w)?.bounds,re=l(P)?.bounds;if(O){let L=new Xa(z,[-1,ee]);d.addConstraint(new Vs(L,Ds.Eq,A.yDist,Oa.required))}else if(j){let L=new Xa(z,W.height/2,[-1,ee],-re.height/2);d.addConstraint(new Vs(L,Ds.Eq,A.yDist,Oa.required))}}else if("sameY"in A){let{for:B}=A;if(B.length<2)continue;let w=B.map(j=>f(`${j}_y`)),P=new Xa(...w.slice(1));d.addConstraint(new Vs(P,Ds.Eq,w[0],Oa.required))}else if("sameX"in A){let{for:B}=A;if(B.length<2)continue;let w=B.map(j=>f(`${j}_x`)),P=new Xa(...w.slice(1));d.addConstraint(new Vs(P,Ds.Eq,w[0],Oa.required))}}d.updateVariables(),LVt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(x).map(([E,A])=>({var:E,val:A.value()}))));let m={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:E,bounds:{width:A,height:B}}of s){let w=f(`${E}_x`),P=f(`${E}_y`),j=w.value()-A/2,O=w.value()+A/2,z=P.value()+B/2,ee=P.value()-B/2;m.left=Math.min(m.left,j),m.right=Math.max(m.right,O),m.top=Math.max(m.top,z),m.bottom=Math.min(m.bottom,ee)}let D={x:-(m.right+m.left)/2,y:-(m.top+m.bottom)/2},b=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();D.x+=b.x,D.y+=b.y;for(let{component:E,selector:A}of s){let B=f(`${A}_x`),w=f(`${A}_y`);E._setPositionFromLayout({x:B.value()+D.x,y:w.value()+D.y})}}},XW=v.union([v.number(),v.string()]),vBe=v.object({x:XW,y:XW,z:XW}),QBe=class extends Qn{get config(){return{componentName:"CadModel",zodProps:GAe}}doInitialCadModelRender(){let r=this._findParentWithPcbComponent();if(!r||!r.pcb_component_id)return;let{db:e}=this.root,{boardThickness:a=0}=this.root?._getBoard()??{},s=r._getPcbCircuitJsonBounds(),l=e.pcb_component.get(r.pcb_component_id),d=this._parsedProps;if(!d||typeof d.modelUrl!="string")return;let x=vBe.parse({x:0,y:0,z:0});if(typeof d.rotationOffset=="number")x.z=Number(d.rotationOffset);else if(typeof d.rotationOffset=="object"){let A=vBe.parse(d.rotationOffset);x.x=Number(A.x),x.y=Number(A.y),x.z=Number(A.z)}let f=l5.parse({x:d.pcbX??0,y:d.pcbY??0,z:d.pcbZ??0,...typeof d.positionOffset=="object"?d.positionOffset:{}}),m=r.props.layer==="bottom"?"bottom":"top",D=new URL(d.modelUrl).pathname.split(".").pop()?.toLowerCase(),b={};D==="stl"?b.model_stl_url=this._addCachebustToModelUrl(d.modelUrl):D==="obj"?b.model_obj_url=this._addCachebustToModelUrl(d.modelUrl):D==="gltf"?b.model_gltf_url=this._addCachebustToModelUrl(d.modelUrl):D==="glb"?b.model_glb_url=this._addCachebustToModelUrl(d.modelUrl):D==="step"||D==="stp"?b.model_step_url=this._addCachebustToModelUrl(d.modelUrl):D==="wrl"||D==="vrml"?b.model_wrl_url=this._addCachebustToModelUrl(d.modelUrl):b.model_stl_url=this._addCachebustToModelUrl(d.modelUrl);let E=e.cad_component.insert({position:{x:s.center.x+Number(f.x),y:s.center.y+Number(f.y),z:(m==="bottom"?-a/2:a/2)+Number(f.z)},rotation:{x:Number(x.x),y:(m==="top"?0:180)+Number(x.y),z:m==="bottom"?-((l?.rotation??0)+Number(x.z))+180:(l?.rotation??0)+Number(x.z)},pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,model_unit_to_mm_scale_factor:typeof d.modelUnitToMmScale=="number"?d.modelUnitToMmScale:void 0,...b});this.cad_component_id=E.cad_component_id}_findParentWithPcbComponent(){let r=this.parent;for(;r&&!r.pcb_component_id;)r=r.parent;return r}_addCachebustToModelUrl(r){if(!r||!r.includes("modelcdn.tscircuit.com"))return r;let e=this.root?.getClientOrigin()??"";return`${r}${r.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(e)}`}},e9e=class extends Qn{constructor(){super(...arguments);q(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:VAe}}},$Vt=(r,e)=>{if(!r)return;let a={};for(let[s,l]of Object.entries(r)){let d=YF(s,e),x={leftMargin:l.marginLeft??l.leftMargin,rightMargin:l.marginRight??l.rightMargin,topMargin:l.marginTop??l.topMargin,bottomMargin:l.marginBottom??l.bottomMargin};a[`pin${d}`]={...a[`pin${d}`],...x}}return a},CBe=class{constructor({input:r}){q(this,"input");this.input=r}solveAndMapToTraces(){let r=[];for(let e of this.input.connections){if(e.pointsToConnect.length!==2)continue;let[a,s]=e.pointsToConnect,l={type:"pcb_trace",pcb_trace_id:"",connection_name:e.name,route:[{route_type:"wire",x:a.x,y:a.y,layer:"top",width:.1},{route_type:"wire",x:s.x,y:s.y,layer:"top",width:.1}]};r.push(l)}return r}},zVt=r=>{let e=Math.min(...r.map(d=>d.center.x)),a=Math.max(...r.map(d=>d.center.x)),s=Math.min(...r.map(d=>d.center.y)),l=Math.max(...r.map(d=>d.center.y));return{minX:e,maxX:a,minY:s,maxY:l}},_Be=["top","bottom","inner1","inner2"],US=(r,e=[])=>{let a=[];if(e.length===0){let f=r[0].layers;for(let m of f)a.push(...US(r.slice(1),[m]));return a}if(r.length===0)return[];let s=r[0],l=s.via||s.optional_via,d=e[e.length-1];if(r.length===1){let f=s;return f.layers&&l?f.layers.map(m=>({layer_path:[...e,m]})):f.layers?.includes(d)?[{layer_path:[...e,d]}]:[]}if(!l)return s.layers&&!s.layers.includes(d)?[]:US(r.slice(1),e.concat([d]));let x=(s.optional_via?_Be:_Be.filter(f=>f!==d)).filter(f=>!s.layers||s.layers?.includes(f));for(let f of x)a.push(...US(r.slice(1),e.concat(f)));return a};function ABe(r){let e={x:r.to.x-r.from.x,y:r.to.y-r.from.y},a=Math.abs(e.x),s=Math.abs(e.y);return a>s?e.x>0?"right":"left":e.y>0?"down":"up"}function qg(r,e){return Math.hypot(r.x-e.x,r.y-e.y)}var qVt=r=>{if(r.length===1)return r[0];if(r.some(m=>m.length===0))throw new Error("Cannot merge routes with zero length");let e=[],a=r[0][0],s=r[0][r[0].length-1],l=r[1][0],d=r[1][r[1].length-1],x=Math.min(qg(a,l),qg(a,d)),f=Math.min(qg(s,l),qg(s,d));x<f?e.push(...r[0].reverse()):e.push(...r[0]);for(let m=1;m<r.length;m++){let D=e[e.length-1],b=r[m],E=b[0],A=b[b.length-1],B=qg(D,E),w=qg(D,A);B<w?e.push(...b):e.push(...b.reverse())}for(let m=1;m<e.length-1;m++){let D=e[m-1],b=e[m];D.route_type==="wire"&&b.route_type==="wire"&&D.layer!==b.layer&&e.splice(m,0,{x:D.x,y:D.y,from_layer:D.layer,to_layer:b.layer,route_type:"via"})}return e},UVt=(r,e)=>{let a="_getGlobalPcbPositionBeforeLayout"in r?r._getGlobalPcbPositionBeforeLayout():r,s="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((a.x-s.x)**2+(a.y-s.y)**2)};function VVt(r,e){if(e.length===0)throw new Error("No candidates given to getClosest method");let a=e[0],s=1/0;for(let l of e){let d=UVt(r,l);d<s&&(a=l,s=d)}return a}var GVt=(r,e)=>{let a=0;a+=r.length??0,a+=e.filter(s=>s.is_crossing).length;for(let s=1;s<e.length;s++){let l=e[s-1],d=e[s],x=Math.abs(l.from.x-l.to.x)<.01,f=Math.abs(d.from.x-d.to.x)<.01;x!==f&&a++}return a},HF=r=>({up:"bottom",down:"top",left:"right",right:"left"})[r]??null,ZW=({firstEdge:r,firstEdgePort:e,firstDominantDirection:a,lastEdge:s,lastEdgePort:l,lastDominantDirection:d})=>{if(r&&e)return ZW({lastEdge:{from:r.to,to:r.from},lastEdgePort:e,lastDominantDirection:a}).reverse().map(f=>({from:f.to,to:f.from}));let x=[];if(s&&l){let f={x:s.to.x,y:s.to.y};d==="left"||d==="right"?(f.x=l.position.x,x.push({from:s.to,to:{...f}}),x.push({from:f,to:{...l.position}})):(f.y=l.position.y,x.push({from:s.to,to:{...f}}),x.push({from:f,to:{...l.position}}))}return x=x.filter(f=>wi(f.from,f.to)>.01),x};function XVt(r){try{return[r(),null]}catch(e){return[null,e]}}var YVt=(r,{db:e})=>{let a=r.map(s=>{let l=e.source_port.get(s.source_port_id);if(!l?.source_component_id)return null;let d=e.source_component.get(l.source_component_id);return d?.ftype==="simple_capacitor"?d.max_decoupling_trace_length:null}).filter(s=>s!==null);if(a.length!==0)return Math.min(...a)};function HVt({ports:r,nets:e}){if(r.length>=2)return`${r[0]?.selector} to ${r[1]?.selector}`;if(r.length===1&&e.length===1)return`${r[0]?.selector} to net.${e[0]._parsedProps.name}`}var WVt=(r,{db:e})=>{let a=e.pcb_board.list()[0];if(a.outline){let m=a.outline,D=(b,E)=>{let A=!1;for(let B=0,w=E.length-1;B<E.length;w=B++){let P=E[B].x,j=E[B].y,O=E[w].x,z=E[w].y;j>b.y!=z>b.y&&b.x<(O-P)*(b.y-j)/(z-j)+P&&(A=!A)}return A};return r.some(b=>!D(b,m))}let s=a.width,l=a.height,d=a.center.x,x=a.center.y;return r.some(m=>m.x<d-s/2||m.y<x-l/2||m.x>d+s/2||m.y>x+l/2)},RBe=(r,e)=>Math.abs(r-e)<1e-4,KVt=(r,e,{viaDiameter:a=.5}={})=>{let s=[];for(let l=0;l<r.length-1;l++){let[d,x]=[r[l],r[l+1]],f=l-1>=0?r[l-1]:null,m=RBe(d.y,x.y),D=RBe(d.x,x.x);if(!m&&!D)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${d.x}, ${d.y}), end: (${x.x}, ${x.y})`);let b={type:"rect",layers:[d.layer],center:{x:(d.x+x.x)/2,y:(d.y+x.y)/2},width:m?Math.abs(d.x-x.x):.1,height:D?Math.abs(d.y-x.y):.1,connectedTo:[e]};if(s.push(b),f&&f.layer===d.layer&&d.layer!==x.layer){let E={type:"rect",layers:[d.layer,x.layer],center:{x:d.x,y:d.y},connectedTo:[e],width:a,height:a};s.push(E)}}return s};function t9e(r,e=4){let{center:a,width:s,height:l,rotation:d}=r,x=[],f=d*Math.PI/180,m=Math.cos(f),D=Math.sin(f),b=(d%360+360)%360;if(l<=s?b>=45&&b<135||b>=225&&b<315:b>=135&&b<225||b>=315||b<45){let A=s/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*m,j=-w*D,O=A*1.1,z=Math.abs(l*m)+Math.abs(A*D);x.push({center:{x:a.x+P,y:a.y+j},width:O,height:z})}}else{let A=l/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*D,j=w*m,O=Math.abs(s*m)+Math.abs(A*D),z=A*1.1;x.push({center:{x:a.x+P,y:a.y+j},width:O,height:z})}}return x}function JVt(r,e={}){if(r.length<3)return[];let{rectHeight:a=.1}=e,s=[],l=r.map(f=>f.y),d=Math.min(...l),x=Math.max(...l);for(let f=d;f<x;f+=a){let m=f+a/2,D=[];for(let b=0;b<r.length;b++){let E=r[b],A=r[(b+1)%r.length];if(E.y<=m&&A.y>m||A.y<=m&&E.y>m){let B=(m-E.y)*(A.x-E.x)/(A.y-E.y)+E.x;D.push(B)}}D.sort((b,E)=>b-E);for(let b=0;b<D.length;b+=2)if(b+1<D.length){let E=D[b],B=D[b+1]-E;B>1e-6&&s.push({center:{x:E+B/2,y:m},width:B,height:a})}}return s}function ZVt(r,e={}){let{center:a,radius:s}=r,{rectHeight:l=.1}=e,d=[],x=Math.ceil(s*2/l);for(let f=0;f<x;f++){let m=a.y-s+(f+.5)*l,D=m-a.y,b=Math.sqrt(s*s-D*D);b>0&&d.push({center:{x:a.x,y:m},width:b*2,height:l})}return d}var nx=["top","inner1","inner2","bottom"],pK=(r,e)=>{let a=l=>e?l.concat(l.map(d=>e?.getNetConnectedToId(d)).filter(Boolean)):l,s=[];for(let l of r)if(l.type==="pcb_smtpad"){if(l.shape==="circle")s.push({type:"oval",layers:[l.layer],center:{x:l.x,y:l.y},width:l.radius*2,height:l.radius*2,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rect")s.push({type:"rect",layers:[l.layer],center:{x:l.x,y:l.y},width:l.width,height:l.height,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rotated_rect"){let d={center:{x:l.x,y:l.y},width:l.width,height:l.height,rotation:l.ccw_rotation},x=t9e(d);for(let f of x)s.push({type:"rect",layers:[l.layer],center:f.center,width:f.width,height:f.height,connectedTo:a([l.pcb_smtpad_id])})}}else if(l.type==="pcb_keepout")l.shape==="circle"?s.push({type:"oval",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.radius*2,height:l.radius*2,connectedTo:[]}):l.shape==="rect"&&s.push({type:"rect",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.type==="pcb_cutout"){if(l.shape==="rect")s.push({type:"rect",layers:nx,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.shape==="circle"){let d=ZVt({center:l.center,radius:l.radius},{rectHeight:.6});for(let x of d)s.push({type:"rect",layers:nx,center:x.center,width:x.width,height:x.height,connectedTo:[]})}else if(l.shape==="polygon"){let d=JVt(l.points,{rectHeight:.6});for(let x of d)s.push({type:"rect",layers:nx,center:x.center,width:x.width,height:x.height,connectedTo:[]})}}else if(l.type==="pcb_hole")l.hole_shape==="oval"?s.push({type:"oval",center:{x:l.x,y:l.y},width:l.hole_width,height:l.hole_height,connectedTo:[]}):l.hole_shape==="square"?s.push({type:"rect",layers:nx,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]}):(l.hole_shape==="round"||l.hole_shape==="circle")&&s.push({type:"rect",layers:nx,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]});else if(l.type==="pcb_plated_hole")l.shape==="circle"?s.push({type:"oval",layers:nx,center:{x:l.x,y:l.y},width:l.outer_diameter,height:l.outer_diameter,connectedTo:a([l.pcb_plated_hole_id])}):l.shape==="circular_hole_with_rect_pad"?s.push({type:"rect",layers:nx,center:{x:l.x,y:l.y},width:l.rect_pad_width,height:l.rect_pad_height,connectedTo:a([l.pcb_plated_hole_id])}):(l.shape==="oval"||l.shape==="pill")&&s.push({type:"oval",layers:nx,center:{x:l.x,y:l.y},width:l.outer_width,height:l.outer_height,connectedTo:a([l.pcb_plated_hole_id])});else if(l.type==="pcb_trace"){let d=KVt(l.route.map(x=>({x:x.x,y:x.y,layer:"layer"in x?x.layer:x.from_layer})),l.source_trace_id);s.push(...d)}else l.type==="pcb_via"&&s.push({type:"rect",layers:l.layers,center:{x:l.x,y:l.y},connectedTo:[],width:l.outer_diameter,height:l.outer_diameter});return s},ax=({anchor_position:r,anchor_side:e,text:a,font_size:s=.18})=>{let l=.1*(s/.18),d=a.length*l,x=s,f={...r};switch(e){case"right":f.x-=d/2;break;case"left":f.x+=d/2;break;case"top":f.y-=x/2;break;case"bottom":f.y+=x/2;break}return f},xK=({db:r,source_trace_id:e,sameNetOnly:a,differentNetOnly:s})=>{!a&&!s&&(s=!0);let l=r.source_trace.get(e),d=[];for(let x of r.schematic_trace.list()){if(x.source_trace_id===e)continue;let m=r.source_trace.get(x.source_trace_id)?.subcircuit_connectivity_map_key===l.subcircuit_connectivity_map_key;s&&m||a&&!m||d.push(x)}return d},QVt=({edges:r,otherEdges:e})=>{let a=[...r];for(let s=0;s<a.length;s++){if(s>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let l=a[s],d=Math.abs(l.from.x-l.to.x)<.01?"vertical":l.from.y===l.to.y?"horizontal":"not-orthogonal";if(d==="not-orthogonal")continue;let x=[];for(let P of e){let j=P.from.x===P.to.x?"vertical":P.from.y===P.to.y?"horizontal":"not-orthogonal";if(j==="not-orthogonal"||d===j)continue;if(zp([l.from,l.to],[P.from,P.to],{lineThickness:.01})){let z=d==="vertical"?l.from.x:P.from.x,ee=d==="vertical"?P.from.y:l.from.y,W={x:z,y:ee};x.push({otherEdge:P,crossingPoint:W,distanceFromEdgeFrom:wi(l.from,W)})}}if(x.length===0)continue;let f=x[0];for(let P of x)P.distanceFromEdgeFrom<f.distanceFromEdgeFrom&&(f=P);let m=f.crossingPoint,D=.075;if(m.x===l.from.x&&m.y===l.from.y)continue;let b=F5(l.from,m),E={x:m.x-b.x*D/2,y:m.y-b.y*D/2},A={x:m.x+b.x*D/2,y:m.y+b.y*D/2},B=wi(A,l.to)<D,w=[{from:l.from,to:E},{from:E,to:A,is_crossing:!0},{from:A,to:l.to}];a.splice(s,1,...w),s+=w.length-2,B&&s++}return a},QW=.001,Ug=(r,e)=>{let a=Math.min(e.from.x,e.to.x),s=Math.max(e.from.x,e.to.x),l=Math.min(e.from.y,e.to.y),d=Math.max(e.from.y,e.to.y);return r.x>=a&&r.x<=s&&r.y>=l&&r.y<=d},SBe=r=>{let e=Math.abs(r.from.x-r.to.x)<QW,a=Math.abs(r.from.y-r.to.y)<QW;return e?"vertical":a?"horizontal":"diagonal"},eGt=(r,e)=>{let a=SBe(r),s=SBe(e);if(a===s)return null;if(a==="vertical"&&s==="horizontal"||a==="horizontal"&&s==="vertical"){let E=a==="vertical"?r:e,A=a==="horizontal"?r:e,B=E.from.x,w=A.from.y,P={x:B,y:w};return Ug(P,r)&&Ug(P,e)?P:null}if(a==="vertical"||s==="vertical"){let E=a==="vertical"?r:e,A=a==="vertical"?e:r,B=E.from.x,w=(A.to.y-A.from.y)/(A.to.x-A.from.x),P=A.from.y-w*A.from.x,j=w*B+P,O={x:B,y:j};return Ug(O,r)&&Ug(O,e)?O:null}let l=(r.to.y-r.from.y)/(r.to.x-r.from.x),d=r.from.y-l*r.from.x,x=(e.to.y-e.from.y)/(e.to.x-e.from.x),f=e.from.y-x*e.from.x;if(Math.abs(l-x)<QW)return null;let m=(f-d)/(l-x),D=l*m+d,b={x:m,y:D};return Ug(b,r)&&Ug(b,e)?b:null},tGt=({edges:r,db:e,source_trace_id:a})=>{let s=xK({db:e,source_trace_id:a,sameNetOnly:!0}).flatMap(d=>d.edges),l=new Map;for(let d of r)for(let x of s){let f=eGt(d,x);if(f){let m=`${f.x.toFixed(6)},${f.y.toFixed(6)}`;l.has(m)||l.set(m,f)}}return Array.from(l.values())};function rGt(r){let e=1/0,a=1/0,s=-1/0,l=-1/0;for(let d of r){let x,f,m,D;d.type==="schematic_component"?(x=d.center?.x,f=d.center?.y,m=d.size?.width,D=d.size?.height):d.type==="schematic_box"?(x=d.x,f=d.y,m=d.width,D=d.height):d.type==="schematic_port"?(x=d.center?.x,f=d.center?.y,m=.2,D=.2):d.type==="schematic_text"&&(x=d.position?.x,f=d.position?.y,m=(d.text?.length??0)*.1,D=.2),typeof x=="number"&&typeof f=="number"&&typeof m=="number"&&typeof D=="number"&&(e=Math.min(e,x-m/2),s=Math.max(s,x+m/2),a=Math.min(a,f-D/2),l=Math.max(l,f+D/2))}return{minX:e,maxX:s,minY:a,maxY:l}}function nGt(r,e={}){let{minX:a,maxX:s,minY:l,maxY:d}=r,x=e.padding??1;if(!isFinite(a)||!isFinite(s)||!isFinite(l)||!isFinite(d))return[];let f=a-x,m=s+x,D=d+x,b=l-x,E=.01;return[{type:"rect",layers:["top"],center:{x:(f+m)/2,y:D},width:m-f,height:E,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(f+m)/2,y:b},width:m-f,height:E,connectedTo:[]},{type:"rect",layers:["top"],center:{x:f,y:(D+b)/2},width:E,height:D-b,connectedTo:[]},{type:"rect",layers:["top"],center:{x:m,y:(D+b)/2},width:E,height:D-b,connectedTo:[]}]}var aGt=r=>{let e=r.root.db,a=r._findConnectedPorts().ports??[],s=new Set(a.map(x=>x.schematic_port_id)),l=[];for(let x of e.toArray()){if(x.type==="schematic_component"){let f=!!x.symbol_name,m=x.size.width>x.size.height?"horz":"vert";l.push({type:"rect",layers:["top"],center:x.center,width:x.size.width+(f&&m==="horz"?-.5:0),height:x.size.height+(f&&m==="vert"?-.5:0),connectedTo:[]})}if(x.type==="schematic_port"){if(s.has(x.schematic_port_id))continue;let f=x.facing_direction?E5(x.facing_direction):{x:0,y:0};l.push({type:"rect",layers:["top"],center:{x:x.center.x-f.x*.1,y:x.center.y-f.y*.1},width:.1+Math.abs(f.x)*.3,height:.1+Math.abs(f.y)*.3,connectedTo:[]})}x.type==="schematic_text"&&l.push({type:"rect",layers:["top"],center:x.position,width:(x.text?.length??0)*.1,height:.2,connectedTo:[]}),x.type==="schematic_box"&&l.push({type:"rect",layers:["top"],center:{x:x.x,y:x.y},width:x.width,height:x.height,connectedTo:[]})}let d=rGt(e.toArray());return l.push(...nGt(d,{padding:1})),l},sGt=({edges:r,db:e,source_trace_id:a})=>{let s=e.source_trace.get(a),l=xK({db:e,source_trace_id:a,differentNetOnly:!0}).flatMap(x=>x.edges),d=x=>{let{from:f,to:m}=x;return f.x===m.x?"vertical":"horizontal"};for(let x of r){let f=d(x),m=()=>l.find(b=>d(b)===f&&zp([x.from,x.to],[b.from,b.to],{lineThickness:.05})),D=m();for(;D;)f==="horizontal"?(x.from.y+=.1,x.to.y+=.1):(x.from.x+=.1,x.to.x+=.1),D=m()}},eK=r=>{switch(r){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},iGt=D4e.version??"unknown",UF=class extends Error{constructor(r){super(`${r} (capacity-autorouter@${iGt})`),this.name="AutorouterError"}},YS=class extends Error{constructor(r){super(r.message),this.errorData=r,this.name="TraceConnectionError"}},oGt=r=>{if(r.root?._featureMspSchematicTraceRouting||r._couldNotFindPort||r.root?.schematicDisabled)return;let{db:e}=r.root,{_parsedProps:a,parent:s}=r;if(!s)throw new Error("Trace has no parent");let l,d;try{let Me=r._findConnectedPorts();l=Me.allPortsFound,d=Me.portsWithSelectors??[]}catch(Me){if(Me instanceof YS){e.source_trace_not_connected_error.insert({...Me.errorData,error_type:"source_trace_not_connected_error"});return}throw Me}let{netsWithSelectors:x}=r._findConnectedNets();if(!l)return;let m=d.map(Me=>Me.port.schematic_port_id).sort().join(","),D=r.root?._getBoard();if(D?._connectedSchematicPortPairs&&D._connectedSchematicPortPairs.has(m))return;let b={name:r.source_trace_id,pointsToConnect:[]},E=aGt(r),A=d.filter(({port:Me})=>Me.schematic_port_id!==null).map(({port:Me})=>({port:Me,position:Me._getGlobalSchematicPositionAfterLayout(),schematic_port_id:Me.schematic_port_id??void 0,facingDirection:Me.facingDirection}));if(A.length===1&&x.length===1){let Me=x[0].net,{port:Ge,position:et}=A[0],dt=r.getSubcircuit().selectAll("netlabel").find(ut=>{let it=ut._parsedProps.connection??ut._parsedProps.connectsTo;return it?Array.isArray(it)?it.some(It=>r.getSubcircuit().selectOne(It,{port:!0})===Ge):r.getSubcircuit().selectOne(it,{port:!0})===Ge:!1});if(!dt){let ut=e.schematic_net_label.getWhere({source_trace_id:r.source_trace_id});ut&&(dt=ut)}if(dt){let ut="_getGlobalSchematicPositionBeforeLayout"in dt?dt._getGlobalSchematicPositionBeforeLayout():dt.anchor_position,it=[];et.x===ut.x||et.y===ut.y?it.push({from:et,to:ut}):(it.push({from:et,to:{x:ut.x,y:et.y}}),it.push({from:{x:ut.x,y:et.y},to:ut}));let Ut=e.schematic_trace.insert({source_trace_id:r.source_trace_id,edges:it,junctions:[],subcircuit_connectivity_map_key:r.subcircuit_connectivity_map_key??void 0});r.schematic_trace_id=Ut.schematic_trace_id;return}if(r.props.schDisplayLabel){let ut=HF(Ge.facingDirection)??"bottom";e.schematic_net_label.insert({text:r.props.schDisplayLabel,source_net_id:Me.source_net_id,anchor_position:et,center:ax({anchor_position:et,anchor_side:ut,text:r.props.schDisplayLabel}),anchor_side:ut});return}let $t=HF(Ge.facingDirection)??"bottom",bt=e.schematic_net_label.insert({text:Me._parsedProps.name,source_net_id:Me.source_net_id,anchor_position:et,center:ax({anchor_position:et,anchor_side:$t,text:Me._parsedProps.name}),anchor_side:$t});return}if(r.props.schDisplayLabel&&("from"in r.props&&"to"in r.props||"path"in r.props)){r._doInitialSchematicTraceRenderWithDisplayLabel();return}if(A.length<2)return;let P=(()=>{let Me=[];for(let et=0;et<A.length-1;et++){let dt=A[et],$t=A[et+1],bt=dg({x:dt.position.x,y:dt.position.y,facingDirection:eK(dt.facingDirection)},{x:$t.position.x,y:$t.position.y,facingDirection:eK($t.facingDirection)});for(let ut=0;ut<bt.length-1;ut++)Me.push({from:bt[ut],to:bt[ut+1]})}let Ge=(et,dt)=>{let $t=dt.width/2,bt=dt.height/2,ut=dt.center.x-$t,it=dt.center.x+$t,Ut=dt.center.y-bt,It=dt.center.y+bt,tr=vt=>vt.x>=ut&&vt.x<=it&&vt.y>=Ut&&vt.y<=It;return tr(et.from)||tr(et.to)?!0:[[{x:ut,y:Ut},{x:it,y:Ut}],[{x:it,y:Ut},{x:it,y:It}],[{x:it,y:It},{x:ut,y:It}],[{x:ut,y:It},{x:ut,y:Ut}]].some(vt=>zp([et.from,et.to],vt,{lineThickness:0}))};for(let et of Me)for(let dt of E)if(Ge(et,dt))return null;return Me})();P&&P.length===0&&(P=null),b.pointsToConnect=A.map(({position:Me})=>({...Me,layer:"top"}));let j=zVt(E),O=2,z={minTraceWidth:.1,obstacles:E,connections:[b],bounds:{minX:j.minX-O,maxX:j.maxX+O,minY:j.minY-O,maxY:j.maxY+O},layerCount:1},ee=o5,W=!1;if(r.getSubcircuit().props._schDirectLineRoutingEnabled&&(ee=CBe,W=!0),!P){let Ge=new ee({input:z,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(Ge.length===0){if(r._isSymbolToChipConnection()||r._isSymbolToSymbolConnection()||r._isChipToChipConnection()){r._doInitialSchematicTraceRenderWithDisplayLabel();return}Ge=new CBe({input:z}).solveAndMapToTraces(),W=!0}let[{route:et}]=Ge;P=[];for(let dt=0;dt<et.length-1;dt++)P.push({from:et[dt],to:et[dt+1]})}let re=r.source_trace_id,L=[];if(!W){sGt({edges:P,db:e,source_trace_id:re});let Me=xK({db:e,source_trace_id:re,differentNetOnly:!0}).flatMap(Ge=>Ge.edges);P=QVt({edges:P,otherEdges:Me}),L=tGt({edges:P,db:e,source_trace_id:r.source_trace_id})}if(!P||P.length===0)return;let K=P[P.length-1],U=A[A.length-1],J=ABe(K);P.push(...ZW({lastEdge:K,lastEdgePort:U,lastDominantDirection:J}));let Q=P[0],de=A[0],oe=ABe(Q);if(P.unshift(...ZW({firstEdge:Q,firstEdgePort:de,firstDominantDirection:oe})),!r.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(r.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&GVt(L,P)>=5&&(r._isSymbolToChipConnection()||r._isSymbolToSymbolConnection()||r._isChipToChipConnection())){r._doInitialSchematicTraceRenderWithDisplayLabel();return}let Te=e.schematic_trace.insert({source_trace_id:r.source_trace_id,edges:P,junctions:L,subcircuit_connectivity_map_key:r.subcircuit_connectivity_map_key??void 0});r.schematic_trace_id=Te.schematic_trace_id;for(let{port:Me}of d)Me.schematic_port_id&&e.schematic_port.update(Me.schematic_port_id,{is_connected:!0});D?._connectedSchematicPortPairs&&D._connectedSchematicPortPairs.add(m)};function r9e(r){let e=0;for(let a=0;a<r.length;a++){let s=r[a];if(s.route_type==="wire"){let l=r[a+1];if(l){let d=l.x-s.x,x=l.y-s.y;e+=Math.sqrt(d*d+x*x)}}else s.route_type==="via"&&(e+=1.6)}return e}var LS=r=>({...r._getGlobalPcbPositionAfterLayout(),layers:r.getAvailablePcbLayers()}),uGt=!1;function cGt(r){if(r.root?.pcbDisabled)return;let{db:e}=r.root,{_parsedProps:a,parent:s}=r,l=r.getSubcircuit();if(!s)throw new Error("Trace has no parent");if(l._parsedProps.routingDisabled)return;let d=l._parsedProps.pcbRouteCache?.pcbTraces;if(d){let J=e.pcb_trace.insert({route:d.flatMap(Q=>Q.route),source_trace_id:r.source_trace_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0});r.pcb_trace_id=J.pcb_trace_id;return}if(a.pcbPath&&a.pcbPath.length>0||!l._shouldUseTraceByTraceRouting())return;let{allPortsFound:x,ports:f}=r._findConnectedPorts(),m=[];if(!x)return;let D=[];for(let J of f)J._hasMatchedPcbPrimitive()||D.push(J);if(D.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:r.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, ${r} wasn't routed. Missing ports: ${D.map(J=>J.getString()).join(", ")}`,pcb_trace_id:r.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:D.map(J=>J.pcb_port_id).filter(Boolean)});return}let b=r._findConnectedNets().netsWithSelectors;if(f.length===0&&b.length===2){r.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(f.length===1&&b.length===1){let J=f[0],de=b[0].net.getAllConnectedPorts().filter(Te=>Te!==J);if(de.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let oe=VVt(J,de);m.push(oe),f.push(oe)}else if(f.length>1&&b.length>=1){r.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 E=f.flatMap(J=>J.matchedComponents.filter(Q=>Q.componentName==="TraceHint")),A=(r._parsedProps.pcbRouteHints??[]).concat(E.flatMap(J=>J.getPcbRouteHints()));if(f.length>2){r.renderError(`Trace has more than two ports (${f.map(J=>J.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(r.getSubcircuit().selectAll("trace").filter(J=>J.renderPhaseStates.PcbTraceRender.initialized).some(J=>J._portsRoutedOnPcb.length===f.length&&J._portsRoutedOnPcb.every(Q=>f.includes(Q))))return;let P=[];A.length===0?P=[LS(f[0]),LS(f[1])]:P=[LS(f[0]),...A,LS(f[1])];let j=US(P);if(uGt&&j.length===0){r.renderError(`Could not find a common layer (using hints) for trace ${r.getString()}`);return}let O=eu(r.root.db.toArray()),[z,ee]=XVt(()=>pK(r.root.db.toArray()));if(ee){r.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:r.pcb_trace_id,message:`Error getting obstacles for autorouting: ${ee.message}`,source_trace_id:r.source_trace_id,center:{x:0,y:0},pcb_port_ids:f.map(J=>J.pcb_port_id),pcb_trace_id:r.pcb_trace_id,pcb_component_ids:[]});return}for(let J of z)if(J.connectedTo.length>0){let de=O.getNetConnectedToId(J.connectedTo[0]);de&&J.connectedTo.push(de)}let W=[];if(j.length===0)W=P;else{let J=j[0].layer_path;W=P.map((Q,de)=>Q.via?{...Q,via_to_layer:J[de]}:{...Q,layers:[J[de]]})}W[0].pcb_port_id=f[0].pcb_port_id,W[W.length-1].pcb_port_id=f[1].pcb_port_id;let re=[];for(let[J,Q]of HBe(W)){let de="via_to_layer"in J?J.via_to_layer:null,oe=2,Te="layers"in J&&J.layers.length===1?J.layers[0]:de??"top",Me="layers"in Q&&Q.layers.length===1?Q.layers[0]:de??"top",Ge="pcb_port_id"in J?J.pcb_port_id:null,et="pcb_port_id"in Q?Q.pcb_port_id:null,dt=r.getSubcircuit()._parsedProps.minTraceWidth??.16,$t=new o5({OBSTACLE_MARGIN:dt*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(Ge&&et),connMap:O,input:{obstacles:z,minTraceWidth:dt,connections:[{name:r.source_trace_id,pointsToConnect:[{...J,layer:Te,pcb_port_id:Ge},{...Q,layer:Me,pcb_port_id:et}]}],layerCount:r.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(J.x,Q.x)-oe,maxX:Math.max(J.x,Q.x)+oe,minY:Math.min(J.y,Q.y)-oe,maxY:Math.max(J.y,Q.y)+oe}}}),bt=null;try{bt=$t.solveAndMapToTraces()}catch(Ut){r.renderError({type:"pcb_trace_error",pcb_trace_error_id:r.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${Ut.message}`,source_trace_id:r.pcb_trace_id,center:{x:(J.x+Q.x)/2,y:(J.y+Q.y)/2},pcb_port_ids:f.map(It=>It.pcb_port_id),pcb_trace_id:r.pcb_trace_id,pcb_component_ids:f.map(It=>It.pcb_component_id)})}if(!bt)return;if(bt.length===0){r.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:r.pcb_trace_id,message:`Could not find a route for ${r}`,source_trace_id:r.source_trace_id,center:{x:(J.x+Q.x)/2,y:(J.y+Q.y)/2},pcb_port_ids:f.map(Ut=>Ut.pcb_port_id),pcb_trace_id:r.pcb_trace_id,pcb_component_ids:f.map(Ut=>Ut.pcb_component_id)});return}let[ut]=bt;de&&(ut.route=ut.route.map(Ut=>(Ut.route_type==="wire"&&!Ut.layer&&(Ut.layer=de),Ut))),Ge&&ut.route[0].route_type==="wire"&&(ut.route[0].start_pcb_port_id=Ge);let it=ut.route[ut.route.length-1];et&&it.route_type==="wire"&&(it.end_pcb_port_id=et),re.push(ut.route)}let L=qVt(re),K=r9e(L),U=e.pcb_trace.insert({route:L,source_trace_id:r.source_trace_id,subcircuit_id:r.getSubcircuit()?.subcircuit_id,trace_length:K});r._portsRoutedOnPcb=f,r.pcb_trace_id=U.pcb_trace_id;for(let J of L)J.route_type==="via"&&e.pcb_via.insert({pcb_trace_id:U.pcb_trace_id,x:J.x,y:J.y,hole_diameter:.3,outer_diameter:.6,layers:[J.from_layer,J.to_layer],from_layer:J.from_layer,to_layer:J.to_layer});r._insertErrorIfTraceIsOutsideBoard(L,f)}function lGt(r){if(r.root?.pcbDisabled)return;let{db:e}=r.root,{_parsedProps:a}=r,s=r.getSubcircuit();if(!a.pcbPath||a.pcbPath.length===0)return;let{allPortsFound:l,ports:d,portsWithSelectors:x}=r._findConnectedPorts();if(!l)return;let f=[];for(let z of d)z._hasMatchedPcbPrimitive()||f.push(z);if(f.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:r.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, ${r} wasn't routed. Missing ports: ${f.map(z=>z.getString()).join(", ")}`,pcb_trace_id:r.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:f.map(z=>z.pcb_port_id).filter(Boolean)});return}let m;a.pcbPathRelativeTo&&(m=x.find(z=>z.selector===a.pcbPathRelativeTo)?.port,m||(m=r.getSubcircuit().selectOne(a.pcbPathRelativeTo))),m||(m=d[0]);let D=d.find(z=>z!==m)??d[1],b=m.getAvailablePcbLayers()[0]||"top",E=a.thickness??r.getSubcircuit()._parsedProps.minTraceWidth??.16,A=m._getGlobalPcbPositionAfterLayout(),B=D._getGlobalPcbPositionAfterLayout(),w=[];w.push({route_type:"wire",x:A.x,y:A.y,width:E,layer:b,start_pcb_port_id:m.pcb_port_id});let P=m?._computePcbGlobalTransformBeforeLayout?.()||Si();for(let z of a.pcbPath){let ee=as(P,{x:z.x,y:z.y});w.push({route_type:"wire",x:ee.x,y:ee.y,width:E,layer:b})}w.push({route_type:"wire",x:B.x,y:B.y,width:E,layer:b,end_pcb_port_id:D.pcb_port_id});let j=r9e(w),O=e.pcb_trace.insert({route:w,source_trace_id:r.source_trace_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0,trace_length:j});r._portsRoutedOnPcb=d,r.pcb_trace_id=O.pcb_trace_id,r._insertErrorIfTraceIsOutsideBoard(w,d)}function dGt(r){if(r.root?.schematicDisabled)return;let{db:e}=r.root,{_parsedProps:a,parent:s}=r;if(!s)throw new Error("Trace has no parent");let{allPortsFound:l,portsWithSelectors:d}=r._findConnectedPorts();if(!l)return;let x=d.map(({port:W})=>({port:W,position:W._getGlobalSchematicPositionAfterLayout(),schematic_port_id:W.schematic_port_id,facingDirection:W.facingDirection}));if(x.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let f,m,D=x[0].position,b=x[0].port;if("path"in r.props){if(r.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[f,m]=r.props.path}else{if(!("from"in r.props&&"to"in r.props))throw new Error("Missing 'from' or 'to' properties in props.");f=r.props.from,m=r.props.to}if(!b.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${f}).`);let E=x[1].position,A=x[1].port;if(!A.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${m}).`);let B=e.schematic_net_label.list().find(W=>W.source_net_id===b.source_port_id),w=e.schematic_net_label.list().find(W=>W.source_net_id===A.source_port_id),[P,j]=d.map(({port:W})=>W),z=P.parent?.config.shouldRenderAsSchematicBox?`${P?.parent?.props.name}_${P?.props.name}`:`${j?.parent?.props.name}_${j?.props.name}`,ee=r.props.schDisplayLabel??z;if(B&&B.text!==ee&&(B.text=`${ee} / ${B.text}`),w&&w?.text!==ee&&(w.text=`${ee} / ${w.text}`),!w){let W=HF(A.facingDirection)??"bottom";e.schematic_net_label.insert({text:r.props.schDisplayLabel??z,source_net_id:A.source_port_id,anchor_position:E,center:ax({anchor_position:E,anchor_side:W,text:r.props.schDisplayLabel??z}),anchor_side:W})}if(!B){let W=HF(b.facingDirection)??"bottom";e.schematic_net_label.insert({text:r.props.schDisplayLabel??z,source_net_id:b.source_port_id,anchor_position:D,center:ax({anchor_position:D,anchor_side:W,text:r.props.schDisplayLabel??z}),anchor_side:W})}}function pGt(r){let{_parsedProps:e,parent:a}=r;if(!a)throw new Error("Trace has no parent");let l=r.getTracePortPathSelectors().map(d=>({selector:d,port:r.getSubcircuit().selectOne(d,{type:"port"})??null}));for(let{selector:d,port:x}of l)if(!x){let f,m,D=d.lastIndexOf(".");if(D!==-1&&D>d.lastIndexOf(" "))f=d.slice(0,D),m=d.slice(D+1);else{let W=d.match(/^(.*[ >])?([^ >]+)$/);f=W?.[1]?.trim()??"",m=W?.[2]??d}let b=f?r.getSubcircuit().selectOne(f):null;if(!b&&f&&!/[.#\[]/.test(f)&&(b=r.getSubcircuit().selectOne(`.${f}`)),!b){let W=f?`Could not find port for selector "${d}". Component "${f}" not found`:`Could not find port for selector "${d}"`,re=r.getSubcircuit(),L=re.getGroup();throw new YS({error_type:"source_trace_not_connected_error",message:W,subcircuit_id:re.subcircuit_id??void 0,source_group_id:L?.source_group_id??void 0,source_trace_id:r.source_trace_id??void 0,selectors_not_found:[d]})}let E=b.children.filter(W=>W.componentName==="Port"),A=m.includes(".")?m.split(".").pop()??"":m,B=E.flatMap(W=>W.getNameAndAliases()),w=B.some(W=>!/^(pin\d+|\d+)$/.test(W)),P=Array.from(new Set(B)).join(", "),j;E.length===0?j="It has no ports":w?j=`It has [${P}]`:j=`It has ${E.length} pins and no pinLabels (consider adding pinLabels)`;let O=`Could not find port for selector "${d}". Component "${b.props.name??f}" found, but does not have pin "${A}". ${j}`,z=r.getSubcircuit(),ee=z.getGroup();throw new YS({error_type:"source_trace_not_connected_error",message:O,subcircuit_id:z.subcircuit_id??void 0,source_group_id:ee?.source_group_id??void 0,source_trace_id:r.source_trace_id??void 0,selectors_not_found:[d]})}return l.some(d=>!d.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:l,ports:l.map(({port:d})=>d)}}var qc=class extends Qn{constructor(e){super(e);q(this,"source_trace_id",null);q(this,"pcb_trace_id",null);q(this,"schematic_trace_id",null);q(this,"_portsRoutedOnPcb");q(this,"subcircuit_connectivity_map_key",null);q(this,"_traceConnectionHash",null);q(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}get config(){return{zodProps:vAe,componentName:"Trace"}}_getTracePortOrNetSelectorListFromProps(){return"from"in this.props&&"to"in this.props?[typeof this.props.from=="string"?this.props.from:this.props.from.getPortSelector(),typeof this.props.to=="string"?this.props.to:this.props.to.getPortSelector()]:"path"in this.props?this.props.path.map(e=>typeof e=="string"?e:e.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>!e.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>e.includes("net."))}_findConnectedPorts(){return pGt(this)}_resolveNet(e){let a=this.getSubcircuit().selectOne(e,{type:"net"});if(a)return a;let s=e.match(/^net\.(.+)$/),l=s?s[1]:null;return l&&this.root._getBoard().getDescendants().find(x=>x.componentName==="Net"&&x._parsedProps.name===l)||null}_findConnectedNets(){let e=this.getTracePathNetSelectors().map(s=>({selector:s,net:this._resolveNet(s)})),a=e.filter(s=>!s.net);return a.length>0&&this.renderError(`Could not find net for selector "${a[0].selector}" inside ${this}`),{netsWithSelectors:e,nets:e.map(s=>s.net)}}_getAllTracesConnectedToSameNet(){let e=this.getSubcircuit().selectAll("trace"),a=this._findConnectedNets().nets,s=this._findConnectedPorts().ports??[];return e.filter(l=>{if(l===this)return!1;let d=l._findConnectedNets().nets,x=l._findConnectedPorts().ports??[];return d.some(f=>a.includes(f))||x.some(f=>s.includes(f))})}_isExplicitlyConnectedToPort(e){let{allPortsFound:a,portsWithSelectors:s}=this._findConnectedPorts();return a?s.map(d=>d.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){uK(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();return!e||!a?null:[...a].sort((d,x)=>(d.pcb_port_id||"").localeCompare(x.pcb_port_id||"")).map(d=>d.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:e}=this.root,{_parsedProps:a,parent:s}=this;if(!s){this.renderError("Trace has no parent");return}let l,d;try{let E=this._findConnectedPorts();l=E.allPortsFound,d=E.portsWithSelectors??[]}catch(E){if(E instanceof YS){e.source_trace_not_connected_error.insert({...E.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw E}if(!l)return;this._traceConnectionHash=this._computeTraceConnectionHash();let f=e.source_trace.list().find(E=>E.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&E.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(f){this.source_trace_id=f.source_trace_id;return}let m=this._findConnectedNets().nets,D=HVt({ports:d,nets:m}),b=e.source_trace.insert({connected_source_port_ids:d.map(E=>E.port.source_port_id),connected_source_net_ids:m.map(E=>E.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:YVt(d.map(E=>E.port),{db:e})??a.maxLength,display_name:D,min_trace_thickness:a.thickness});this.source_trace_id=b.source_trace_id}_insertErrorIfTraceIsOutsideBoard(e,a){let{db:s}=this.root;WVt(e,{db:s})&&s.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:a.map(d=>d.pcb_port_id)})}doInitialPcbManualTraceRender(){lGt(this)}doInitialPcbTraceRender(){cGt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){dGt(this)}_isSymbolToChipConnection(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();if(!e||a.length!==2)return!1;let[s,l]=a;if(!s?.parent||!l?.parent)return!1;let d=s.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return d&&!x||!d&&x}_isSymbolToSymbolConnection(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();if(!e||a.length!==2)return!1;let[s,l]=a;if(!s?.parent||!l?.parent)return!1;let d=!s.parent.config.shouldRenderAsSchematicBox,x=!l.parent.config.shouldRenderAsSchematicBox;return d&&x}_isChipToChipConnection(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();if(!e||a.length!==2)return!1;let[s,l]=a;if(!s?.parent||!l?.parent)return!1;let d=s.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return d&&x}doInitialSchematicTraceRender(){oGt(this)}},xGt=r=>{let{db:e}=r.root;if(r.pcb_component_id){let a=e.pcb_component.get(r.pcb_component_id);return a?{width:a.width,height:a.height}:null}if(r.pcb_group_id){let a=e.pcb_group.get(r.pcb_group_id);return a?{width:a.width,height:a.height}:null}return null},fGt=(r,e)=>{let{db:a}=r.root,s=a.toArray();if(r.pcb_component_id){C5(s,r.pcb_component_id,e);return}if(r.source_group_id){_5(s,r.source_group_id,e);return}throw new Error(`Cannot reposition component ${r.getString()}: no pcb_component_id or source_group_id`)},hGt=r=>{let{db:e}=r.root;if(!r.source_component_id)return;let a=r.selectAll("port"),s=e.source_trace.list(),l=new Set;for(let x of s)for(let f of x.connected_source_port_ids)l.add(f);let d=r._getInternallyConnectedPins();for(let x of d)if(x.some(f=>f.source_port_id&&l.has(f.source_port_id)))for(let f of x)f.source_port_id&&l.add(f.source_port_id);for(let x of a)x.source_port_id&&mGt(r,x)&&(l.has(x.source_port_id)||e.source_pin_missing_trace_warning.insert({message:`Port ${x.getNameAndAliases()[0]} on ${r.props.name} is missing a trace`,source_component_id:r.source_component_id,source_port_id:x.source_port_id,subcircuit_id:r.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},mGt=(r,e)=>{if(r.config.componentName==="Chip"){let a=r.props.pinAttributes;if(!a)return!1;for(let s of e.getNameAndAliases()){let l=a[s];if(l?.requiresPower||l?.requiresGround||l?.requiresVoltage!==void 0)return!0}return!1}return!0};function gGt(r){let e=r.font_size,a=r.text.length*e*.6,s=e,l=r.anchor_alignment||"center",d=r.anchor_position.x,x=r.anchor_position.y;switch(l){case"top_left":d=r.anchor_position.x+a/2,x=r.anchor_position.y+s/2;break;case"top_center":d=r.anchor_position.x,x=r.anchor_position.y+s/2;break;case"top_right":d=r.anchor_position.x-a/2,x=r.anchor_position.y+s/2;break;case"center_left":d=r.anchor_position.x+a/2,x=r.anchor_position.y;break;case"center":d=r.anchor_position.x,x=r.anchor_position.y;break;case"center_right":d=r.anchor_position.x-a/2,x=r.anchor_position.y;break;case"bottom_left":d=r.anchor_position.x+a/2,x=r.anchor_position.y-s/2;break;case"bottom_center":d=r.anchor_position.x,x=r.anchor_position.y-s/2;break;case"bottom_right":d=r.anchor_position.x-a/2,x=r.anchor_position.y-s/2;break;default:d=r.anchor_position.x,x=r.anchor_position.y;break}return{x:d-a/2,y:x-s/2,width:a,height:s}}function DGt(r){if(!r._adjustSilkscreenTextAutomatically||r.root?.pcbDisabled||!r.pcb_component_id)return;let{db:e}=r.root,s=r._getPcbCircuitJsonBounds().center,l=e.pcb_silkscreen_text.list({pcb_component_id:r.pcb_component_id}).filter(m=>m.text===r.name);if(l.length===0)return;let f=r.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(m=>m!==r&&m.pcb_component_id).map(m=>{let D=m._getPcbCircuitJsonBounds(),b={center:D.center,width:D.width,height:D.height};return td(b)});for(let m of l){let D=m.anchor_position,b=gGt(m),E={center:{x:b.x+b.width/2,y:b.y+b.height/2},width:b.width,height:b.height},A=td(E);if(!f.some(ee=>Yb(A,ee)))continue;let w=2*s.x-D.x,P=2*s.y-D.y,j={center:{x:w,y:P},width:b.width,height:b.height},O=td(j);f.some(ee=>Yb(O,ee))||e.pcb_silkscreen_text.update(m.pcb_silkscreen_text_id,{anchor_position:{x:w,y:P}})}}function yGt(r){if(!r)return{validPinLabels:r,invalidPinLabelsMessages:[]};let e={},a=[];for(let[s,l]of Object.entries(r)){let d=Array.isArray(l)?l.slice():[l],x=[];for(let f of d)bGt(s,f)?x.push(f):a.push(`Invalid pin label: ${s} = '${f}' - excluding from component. Please use a valid pin label.`);x.length>0&&(e[s]=Array.isArray(l)?x:x[0])}return{validPinLabels:Object.keys(e).length>0?e:void 0,invalidPinLabelsMessages:a}}function bGt(r,e){try{let a={name:"test",footprint:"test",pinLabels:{[r]:e}};return og.safeParse(a).success}catch{return!1}}var HS=r=>r.startsWith("http://")||r.startsWith("https://"),rK=r=>{if(HS(r))return null;let e=r.indexOf(":");if(e<=0)return null;let a=r.slice(0,e),s=r.slice(e+1);return!a||!s?null:{footprintLib:a,footprintName:s}};function FGt(r,e){let{footprint:a}=r.props;if(a??(a=r._getImpliedFootprintString?.()),!a)return;let{pcbRotation:s,pinLabels:l,pcbPinLabels:d}=r.props;if(typeof a=="string"&&HS(a)){if(r._hasStartedFootprintUrlLoad)return;r._hasStartedFootprintUrlLoad=!0;let x=a;e("load-footprint-url",async()=>{try{let f=await fetch(x);if(!f.ok)throw new Error(`Failed to fetch footprint: ${f.status}`);let m=await f.json(),D=qS({componentName:r.name,componentRotation:s,footprint:x,pinLabels:l,pcbPinLabels:d},m);r.addAll(D),r._markDirty("InitializePortsFromChildren")}catch(f){let m=r.root?.db;if(m&&r.source_component_id&&r.pcb_component_id){let D=r.getSubcircuit(),b=`${r.getString()} failed to load external footprint "${x}": `+(f instanceof Error?f.message:String(f)),E=yb.parse({type:"external_footprint_load_error",message:b,pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,subcircuit_id:D.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0,footprinter_string:x});m.external_footprint_load_error.insert(E)}throw f}});return}if(typeof a=="string"){let x=rK(a);if(!x||r._hasStartedFootprintUrlLoad)return;r._hasStartedFootprintUrlLoad=!0;let m=r.root?.platform?.footprintLibraryMap?.[x.footprintLib],D;if(typeof m=="function"&&(D=m),!D)return;e("load-lib-footprint",async()=>{try{let b=await D(x.footprintName),E=null;if(Array.isArray(b)?E=b:Array.isArray(b.footprintCircuitJson)&&(E=b.footprintCircuitJson),!E)return;let A=qS({componentName:r.name,componentRotation:s,footprint:a,pinLabels:l,pcbPinLabels:d},E);r.addAll(A),!Array.isArray(b)&&b.cadModel&&(r._asyncFootprintCadModel=b.cadModel);for(let B of r.children)B.componentName==="Port"&&B._markDirty?.("PcbPortRender");r._markDirty("InitializePortsFromChildren")}catch(b){let E=r.root?.db;if(E&&r.source_component_id&&r.pcb_component_id){let A=r.getSubcircuit(),B=`${r.getString()} failed to load external footprint "${a}": `+(b instanceof Error?b.message:String(b)),w=yb.parse({type:"external_footprint_load_error",message:B,pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,subcircuit_id:A.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0,footprinter_string:a});E.external_footprint_load_error.insert(w)}throw b}});return}if(!(0,tK.isValidElement)(a)&&a.componentName==="Footprint"&&r.add(a),Array.isArray(a)&&!(0,tK.isValidElement)(a)&&a.length>0){try{let x=qS({componentName:r.name,componentRotation:s,footprint:"",pinLabels:l,pcbPinLabels:d},a);r.addAll(x)}catch(x){let f=r.root?.db;if(f&&r.source_component_id&&r.pcb_component_id){let m=r.getSubcircuit(),D=`${r.getString()} failed to load json footprint: `+(x instanceof Error?x.message:String(x)),b=VA.parse({type:"circuit_json_footprint_load_error",message:D,pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,subcircuit_id:m.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0});f.circuit_json_footprint_load_error.insert(b)}throw x}return}}function EGt(r){if(r.root?.pcbDisabled||!r.pcb_component_id)return;let{pcbX:e,pcbY:a}=r._parsedProps,s=r.props?.pcbPositionAnchor;if(!s||e===void 0&&a===void 0)return;let l=ZS(r.children);if(l.width===0||l.height===0)return;let x={...{x:(l.minX+l.maxX)/2,y:(l.minY+l.maxY)/2}},f=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(s)){let b={left:l.minX,right:l.maxX,top:l.minY,bottom:l.maxY};switch(s){case"center":f=x;break;case"top_left":f={x:b.left,y:b.top};break;case"top_center":f={x:x.x,y:b.top};break;case"top_right":f={x:b.right,y:b.top};break;case"center_left":f={x:b.left,y:x.y};break;case"center_right":f={x:b.right,y:x.y};break;case"bottom_left":f={x:b.left,y:b.bottom};break;case"bottom_center":f={x:x.x,y:b.bottom};break;case"bottom_right":f={x:b.right,y:b.bottom};break}}else try{let b=r.portMap[s];b&&(f=b._getGlobalPcbPositionBeforeLayout())}catch{}if(!f)return;let D={...x};e!==void 0&&(D.x+=e-f.x),a!==void 0&&(D.y+=a-f.y),(Math.abs(D.x-x.x)>1e-6||Math.abs(D.y-x.y)>1e-6)&&r._repositionOnPcb(D)}var vGt=(0,UBe.default)("tscircuit:core"),CGt=v.object({x:Vn,y:Vn,z:Vn}),es=class extends Qn{constructor(e){let a={...e},s=[];if(a.pinLabels&&!Array.isArray(a.pinLabels)){let{validPinLabels:l,invalidPinLabelsMessages:d}=yGt(a.pinLabels);a.pinLabels=l,s=d}super(a);q(this,"reactSubtrees",[]);q(this,"_impliedFootprint");q(this,"isPrimitiveContainer",!0);q(this,"_isNormalComponent",!0);q(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});q(this,"_asyncSupplierPartNumbers");q(this,"_asyncFootprintCadModel");q(this,"_isCadModelChild");q(this,"pcb_missing_footprint_error_id");q(this,"_hasStartedFootprintUrlLoad",!1);q(this,"_invalidPinLabelMessages",[]);q(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=s,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(a=>a.map(s=>typeof s=="number"?`pin${s}`:s))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let e=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(l=>l!==this&&l._isNormalComponent&&l.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let l=this._getGlobalPcbPositionBeforeLayout(),d=this._getGlobalSchematicPositionBeforeLayout();e.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:l,schematic_center:d}),this.shouldBeRemoved=!0;let x=[...this.children];for(let f of x)this.remove(f)}}initPorts(e={}){if(this.root?.schematicDisabled)return;let{config:a}=this,s=[],l=this._getSchematicPortArrangement();if(l&&!this._parsedProps.pinLabels){for(let D in l){let b=l[D].pins;if(Array.isArray(b))for(let E of b){let A=YF(E,this._parsedProps.pinLabels);s.push(new Ni({pinNumber:A,aliases:e.additionalAliases?.[`pin${A}`]??[]},{originDescription:`schPortArrangement:${D}`}))}}let f=["left","right","top","bottom"],m=1;for(let D of f){let b=l[`${D}Size`];for(let E=0;E<b;E++)s.push(new Ni({pinNumber:m++,aliases:e.additionalAliases?.[`pin${m}`]??[]},{originDescription:`schPortArrangement:${D}`}))}}let d=this._parsedProps.pinLabels;if(d)for(let[f,m]of Object.entries(d)){f=f.replace("pin","");let D=s.find(A=>A._parsedProps.pinNumber===Number(f)),b=Array.isArray(m)?m[0]:m,E=Array.isArray(m)?m.slice(1):[];D?(D.externallyAddedAliases.push(b,...E),D.props.name=b):(D=new Ni({pinNumber:parseInt(f),name:b,aliases:[...E,...e.additionalAliases?.[`pin${parseInt(f)}`]??[]]},{originDescription:`pinLabels:pin${f}`}),s.push(D))}if(a.schematicSymbolName&&!e.ignoreSymbolPorts){let f=ks[this._getSchematicSymbolNameOrThrow()];if(!f)return;for(let m of f.ports){let D=WBe(m.labels);if(!D)continue;let b=s.find(E=>E._parsedProps.pinNumber===Number(D));if(b)b.schematicSymbolPortDef=m;else{let E=qF(m.labels.concat(e.additionalAliases?.[`pin${D}`]??[]));E&&(E.originDescription=`schematicSymbol:labels[0]:${m.labels[0]}`,E.schematicSymbolPortDef=m,s.push(E))}}this.addAll(s)}if(!this._getSchematicPortArrangement()){let f=this.getPortsFromFootprint(e);for(let m of f)s.some(D=>D.isMatchingAnyOf(m.getNameAndAliases()))||s.push(m)}let x=e.pinCount??this._getPinCount()??0;for(let f=1;f<=x;f++){if(s.find(D=>D._parsedProps.pinNumber===f))continue;if(!l){s.push(new Ni({pinNumber:f,aliases:e.additionalAliases?.[`pin${f}`]??[]}));continue}let m=[...l.leftSide?.pins??[],...l.rightSide?.pins??[],...l.topSide?.pins??[],...l.bottomSide?.pins??[]].map(D=>YF(D,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(D=>D in l)&&(m=Array.from({length:this._getPinCount()},(D,b)=>b+1)),m.includes(f)&&s.push(new Ni({pinNumber:f,aliases:e.additionalAliases?.[`pin${f}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${f}`}))}s.length>0&&this.addAll(s)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:e,pinLabels:a,pcbPinLabels:s}=this.props,{footprint:l}=this.props;if(l??(l=this._getImpliedFootprintString?.()),!!l&&typeof l=="string"){if(HS(l)||rK(l))return;let d=Vq.string(l).soup(),x=qS({componentName:this.name??this.componentName,componentRotation:e,footprint:l,pinLabels:a,pcbPinLabels:s},d);this.addAll(x)}}get portMap(){return new Proxy({},{get:(e,a)=>{let s=this.children.find(l=>l.componentName==="Port"&&l.isMatchingNameOrAlias(a));if(!s)throw new Error(`There was an issue finding the port "${a.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return s}})}getInstanceForReactElement(e){for(let a of this.reactSubtrees)if(a.element===e)return a.component;return null}doInitialSourceRender(){let e=this.config.sourceFtype;if(!e)return;let{db:a}=this.root,{_parsedProps:s}=this,l=a.source_component.insert({ftype:e,name:this.name,manufacturer_part_number:s.manufacturerPartNumber??s.mfn,supplier_part_numbers:s.supplierPartNumbers});this.source_component_id=l.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let l of this._invalidPinLabelMessages){let d="pinLabels",x=l.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);x&&(d=`pinLabels['${x[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:d,message:l,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:a}=this.config;a?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let s=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&s){if(!this.schematic_component_id)return;let l=qA.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});e.schematic_manual_edit_conflict_warning.insert(l)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let e=[];for(let a of this.internallyConnectedPinNames){let s=[];for(let l of a)s.push(this.portMap[l]);e.push(s)}return e}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getSchematicSymbolNameOrThrow(),l=ks[s],d=this._getGlobalSchematicPositionBeforeLayout();if(l){let x=e.schematic_component.insert({center:d,size:l.size,source_component_id:this.source_component_id,symbol_name:s,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=x.schematic_component_id}}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getSchematicBoxDimensions(),l={};if(Array.isArray(a.pinLabels))a.pinLabels.forEach((B,w)=>{l[String(w+1)]=B});else for(let[B,w]of Object.entries(a.pinLabels??{}))l[B]=Array.isArray(w)?w[0]:w;let d=this._getGlobalSchematicPositionBeforeLayout(),x=this._getSchematicPortArrangement(),f=e.schematic_component.insert({center:d,rotation:a.schRotation??0,size:s.getSize(),port_arrangement:BVt(x),pin_spacing:a.schPinSpacing??.2,pin_styles:SVt(a.schPinStyle,a.pinLabels),port_labels:l,source_component_id:this.source_component_id}),m=x?.topSide!==void 0||x?.bottomSide!==void 0,D=s?.getSize().width,b=s?.getSize().height,E=e.schematic_text.insert({text:a.manufacturerPartNumber??"",schematic_component_id:f.schematic_component_id,anchor:"left",rotation:0,position:{x:m?d.x+(D??0)/2+.1:d.x-(D??0)/2,y:m?d.y+(b??0)/2+.35:d.y-(b??0)/2-.13},color:"#006464",font_size:.18}),A=e.schematic_text.insert({text:a.name??"",schematic_component_id:f.schematic_component_id,anchor:"left",rotation:0,position:{x:m?d.x+(D??0)/2+.1:d.x-(D??0)/2,y:m?d.y+(b??0)/2+.55:d.y+(b??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=f.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=e.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:s.subcircuit_id??void 0});if(!(a.footprint??this._getImpliedFootprintString())&&!this.isGroup){let f=e.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=f.pcb_missing_footprint_error_id}this.pcb_component_id=l.pcb_component_id;let x=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&x){let f=GA.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:s.subcircuit_id??void 0});e.pcb_manual_edit_conflict_warning.insert(f)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:e}=this.root,{_parsedProps:a}=this,s=ZS(this.children);if(s.width===0||s.height===0)return;let l={x:(s.minX+s.maxX)/2,y:(s.minY+s.maxY)/2};e.pcb_component.update(this.pcb_component_id,{center:l,width:s.width,height:s.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){EGt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(e){let a=YBe(e);return{element:e,component:a}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let e=this.props.footprint;(0,B1.isValidElement)(e)&&(this.children.some(l=>l.componentName==="Footprint")||this.add(e));let a=this.props.cadModel;if((0,B1.isValidElement)(a)){this._isCadModelChild=!0;let s=this.children.some(d=>d.componentName==="CadAssembly"),l=this.children.some(d=>d.componentName==="CadModel");!s&&!l&&this.add(a)}}doInitialPcbFootprintStringRender(){FGt(this,(e,a)=>this._queueAsyncEffect(e,a))}_hasExistingPortExactly(e){return this.children.filter(s=>s.componentName==="Port").some(s=>{let l=e.getNameAndAliases(),d=s.getNameAndAliases();return l.length===d.length&&l.every(x=>d.includes(x))})}add(e){let a;if((0,B1.isValidElement)(e)){let s=this._renderReactSubtree(e);this.reactSubtrees.push(s),a=s.component}else a=e;if(a.componentName==="Port"){if(this._hasExistingPortExactly(a))return;let l=this.children.filter(d=>d.componentName==="Port").find(d=>d.isMatchingAnyOf(a.getNameAndAliases()));l&&vGt(`Similar ports added. Port 1: ${l}, Port 2: ${a}`)}super.add(a)}getPortsFromFootprint(e){let{footprint:a}=this.props;if((!a||(0,B1.isValidElement)(a))&&(a=this.children.find(l=>l.componentName==="Footprint")),typeof a=="string"){if(HS(a))return[];if(rK(a))return[];let l=Vq.string(a).soup(),d=[];for(let x of l)if("port_hints"in x&&x.port_hints){let f=qF(x.port_hints,e);if(!f)continue;f.originDescription=`footprint:string:${a}:port_hints[0]:${x.port_hints[0]}`,d.push(f)}return d}if(!(0,B1.isValidElement)(a)&&a&&a.componentName==="Footprint"){let l=a,d=1,x=[];for(let f of l.children){if(!f.props.portHints)continue;let m=f.props.portHints;m.some(E=>E.startsWith("pin"))||(m=[...m,`pin${d}`]),d++;let b=qF(m);b&&(b.originDescription=`footprint:${a}`,x.push(b))}return x}let s=[];if(!a){for(let l of this.children)if(l.props.portHints&&l.isPcbPrimitive){let d=qF(l.props.portHints);d&&s.push(d)}}return s}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:e}=this;if(!e.schematicSymbolName)return[];let a=ks[e.schematicSymbolName];if(!a)return[];let s=[];for(let l of a.ports){let d=qF(l.labels);d&&(d.schematicSymbolPortDef=l,s.push(d))}return s}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:e}=this,a=[];if(e.connections)for(let[s,l]of Object.entries(e.connections)){let d=Array.isArray(l)?l:[l];for(let x of d)a.push(x)}return a}_createNetsFromProps(e){uK(this,e)}_getPcbCircuitJsonBounds(){let{db:e}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let a=e.pcb_component.get(this.pcb_component_id);return{center:{x:a.center.x,y:a.center.y},bounds:{left:a.center.x-a.width/2,top:a.center.y-a.height/2,right:a.center.x+a.width/2,bottom:a.center.y+a.height/2},width:a.width,height:a.height}}_getPinCountFromSchematicPortArrangement(){let e=this._getSchematicPortArrangement();if(!e)return 0;if(!KBe(e))return(e.leftSize??e.leftPinCount??0)+(e.rightSize??e.rightPinCount??0)+(e.topSize??e.topPinCount??0)+(e.bottomSize??e.bottomPinCount??0);let{leftSide:s,rightSide:l,topSide:d,bottomSide:x}=e;return Math.max(...s?.pins??[],...l?.pins??[],...d?.pins??[],...x?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let a=this.getPortsFromFootprint();if(a.length>0)return a.length;let{pinLabels:s}=this._parsedProps;if(s){if(Array.isArray(s))return s.length;let l=Object.keys(s).map(d=>d.startsWith("pin")?parseInt(d.slice(3)):parseInt(d)).filter(d=>!Number.isNaN(d));return l.length>0?Math.max(...l):Object.keys(s).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this,a=this._getPinCount(),s=e.schPinSpacing??.2;return OVt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:s,numericSchPinStyle:$Vt(e.schPinStyle,e.pinLabels),pinCount:a,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:e.pinLabels})}doInitialCadModelRender(){if(this._isCadModelChild)return;let{db:e}=this.root,{boardThickness:a=0}=this.root?._getBoard()??{},s=this._parsedProps.cadModel,l=s===void 0?this._asyncFootprintCadModel:s,d=this.props.footprint??this._getImpliedFootprintString();if(!this.pcb_component_id||!l&&!d||l===null)return;let x=this._getPcbCircuitJsonBounds(),f=e.pcb_component.get(this.pcb_component_id);if(typeof l=="string")throw new Error("String cadModel not yet implemented");let m=CGt.parse({x:0,y:0,z:typeof l?.rotationOffset=="number"?l.rotationOffset:0,...typeof l?.rotationOffset=="object"?l.rotationOffset??{}:{}}),D=Vf.parse({x:0,y:0,z:0,...typeof l?.positionOffset=="object"?l.positionOffset:{}}),b=this.props.layer==="bottom"?"bottom":"top",E=e.cad_component.insert({position:{x:x.center.x+D.x,y:x.center.y+D.y,z:(b==="bottom"?-a/2:a/2)+D.z},rotation:{x:m.x,y:(b==="top"?0:180)+m.y,z:b==="bottom"?-((f?.rotation??0)+m.z)+180:(f?.rotation??0)+m.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(l??{})?this._addCachebustToModelUrl(l.stlUrl):void 0,model_obj_url:"objUrl"in(l??{})?this._addCachebustToModelUrl(l.objUrl):void 0,model_mtl_url:"mtlUrl"in(l??{})?this._addCachebustToModelUrl(l.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(l??{})?this._addCachebustToModelUrl(l.gltfUrl):void 0,model_glb_url:"glbUrl"in(l??{})?this._addCachebustToModelUrl(l.glbUrl):void 0,model_step_url:"stepUrl"in(l??{})?this._addCachebustToModelUrl(l.stepUrl):void 0,model_wrl_url:"wrlUrl"in(l??{})?this._addCachebustToModelUrl(l.wrlUrl):void 0,model_jscad:"jscad"in(l??{})?l.jscad:void 0,model_unit_to_mm_scale_factor:typeof l?.modelUnitToMmScale=="number"?l.modelUnitToMmScale:void 0,footprinter_string:typeof d=="string"&&!l?d:void 0});this.cad_component_id=E.cad_component_id}_addCachebustToModelUrl(e){if(!e||!e.includes("modelcdn.tscircuit.com"))return e;let a=this.root?.getClientOrigin()??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(a)}`}_getPartsEngineCacheKey(e,a){return JSON.stringify({ftype:e.ftype,name:e.name,manufacturer_part_number:e.manufacturer_part_number,footprinterString:a})}async _getSupplierPartNumbers(e,a,s){if(this.props.doNotPlace)return{};let l=this.root?.platform?.localCacheEngine,d=this._getPartsEngineCacheKey(a,s);if(l){let m=await l.getItem(d);if(m)try{return JSON.parse(m)}catch{}}let x=await Promise.resolve(e.findPart({sourceComponent:a,footprinterString:s})),f=x==="Not found"?{}:x;if(l)try{await l.setItem(d,JSON.stringify(f))}catch{}return f}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let e=this.getInheritedProperty("partsEngine");if(!e)return;let{db:a}=this.root,s=a.source_component.get(this.source_component_id);if(!s||s.supplier_part_numbers)return;let l;this.props.footprint&&typeof this.props.footprint=="string"&&(l=this.props.footprint);let d=this._getSupplierPartNumbers(e,s,l);if(!(d instanceof Promise)){a.source_component.update(this.source_component_id,{supplier_part_numbers:d});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await d,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:e}=this.root,a=e.source_component.get(this.source_component_id);if(a&&!a.supplier_part_numbers&&this._asyncSupplierPartNumbers){e.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:e}=this;e.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:e}=this;if(e.connections)for(let[a,s]of Object.entries(e.connections)){let l=Array.isArray(s)?s:[s];for(let d of l)this.add(new qc({from:`${this.getSubcircuitSelector()} > port.${a}`,to:d}))}}doInitialSourceDesignRuleChecks(){hGt(this)}_getMinimumFlexContainerSize(){return xGt(this)}_repositionOnPcb(e){return fGt(this,e)}doInitialSilkscreenOverlapAdjustment(){return DGt(this)}},_Gt=class{constructor(r,e={}){q(this,"input");q(this,"isRouting",!1);q(this,"solver");q(this,"eventHandlers",{complete:[],error:[],progress:[]});q(this,"cycleCount",0);q(this,"stepDelay");q(this,"timeoutId");this.input=r;let{capacityDepth:a,targetMinCapacity:s,stepDelay:l=0}=e;this.solver=new R6e(r,{capacityDepth:a,targetMinCapacity:s,cacheProvider:null}),this.stepDelay=l}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 UF(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let r=Date.now(),e=this.solver.iterations;for(;Date.now()-r<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let a=(this.solver.iterations-e)/(Date.now()-r)*1e3;this.cycleCount++;let s=this.solver?.preview()||void 0,l=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:a,progress:l,phase:this.solver.getCurrentPhase(),debugGraphics:s}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(r){this.emitEvent({type:"error",error:r instanceof Error?new UF(r.message):new UF(String(r))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(r,e){r==="complete"?this.eventHandlers.complete.push(e):r==="error"?this.eventHandlers.error.push(e):r==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(r){if(r.type==="complete")for(let e of this.eventHandlers.complete)e(r);else if(r.type==="error")for(let e of this.eventHandlers.error)e(r);else if(r.type==="progress")for(let e of this.eventHandlers.progress)e(r)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new UF(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},fK=class extends Qn{constructor(){super(...arguments);q(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:n4e}}doInitialPortMatching(){let{db:e}=this.root,{_parsedProps:a,parent:s}=this;if(!s)return;if(s.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!s)throw new Error("TraceHint has no parent");if(!a.for){this.renderError(`TraceHint has no for property (${this})`);return}let l=s.selectOne(a.for,{type:"port"});l||this.renderError(`${this} could not find port for selector "${a.for}"`),this.matchedPort=l,l.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:e}=this,a=e.offset?[e.offset]:e.offsets;if(!a)return[];let s=this._computePcbGlobalTransformBeforeLayout();return a.map(l=>({...as(s,l),via:l.via,to_layer:l.to_layer,trace_width:l.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this;e.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},n9e=({circuitJson:r,editEvents:e,manualEditsFile:a})=>{let s={...a,pcb_placements:[...a.pcb_placements??[]]};for(let l of e)if(l.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:d,new_center:x}=l,f=ua(r).pcb_component.get(d);if(!f)continue;let m=ua(r).source_component.get(f.source_component_id);if(!m)continue;let D=s.pcb_placements?.findIndex(E=>E.selector===m.name),b={selector:m.name,center:x,relative_to:"group_center"};D>=0?s.pcb_placements[D]=b:s.pcb_placements.push(b)}return s},a9e=({circuitJson:r,editEvents:e,manualEditsFile:a})=>{let s={...a,schematic_placements:[...a.schematic_placements??[]]};for(let l of e)if(l.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:d,new_center:x}=l,f=ua(r).schematic_component.get(d);if(!f||!f.source_component_id)continue;let m=ua(r).source_component.get(f.source_component_id);if(!m)continue;let D=s.schematic_placements?.findIndex(E=>E.selector===m.name),b={selector:m.name,center:x,relative_to:"group_center"};D>=0?s.schematic_placements[D]=b:s.schematic_placements.push(b)}return s},AGt=({circuitJson:r,editEvents:e,manualEditsFile:a})=>{let s=e.filter(x=>x.edit_event_type==="edit_schematic_component_location"),l=e.filter(x=>x.edit_event_type==="edit_pcb_component_location"),d=a;return s.length>0&&(d=a9e({circuitJson:r,editEvents:s,manualEditsFile:d})),l.length>0&&(d=n9e({circuitJson:r,editEvents:l,manualEditsFile:d})),d},RGt=(r,e)=>{if(ua(r).pcb_trace_hint.get(e.pcb_trace_hint_id))r=r.map(s=>s.pcb_trace_hint_id===e.pcb_trace_hint_id?{...s,route:e.route}:s);else{let s=ua(r).pcb_port.get(e.pcb_port_id);r=r.filter(l=>!(l.type==="pcb_trace_hint"&&l.pcb_port_id===e.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:e.pcb_trace_hint_id,route:e.route,pcb_port_id:e.pcb_port_id,pcb_component_id:s?.pcb_component_id}])}return r},SGt=({circuitJson:r,editEvents:e})=>{r=JSON.parse(JSON.stringify(r));for(let a of e)if(a.edit_event_type==="edit_pcb_component_location"){let s=r.find(d=>d.type==="pcb_component"&&d.pcb_component_id===a.pcb_component_id);if((!s||s.center.x!==a.new_center.x||s.center.y!==a.new_center.y)&&a.original_center){let d=Ma(a.new_center.x-a.original_center.x,a.new_center.y-a.original_center.y);r=r.map(x=>x.pcb_component_id!==a.pcb_component_id?x:IY(x,d))}}else a.edit_event_type==="edit_schematic_component_location"?r=r.map(s=>s.type==="schematic_component"&&s.schematic_component_id===a.schematic_component_id?{...s,center:a.new_center}:s):a.edit_event_type==="edit_pcb_trace_hint"&&(r=RGt(r,a));return r},s9e=(r,e)=>{let a=r.source_group.list(),s=[],l=d=>{let x=a.filter(f=>f.parent_subcircuit_id===d);for(let f of x)f.subcircuit_id&&(s.push(f.subcircuit_id),l(f.subcircuit_id))};return l(e),s},nK=({db:r,circuitJson:e,subcircuit_id:a,minTraceWidth:s=.1})=>{if(!r&&e&&(r=ua(e)),!r)throw new Error("db or circuitJson is required");let l=r.pcb_trace_hint.list(),d=a?new Set([a]):null;if(a){let K=s9e(r,a);for(let U of K)d.add(U)}let x=(e??r.toArray()).filter(K=>!a||"subcircuit_id"in K&&d.has(K.subcircuit_id)),f=r.pcb_board.list()[0];r=ua(x);let m=eu(x),D=pK([...r.pcb_component.list(),...r.pcb_smtpad.list(),...r.pcb_plated_hole.list(),...r.pcb_hole.list(),...r.pcb_via.list(),...r.pcb_cutout.list()].filter(K=>!a||d?.has(K.subcircuit_id)),m);for(let K of D){let U=K.connectedTo.flatMap(J=>m.getIdsConnectedToNet(J));K.connectedTo.push(...U)}let b=D.flatMap(K=>[{x:K.center.x-K.width/2,y:K.center.y-K.height/2},{x:K.center.x+K.width/2,y:K.center.y+K.height/2}]),E;if(f?E={minX:f.center.x-f.width/2,maxX:f.center.x+f.width/2,minY:f.center.y-f.height/2,maxY:f.center.y+f.height/2}:E={minX:Math.min(...b.map(K=>K.x))-1,maxX:Math.max(...b.map(K=>K.x))+1,minY:Math.min(...b.map(K=>K.y))-1,maxY:Math.max(...b.map(K=>K.y))+1},a){let K=r.pcb_group.getWhere({subcircuit_id:a});if(K){let U={minX:K.center.x-K.width/2,maxX:K.center.x+K.width/2,minY:K.center.y-K.height/2,maxY:K.center.y+K.height/2};E={minX:Math.min(E.minX,U.minX),maxX:Math.max(E.maxX,U.maxX),minY:Math.min(E.minY,U.minY),maxY:Math.max(E.maxY,U.maxY)}}}let A=new Set(r.pcb_trace.list().map(K=>K.source_trace_id).filter(K=>!!K)),B=r.source_trace.list().filter(K=>!A.has(K.source_trace_id)).map(K=>{let U=K.connected_source_port_ids.map(Ge=>{let et=r.source_port.get(Ge),dt=r.pcb_port.getWhere({source_port_id:Ge});return{...et,...dt}});if(U.length<2)return null;let[J,Q]=U,de=J.layers?.[0]??"top",oe=Q.layers?.[0]??"top",Te=l.filter(Ge=>Ge.pcb_port_id===J.pcb_port_id||Ge.pcb_port_id===Q.pcb_port_id),Me=[];for(let Ge of Te){let dt=r.pcb_port.get(Ge.pcb_port_id)?.layers?.[0]??"top";for(let $t of Ge.route)Me.push({x:$t.x,y:$t.y,layer:dt})}return{name:K.source_trace_id??m.getNetConnectedToId(K.source_trace_id)??"",source_trace_id:K.source_trace_id,pointsToConnect:[{x:J.x,y:J.y,layer:de,pointId:J.pcb_port_id,pcb_port_id:J.pcb_port_id},...Me,{x:Q.x,y:Q.y,layer:oe,pointId:Q.pcb_port_id,pcb_port_id:Q.pcb_port_id}]}}).filter(K=>K!==null),w=new Map(B.map(K=>[K.source_trace_id,K])),P=r.source_net.list().filter(K=>!a||d?.has(K.subcircuit_id)),j=[];for(let K of P){let U=r.source_trace.list().filter(J=>J.connected_source_net_ids?.includes(K.source_net_id));j.push({name:K.source_net_id??m.getNetConnectedToId(K.source_net_id),pointsToConnect:U.flatMap(J=>r.pcb_port.list().filter(de=>J.connected_source_port_ids.includes(de.source_port_id)).map(de=>({x:de.x,y:de.y,layer:de.layers?.[0]??"top",pointId:de.pcb_port_id,pcb_port_id:de.pcb_port_id})))})}let O=r.pcb_breakout_point.list().filter(K=>!a||d?.has(K.subcircuit_id)),z=[],ee=new Map;for(let K of O){let U={x:K.x,y:K.y,layer:"top"};if(K.source_trace_id){let J=w.get(K.source_trace_id)??ee.get(K.source_trace_id);if(J)J.pointsToConnect.push(U);else{let Q={name:K.source_trace_id,source_trace_id:K.source_trace_id,pointsToConnect:[U]};z.push(Q),ee.set(K.source_trace_id,Q)}}else if(K.source_net_id){let J=j.find(Q=>Q.name===K.source_net_id);J?J.pointsToConnect.push(U):z.push({name:K.source_net_id,pointsToConnect:[U]})}else if(K.source_port_id){let J=r.pcb_port.getWhere({source_port_id:K.source_port_id});J&&z.push({name:K.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:J.x,y:J.y,layer:J.layers?.[0]??"top",pointId:J.pcb_port_id,pcb_port_id:J.pcb_port_id},U]})}}let W=[...B,...j,...z],re=new Map;for(let K of W)for(let U of K.pointsToConnect)U.pointId&&re.set(U.pointId,K);let L=r.pcb_trace.list().filter(K=>!a||d?.has(K.subcircuit_id));for(let K of L){let U=new Set;for(let de of K.route)de.start_pcb_port_id&&U.add(de.start_pcb_port_id),de.end_pcb_port_id&&U.add(de.end_pcb_port_id);if(U.size<2)continue;let J=U.values().next().value;if(!J)continue;let Q=re.get(J);Q&&[...U].every(de=>re.get(de)===Q)&&(Q.externallyConnectedPointIds??(Q.externallyConnectedPointIds=[]),Q.externallyConnectedPointIds.push([...U]))}return{simpleRouteJson:{bounds:E,obstacles:D,connections:W,layerCount:f?.num_layers??2,minTraceWidth:s},connMap:m}},BGt=r=>{let e={};if(!r)return e;for(let s of ld)e[s]=0;let a=new Map;for(let s of r){let[,,l,d]=s.type.split(":");if(d==="start"){a.set(`${l}:${s.renderId}`,s);continue}if(d==="end"){let x=a.get(`${l}:${s.renderId}`);if(x){let f=s.createdAt-x.createdAt;e[l]=(e[l]||0)+f}}}return e},wGt=r=>{let e=r.map(m=>[...new Set(m)]),a=e.map(()=>[]),s=e.map(()=>null);for(let m=0;m<e.length;m++)for(let D of e[m])if(/^\d+$/.test(D)){s[m]=Number.parseInt(D);break}let l=0,d=new Set;for(let m=0;m<s.length;m++){let D=s[m];if(D===null||D<1)continue;if(!d.has(D)){d.add(D),a[m].push(`pin${D}`),l=Math.max(l,D);continue}let b=0;for(let E of a[m])E.startsWith(`pin${D}_alt`)&&b++;a[m].push(`pin${D}_alt${b+1}`)}for(let m=0;m<a.length;m++)a[m][0]?.includes("_alt")&&(l++,a[m].unshift(`pin${l}`));for(let m=0;m<a.length;m++)a[m].length===0&&(l++,a[m].push(`pin${l}`));let x={};for(let m of e)for(let D of m)/^\d+$/.test(D)||(x[D]=(x[D]??0)+1);let f={};for(let m=0;m<e.length;m++){let D=e[m];for(let b of D)/^\d+$/.test(b)||(x[b]===1?a[m].push(b):(f[b]=(f[b]??0)+1,a[m].push(`${b}${f[b]}`)))}return a},BBe=(0,i9e.default)("Group_doInitialSchematicLayoutMatchAdapt");function TGt(r){let{db:e}=r.root,a=Hb(e.toArray(),{source_group_id:r.source_group_id}),s=uH(a);BBe.enabled&&global.debugGraphics?.push(Wp(s,{title:`floatingBpcGraph-${r.name}`}));let l=uH(a),d={boxes:l.boxes,pins:l.pins.map(m=>({...m,color:m.color.replace("not_connected","normal")}))},{result:x}=r5e([{variantName:"default",floatingGraph:l},{variantName:"noNotConnected",floatingGraph:d}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(l.boxes.filter(m=>l.pins.filter(E=>E.boxId===m.boxId).filter(E=>!E.color.includes("center")).length<=2).map(m=>m.boxId)),corpus:{}});BBe.enabled&&global.debugGraphics?.push(Wp(x,{title:`laidOutBpcGraph-${r.name}`}));let f=r._getGlobalSchematicPositionBeforeLayout();for(let m of x.boxes){if(!m.center)continue;let D=e.schematic_component.get(m.boxId);if(D){let E={x:m.center.x+f.x,y:m.center.y+f.y},A=e.schematic_port.list({schematic_component_id:D.schematic_component_id}),B=e.schematic_text.list({schematic_component_id:D.schematic_component_id}),w={x:E.x-D.center.x,y:E.y-D.center.y};for(let P of A)P.center.x+=w.x,P.center.y+=w.y;for(let P of B)P.position.x+=w.x,P.position.y+=w.y;D.center=E;continue}let b=e.schematic_net_label.get(m.boxId);if(b){let E=x.pins.find(B=>B.boxId===m.boxId&&B.color==="netlabel_center");if(!E)throw new Error(`No pin found for net label: ${m.boxId}`);let A={x:m.center.x+f.x,y:m.center.y+f.y};b.center=A,b.anchor_position={x:A.x+E.offset.x,y:A.y+E.offset.y};continue}console.error(`No schematic element found for box: ${m.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var an=(0,o9e.default)("Group_doInitialSchematicLayoutMatchpack");function wBe(r){switch(r){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function TBe(r,e){let a=["right","up","left","down"],s=a.indexOf(r);if(s===-1)return r;let l=Math.round(e/90),d=(s+l)%4;return a[d<0?d+4:d]}function PGt(r,e,a){let s={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};an(`[${a.name}] Processing ${r.childNodes.length} child nodes for input problem`),r.childNodes.forEach((d,x)=>{if(an(`[${a.name}] Processing child ${x}: nodeType=${d.nodeType}`),d.nodeType==="component"?an(`[${a.name}] - Component: ${d.sourceComponent?.name}`):d.nodeType==="group"&&an(`[${a.name}] - Group: ${d.sourceGroup?.name}`),d.nodeType==="component"&&d.sourceComponent){let f=d.sourceComponent.name||`chip_${x}`,m=e.schematic_component.getWhere({source_component_id:d.sourceComponent.source_component_id});if(!m)return;let D=a.children.find(z=>z.source_component_id===d.sourceComponent?.source_component_id),b=[0,90,180,270];D?._parsedProps?.schOrientation&&(b=[0]),D?._parsedProps?.schRotation!==void 0&&(b=[0]);let E=D?._parsedProps?.schMarginLeft??D?._parsedProps?.schMarginX??0,A=D?._parsedProps?.schMarginRight??D?._parsedProps?.schMarginX??0,B=D?._parsedProps?.schMarginTop??D?._parsedProps?.schMarginY??0,w=D?._parsedProps?.schMarginBottom??D?._parsedProps?.schMarginY??0;D?.config.shouldRenderAsSchematicBox&&(B+=.4,w+=.4);let P=(A-E)/2,j=(B-w)/2;s.chipMap[f]={chipId:f,pins:[],size:{x:(m.size?.width||1)+E+A,y:(m.size?.height||1)+B+w},availableRotations:b};let O=e.schematic_port.list({schematic_component_id:m.schematic_component_id});for(let z of O){let ee=e.source_port.get(z.source_port_id);if(!ee)continue;let W=`${f}.${ee.pin_number||ee.name||z.schematic_port_id}`;s.chipMap[f].pins.push(W);let re=wBe(z.facing_direction);s.chipPinMap[W]={pinId:W,offset:{x:(z.center?.x||0)-(m.center.x||0)+P,y:(z.center?.y||0)-(m.center.y||0)+j},side:re}}}else if(d.nodeType==="group"&&d.sourceGroup){let f=d.sourceGroup.name||`group_${x}`;an(`[${a.name}] Processing nested group: ${f}`);let m=e.schematic_group?.getWhere?.({source_group_id:d.sourceGroup.source_group_id}),D=a.children.find(b=>b.source_group_id===d.sourceGroup?.source_group_id);if(an(`[${a.name}] Found schematic_group for ${f}:`,m),m){an(`[${a.name}] Treating group ${f} as composite chip`);let b=e.schematic_component.list({schematic_group_id:m.schematic_group_id});an(`[${a.name}] Group ${f} has ${b.length} components:`,b.map(J=>J.source_component_id));let E=1/0,A=-1/0,B=1/0,w=-1/0,P=!1;for(let J of b)if(J.center&&J.size){P=!0;let Q=J.size.width/2,de=J.size.height/2;E=Math.min(E,J.center.x-Q),A=Math.max(A,J.center.x+Q),B=Math.min(B,J.center.y-de),w=Math.max(w,J.center.y+de)}let j=D?._parsedProps?.schMarginLeft??D?._parsedProps?.schMarginX??0,O=D?._parsedProps?.schMarginRight??D?._parsedProps?.schMarginX??0,z=D?._parsedProps?.schMarginTop??D?._parsedProps?.schMarginY??0,ee=D?._parsedProps?.schMarginBottom??D?._parsedProps?.schMarginY??0,W=(O-j)/2,re=(z-ee)/2,L=(P?A-E:2)+j+O,K=(P?w-B:2)+z+ee;an(`[${a.name}] Group ${f} computed size: ${L} x ${K}`);let U=[];for(let J of b){let Q=e.schematic_port.list({schematic_component_id:J.schematic_component_id});for(let de of Q){let oe=e.source_port.get(de.source_port_id);if(!oe)continue;let Te=`${f}.${oe.pin_number||oe.name||de.schematic_port_id}`;U.push(Te);let Me=m.center||{x:0,y:0},Ge=wBe(de.facing_direction);s.chipPinMap[Te]={pinId:Te,offset:{x:(de.center?.x||0)-Me.x+W,y:(de.center?.y||0)-Me.y+re},side:Ge}}}an(`[${a.name}] Group ${f} has ${U.length} pins:`,U),s.chipMap[f]={chipId:f,pins:U,size:{x:L,y:K}},an(`[${a.name}] Added group ${f} to chipMap`)}else an(`[${a.name}] Warning: No schematic_group found for group ${f}`)}}),an(`[${a.name}] Creating connections using connectivity keys`);let l=new Map;for(let[d,x]of Object.entries(s.chipMap))for(let f of x.pins){let m=f.split(".").pop(),D=r.childNodes.find(b=>b.nodeType==="component"&&b.sourceComponent?b.sourceComponent.name===d:b.nodeType==="group"&&b.sourceGroup?`group_${r.childNodes.indexOf(b)}`===d:!1);if(D?.nodeType==="group"&&D.sourceGroup){let b=e.schematic_group?.getWhere?.({source_group_id:D.sourceGroup.source_group_id});if(b){let E=e.schematic_component.list({schematic_group_id:b.schematic_group_id});for(let A of E){let B=e.source_port.list({source_component_id:A.source_component_id});for(let w of B){let P=w.pin_number||w.name;if(String(P)===String(m))if(w.subcircuit_connectivity_map_key){let j=w.subcircuit_connectivity_map_key;l.has(j)||l.set(j,[]),l.get(j).push(f),an(`[${a.name}] \u2713 Pin ${f} has connectivity key: ${j}`)}else an(`[${a.name}] Pin ${f} has no connectivity key`)}}}}else if(D?.nodeType==="component"&&D.sourceComponent){let b=e.source_port.list({source_component_id:D.sourceComponent.source_component_id});for(let E of b){let A=E.pin_number||E.name;if(String(A)===String(m)&&E.subcircuit_connectivity_map_key){let B=E.subcircuit_connectivity_map_key;l.has(B)||l.set(B,[]),l.get(B).push(f),an(`[${a.name}] Pin ${f} has connectivity key: ${B}`)}}}}an(`[${a.name}] Found ${l.size} connectivity groups:`,Array.from(l.entries()).map(([d,x])=>({key:d,pins:x})));for(let[d,x]of l)if(x.length>=2){let f=e.source_trace.list().filter(b=>b.subcircuit_connectivity_map_key===d),m=f.some(b=>b.connected_source_net_ids&&b.connected_source_net_ids.length>0),D=f.some(b=>b.connected_source_port_ids&&b.connected_source_port_ids.length>=2);if(an(`[${a.name}] Connectivity ${d}: hasNetConnections=${m}, hasDirectConnections=${D}`),D){for(let b of f)if(b.connected_source_port_ids&&b.connected_source_port_ids.length>=2){let E=[];for(let A of b.connected_source_port_ids)for(let B of x){let w=B.split(".").pop(),P=e.source_port.get(A);if(P&&String(P.pin_number||P.name)===String(w)){let j=B.split(".")[0],O=r.childNodes.find(z=>z.nodeType==="component"&&z.sourceComponent?z.sourceComponent.name===j:z.nodeType==="group"&&z.sourceGroup?`group_${r.childNodes.indexOf(z)}`===j:!1);O?.nodeType==="component"&&O.sourceComponent&&e.source_port.list({source_component_id:O.sourceComponent.source_component_id}).some(ee=>ee.source_port_id===A)&&E.push(B)}}for(let A=0;A<E.length;A++)for(let B=A+1;B<E.length;B++){let w=E[A],P=E[B];s.pinStrongConnMap[`${w}-${P}`]=!0,s.pinStrongConnMap[`${P}-${w}`]=!0,an(`[${a.name}] Created strong connection: ${w} <-> ${P}`)}}}if(m){let b=e.source_net.getWhere({subcircuit_connectivity_map_key:d}),E=b?.is_ground??!1,A=b?.is_power??!1;s.netMap[d]={netId:d,isGround:E,isPositiveVoltageSource:A};for(let B of x)s.netConnMap[`${B}-${d}`]=!0;an(`[${a.name}] Created net ${d} with ${x.length} pins:`,x)}}return s}function IGt(r){let{db:e}=r.root,a=xg(e.toArray(),{source_group_id:r.source_group_id});if(an(`[${r.name}] Starting matchpack layout with ${a.childNodes.length} children`),an(`[${r.name}] Tree structure:`,JSON.stringify(a,null,2)),a.childNodes.length<=1){an(`[${r.name}] Only ${a.childNodes.length} children, skipping layout`);return}an("Converting circuit tree to InputProblem...");let s=PGt(a,e,r);an.enabled&&r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${r.name}`,content:JSON.stringify(s,null,2)});let l=new sSe(s);if(an("Starting LayoutPipelineSolver..."),an.enabled&&global.debugGraphics){let m=l.visualize();global.debugGraphics.push({...m,title:`matchpack-initial-${r.name}`})}if(l.solve(),an(`Solver completed in ${l.iterations} iterations`),an(`Solved: ${l.solved}, Failed: ${l.failed}`),l.failed)throw an(`Solver failed with error: ${l.error}`),new Error(`Matchpack layout solver failed: ${l.error}`);let d=l.getOutputLayout();if(an("OutputLayout:",JSON.stringify(d,null,2)),an("Solver completed successfully:",!l.failed),an.enabled&&global.debugGraphics){let m=l.visualize();global.debugGraphics.push({...m,title:`matchpack-final-${r.name}`})}let x=l.checkForOverlaps(d);if(x.length>0){an(`Warning: Found ${x.length} overlapping components:`);for(let m of x)an(` ${m.chip1} overlaps ${m.chip2} (area: ${m.overlapArea})`)}let f=r._getGlobalSchematicPositionBeforeLayout();an(`Group offset: x=${f.x}, y=${f.y}`),an(`Applying layout results for ${Object.keys(d.chipPlacements).length} chip placements`);for(let[m,D]of Object.entries(d.chipPlacements)){an(`Processing placement for chip: ${m} at (${D.x}, ${D.y})`);let b=a.childNodes.find(A=>{if(A.nodeType==="component"&&A.sourceComponent){let B=A.sourceComponent.name===m;return an(` Checking component ${A.sourceComponent.name}: matches=${B}`),B}if(A.nodeType==="group"&&A.sourceGroup){let B=A.sourceGroup.name,w=`group_${a.childNodes.indexOf(A)}`,P=w===m;return an(` Checking group ${B} (expected chipId: ${w}): matches=${P}`),P}return!1});if(!b){an(`Warning: No tree node found for chip: ${m}`),an("Available tree nodes:",a.childNodes.map((A,B)=>({type:A.nodeType,name:A.nodeType==="component"?A.sourceComponent?.name:A.sourceGroup?.name,expectedChipId:A.nodeType==="group"?`group_${B}`:A.sourceComponent?.name})));continue}let E={x:D.x+f.x,y:D.y+f.y};if(b.nodeType==="component"&&b.sourceComponent){let A=e.schematic_component.getWhere({source_component_id:b.sourceComponent.source_component_id});if(A){an(`Moving component ${m} to (${E.x}, ${E.y})`);let B=e.schematic_port.list({schematic_component_id:A.schematic_component_id}),w=e.schematic_text.list({schematic_component_id:A.schematic_component_id}),P={x:E.x-A.center.x,y:E.y-A.center.y};for(let j of B)j.center.x+=P.x,j.center.y+=P.y;for(let j of w)j.position.x+=P.x,j.position.y+=P.y;if(A.center=E,D.ccwRotationDegrees!==0){an(`Component ${m} has rotation: ${D.ccwRotationDegrees}\xB0`);let j=D.ccwRotationDegrees*Math.PI/180,O=Math.cos(j),z=Math.sin(j);for(let ee of B){let W=ee.center.x-E.x,re=ee.center.y-E.y,L=W*O-re*z,K=W*z+re*O;ee.center.x=E.x+L,ee.center.y=E.y+K;let U=ee.facing_direction||"right";ee.facing_direction=TBe(U,D.ccwRotationDegrees)}for(let ee of w){let W=ee.position.x-E.x,re=ee.position.y-E.y,L=W*O-re*z,K=W*z+re*O;ee.position.x=E.x+L,ee.position.y=E.y+K}if(A.symbol_name){let ee=A.symbol_name.match(/_(right|left|up|down)$/);ee&&(A.symbol_name=A.symbol_name.replace(ee[0],`_${TBe(ee[1],D.ccwRotationDegrees)}`))}}}}else if(b.nodeType==="group"&&b.sourceGroup){let A=e.schematic_group?.getWhere?.({source_group_id:b.sourceGroup.source_group_id});if(A){an(`Moving group ${m} to (${E.x}, ${E.y}) from (${A.center?.x}, ${A.center?.y})`);let B=e.schematic_component.list({schematic_group_id:A.schematic_group_id});an(`Group ${m} has ${B.length} components to move`);let w=A.center||{x:0,y:0},P={x:E.x-w.x,y:E.y-w.y};an(`Position delta for group ${m}: (${P.x}, ${P.y})`);for(let j of B)if(j.center){let O={...j.center};j.center.x+=P.x,j.center.y+=P.y,an(`Moved component ${j.source_component_id} from (${O.x}, ${O.y}) to (${j.center.x}, ${j.center.y})`);let z=e.schematic_port.list({schematic_component_id:j.schematic_component_id}),ee=e.schematic_text.list({schematic_component_id:j.schematic_component_id});for(let W of z)W.center&&(W.center.x+=P.x,W.center.y+=P.y);for(let W of ee)W.position&&(W.position.x+=P.x,W.position.y+=P.y)}A.center=E,an(`Updated group ${m} center to (${E.x}, ${E.y})`)}}}an("Matchpack layout completed successfully")}function jGt(r){if(!r.isSubcircuit)return;let{db:e}=r.root,a=r.selectAll("trace"),s=new $b({});s.addConnections(a.map(f=>{let m=e.source_trace.get(f.source_trace_id);return m?[m.source_trace_id,...m.connected_source_port_ids,...m.connected_source_net_ids]:null}).filter(f=>f!==null));let{name:l}=r._parsedProps;for(let f of a){if(!f.source_trace_id)continue;let m=s.getNetConnectedToId(f.source_trace_id);m&&(f.subcircuit_connectivity_map_key=`${l??`unnamedsubcircuit${r._renderId}`}_${m}`,e.source_trace.update(f.source_trace_id,{subcircuit_connectivity_map_key:f.subcircuit_connectivity_map_key}))}let d=new Set;for(let f of a){if(!f.source_trace_id)continue;let m=e.source_trace.get(f.source_trace_id);if(m)for(let D of m.connected_source_port_ids)d.add(D)}for(let f of d){let m=s.getNetConnectedToId(f);if(!m)continue;let D=`${l??`unnamedsubcircuit${r._renderId}`}_${m}`;e.source_port.update(f,{subcircuit_connectivity_map_key:D})}let x=new Set;for(let f of a){if(!f.source_trace_id)continue;let m=e.source_trace.get(f.source_trace_id);if(m)for(let D of m.connected_source_net_ids)x.add(D)}for(let f of x){let m=s.getNetConnectedToId(f);if(!m)continue;let D=`${l??`unnamedsubcircuit${r._renderId}`}_${m}`;e.source_net.update(f,{subcircuit_connectivity_map_key:D})}}function kGt(r){let{db:e}=r.root,a=r._parsedProps,s=r.children.filter(re=>{let L=re._parsedProps?.schX!==void 0||re._parsedProps?.schY!==void 0;return re.schematic_component_id&&!L});if(s.length===0)return;let l=0,d=0;for(let re of s){let L=e.schematic_component.get(re.schematic_component_id);L?.size&&(l=Math.max(l,L.size.width),d=Math.max(d,L.size.height))}l===0&&s.length>0&&(l=1),d===0&&s.length>0&&(d=1);let x=a.gridCols,f,m=a.gridGap,D=a.gridRowGap,b=a.gridColumnGap;a.schLayout?.grid&&(x=a.schLayout.grid.cols??x,f=a.schLayout.grid.rows,m=a.schLayout.gridGap??m,D=a.schLayout.gridRowGap??D,b=a.schLayout.gridColumnGap??b);let E,A;x!==void 0&&f!==void 0?(E=x,A=f):x!==void 0?(E=x,A=Math.ceil(s.length/E)):f!==void 0?(A=f,E=Math.ceil(s.length/A)):(E=Math.ceil(Math.sqrt(s.length)),A=Math.ceil(s.length/E)),E===0&&s.length>0&&(E=1),A===0&&s.length>0&&(A=s.length);let B,w,P=re=>{if(re!==void 0)return typeof re=="number"?re:pe.parse(re)};if(D!==void 0||b!==void 0){let re=typeof m=="object"&&m!==null?m.x:m,L=typeof m=="object"&&m!==null?m.y:m;B=P(b??re)??1,w=P(D??L)??1}else if(typeof m=="number")B=m,w=m;else if(typeof m=="string"){let re=pe.parse(m);B=re,w=re}else if(typeof m=="object"&&m!==null){let re=m.x,L=m.y;B=typeof re=="number"?re:pe.parse(re??"0mm"),w=typeof L=="number"?L:pe.parse(L??"0mm")}else B=1,w=1;let j=E*l+Math.max(0,E-1)*B,O=A*d+Math.max(0,A-1)*w,z=r._getGlobalSchematicPositionBeforeLayout(),ee=z.x-j/2+l/2,W=z.y+O/2-d/2;for(let re=0;re<s.length;re++){let L=s[re];if(!L.schematic_component_id)continue;let K=Math.floor(re/E),U=re%E;if(K>=A||U>=E){console.warn(`Schematic grid layout: Child ${L.getString()} at index ${re} (row ${K}, col ${U}) exceeds specified grid dimensions (${A}x${E}). Skipping placement.`);continue}let J=ee+U*(l+B),Q=W-K*(d+w),de=e.schematic_component.get(L.schematic_component_id);if(de){let oe=de.center,Te={x:J,y:Q};e.schematic_component.update(L.schematic_component_id,{center:Te});let Me=Te.x-oe.x,Ge=Te.y-oe.y,et=e.schematic_port.list({schematic_component_id:L.schematic_component_id});for(let $t of et)e.schematic_port.update($t.schematic_port_id,{center:{x:$t.center.x+Me,y:$t.center.y+Ge}});let dt=e.schematic_text.list({schematic_component_id:L.schematic_component_id});for(let $t of dt)e.schematic_text.update($t.schematic_text_id,{position:{x:$t.position.x+Me,y:$t.position.y+Ge}})}}r.schematic_group_id&&e.schematic_group.update(r.schematic_group_id,{width:j,height:O,center:z})}var PBe=(r,e)=>{let{sourceComponent:a,sourceGroup:s}=e;if(e.nodeType==="component"){let l=r.schematic_component.getWhere({source_component_id:a?.source_component_id});return l?.size?{width:l.size.width,height:l.size.height}:null}if(e.nodeType==="group"){let l=r.schematic_group.getWhere({source_group_id:s?.source_group_id});if(l?.width&&l?.height)return{width:l.width,height:l.height};let d=r.schematic_component.list({schematic_group_id:l?.schematic_group_id}),x=1/0,f=-1/0,m=1/0,D=-1/0;for(let A of d)if(A.center&&A.size){let B=A.size.width/2,w=A.size.height/2;x=Math.min(x,A.center.x-B),f=Math.max(f,A.center.x+B),m=Math.min(m,A.center.y-w),D=Math.max(D,A.center.y+w)}let b=f-x,E=D-m;return{width:b,height:E}}return null},NGt=r=>{let{db:e}=r.root,a=r._parsedProps,s=xg(e.toArray(),{source_group_id:r.source_group_id}),l=a.schJustifyContent??a.justifyContent,d=a.schAlignItems??a.alignItems,x=a.schFlexGap??a.schGap??a.gap,f=a.schFlexDirection??"row",m={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"}[l??"space-between"],D={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[d??"center"];if(!m)throw new Error(`Invalid justifyContent value: "${l}"`);if(!D)throw new Error(`Invalid alignItems value: "${d}"`);let b=0,E=0;typeof x=="object"?(b=x.y??0,E=x.x??0):typeof x=="number"?(b=x,E=x):typeof x=="string"&&(b=pe.parse(x),E=pe.parse(x));let A,B=a.width??a.schWidth??void 0,w=a.height??a.schHeight??void 0;(B===void 0||w===void 0)&&(A=A5(s.childNodes.map(W=>PBe(e,W)).filter(W=>W!==null),{alignItems:D,justifyContent:m,direction:f,rowGap:b,columnGap:E}),B=A.width,w=A.height);let j=new _S(B,w,{alignItems:D,justifyContent:m,direction:f,rowGap:b,columnGap:E});for(let W of s.childNodes){let re=PBe(e,W);j.addChild({metadata:W,width:re?.width??0,height:re?.height??0,flexBasis:re?f==="row"?re.width:re.height:void 0})}j.build();let O={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let W of j.children)O.minX=Math.min(O.minX,W.position.x),O.minY=Math.min(O.minY,W.position.y),O.maxX=Math.max(O.maxX,W.position.x+W.size.width),O.maxY=Math.max(O.maxY,W.position.y+W.size.height);O.width=O.maxX-O.minX,O.height=O.maxY-O.minY;let z={x:-(O.maxX+O.minX)/2,y:-(O.maxY+O.minY)/2},ee=e.toArray();for(let W of j.children){let{sourceComponent:re,sourceGroup:L}=W.metadata;if(re){let K=e.schematic_component.getWhere({source_component_id:re.source_component_id});if(!K)continue;S4e(ee,K.schematic_component_id,{x:W.position.x+W.size.width/2+z.x,y:W.position.y+W.size.height/2+z.y})}if(L){if(!e.schematic_group.getWhere({source_group_id:L.source_group_id}))continue;w4e(ee,L.source_group_id,{x:W.position.x+W.size.width/2+z.x,y:W.position.y+W.size.height/2+z.y})}}r.schematic_group_id&&e.schematic_group.update(r.schematic_group_id,{width:O.width,height:O.height})},YW=1;function MGt(r){let{db:e}=r.root,a=r._parsedProps,s=OGt(r);if(s.length===0)return;let l=LGt({db:e,pcbChildren:s}),d=$Gt(a),x=zGt({props:a,pcbChildren:s,childDimensions:l,gridConfig:d}),f=VGt({pcbChildren:s,childDimensions:l,gridLayout:x,gridConfig:d}),{itemCoordinates:m}=f.layout();GGt({db:e,group:r,pcbChildren:s,itemCoordinates:m,gridLayout:x}),XGt({db:e,group:r,props:a,gridLayout:x})}function OGt(r){return r.children.filter(e=>e.pcb_component_id||e.pcb_group_id)}function LGt(r){let{db:e,pcbChildren:a}=r,s=0,l=0;for(let d of a){let x=0,f=0;if(d.pcb_group_id){let m=e.pcb_group.get(d.pcb_group_id);x=m?.width??0,f=m?.height??0}else if(d.pcb_component_id){let m=e.pcb_component.get(d.pcb_component_id);x=m?.width??0,f=m?.height??0}s=Math.max(s,x),l=Math.max(l,f)}return{width:s,height:l}}function $Gt(r){let e=r.pcbGridCols??r.gridCols??r.pcbLayout?.grid?.cols,a=r.pcbGridRows??r.pcbLayout?.grid?.rows,s=r.pcbGridTemplateColumns,l=r.pcbGridTemplateRows,d=E=>E===void 0?YW:typeof E=="number"?E:pe.parse(E),x=r.pcbGridGap??r.gridGap??r.pcbLayout?.gridGap,f=r.pcbGridRowGap??r.gridRowGap??r.pcbLayout?.gridRowGap,m=r.pcbGridColumnGap??r.gridColumnGap??r.pcbLayout?.gridColumnGap,D=YW,b=YW;if(f!==void 0||m!==void 0){let E=typeof x=="object"?x?.x:x,A=typeof x=="object"?x?.y:x;D=d(m??E),b=d(f??A)}else if(typeof x=="object"&&x!==null)D=d(x.x),b=d(x.y);else{let E=d(x);D=E,b=E}return{cols:e,rows:a,gapX:D,gapY:b,templateColumns:s,templateRows:l}}function zGt(r){let{props:e,pcbChildren:a,childDimensions:s,gridConfig:l}=r;return e.pcbGridTemplateColumns||e.pcbGridTemplateRows?qGt({props:e,gridConfig:l,pcbChildren:a,childDimensions:s}):UGt({gridConfig:l,pcbChildren:a,childDimensions:s})}function qGt(r){let{props:e,gridConfig:a,pcbChildren:s,childDimensions:l}=r,d=e.pcbGridTemplateColumns??"",x=e.pcbGridTemplateRows??"",f=A=>{let B=A.match(/repeat\((\d+),/);return B?parseInt(B[1]):Math.ceil(Math.sqrt(s.length))},m=e.pcbGridTemplateColumns?f(d):Math.ceil(Math.sqrt(s.length)),D=e.pcbGridTemplateRows?f(x):Math.ceil(s.length/m),b=m*l.width+Math.max(0,m-1)*a.gapX,E=D*l.height+Math.max(0,D-1)*a.gapY;return{gridTemplateColumns:d,gridTemplateRows:x,containerWidth:b,containerHeight:E}}function UGt(r){let{gridConfig:e,pcbChildren:a,childDimensions:s}=r,l,d;e.cols!==void 0&&e.rows!==void 0?(l=e.cols,d=e.rows):e.cols!==void 0?(l=e.cols,d=Math.ceil(a.length/l)):e.rows!==void 0?(d=e.rows,l=Math.ceil(a.length/d)):(l=Math.ceil(Math.sqrt(a.length)),d=Math.ceil(a.length/l)),l=Math.max(1,l),d=Math.max(1,d);let x=l*s.width+Math.max(0,l-1)*e.gapX,f=d*s.height+Math.max(0,d-1)*e.gapY,m=`repeat(${l}, ${s.width}px)`,D=`repeat(${d}, ${s.height}px)`;return{gridTemplateColumns:m,gridTemplateRows:D,containerWidth:x,containerHeight:f}}function VGt(r){let{pcbChildren:e,childDimensions:a,gridLayout:s,gridConfig:l}=r,d=e.map((x,f)=>({key:x.getString()||`child-${f}`,contentWidth:a.width,contentHeight:a.height}));return new fSe({containerWidth:s.containerWidth,containerHeight:s.containerHeight,gridTemplateColumns:s.gridTemplateColumns,gridTemplateRows:s.gridTemplateRows,gap:[l.gapY,l.gapX],children:d})}function GGt(r){let{db:e,group:a,pcbChildren:s,itemCoordinates:l,gridLayout:d}=r,x=a._getGlobalPcbPositionBeforeLayout(),f=e.toArray();for(let m=0;m<s.length;m++){let D=s[m],b=D.getString()||`child-${m}`,E=l[b];if(!E){console.warn(`PCB grid layout: No coordinates found for child ${b}`);continue}let A=x.x-d.containerWidth/2+E.x+E.width/2,B=x.y+d.containerHeight/2-E.y-E.height/2;if(D.pcb_component_id)C5(f,D.pcb_component_id,{x:A,y:B});else{let w=D;w.pcb_group_id&&w.source_group_id&&_5(f,w.source_group_id,{x:A,y:B})}}}function XGt(r){let{db:e,group:a,props:s,gridLayout:l}=r;if(a.pcb_group_id){let d=a._getGlobalPcbPositionBeforeLayout();e.pcb_group.update(a.pcb_group_id,{width:s.width??l.containerWidth,height:s.height??l.containerHeight,center:d})}}function YGt(r){let e={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof r=="object"&&!r.preset)return{local:!(r.serverUrl||r.serverMode||r.serverCacheEnabled),...e,...r};let a=typeof r=="object"?r.preset:r,s=typeof r=="object"?r:{};switch(a){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:l,local:d,groupMode:x,...f}=s;return{local:!1,groupMode:"subcircuit",...e,...f}}default:return{local:!0,groupMode:"subcircuit"}}}var HGt=(r,e)=>{let a=r.children.filter(E=>E.componentName==="Constraint"&&E._parsedProps.pcb),s=new Map,l={},d=E=>(l[E]!==E&&(l[E]=d(l[E])),l[E]),x=(E,A)=>{let B=d(E),w=d(A);B!==w&&(l[w]=B)},f=E=>{E in l||(l[E]=E)},m=E=>{let A=E.startsWith(".")?E.slice(1):E;return r.children.find(w=>w.name===A)?.pcb_component_id??void 0};for(let E of a){let A=E._parsedProps;if("left"in A&&"right"in A){let B=m(A.left),w=m(A.right);B&&w&&(f(B),f(w),x(B,w))}else if("top"in A&&"bottom"in A){let B=m(A.top),w=m(A.bottom);B&&w&&(f(B),f(w),x(B,w))}else if("for"in A&&Array.isArray(A.for)){let B=A.for.map(w=>m(w)).filter(w=>!!w);for(let w of B)f(w);for(let w=1;w<B.length;w++)x(B[0],B[w])}}for(let E of Object.keys(l)){let A=d(E);s.has(A)||s.set(A,{componentIds:[],constraints:[]}),s.get(A).componentIds.push(E)}for(let E of a){let A=E._parsedProps,B;if("left"in A?B=m(A.left):"top"in A?B=m(A.top):"for"in A&&(B=m(A.for[0])),!B)continue;let w=d(B);s.get(w)?.constraints.push(E)}let D={},b=Object.fromEntries(e.components.map(E=>[E.componentId,E]));for(let[E,A]of s.entries()){if(A.componentIds.length<=1)continue;let B=new ug,w={},P=(J,Q)=>{let de=`${J}_${Q}`;return w[de]||(w[de]=new rd(de)),w[de]},j=A.componentIds[0];B.addConstraint(new Vs(P(j,"x"),Ds.Eq,0,Oa.required)),B.addConstraint(new Vs(P(j,"y"),Ds.Eq,0,Oa.required));for(let J of A.constraints){let Q=J._parsedProps;if("xDist"in Q){let de=m(Q.left),oe=m(Q.right);de&&oe&&B.addConstraint(new Vs(new Xa(P(oe,"x"),[-1,P(de,"x")]),Ds.Eq,Q.xDist,Oa.required))}else if("yDist"in Q){let de=m(Q.top),oe=m(Q.bottom);de&&oe&&B.addConstraint(new Vs(new Xa(P(de,"y"),[-1,P(oe,"y")]),Ds.Eq,Q.yDist,Oa.required))}else if("sameX"in Q&&Array.isArray(Q.for)){let de=Q.for.map(oe=>m(oe)).filter(oe=>!!oe);if(de.length>1){let oe=P(de[0],"x");for(let Te=1;Te<de.length;Te++)B.addConstraint(new Vs(new Xa(P(de[Te],"x"),[-1,oe]),Ds.Eq,0,Oa.required))}}else if("sameY"in Q&&Array.isArray(Q.for)){let de=Q.for.map(oe=>m(oe)).filter(oe=>!!oe);if(de.length>1){let oe=P(de[0],"y");for(let Te=1;Te<de.length;Te++)B.addConstraint(new Vs(new Xa(P(de[Te],"y"),[-1,oe]),Ds.Eq,0,Oa.required))}}}B.updateVariables();let O={};for(let J of A.componentIds)O[J]={x:P(J,"x").value(),y:P(J,"y").value()};let z=1/0,ee=1/0,W=-1/0,re=-1/0;for(let J of A.componentIds){let Q=b[J],de=O[J];if(Q)for(let oe of Q.pads){let Te=de.x+oe.offset.x,Me=de.y+oe.offset.y;z=Math.min(z,Te-oe.size.x/2),W=Math.max(W,Te+oe.size.x/2),ee=Math.min(ee,Me-oe.size.y/2),re=Math.max(re,Me+oe.size.y/2)}}let L={x:(z+W)/2,y:(ee+re)/2},K=[],U={};for(let J of A.componentIds){let Q=b[J],de=O[J];if(Q){U[J]={x:de.x-L.x,y:de.y-L.y};for(let oe of Q.pads)K.push({padId:oe.padId,networkId:oe.networkId,type:oe.type,size:oe.size,offset:{x:de.x+oe.offset.x-L.x,y:de.y+oe.offset.y-L.y}})}}e.components=e.components.filter(J=>!A.componentIds.includes(J.componentId)),e.components.push({componentId:A.componentIds[0],pads:K,availableRotationDegrees:[0]}),A.relativeCenters=U,D[A.componentIds[0]]=A}return D},VF=(r,e,a)=>{if(e===a)return!0;let s=r.source_group.get(e);return!s||!s.parent_source_group_id?!1:VF(r,s.parent_source_group_id,a)},WGt=(r,e,a)=>{let{db:s}=r.root;for(let l of e.components){let{center:d,componentId:x,ccwRotationOffset:f,ccwRotationDegrees:m}=l,D=a[x];if(D){let O=(m??f??0)*Math.PI/180;for(let z of D.componentIds){let ee=D.relativeCenters[z];if(!ee)continue;let W={x:ee.x*Math.cos(O)-ee.y*Math.sin(O),y:ee.x*Math.sin(O)+ee.y*Math.cos(O)},re=s.pcb_component.get(z);if(!re)continue;let L=re.center,K=js(r._computePcbGlobalTransformBeforeLayout(),Ma(d.x+W.x,d.y+W.y),Ip(O),Ma(-L.x,-L.y)),U=s.toArray().filter(J=>"pcb_component_id"in J&&J.pcb_component_id===z);pg(U,K)}continue}let b=s.pcb_component.get(x);if(b){let j=r.source_group_id,z=s.source_component.get(b.source_component_id)?.source_group_id;if(z!==void 0&&!VF(s,z,j))continue;let ee=b.center,W=m??f??0,re=js(r._computePcbGlobalTransformBeforeLayout(),Ma(d.x,d.y),Ip(W*Math.PI/180),Ma(-ee.x,-ee.y)),L=s.toArray().filter(K=>"pcb_component_id"in K&&K.pcb_component_id===x);pg(L,re);continue}let E=s.pcb_group.list().find(j=>j.source_group_id===x);if(!E)continue;let A=E.center,B=m??f??0,w=js(r._computePcbGlobalTransformBeforeLayout(),Ma(d.x,d.y),Ip(B*Math.PI/180),Ma(-A.x,-A.y)),P=s.toArray().filter(j=>{if("source_group_id"in j&&j.source_group_id&&(j.source_group_id===x||VF(s,j.source_group_id,x)))return!0;if("source_component_id"in j&&j.source_component_id){let O=s.source_component.get(j.source_component_id);if(O?.source_group_id&&(O.source_group_id===x||VF(s,O.source_group_id,x)))return!0}if("pcb_component_id"in j&&j.pcb_component_id){let O=s.pcb_component.get(j.pcb_component_id);if(O?.source_component_id){let z=s.source_component.get(O.source_component_id);if(z?.source_group_id&&(z.source_group_id===x||VF(s,z.source_group_id,x)))return!0}}return!1});pg(P,w),s.pcb_group.update(E.pcb_group_id,{center:d})}},KGt="1mm",IBe=(0,u9e.default)("Group_doInitialPcbLayoutPack"),JGt=r=>{let{db:e}=r.root,{_parsedProps:a}=r,{packOrderStrategy:s,packPlacementStrategy:l,gap:d,pcbGap:x,pcbPackGap:f}=a,m=f??x??d,D=pe.parse(m??KGt),b={},E=P=>{if(P?.pcb_component_id&&P?._parsedProps){let j=P._parsedProps,O=pe.parse(j.pcbMarginLeft??j.pcbMarginX??0),z=pe.parse(j.pcbMarginRight??j.pcbMarginX??0),ee=pe.parse(j.pcbMarginTop??j.pcbMarginY??0),W=pe.parse(j.pcbMarginBottom??j.pcbMarginY??0);(O||z||ee||W)&&(b[P.pcb_component_id]={left:O,right:z,top:ee,bottom:W})}P?.children&&P.children.forEach(E)};E(r);let A={...nSe(rSe(e.toArray(),{source_group_id:r.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:b})),orderStrategy:s??"largest_to_smallest",placementStrategy:l??"minimum_sum_squared_distance_to_network",minGap:D},B=HGt(r,A);IBe.enabled&&(r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${r.name}`,content:JSON.stringify(e.toArray())}),r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${r.name}`,content:A}));let w=ES(A);if(IBe.enabled){let P=yW(w);P.title=`packOutput-${r.name}`,global.debugGraphics?.push(P)}WGt(r,w,B)},ZGt=r=>{let{db:e}=r.root,{_parsedProps:a}=r,s=r.children.filter(re=>re.pcb_component_id||re.pcb_group_id);if(s.some(re=>{let L=re._parsedProps;return L?.pcbX!==void 0||L?.pcbY!==void 0}))return;let d=a.pcbJustifyContent??a.justifyContent,x=a.pcbAlignItems??a.alignItems,f=a.pcbFlexGap??a.pcbGap??a.gap,m=a.pcbFlexDirection??"row",D={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"}[d??"space-between"],b={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[x??"center"];if(!D)throw new Error(`Invalid justifyContent value: "${d}"`);if(!b)throw new Error(`Invalid alignItems value: "${x}"`);let E=0,A=0;typeof f=="object"?(E=f.y??0,A=f.x??0):typeof f=="number"?(E=f,A=f):typeof f=="string"&&(E=pe.parse(f),A=pe.parse(f));let B,w=a.width??a.pcbWidth??void 0,P=a.height??a.pcbHeight??void 0;(w===void 0||P===void 0)&&(B=A5(s.map(re=>re._getMinimumFlexContainerSize()).filter(re=>re!==null),{alignItems:b,justifyContent:D,direction:m,rowGap:E,columnGap:A}),w=B.width,P=B.height);let O=new _S(w,P,{alignItems:b,justifyContent:D,direction:m,rowGap:E,columnGap:A});for(let re of s){let L=re._getMinimumFlexContainerSize();O.addChild({metadata:re,width:L?.width??0,height:L?.height??0,flexBasis:L?m==="row"?L.width:L.height:void 0})}O.build();let z={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let re of O.children)z.minX=Math.min(z.minX,re.position.x),z.minY=Math.min(z.minY,re.position.y),z.maxX=Math.max(z.maxX,re.position.x+re.size.width),z.maxY=Math.max(z.maxY,re.position.y+re.size.height);z.width=z.maxX-z.minX,z.height=z.maxY-z.minY;let ee=r._getGlobalPcbPositionBeforeLayout(),W={x:ee.x-(z.maxX+z.minX)/2,y:ee.y-(z.maxY+z.minY)/2};for(let re of O.children)re.metadata._repositionOnPcb({x:re.position.x+re.size.width/2+W.x,y:re.position.y+re.size.height/2+W.y});e.pcb_group.update(r.pcb_group_id,{width:z.width,height:z.height,center:ee})};function QGt(r){let{db:e}=r.root,a=new Map,s=new Map,l=new Set,x=r.selectAll("trace").filter(Q=>Q._parsedProps?.schDisplayLabel),f=r.selectAll("group"),m=[r.schematic_group_id,...f.map(Q=>Q.schematic_group_id)],D=e.schematic_component.list().filter(Q=>m.includes(Q.schematic_group_id)),b=[],E=new Map,A=new Map;for(let Q of D){let de=Q.schematic_component_id,oe=[],Te=e.source_component.getWhere({source_component_id:Q.source_component_id}),Me=e.schematic_port.list({schematic_component_id:Q.schematic_component_id});for(let Ge of Me){let et=`${Te?.name??Q.schematic_component_id}.${Ge.pin_number}`;E.set(et,Ge.schematic_port_id),A.set(Ge.schematic_port_id,et)}for(let Ge of Me){let et=A.get(Ge.schematic_port_id);oe.push({pinId:et,x:Ge.center.x,y:Ge.center.y})}b.push({chipId:de,center:Q.center,width:Q.size.width,height:Q.size.height,pins:oe})}let B=new Set,w=new Map,P=new Map,j=new Map;for(let Q of D){let de=e.schematic_port.list({schematic_component_id:Q.schematic_component_id});for(let oe of de)B.add(oe.schematic_port_id),oe.source_port_id&&(w.set(oe.schematic_port_id,oe.source_port_id),P.set(oe.source_port_id,oe.schematic_port_id))}let O=new Set;r.subcircuit_id&&O.add(r.subcircuit_id);for(let Q of f)Q.subcircuit_id&&O.add(Q.subcircuit_id);let ee=e.source_trace.list().filter(Q=>{if(Q.subcircuit_id===r.subcircuit_id)return!0;for(let de of Q.connected_source_port_ids)if(P.has(de))return!0;return!1}).flatMap(Q=>Q.connected_source_net_ids);for(let Q of ee){let de=e.source_net.get(Q);de?.subcircuit_id&&O.add(de.subcircuit_id)}let W=[],re=new Map;for(let Q of e.source_trace.list()){if(Q.subcircuit_id&&!O.has(Q.subcircuit_id))continue;let de=(Q.connected_source_port_ids??[]).map(oe=>P.get(oe)).filter(oe=>!!oe&&B.has(oe));if(de.length>=2){let[oe,Te]=de.slice(0,2),Me=[oe,Te].sort().join("::");if(!re.has(Me)){re.set(Me,Q.source_trace_id);let Ge=Q.display_name??Q.source_trace_id;Q.subcircuit_connectivity_map_key&&(l.add(Q.subcircuit_connectivity_map_key),j.set(Ge,Q.subcircuit_connectivity_map_key),s.set(Q.subcircuit_connectivity_map_key,Ge)),W.push({pinIds:[oe,Te].map(et=>A.get(et)),netId:Ge})}}}let L=[];for(let Q of e.source_net.list().filter(de=>!de.subcircuit_id||O.has(de.subcircuit_id)))Q.subcircuit_connectivity_map_key&&(l.add(Q.subcircuit_connectivity_map_key),a.set(Q.subcircuit_connectivity_map_key,Q));let K=new Map;for(let[Q,de]of w){let oe=e.source_port.get(de);if(!oe?.subcircuit_connectivity_map_key)continue;let Te=oe.subcircuit_connectivity_map_key;l.add(Te),K.has(Te)||K.set(Te,[]),K.get(Te).push(Q)}for(let[Q,de]of K){let oe=a.get(Q);if(oe&&de.length>=2){let Te=String(oe.name||oe.source_net_id||Q);j.set(Te,Q),s.set(Q,Te);let Ge=.1*(.18/.18),et=Number((String(Te).length*Ge).toFixed(2));L.push({netId:Te,pinIds:de.map(dt=>A.get(dt)),netLabelWidth:et})}}let U=(()=>{let Q={},de=new Set(L.map(oe=>oe.netId));for(let oe of e.source_net.list().filter(Te=>!Te.subcircuit_id||O.has(Te.subcircuit_id)))oe.name&&de.has(oe.name)&&(oe.is_ground||oe.name.toLowerCase().startsWith("gnd")?Q[oe.name]=["y-"]:oe.is_power||oe.name.toLowerCase().startsWith("v")?Q[oe.name]=["y+"]:Q[oe.name]=["x-","x+"]);return Q})();return{inputProblem:{chips:b,directConnections:W,netConnections:L,availableNetLabelOrientations:U,maxMspPairDistance:r._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:E,pairKeyToSourceTraceId:re,sckToSourceNet:a,sckToUserNetId:s,userNetIdToSck:j,allSourceAndSchematicPortIdsInScope:B,schPortIdToSourcePortId:w,displayLabelTraces:x,allScks:l}}var Qi=1e-6;function jBe(r){let e=Math.abs(r.to.x-r.from.x),a=Math.abs(r.to.y-r.from.y);return e>=a}function WS(r,e){return Math.hypot(e.x-r.x,e.y-r.y)}function kBe(r,e,a){return{x:r.x+(e.x-r.x)*a,y:r.y+(e.y-r.y)*a}}function NBe(r,e,a){let s=WS(r,e);if(s<Qi)return 0;let l=((a.x-r.x)*(e.x-r.x)+(a.y-r.y)*(e.y-r.y))/((e.x-r.x)*(e.x-r.x)+(e.y-r.y)*(e.y-r.y));return Math.max(0,Math.min(1,l))*s}function $S(r,e,a,s){return r*s-e*a}function eXt(r,e,a,s){let l={x:e.x-r.x,y:e.y-r.y},d={x:s.x-a.x,y:s.y-a.y},x=$S(l.x,l.y,d.x,d.y),f={x:a.x-r.x,y:a.y-r.y},m=$S(f.x,f.y,l.x,l.y);if(Math.abs(x)<Qi&&Math.abs(m)<Qi||Math.abs(x)<Qi&&Math.abs(m)>=Qi)return null;let D=$S(f.x,f.y,d.x,d.y)/x,b=$S(f.x,f.y,l.x,l.y)/x;return D<-Qi||D>1+Qi||b<-Qi||b>1+Qi?null:{x:r.x+D*l.x,y:r.y+D*l.y}}function tXt(r,e=Qi){if(r.length===0)return r;r.sort((l,d)=>l.start-d.start);let a=[],s={...r[0]};for(let l=1;l<r.length;l++){let d=r[l];d.start<=s.end+e?s.end=Math.max(s.end,d.end):(a.push(s),s={...d})}return a.push(s),a}function rXt(r,e,a){let s=WS(r.from,r.to);if(s<Qi||e.length===0)return[r];let l=a/2,d=e.map(E=>({start:Math.max(0,E-l),end:Math.min(s,E+l)})).filter(E=>E.end-E.start>Qi),x=tXt(d),f=[],m=0,D={x:r.to.x-r.from.x,y:r.to.y-r.from.y},b=(E,A,B)=>{if(A-E<=Qi)return;let w=E/s,P=A/s;f.push({from:kBe(r.from,r.to,w),to:kBe(r.from,r.to,P),...B?{is_crossing:!0}:{}})};for(let E of x)E.start-m>Qi&&b(m,E.start,!1),b(E.start,E.end,!0),m=E.end;return s-m>Qi&&b(m,s,!1),f.length>0?f:[r]}function nXt(r,e={}){let a=e.crossSegmentLength??.075,s=e.tolerance??Qi,l=new Map,d=m=>`${m.traceIdx}:${m.edgeIdx}`,x=m=>r[m.traceIdx].edges[m.edgeIdx];for(let m=0;m<r.length;m++){let D=r[m];for(let b=0;b<D.edges.length;b++){let E=D.edges[b];for(let A=m;A<r.length;A++){let B=r[A];for(let w=A===m?b+1:0;w<B.edges.length;w++){let P=B.edges[w],j=eXt(E.from,E.to,P.from,P.to);if(!j)continue;let O=WS(E.from,E.to),z=WS(P.from,P.to);if(O<s||z<s)continue;let ee=NBe(E.from,E.to,j),W=NBe(P.from,P.to,j),re=ee<=s||Math.abs(O-ee)<=s||Number.isNaN(ee),L=W<=s||Math.abs(z-W)<=s||Number.isNaN(W);if(!re&&!L){let K=jBe(E),U=jBe(P),J;if(K!==U)J=K;else{let oe=Math.abs(E.to.x-E.from.x),Te=Math.abs(E.to.y-E.from.y),Me=Math.abs(P.to.x-P.from.x),Ge=Math.abs(P.to.y-P.from.y),et=oe-Te,dt=Me-Ge;J=et===dt?!0:et>dt}let Q=d({traceIdx:J?m:A,edgeIdx:J?b:w}),de=l.get(Q)??[];de.push(J?ee:W),l.set(Q,de)}}}}}let f=r.map(m=>({source_trace_id:m.source_trace_id,edges:[]}));for(let m=0;m<r.length;m++){let D=r[m];for(let b=0;b<D.edges.length;b++){let E=d({traceIdx:m,edgeIdx:b}),A=l.get(E)??[];if(A.length===0){f[m].edges.push(D.edges[b]);continue}let B=Array.from(new Set(A.map(P=>Number(P.toFixed(6))))).sort((P,j)=>P-j),w=rXt(D.edges[b],B,a);f[m].edges.push(...w)}}return f}var al=1e-6;function KS(r,e,a=al){return Math.abs(r-e)<=a}function Hg(r,e,a=al){return KS(r.x,e.x,a)&&KS(r.y,e.y,a)}function MBe(r,e,a,s=al){let l=Math.min(e.x,a.x)-s,d=Math.max(e.x,a.x)+s,x=Math.min(e.y,a.y)-s,f=Math.max(e.y,a.y)+s;return r.x<l||r.x>d||r.y<x||r.y>f?!1:Math.abs((a.x-e.x)*(r.y-e.y)-(a.y-e.y)*(r.x-e.x))<=s}function OBe(r,e=al){let a=new Map;for(let s of r){let l=`${s.x.toFixed(6)},${s.y.toFixed(6)}`;a.has(l)||a.set(l,s)}return Array.from(a.values())}function LBe(r){return{x:r.to.x-r.from.x,y:r.to.y-r.from.y}}function HW(r,e,a=al){let s=LBe(r),l=LBe(e),d=Math.hypot(s.x,s.y),x=Math.hypot(l.x,l.y);if(d<a||x<a)return!0;let f=s.x*l.y-s.y*l.x;return Math.abs(f)<=a*d*x}function GF(r,e,a=al){return r.edges.filter(s=>Hg(s.from,e,a)||Hg(s.to,e,a))}function $Be(r,e,a=al){for(let s of r.edges){if(Hg(s.from,e,a))return s.from;if(Hg(s.to,e,a))return s.to}return null}function aXt(r,e,a=al){let s=Hg(r.from,e,a)||KS(r.from.x,e.x,a)&&KS(r.from.y,e.y,a)?r.to:r.from,l=s.x-e.x,d=s.y-e.y;return Math.abs(l)<a&&Math.abs(d)<a?null:Math.abs(l)>=Math.abs(d)?l>=0?"right":"left":d>=0?"up":"down"}function Vg(r,e,a=al){let s=GF(r,e,a);if(s.length<2)return null;let l=s.map(E=>aXt(E,e,a)),d=l.includes("up"),x=l.includes("down"),f=l.includes("left"),m=l.includes("right"),D=d?"up":x?"down":null,b=m?"right":f?"left":null;return D&&b?`${D}-${b}`:null}function sXt(r,e={}){let a=e.tolerance??al,s={};for(let d of r)s[d.source_trace_id]=[];let l=r.map(d=>{let x=[];for(let f of d.edges)x.push(f.from,f.to);return OBe(x,a)});for(let d=0;d<r.length;d++){let x=r[d],f=l[d];for(let m=d+1;m<r.length;m++){let D=r[m],b=l[m];for(let E of f)for(let A of b)if(Hg(E,A,a)){let B=GF(x,E,a),w=GF(D,A,a),P=B.some(ee=>w.some(W=>!HW(ee,W,a))),j=Vg(x,E,a),O=Vg(D,A,a);P&&!(j!==null&&O!==null&&j===O)&&(s[x.source_trace_id].push(E),x.source_trace_id!==D.source_trace_id&&s[D.source_trace_id].push(A))}for(let E of f)for(let A of D.edges)if(MBe(E,A.from,A.to,a)){let w=GF(x,E,a).some(ee=>!HW(ee,A,a)),P=Vg(x,E,a),j=$Be(D,E,a*1e3),O=j?Vg(D,j,a):null;w&&!(P!==null&&O!==null&&P===O)&&(s[x.source_trace_id].push(E),x.source_trace_id!==D.source_trace_id&&s[D.source_trace_id].push(E))}for(let E of b)for(let A of x.edges)if(MBe(E,A.from,A.to,a)){let w=GF(D,E,a).some(ee=>!HW(A,ee,a)),P=Vg(D,E,a),j=$Be(x,E,a*1e3),O=j?Vg(x,j,a):null;w&&!(O!==null&&P!==null&&O===P)&&(s[D.source_trace_id].push(E),x.source_trace_id!==D.source_trace_id&&s[x.source_trace_id].push(E))}}}for(let d of Object.keys(s))s[d]=OBe(s[d],a);return s}var WW=(0,l9e.default)("Group_doInitialSchematicTraceRender");function iXt(r){let{group:e,solver:a,pinIdToSchematicPortId:s,userNetIdToSck:l}=r,{db:d}=e.root,x=a.traceOverlapShiftSolver?.correctedTraceMap,f=[];WW(`Traces inside SchematicTraceSolver output: ${Object.values(x??{}).length}`);for(let b of Object.values(x??{})){let E=b?.tracePath;if(!Array.isArray(E)||E.length<2){WW(`Skipping trace ${b?.pinIds.join(",")} because it has less than 2 points`);continue}let A=[];for(let P=0;P<E.length-1;P++)A.push({from:{x:E[P].x,y:E[P].y},to:{x:E[P+1].x,y:E[P+1].y}});let B=null,w;if(Array.isArray(b?.pins)&&b.pins.length===2){let P=s.get(b.pins[0]?.pinId),j=s.get(b.pins[1]?.pinId);if(P&&j){for(let O of[P,j])d.schematic_port.get(O)&&d.schematic_port.update(O,{is_connected:!0});w=l.get(String(b.userNetId))}}B||(B=`solver_${b?.mspPairId}`,w=l.get(String(b.userNetId))),f.push({source_trace_id:B,edges:A,subcircuit_connectivity_map_key:w})}WW(`Applying ${f.length} traces from SchematicTraceSolver output`);let m=nXt(f.map(b=>({source_trace_id:b.source_trace_id,edges:b.edges}))),D=sXt(m);for(let b of m)d.schematic_trace.insert({source_trace_id:b.source_trace_id,edges:b.edges,junctions:D[b.source_trace_id]??[],subcircuit_connectivity_map_key:f.find(E=>E.source_trace_id===b.source_trace_id)?.subcircuit_connectivity_map_key})}var oXt=r=>{switch(r){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"}},uXt=r=>{for(let a of r){let s=a._getDirectlyConnectedTraces();for(let l of s){let d=l._parsedProps.schDisplayLabel;if(d)return{name:d,wasAssignedDisplayLabel:!0}}}return{name:r.map(a=>a._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},KW=(0,d9e.default)("Group_doInitialSchematicTraceRender");function cXt(r){let{group:e,solver:a,sckToSourceNet:s,allScks:l,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,userNetIdToSck:f,pinIdToSchematicPortId:m,schematicPortIdsWithPreExistingNetLabels:D,schematicPortIdsWithRoutedTraces:b}=r,{db:E}=e.root,A=a.netLabelPlacementSolver?.netLabelPlacements??[],B=a.mspConnectionPairSolver.globalConnMap;for(let w of A){KW(`processing placement: ${w.netId}`);let P=B.getIdsConnectedToNet(w.globalConnNetId).find(Q=>f.get(Q)),j=f.get(P),O=w.anchorPoint,z=w.orientation,ee=oXt(z),W=j?s.get(j):void 0,re=w.pinIds.map(Q=>m.get(Q));if(re.some(Q=>D.has(Q))){KW(`skipping net label placement for "${w.netId}" REASON:schematic port has pre-existing net label`);continue}if(W){let Q=W.name,de=ax({anchor_position:O,anchor_side:ee,text:Q});E.schematic_net_label.insert({text:Q,anchor_position:O,center:de,anchor_side:ee,...W?.source_net_id?{source_net_id:W.source_net_id}:{}});continue}let L=e.selectAll("port").filter(Q=>Q._getSubcircuitConnectivityKey()===j),{name:K,wasAssignedDisplayLabel:U}=uXt(L);if(!U&&re.some(Q=>b.has(Q))){KW(`skipping net label placement for "${w.netId}" REASON:schematic port has routed traces and no display label`);continue}let J=ax({anchor_position:O,anchor_side:ee,text:K});E.schematic_net_label.insert({text:K,anchor_position:O,center:J,anchor_side:ee})}}var lXt=({allSourceAndSchematicPortIdsInScope:r,group:e,schPortIdToSourcePortId:a,sckToSourceNet:s,pinIdToSchematicPortId:l,schematicPortIdsWithPreExistingNetLabels:d})=>{let{db:x}=e.root;for(let f of Array.from(r)){let m=x.schematic_port.get(f);if(!m||m.is_connected)continue;let D=a.get(f);if(!D)continue;let E=x.source_port.get(D)?.subcircuit_connectivity_map_key;if(!E)continue;let A=s.get(E);if(!A||x.schematic_net_label.list().some(O=>Math.abs(O.anchor_position.x-m.center.x)<.1&&Math.abs(O.anchor_position.y-m.center.y)<.1?A.source_net_id&&O.source_net_id?O.source_net_id===A.source_net_id:O.text===(A.name||E):!1))continue;let w=A.name||A.source_net_id||E,P=HF(m.facing_direction||"right")||"right",j=ax({anchor_position:m.center,anchor_side:P,text:w});x.schematic_net_label.insert({text:w,anchor_position:m.center,center:j,anchor_side:P,...A.source_net_id?{source_net_id:A.source_net_id}:{}})}},dXt=r=>{let e=new Set,a=r.selectAll("netlabel");for(let s of a){let l=s._getConnectedPorts();for(let d of l)d.schematic_port_id&&e.add(d.schematic_port_id)}return e},pXt=({solver:r,pinIdToSchematicPortId:e})=>{let a=r.schematicTraceLinesSolver.solvedTracePaths,s=new Set;for(let l of a)for(let d of l.pinIds){let x=e.get(d);x&&s.add(x)}return s},xXt=(0,c9e.default)("Group_doInitialSchematicTraceRender"),fXt=r=>{if(!r.root?._featureMspSchematicTraceRouting||!r.isSubcircuit||r.root?.schematicDisabled)return;let{inputProblem:e,pinIdToSchematicPortId:a,pairKeyToSourceTraceId:s,sckToSourceNet:l,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,displayLabelTraces:f,allScks:m,userNetIdToSck:D}=QGt(r),b=dXt(r);xXt.enabled&&r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(e,null,2)});let E=new RSe(e);E.solve();let A=pXt({solver:E,pinIdToSchematicPortId:a});iXt({group:r,solver:E,pinIdToSchematicPortId:a,userNetIdToSck:D}),cXt({group:r,solver:E,sckToSourceNet:l,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,pinIdToSchematicPortId:a,allScks:m,userNetIdToSck:D,schematicPortIdsWithPreExistingNetLabels:b,schematicPortIdsWithRoutedTraces:A}),lXt({group:r,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,sckToSourceNet:l,pinIdToSchematicPortId:a,schematicPortIdsWithPreExistingNetLabels:b})},Wg=class extends es{constructor(){super(...arguments);q(this,"pcb_group_id",null);q(this,"schematic_group_id",null);q(this,"subcircuit_id",null);q(this,"_hasStartedAsyncAutorouting",!1);q(this,"_asyncAutoroutingResult",null);q(this,"unnamedElementCounter",{})}get config(){return{zodProps:oAe,componentName:"Group"}}doInitialSourceGroupRender(){let{db:e}=this.root,a=e.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit});this.source_group_id=a.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${a.source_group_id}`,e.source_group.update(a.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:e}=this.root;for(let a of this.children)e.source_component.update(a.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:e}=this.root,a=this.parent?.getGroup?.();if(a?.source_group_id&&e.source_group.update(this.source_group_id,{parent_source_group_id:a.source_group_id}),!this.isSubcircuit)return;let s=this.parent?.getSubcircuit?.()?.subcircuit_id;s&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:s})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.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:a.autorouter?{trace_clearance:a.autorouter.traceClearance}:void 0});this.pcb_group_id=s.pcb_group_id;for(let l of this.children)e.pcb_component.update(l.pcb_component_id,{pcb_group_id:s.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,a=this._parsedProps,s=ZS(this.children);if(this.pcb_group_id){let l=s.width,d=s.height,x=(s.minX+s.maxX)/2,f=(s.minY+s.maxY)/2;if(this.isSubcircuit){let{padLeft:b,padRight:E,padTop:A,padBottom:B}=this._resolvePcbPadding();l+=b+E,d+=A+B,x+=(E-b)/2,f+=(A-B)/2}let D=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0?e.pcb_group.get(this.pcb_group_id)?.center??{x,y:f}:{x,y:f};e.pcb_group.update(this.pcb_group_id,{width:Number(a.width??l),height:Number(a.height??d),center:D})}}getNextAvailableName(e){var a,s;return(a=this.unnamedElementCounter)[s=e.lowercaseComponentName]??(a[s]=1),`unnamed_${e.lowercaseComponentName}${this.unnamedElementCounter[e.lowercaseComponentName]++}`}_resolvePcbPadding(){let e=this._parsedProps,a=e.pcbLayout,s=E=>{let A=a?.[E],B=e[E];if(typeof A=="number")return A;if(typeof B=="number")return B},l=s("padding")??0,d=s("paddingX"),x=s("paddingY"),f=s("paddingLeft")??d??l,m=s("paddingRight")??d??l,D=s("paddingTop")??x??l,b=s("paddingBottom")??x??l;return{padLeft:f,padRight:m,padTop:D,padBottom:b}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:e}=this,{db:a}=this.root,s=e;if(!this.isSubcircuit)return;let l=s.manualEdits?.manual_trace_hints;if(l)for(let d of l)this.add(new fK({for:d.pcb_port_selector,offsets:d.offsets}))}doInitialSourceAddConnectivityMapKey(){jGt(this)}_areChildSubcircuitsRouted(){let e=this.selectAll("group").filter(a=>a.isSubcircuit);for(let a of e)if(a._shouldRouteAsync()&&!a._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let e=this._getAutorouterConfig();return e.groupMode==="sequential-trace"?!1:!!(e.local&&e.groupMode==="subcircuit"||!e.local)}_hasTracesToRoute(){let e=(0,Gg.default)("tscircuit:core:_hasTracesToRoute"),a=this.selectAll("trace");return e(`[${this.getString()}] has ${a.length} traces to route`),a.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:e}=this.root,a=(0,Gg.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),s=this._parsedProps,l=this._getAutorouterConfig(),d=l.serverUrl,x=l.serverMode,f=(b,E)=>(a("fetching",b),E.headers&&(E.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(b,E)),m=this.root.db.toArray().filter(b=>b.type.startsWith("source_")||b.type.startsWith("pcb_"));if(x==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:E}=await f(`${d}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:nK({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(A=>A.json());this._asyncAutoroutingResult=E,this._markDirty("PcbTraceRender");return}let{autorouting_result:b}=await f(`${d}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:m,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(E=>E.json());this._asyncAutoroutingResult=b,this._markDirty("PcbTraceRender");return}let{autorouting_job:D}=await f(`${d}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:m,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:l.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(b=>b.json());for(;;){let{autorouting_job:b}=await f(`${d}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:D.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(E=>E.json());if(b.is_finished){let{autorouting_job_output:E}=await f(`${d}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:D.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(A=>A.json());this._asyncAutoroutingResult={output_pcb_traces:E.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(b.has_error){let E=new UF(`Autorouting job failed: ${JSON.stringify(b.error)}`);throw e.pcb_autorouting_error.insert({pcb_error_id:D.autorouting_job_id,error_type:"pcb_autorouting_error",message:E.message}),E}await new Promise(E=>setTimeout(E,100))}}async _runLocalAutorouting(){let{db:e}=this.root,a=this._parsedProps,s=(0,Gg.default)("tscircuit:core:_runLocalAutorouting");s(`[${this.getString()}] starting local autorouting`);let l=this._getAutorouterConfig(),{simpleRouteJson:d}=nK({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(s.enabled){let m=aH(d);m.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(m)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:d});let x;l.algorithmFn?x=await l.algorithmFn(d):x=new _Gt(d,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity});let f=new Promise((m,D)=>{x.on("complete",b=>{s(`[${this.getString()}] local autorouting complete`),m(b.traces)}),x.on("error",b=>{s(`[${this.getString()}] local autorouting error: ${b.error.message}`),D(b.error)})});x.on("progress",m=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...m})}),x.start();try{let m=await f;this._asyncAutoroutingResult={output_pcb_traces:m},this._markDirty("PcbTraceRender")}catch(m){let{db:D}=this.root;throw D.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:m instanceof Error?m.message:String(m)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:m instanceof Error?m.message:String(m)},simpleRouteJson:d}),m}finally{x.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let e=(0,Gg.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){e(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}e(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){fXt(this)}updatePcbTraceRender(){let e=(0,Gg.default)("tscircuit:core:updatePcbTraceRender");if(e(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(e(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:a}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){e(`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){e(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:e}=this.root,{traces:a}=this._asyncAutoroutingResult.output_simple_route_json;if(a)for(let s of a){let l=e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:s.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;let{db:a}=this.root;for(let s of e)if(s.type==="pcb_trace"){if(s.subcircuit_id=this.subcircuit_id,s.connection_name){let l=s.connection_name;s.source_trace_id=l}a.pcb_trace.insert(s)}for(let s of e)if(s.type!=="pcb_via"&&s.type==="pcb_trace")for(let l of s.route)l.route_type==="via"&&a.pcb_via.insert({pcb_trace_id:s.pcb_trace_id,x:l.x,y:l.y,hole_diameter:.3,outer_diameter:.6,layers:[l.from_layer,l.to_layer],from_layer:l.from_layer,to_layer:l.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=s.schematic_group_id;for(let l of this.children)l.schematic_component_id&&e.schematic_component.update(l.schematic_component_id,{schematic_group_id:s.schematic_group_id})}_getSchematicLayoutMode(){let e=this._parsedProps;if(e.schLayout?.layoutMode==="none"||e.schLayout?.layoutMode==="relative")return"relative";if(e.schLayout?.matchAdapt)return"match-adapt";if(e.schLayout?.flex)return"flex";if(e.schLayout?.grid)return"grid";if(e.schMatchAdapt)return"match-adapt";if(e.schFlex)return"flex";if(e.schGrid)return"grid";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";if(e.relative||e.schRelative)return"relative";let a=this.children.some(l=>{let d=l._parsedProps;return d?.schX!==void 0||d?.schY!==void 0}),s=(e.manualEdits?.schematic_placements?.length??0)>0;return!a&&!s?"match-adapt":"relative"}doInitialSchematicLayout(){let e=this._getSchematicLayoutMode();e==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),e==="grid"&&this._doInitialSchematicLayoutGrid(),e==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){TGt(this)}_doInitialSchematicLayoutMatchpack(){IGt(this)}_doInitialSchematicLayoutGrid(){kGt(this)}_doInitialSchematicLayoutFlex(){NGt(this)}_getPcbLayoutMode(){let e=this._parsedProps;if(e.pcbRelative)return"none";if(e.pcbLayout?.matchAdapt)return"match-adapt";if(e.pcbLayout?.flex)return"flex";if(e.pcbLayout?.grid)return"grid";if(e.pcbLayout?.pack)return"pack";if(e.pcbFlex)return"flex";if(e.pcbGrid)return"grid";if(e.pcbPack||e.pack)return"pack";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";let a=e.pcbX!==void 0||e.pcbY!==void 0,s=(e.manualEdits?.pcb_placements?.length??0)>0;if(this.children.some(x=>{let f=x._parsedProps;return f?.pcbX!==void 0||f?.pcbY!==void 0}))return"none";let d=this.children.reduce((x,f)=>{let m=f._parsedProps,D=m?.pcbX!==void 0||m?.pcbY!==void 0;return x+(D?0:1)},0);return!a&&!s&&d>1?"pack":"none"}doInitialPcbLayout(){let e=this._getPcbLayoutMode();e==="grid"?this._doInitialPcbLayoutGrid():e==="pack"?this._doInitialPcbLayoutPack():e==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){MGt(this)}_doInitialPcbLayoutPack(){JGt(this)}_doInitialPcbLayoutFlex(){ZGt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,a=this._parsedProps;if(!a.border)return;let s=typeof a.schWidth=="number"?a.schWidth:void 0,l=typeof a.schHeight=="number"?a.schHeight:void 0,d=typeof a.schPadding=="number"?a.schPadding:0,x=typeof a.schPaddingLeft=="number"?a.schPaddingLeft:d,f=typeof a.schPaddingRight=="number"?a.schPaddingRight:d,m=typeof a.schPaddingTop=="number"?a.schPaddingTop:d,D=typeof a.schPaddingBottom=="number"?a.schPaddingBottom:d,b=this.schematic_group_id?e.schematic_group.get(this.schematic_group_id):null;if(b&&(s===void 0&&typeof b.width=="number"&&(s=b.width),l===void 0&&typeof b.height=="number"&&(l=b.height)),s===void 0||l===void 0)return;let E=b?.center??this._getGlobalSchematicPositionBeforeLayout(),A=E.x-s/2-x,B=E.y-l/2-D,w=s+x+f,P=l+m+D;e.schematic_box.insert({width:w,height:P,x:A,y:B,is_dashed:a.border?.dashed??!1})}_determineSideFromPosition(e,a){if(!e.center||!a.center)return"left";let s=e.center.x-a.center.x,l=e.center.y-a.center.y;return Math.abs(s)>Math.abs(l)?s>0?"right":"left":l>0?"bottom":"top"}_calculateSchematicBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let a=1/0,s=-1/0,l=1/0,d=-1/0;for(let f of e)a=Math.min(a,f.centerX),s=Math.max(s,f.centerX),l=Math.min(l,f.centerY),d=Math.max(d,f.centerY);let x=2;return{minX:a-x,maxX:s+x,minY:l-x,maxY:d+x}}_getAutorouterConfig(){let e=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return YGt(e)}_getSubcircuitLayerCount(){let e=this.getInheritedProperty("layers");return typeof e=="number"?e:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(this.isSubcircuit){let a=new Map;for(let s of this.children)if(!s.isSubcircuit&&s._parsedProps.name){let l=a.get(s._parsedProps.name)||[];l.push(s),a.set(s._parsedProps.name,l)}for(let[s,l]of a.entries())l.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${s}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:l.map(d=>d.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:e}=this.root,a=e;for(let s of a.schematic_net_label.list()){let l=a.source_net.get(s.source_net_id),d=s.text||l?.name||"";if(s.anchor_side==="top"&&/^gnd/i.test(d)){a.schematic_net_label.update(s.schematic_net_label_id,{symbol_name:"rail_down"});continue}s.anchor_side==="bottom"&&/^v/i.test(d)&&a.schematic_net_label.update(s.schematic_net_label_id,{symbol_name:"rail_up"})}}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(e){return super._repositionOnPcb(e)}},zBe=(r,e,a)=>{let s=Math.min(a,r/2,e/2),l=Math.max(1,Math.ceil(Math.PI/2*s)),d=Math.PI/2/l,x=r/2,f=e/2,m=[];m.push({x:-x+s,y:-f}),m.push({x:x-s,y:-f});for(let D=1;D<=l;D++){let b=-Math.PI/2+D*d;m.push({x:x-s+s*Math.cos(b),y:-f+s+s*Math.sin(b)})}m.push({x,y:f-s});for(let D=1;D<=l;D++){let b=0+D*d;m.push({x:x-s+s*Math.cos(b),y:f-s+s*Math.sin(b)})}m.push({x:-x+s,y:f});for(let D=1;D<=l;D++){let b=Math.PI/2+D*d;m.push({x:-x+s+s*Math.cos(b),y:f-s+s*Math.sin(b)})}m.push({x:-x,y:-f+s});for(let D=1;D<=l;D++){let b=Math.PI+D*d;m.push({x:-x+s+s*Math.cos(b),y:-f+s+s*Math.sin(b)})}return m},p9e=class extends Wg{constructor(){super(...arguments);q(this,"pcb_board_id",null);q(this,"_drcChecksComplete",!1);q(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:SY}}get boardThickness(){let{_parsedProps:e}=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:e}=this.root,{_parsedProps:a}=this;if(a.width&&a.height)return;let s=1/0,l=1/0,d=-1/0,x=-1/0,f=s9e(e,this.subcircuit_id),m=new Set([this.subcircuit_id,...f]),D=e.pcb_component.list().filter(re=>re.subcircuit_id&&m.has(re.subcircuit_id)),b=e.pcb_group.list().filter(re=>re.subcircuit_id&&m.has(re.subcircuit_id)),E=!1,A=(re,L,K)=>{L===0||K===0||(E=!0,s=Math.min(s,re.x-L/2),l=Math.min(l,re.y-K/2),d=Math.max(d,re.x+L/2),x=Math.max(x,re.y+K/2))};for(let re of D)A(re.center,re.width,re.height);for(let re of b)A(re.center,re.width,re.height);let B=2,w=E?d-s+B*2:0,P=E?x-l+B*2:0,j={x:E?(s+d)/2+(a.outlineOffsetX??0):a.outlineOffsetX??0,y:E?(l+x)/2+(a.outlineOffsetY??0):a.outlineOffsetY??0},O=a.width??w,z=a.height??P,ee=a.outline;!ee&&a.borderRadius!=null&&O>0&&z>0&&(ee=zBe(O,z,a.borderRadius));let W={width:O,height:z,center:j};ee&&(W.outline=ee.map(re=>({x:re.x+(a.outlineOffsetX??0),y:re.y+(a.outlineOffsetY??0)}))),e.pcb_board.update(this.pcb_board_id,W)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let e=this.root?.platform;if(!e?.printBoardInformationToSilkscreen)return;let a=this.root.db.pcb_board.get(this.pcb_board_id);if(!a)return;let s=[];if(e.projectName&&s.push(e.projectName),e.version&&s.push(`v${e.version}`),e.url&&s.push(e.url),s.length===0)return;let l=s.join(`
|
|
1038
|
-
`),f={x:a.center.x+a.width/2-.25,y:a.center.y-a.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:l,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:f})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=a.width??0,l=a.height??0,d={x:(a.pcbX??0)+(a.outlineOffsetX??0),y:(a.pcbY??0)+(a.outlineOffsetY??0)};if(a.outline){let m=a.outline.map(w=>w.x),D=a.outline.map(w=>w.y),b=Math.min(...m),E=Math.max(...m),A=Math.min(...D),B=Math.max(...D);s=E-b,l=B-A,d={x:(b+E)/2+(a.outlineOffsetX??0),y:(A+B)/2+(a.outlineOffsetY??0)}}let x=a.outline;!x&&a.borderRadius!=null&&s>0&&l>0&&(x=zBe(s,l,a.borderRadius));let f=e.pcb_board.insert({center:d,thickness:this.boardThickness,num_layers:this.allLayers.length,width:s,height:l,outline:x?.map(m=>({x:m.x+(a.outlineOffsetX??0),y:m.y+(a.outlineOffsetY??0)})),material:a.material});this.pcb_board_id=f.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:e}=this.root;this.pcb_board_id&&(e.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return Si()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let a=TSe(e.toArray());for(let d of a)e.pcb_trace_error.insert(d);let s=wSe(e.toArray());for(let d of s)e.pcb_port_not_connected_error.insert(d);let l=jSe(e.toArray());for(let d of l)e.pcb_component_outside_board_error.insert(d)}_emitRenderLifecycleEvent(e,a){super._emitRenderLifecycleEvent(e,a),a==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e})}},hXt=new Proxy({},{get:(r,e)=>e}),dd=hXt,x9e=class extends es{constructor(){super(...arguments);q(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:gAe,sourceFtype:dd.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let e=this.props.capacitance,a=typeof e=="string"?e:`${Ns(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${a}/${Ns(this._parsedProps.maxVoltageRating)}V`:a}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new qc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new qc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,capacitance:a.capacitance,max_voltage_rating:a.maxVoltageRating,max_decoupling_trace_length:a.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!a.polarized});this.source_component_id=s.source_component_id}},QS=class extends es{constructor(e){super(e);q(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:og,shouldRenderAsSchematicBox:!0}}initPorts(e={}){super.initPorts(e);let{_parsedProps:a}=this;if(a.externallyConnectedPins){let s=new Set;for(let[l,d]of a.externallyConnectedPins)s.add(l),s.add(d);for(let l of s)if(!this.children.find(x=>x instanceof Ni&&x.isMatchingAnyOf([l]))){let x=l.match(/^pin(\d+)$/);if(x){let f=parseInt(x[1]);this.add(new Ni({pinNumber:f,aliases:[l]}))}else this.add(new Ni({name:l,aliases:[l]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:e}=this;e?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=s.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:e}=this;if(e.externallyConnectedPins)for(let[a,s]of e.externallyConnectedPins)this.add(new qc({from:`${this.getSubcircuitSelector()} > port.${a}`,to:`${this.getSubcircuitSelector()} > port.${s}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:e}=this.root,{pinAttributes:a}=this.props;if(!a)return;let s=null,l=null,d,x=this.selectAll("port");for(let E of x)for(let A of E.getNameAndAliases())if(a[A]){let B=a[A];B.providesPower&&(s=E,d=B.providesVoltage),B.providesGround&&(l=E)}if(!s||!l||d===void 0)return;let f=e.source_port.get(s.source_port_id);if(!f?.subcircuit_connectivity_map_key)return;let m=e.source_port.get(l.source_port_id);if(!m?.subcircuit_connectivity_map_key)return;let D=e.source_net.getWhere({subcircuit_connectivity_map_key:f.subcircuit_connectivity_map_key}),b=e.source_net.getWhere({subcircuit_connectivity_map_key:m.subcircuit_connectivity_map_key});!D||!b||e.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:s.source_port_id,positive_source_net_id:D.source_net_id,negative_source_port_id:l.source_port_id,negative_source_net_id:b.source_net_id,voltage:d})}},f9e=class extends QS{constructor(r){super(r)}get config(){return{...super.config,componentName:"Pinout",zodProps:uAe}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:e.manufacturerPartNumber,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=a.source_component_id}},h9e=class extends es{constructor(){super(...arguments);q(this,"pos",this.portMap.pin1);q(this,"anode",this.portMap.pin1);q(this,"neg",this.portMap.pin2);q(this,"cathode",this.portMap.pin2)}get config(){let e={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},a=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:a?e[a]:this.props.symbolName??"diode",componentName:"Diode",zodProps:PAe,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=s.source_component_id}},m9e=class extends es{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:lAe,sourceFtype:dd.simple_fuse}}_getSchematicSymbolDisplayValue(){let r=this._parsedProps.currentRating,e=this._parsedProps.voltageRating,a=typeof r=="string"?parseFloat(r):r,s=typeof e=="string"?parseFloat(e):e;return`${Ns(a)}A / ${Ns(s)}V`}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=typeof e.currentRating=="string"?parseFloat(e.currentRating):e.currentRating,s=typeof e.voltageRating=="string"?parseFloat(e.voltageRating):e.voltageRating,l=r.source_component.insert({name:this.name,ftype:dd.simple_fuse,current_rating_amps:a,voltage_rating_volts:s,display_current_rating:`${Ns(a)}A`,display_voltage_rating:`${Ns(s)}V`});this.source_component_id=l.source_component_id}},g9e=class extends es{constructor(){super(...arguments);q(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:BY,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let a=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),s=this._parsedProps.schDirection??"right";return{leftSize:s==="left"?a:0,rightSize:s==="right"?a:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,a=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),s={};for(let x=0;x<a.length;x++){let f=a[x],m=e.source_port.get(f.source_port_id),D="";if(typeof m?.pin_number=="number")D=m.pin_number.toString();else if(Array.isArray(m?.port_hints)){let b=m.port_hints.find(E=>/^(pin)?\d+$/.test(E));b&&(/^pin\d+$/.test(b)?D=b.replace(/^pin/,""):D=b)}s[D]=f.pcb_port_id}let l=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),d=x=>{if(x&&typeof x=="string"&&x.startsWith("{PIN")){let f=x.replace("{PIN","").replace("}","");return s[f]||x}return x};for(let x of l)if(x.route)for(let f of x.route)f.route_type==="wire"&&(f.start_pcb_port_id=d(f.start_pcb_port_id),f.end_pcb_port_id=d(f.end_pcb_port_id))}},D9e=class extends es{constructor(){super(...arguments);q(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(e){return this.selectOne(`port.${e}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let e=this.children.filter(a=>a.componentName==="Port").map(a=>a.name);return e.length>0?[e]:[]}return this._parsedProps.bridgedPins??[]}get config(){let e=this._parsedProps??this.props,a=e.pinCount;if(e.pinCount==null&&!e.footprint&&(a=2),e.pinCount==null){let d=(e.bridgedPins??[]).flat().map(D=>this._getPinNumberFromBridgedPinName(D)).filter(D=>D!==null),x=d.length>0?Math.max(...d):0,f=e.pinLabels?Object.keys(e.pinLabels).length:0,m=Math.max(x,f);(m===2||m===3)&&(a=m),a==null&&e.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(a=this.getPortsFromFootprint().length)}let s="";a?s+=`solderjumper${a}`:s="solderjumper";let l=[];return Array.isArray(e.bridgedPins)&&e.bridgedPins.length>0?l=Array.from(new Set(e.bridgedPins.flat().map(d=>this._getPinNumberFromBridgedPinName(d)).filter(d=>d!==null))).sort((d,x)=>d-x):e.bridged&&a&&(l=Array.from({length:a},(d,x)=>x+1)),l.length>0&&(s+=`_bridged${l.join("")}`),{schematicSymbolName:e.symbolName??s,componentName:"SolderJumper",zodProps:cAe,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let a=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);a==null&&!this._parsedProps.footprint&&(a=2);let s=this._parsedProps.schDirection??"right";return{leftSize:s==="left"?a:0,rightSize:s==="right"?a:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,a=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),s={};for(let x=0;x<a.length;x++){let f=a[x],m=e.source_port.get(f.source_port_id),D="";if(typeof m?.pin_number=="number")D=m.pin_number.toString();else if(Array.isArray(m?.port_hints)){let b=m.port_hints.find(E=>/^(pin)?\d+$/.test(E));b&&(/^pin\d+$/.test(b)?D=b.replace(/^pin/,""):D=b)}s[D]=f.pcb_port_id}let l=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),d=x=>{if(x&&typeof x=="string"&&x.startsWith("{PIN")){let f=x.replace("{PIN","").replace("}","");return s[f]||x}return x};for(let x of l)if(x.route)for(let f of x.route)f.route_type==="wire"&&(f.start_pcb_port_id=d(f.start_pcb_port_id),f.end_pcb_port_id=d(f.end_pcb_port_id))}},y9e=class extends es{constructor(){super(...arguments);q(this,"pos",this.portMap.pin1);q(this,"anode",this.portMap.pin1);q(this,"neg",this.portMap.pin2);q(this,"cathode",this.portMap.pin2)}get config(){let e={laser:"laser_diode"},a=this.props.laser?"laser":null;return{schematicSymbolName:a?e[a]:this.props.symbolName??"led",componentName:"Led",zodProps:jAe,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_led",name:this.name,wave_length:a.wavelength,color:a.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=s.source_component_id}},b9e=class extends es{constructor(){super(...arguments);q(this,"pos",this.portMap.pin1);q(this,"positive",this.portMap.pin1);q(this,"neg",this.portMap.pin2);q(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:XAe,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Ni({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Ni({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:a.voltage,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=s.source_component_id}},mXt=gs.extend({voltage:Us.optional(),frequency:Oc.optional(),peakToPeakVoltage:Us.optional(),waveShape:v.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Vn.optional(),dutyCycle:v.number().optional()}),F9e=class extends es{constructor(){super(...arguments);q(this,"terminal1",this.portMap.terminal1);q(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:mXt,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(e){if(!e.startsWith("Pcb"))for(let a of this.children)a.runRenderPhaseForChildren(e),a.runRenderPhase(e)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:a.voltage,frequency:a.frequency,peak_to_peak_voltage:a.peakToPeakVoltage,wave_shape:a.waveShape,phase:a.phase,duty_cycle:a.dutyCycle,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialSimulationRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.portMap.terminal1,l=this.portMap.terminal2;e.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:s.source_port_id,terminal2_source_port_id:l.source_port_id,voltage:a.voltage,frequency:a.frequency,peak_to_peak_voltage:a.peakToPeakVoltage,wave_shape:a.waveShape,phase:a.phase,duty_cycle:a.dutyCycle})}},E9e=class extends es{constructor(){super(...arguments);q(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:pAe,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${Ns(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 qc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new qc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new qc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new qc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,resistance:a.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}},gXt=["leftedge","rightedge","topedge","bottomedge","center"],v9e=class extends Qn{get config(){return{componentName:"Constraint",zodProps:yAe}}constructor(r){if(super(r),("xdist"in r||"ydist"in r)&&!("edgeToEdge"in r)&&!("centerToCenter"in r))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in r&&r.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let r=[],e=this.getPrimitiveContainer();function a(s){let l=s.split(" ").pop(),d=gXt.includes(l)?l:void 0,x=d?s.replace(` ${d}`,""):s,f=e.selectOne(x,{pcbPrimitive:!0});f&&r.push({selector:s,component:f,componentSelector:x,edge:d})}for(let s of["left","right","top","bottom"])s in this._parsedProps&&a(this._parsedProps[s]);if("for"in this._parsedProps)for(let s of this._parsedProps.for)a(s);return{componentsWithSelectors:r}}},C9e=class extends Qn{constructor(){super(...arguments);q(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:OAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,a=this.getSubcircuit(),{_parsedProps:s}=this,l=s.layer??"top";if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenPath. Must be "top" or "bottom".`);let d=this._computePcbGlobalTransformBeforeLayout(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,f=e.pcb_fabrication_note_path.insert({pcb_component_id:x,layer:l,color:s.color,route:s.route.map(m=>{let D=as(d,{x:m.x,y:m.y});return{...m,x:D.x,y:D.y}}),stroke_width:s.strokeWidth??.1,subcircuit_id:a?.subcircuit_id??void 0});this.fabrication_note_path_id=f.pcb_fabrication_note_path_id}},_9e=class extends Qn{get config(){return{componentName:"FabricationNoteText",zodProps:MAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:r}=this.root,{_parsedProps:e}=this,a=this.getPrimitiveContainer(),s=this.getSubcircuit();r.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:e.pcbX??0,y:e.pcbY??0},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:e.text??"",pcb_component_id:a.pcb_component_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},A9e=class extends Wg{constructor(r){super({...r,subcircuit:!0})}},R9e=class extends Wg{constructor(r){super({...r,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:r}=this.root,e=this._parsedProps;if(!this.pcb_group_id)return;let a=r.pcb_group.get(this.pcb_group_id),s=e.paddingLeft??e.padding??0,l=e.paddingRight??e.padding??0,d=e.paddingTop??e.padding??0,x=e.paddingBottom??e.padding??0;r.pcb_group.update(this.pcb_group_id,{width:a.width+s+l,height:a.height+d+x,center:{x:a.center.x+(l-s)/2,y:a.center.y+(d-x)/2}})}},S9e=class extends Qn{constructor(){super(...arguments);q(this,"pcb_breakout_point_id",null);q(this,"matchedPort",null);q(this,"matchedNet",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:zAe}}_matchConnection(){let{connection:e}=this._parsedProps,a=this.getSubcircuit();a&&(this.matchedPort=a.selectOne(e,{type:"port"}),this.matchedPort||(this.matchedNet=a.selectOne(e,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${e}"`))}_getSourceTraceIdForPort(e){let{db:a}=this.root;return a.source_trace.list().find(l=>l.connected_source_port_ids.includes(e.source_port_id))?.source_trace_id}_getSourceNetIdForPort(e){let{db:a}=this.root;return a.source_trace.list().find(l=>l.connected_source_port_ids.includes(e.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;this._matchConnection();let{pcbX:a=0,pcbY:s=0}=this._parsedProps,l=this.parent?.getGroup(),d=this.getSubcircuit();if(!l||!l.pcb_group_id)return;let x=e.pcb_breakout_point.insert({pcb_group_id:l.pcb_group_id,subcircuit_id:d?.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:a,y:s});this.pcb_breakout_point_id=x.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:e=0,pcbY:a=0}=this._parsedProps;return{center:{x:e,y:a},bounds:{left:e,top:a,right:e,bottom:a},width:0,height:0}}_setPositionFromLayout(e){let{db:a}=this.root;this.pcb_breakout_point_id&&a.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:e.x,y:e.y})}getPcbSize(){return{width:0,height:0}}},B9e=class extends Qn{constructor(){super(...arguments);q(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:RAe}}_getAnchorSide(){let{_parsedProps:e}=this;if(e.anchorSide)return e.anchorSide;if(!this._resolveConnectsTo())return"right";let s=this._getGlobalSchematicPositionBeforeLayout(),l=this._getConnectedPorts();if(l.length===0)return"right";let d=l[0]._getGlobalSchematicPositionBeforeLayout(),x=d.x-s.x,f=d.y-s.y;if(Math.abs(x)>Math.abs(f)){if(x>0)return"right";if(x<0)return"left"}else{if(f>0)return"top";if(f<0)return"bottom"}return"right"}_getConnectedPorts(){let e=this._resolveConnectsTo();if(!e)return[];let a=[];for(let s of e){let l=this.getSubcircuit().selectOne(s);l&&a.push(l)}return a}computeSchematicPropsTransform(){let{_parsedProps:e}=this;if(e.schX===void 0&&e.schY===void 0){let a=this._getConnectedPorts();if(a.length>0){let s=a[0]._getGlobalSchematicPositionBeforeLayout(),l=as(this.parent?.computeSchematicGlobalTransform?.()??Si(),{x:0,y:0});return Ma(s.x-l.x,s.y-l.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalSchematicPositionBeforeLayout(),l=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),d=a.anchorSide??"right",x=ax({anchor_position:s,anchor_side:d,text:a.net}),f=e.schematic_net_label.insert({text:a.net,source_net_id:l.source_net_id,anchor_position:s,center:x,anchor_side:this._getAnchorSide()});this.source_net_label_id=f.source_net_id}_resolveConnectsTo(){let{_parsedProps:e}=this,a=e.connectsTo??e.connection;if(Array.isArray(a))return a;if(typeof a=="string")return[a]}_getNetName(){let{_parsedProps:e}=this;return e.net}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;e.net&&uK(this,[`net.${e.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let e=this._resolveConnectsTo();if(e)for(let a of e)this.add(new qc({from:a,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:e}=this.root,a=this._resolveConnectsTo();if(!a||a.length===0)return;let s=this._getGlobalSchematicPositionBeforeLayout(),l=this._getAnchorSide(),x={left:"x-",right:"x+",top:"y+",bottom:"y-"}[l],f=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let m of a){let D=this.getSubcircuit().selectOne(m,{type:"port"});if(!D||!D.schematic_port_id)continue;let b=!1;if(f?.source_net_id){let O=e.source_trace.list().find(z=>z.connected_source_net_ids?.includes(f.source_net_id)&&z.connected_source_port_ids?.includes(D.source_port_id??""));if(O&&(b=e.schematic_trace.list().some(z=>z.source_trace_id===O.source_trace_id)),b)continue}let E=D._getGlobalSchematicPositionAfterLayout(),A=eK(D.facingDirection??"right")??"x+",B=dg({x:E.x,y:E.y,facingDirection:A},{x:s.x,y:s.y,facingDirection:x});if(!Array.isArray(B)||B.length<2)continue;let w=[];for(let O=0;O<B.length-1;O++)w.push({from:{x:B[O].x,y:B[O].y},to:{x:B[O+1].x,y:B[O+1].y}});let P,j;if(f?.source_net_id&&D.source_port_id){let O=e.source_trace.list().find(z=>z.connected_source_net_ids?.includes(f.source_net_id)&&z.connected_source_port_ids?.includes(D.source_port_id));P=O?.source_trace_id,j=O?.subcircuit_connectivity_map_key||e.source_net.get(f.source_net_id)?.subcircuit_connectivity_map_key}e.schematic_trace.insert({source_trace_id:P,edges:w,junctions:[],subcircuit_connectivity_map_key:j}),e.schematic_port.update(D.schematic_port_id,{is_connected:!0})}}},w9e=class extends Qn{constructor(){super(...arguments);q(this,"pcb_silkscreen_circle_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:r4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenCircle. Must be "top" or "bottom".`);let d=this._computePcbGlobalTransformBeforeLayout(),x=this.getSubcircuit(),f=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=e.pcb_silkscreen_circle.insert({pcb_component_id:f,layer:l,center:{x:a.pcbX??0,y:a.pcbY??0},radius:a.radius,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:a.strokeWidth??.1});this.pcb_silkscreen_circle_id=m.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:e}=this,a=e.radius*2;return{width:a,height:a}}},T9e=class extends Qn{constructor(){super(...arguments);q(this,"pcb_silkscreen_rect_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:t4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenRect. Must be "top" or "bottom".`);let d=this.getSubcircuit(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,f=e.pcb_silkscreen_rect.insert({pcb_component_id:x,layer:l,center:{x:a.pcbX??0,y:a.pcbY??0},width:a.width,height:a.height,subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:a.strokeWidth??.1});this.pcb_silkscreen_rect_id=f.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},P9e=class extends Qn{constructor(){super(...arguments);q(this,"pcb_silkscreen_line_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:e4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenLine. Must be "top" or "bottom".`);let d=this.getSubcircuit(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,f=e.pcb_silkscreen_line.insert({pcb_component_id:x,layer:l,x1:a.x1,y1:a.y1,x2:a.x2,y2:a.y2,stroke_width:a.strokeWidth??.1,subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:d?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=f.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:e}=this,a=Math.abs(e.x2-e.x1),s=Math.abs(e.y2-e.y1);return{width:a,height:s}}},I9e=class extends Qn{constructor(e){super(e);q(this,"pcb_via_id",null);q(this,"matchedPort",null);q(this,"isPcbPrimitive",!0);q(this,"source_manually_placed_via_id",null);let a=this._getLayers();this._parsedProps.layers=a,this.initPorts()}get config(){return{componentName:"Via",zodProps:LAe}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:e}=this;return{width:e.outerDiameter,height:e.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_via.get(this.pcb_via_id),s=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-s.width/2,top:a.y-s.height/2,right:a.x+s.width/2,bottom:a.y+s.height/2},width:s.width,height:s.height}}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}_getLayers(){let{fromLayer:e="top",toLayer:a="bottom"}=this._parsedProps;return e===a?[e]:[e,a]}initPorts(){let e=this._parsedProps.layers;for(let s of e){let l=new Ni({name:s,layer:s});l.registerMatch(this),this.add(l)}let a=new Ni({name:"pin1"});a.registerMatch(this),this.add(a)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalPcbPositionBeforeLayout(),l=this.getSubcircuit(),d=e.pcb_component.insert({center:s,width:a.outerDiameter,height:a.outerDiameter,layer:a.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:l?.subcircuit_id??void 0});this.pcb_component_id=d.pcb_component_id}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getGroup(),l=this.getSubcircuit(),d=e.source_manually_placed_via.insert({source_group_id:s?.source_group_id,source_net_id:a.net??"",subcircuit_id:l?.subcircuit_id??void 0});this.source_component_id=d.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalPcbPositionBeforeLayout(),l=this.getSubcircuit(),d=e.pcb_via.insert({x:s.x,y:s.y,hole_diameter:a.holeDiameter,outer_diameter:a.outerDiameter,layers:["bottom","top"],from_layer:a.fromLayer||"bottom",to_layer:a.toLayer||"top",subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_via_id=d.pcb_via_id}},j9e=class extends Qn{constructor(){super(...arguments);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:UAe}}getPcbSize(){return{width:0,height:0}}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit().selectOne(a.connectsTo);if(!s||!s.source_net_id){this.renderError(`Net "${a.connectsTo}" not found for copper pour`);return}let l=e.pcb_board.list()[0];if(!l){this.renderError("No board found for copper pour");return}let d;l.outline&&l.outline.length>0?d=new se.Polygon(l.outline.map(B=>se.point(B.x,B.y))):d=new se.Polygon(new se.Box(l.center.x-l.width/2,l.center.y-l.height/2,l.center.x+l.width/2,l.center.y+l.height/2).toPoints());let x=eu(e.toArray()),f=pK(e.toArray(),x).filter(B=>B.layers.includes(a.layer));for(let B of e.pcb_trace.list())if(B.route)for(let w=0;w<B.route.length-1;w++){let P=B.route[w],j=B.route[w+1];if(P.route_type!=="wire"||j.route_type!=="wire"||P.layer!==a.layer)continue;let O=P.width;if(O===0)continue;let z=Math.hypot(P.x-j.x,P.y-j.y);if(z===0)continue;let ee=(P.x+j.x)/2,W=(P.y+j.y)/2,re=Math.atan2(j.y-P.y,j.x-P.x)*180/Math.PI,K=t9e({center:{x:ee,y:W},width:z,height:O,rotation:re});for(let U of K)f.push({type:"rect",layers:[P.layer],center:U.center,width:U.width,height:U.height,connectedTo:B.source_trace_id?[B.source_trace_id]:[],obstacle_type:"trace"})}let m=[],D=[],b=a.traceMargin??.2,E=a.padMargin??.2;for(let B of f){if(B.connectedTo.some(O=>x.areIdsConnected(O,s.source_net_id)))continue;if(B.type==="oval"&&B.width===B.height){let O=B.width/2+E;D.push({center:B.center,radius:O});continue}if(B.type==="rect"&&B.width===B.height&&B.connectedTo.length===0){let O=B.width/2;D.push({center:B.center,radius:O});continue}let P=b,j=new se.Box(B.center.x-B.width/2-P,B.center.y-B.height/2-P,B.center.x+B.width/2+P,B.center.y+B.height/2+P);m.push(new se.Polygon(j.toPoints()))}let A=d;if(m.length>0){let B=m.reduce((w,P)=>se.BooleanOperations.unify(w,P));B&&!B.isEmpty()&&(A=se.BooleanOperations.subtract(d,B))}Array.isArray(A)||(A=[A]);for(let B of A){let w=B.splitToIslands();for(let P of w){if(P.isEmpty())continue;let j=[...P.faces],O=j.find(L=>L.orientation()===se.ORIENTATION.CCW),z=j.filter(L=>L.orientation()===se.ORIENTATION.CW);if(!O)continue;if(!e.pcb_copper_pour){this.renderError("db.pcb_copper_pour not found. The database schema may be outdated.");return}let ee=L=>L.edges.map(K=>{let U={x:K.start.x,y:K.start.y};if(K.isArc){let J=Math.tan(K.shape.sweep/4);Math.abs(J)>1e-9&&(U.bulge=J)}return U});O.reverse();let W=ee(O),re=z.map(L=>(L.reverse(),{vertices:ee(L)}));for(let L of D){let K=se.point(L.center.x,L.center.y);P.contains(K)&&re.push({vertices:[{x:L.center.x,y:L.center.y-L.radius,bulge:1},{x:L.center.x,y:L.center.y+L.radius,bulge:1}]})}e.pcb_copper_pour.insert({shape:"brep",layer:a.layer,brep_shape:{outer_ring:{vertices:W},inner_rings:re},source_net_id:s.source_net_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0})}}})}},k9e=class extends es{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:_Ae,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=a.source_component_id}},N9e=class extends es{_getPcbRotationBeforeLayout(){let r=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+r}get config(){return{componentName:"PinHeader",zodProps:AAe,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let r=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),e=this._parsedProps.holeDiameter,a=this._parsedProps.platedDiameter,s=this._parsedProps.pitch,l=this._parsedProps.showSilkscreenPinLabels;if(r>0){let d;if(s)!e&&!a?d=`pinrow${r}_p${s}`:d=`pinrow${r}_p${s}_id${e}_od${a}`;else if(!e&&!a)d=`pinrow${r}`;else return null;return l!==!0&&(d+="_nopinlabels"),d}return null}initPorts(){let r=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let e=1;e<=r;e++){let a=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[e-1]:this._parsedProps.pinLabels?.[`pin${e}`];if(a){let s=Array.isArray(a)?a[0]:a,l=Array.isArray(a)?a.slice(1):[];this.add(new Ni({pinNumber:e,name:s,aliases:[`pin${e}`,...l]}))}else this.add(new Ni({pinNumber:e,name:`pin${e}`}))}}_getSchematicPortArrangement(){let r=this._parsedProps.pinCount??1,e=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",a=this._parsedProps.schPinArrangement;return e==="left"?{leftSide:{direction:a?.leftSide?.direction??"top-to-bottom",pins:a?.leftSide?.pins??Array.from({length:r},(s,l)=>`pin${l+1}`)}}:{rightSide:{direction:a?.rightSide?.direction??"top-to-bottom",pins:a?.rightSide?.pins??Array.from({length:r},(s,l)=>`pin${l+1}`)}}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:e.supplierPartNumbers,pin_count:e.pinCount,gender:e.gender,are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}};function DXt(r){switch(r){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var M9e=class extends es{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??DXt(this.props.pinVariant),zodProps:mAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=e.pinVariant||"no_ground",s=r.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:a,are_pins_interchangeable:a==="no_ground"||a==="ground_pin"});this.source_component_id=s.source_component_id}_getSchematicSymbolDisplayValue(){let r=`${Ns(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${r} / ${Ns(this._parsedProps.loadCapacitance)}F`:r}},O9e=class extends es{constructor(){super(...arguments);q(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:TAe,sourceFtype:dd.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${Ns(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({name:this.name,ftype:dd.simple_inductor,inductance:a.inductance,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}};function yXt(r){switch(r){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var L9e=class extends es{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??yXt(this.props.pinVariant),zodProps:fAe,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${Ns(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=e.pinVariant||"two_pin",s=r.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:e.maxResistance,pin_variant:a,are_pins_interchangeable:a==="two_pin"});this.source_component_id=s.source_component_id}},$9e=class extends es{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:SAe,sourceFtype:dd.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let r=ks[this._getSchematicSymbolNameOrThrow()],e=r.ports.find(D=>D.labels.includes("1")),a=r.ports.find(D=>D.labels.includes("2")),s=this.selectAll("port"),l=s.find(D=>D.props.pinNumber===1),d=s.find(D=>D.props.pinNumber===2),x=s.find(D=>D.props.pinNumber===3),f=s.find(D=>D.props.pinNumber===4),{internallyConnectedPins:m}=this._parsedProps;l.schematicSymbolPortDef=e,(!m||m.length===0)&&(d.schematicSymbolPortDef=a);for(let[D,b]of[[2,d],[3,x],[4,f]]){let E=m?.find(([B,w])=>B===`pin${D}`||w===`pin${D}`);if(!E){b.schematicSymbolPortDef=a;break}(E?.[0]===`pin${D}`?E[1]:E?.[0])!=="pin1"&&(b.schematicSymbolPortDef=a)}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({name:this.name,ftype:dd.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}},z9e=class extends es{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:hAe,sourceFtype:"simple_crystal"}}initPorts(){let r=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:r})}_getSchematicSymbolDisplayValue(){let r=`${Ns(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${r} / ${Ns(this._parsedProps.loadCapacitance)}F`:r}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:e.frequency,load_capacitance:e.loadCapacitance,pin_variant:e.pinVariant||"two_pin",are_pins_interchangeable:(e.pinVariant||"two_pin")==="two_pin"});this.source_component_id=a.source_component_id}},q9e=class extends es{constructor(){super(...arguments);q(this,"emitter",this.portMap.pin1);q(this,"collector",this.portMap.pin2);q(this,"base",this.portMap.pin3)}get config(){let e=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??e,zodProps:BAe,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let e={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:e})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:a.type});this.source_component_id=s.source_component_id}},U9e=class extends es{get config(){let r=this.props.mosfetMode==="depletion"?"d":"e",a=`${this.props.channelType}_channel_${r}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??a,zodProps:wAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=a.source_component_id}},V9e=class extends es{_getSwitchType(){let{spst:r,spdt:e,dpst:a,dpdt:s,type:l}=this._parsedProps??{};return s?"dpdt":r?"spst":e?"spdt":a?"dpst":l??"spst"}get config(){let r=this._getSwitchType(),{isNormallyClosed:e}=this._parsedProps??{},s={spst:e?"spst_normally_closed_switch":"spst_switch",spdt:e?"spdt_normally_closed_switch":"spdt_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"}[r]??"spst_switch";return{componentName:"Switch",schematicSymbolName:this.props.symbolName??s,zodProps:NAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({ftype:"simple_switch",name:this.name,switch_type:e.type,is_normally_closed:e.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=a.source_component_id}},JW={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},G9e=class extends es{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:$Ae,sourceFtype:dd.simple_test_point}}_getPropsWithDefaults(){let{padShape:r,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:d}=this._parsedProps;return!a&&e&&(a="through_hole"),a??(a="through_hole"),r??(r="circle"),a==="pad"?r==="circle"?s??(s=JW.SMT_CIRCLE_DIAMETER):r==="rect"&&(l??(l=JW.SMT_RECT_SIZE),d??(d=l)):a==="through_hole"&&(e??(e=JW.HOLE_DIAMETER)),{padShape:r,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:d}}_getImpliedFootprintString(){let{padShape:r,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:d}=this._getPropsWithDefaults();if(a==="through_hole")return`platedhole_d${e}`;if(a==="pad"){if(r==="circle")return`smtpad_circle_d${s}`;if(r==="rect")return`smtpad_rect_w${l}_h${d}`}throw new Error(`Footprint variant "${a}" with pad shape "${r}" not implemented`)}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,{padShape:a,holeDiameter:s,footprintVariant:l,padDiameter:d,width:x,height:f}=this._getPropsWithDefaults(),m=r.source_component.insert({ftype:dd.simple_test_point,name:this.name,supplier_part_numbers:e.supplierPartNumbers,footprint_variant:l,pad_shape:a,pad_diameter:d,hole_diameter:s,width:x,height:f,are_pins_interchangeable:!0});this.source_component_id=m.source_component_id}},X9e=class extends Qn{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:HAe}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalSchematicPositionBeforeLayout();e.schematic_text.insert({anchor:a.anchor??"center",text:a.text,font_size:a.fontSize,color:a.color||"#000000",position:{x:s.x,y:s.y},rotation:a.schRotation??0})}};function bXt({anchor:r,x:e,y:a,width:s,height:l,isInside:d}){switch(r){case"top_left":return{x:e,y:a+l,textAnchor:d?"top_left":"bottom_left"};case"top_center":return{x:e+s/2,y:a+l,textAnchor:d?"top_center":"bottom_center"};case"top_right":return{x:e+s,y:a+l,textAnchor:d?"top_right":"bottom_right"};case"center_left":return{x:e,y:a+l/2,textAnchor:d?"center_left":"center_right"};case"center":return{x:e+s/2,y:a+l/2,textAnchor:"center"};case"center_right":return{x:e+s,y:a+l/2,textAnchor:d?"center_right":"center_left"};case"bottom_left":return{x:e,y:a,textAnchor:d?"bottom_left":"top_left"};case"bottom_center":return{x:e+s/2,y:a,textAnchor:d?"bottom_center":"top_center"};case"bottom_right":return{x:e+s,y:a,textAnchor:d?"bottom_right":"top_right"};default:return{x:e+s/2,y:a+l,textAnchor:"center"}}}var Y9e=class extends Qn{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:YAe,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=.6,l=typeof a.padding=="number"?a.padding:0,d=typeof a.paddingTop=="number"?a.paddingTop:l,x=typeof a.paddingBottom=="number"?a.paddingBottom:l,f=typeof a.paddingLeft=="number"?a.paddingLeft:l,m=typeof a.paddingRight=="number"?a.paddingRight:l,D=a.overlay&&a.overlay.length>0,b=typeof a.width=="number"&&typeof a.height=="number",E,A,B,w,P,j;if(D){let z=a.overlay.map(it=>({selector:it,port:this.getSubcircuit().selectOne(it,{type:"port"})})).filter(({port:it})=>it!=null).map(({port:it})=>({position:it._getGlobalSchematicPositionAfterLayout()}));if(z.length===0)return;let ee=z.map(it=>it.position.x),W=z.map(it=>it.position.y),re=Math.min(...ee),L=Math.max(...ee),K=Math.min(...W),U=Math.max(...W),J=L-re,Q=U-K,de=J===0?s:0,oe=Q===0?s:0,Te=f+de/2,Me=m+de/2,Ge=d+oe/2,et=x+oe/2,dt=re-Te,$t=L+Me,bt=K-et,ut=U+Ge;E=$t-dt,A=ut-bt,B=dt+(a.schX??0),w=bt+(a.schY??0),P=B+E/2,j=w+A/2}else if(b){E=a.width,A=a.height;let O=this._getGlobalSchematicPositionBeforeLayout();P=O.x,j=O.y,B=P-E/2,w=j-A/2}else return;if(e.schematic_box.insert({height:A,width:E,x:B,y:w,is_dashed:a.strokeStyle==="dashed"}),a.title){let O=a.titleInside,z=.1,ee=a.titleAlignment,W=bXt({anchor:ee,x:B,y:w,width:E,height:A,isInside:O}),re,L,K=W.textAnchor;O?(re=ee.includes("top")?-z:ee.includes("bottom")?z:0,L=ee.includes("left")?z:ee.includes("right")?-z:0):(re=ee.includes("top")?z:ee.includes("bottom")?-z:0,L=ee.includes("center_left")?-z:ee.includes("center_right")?z:0);let U=W.x+L,J=W.y+re;e.schematic_text.insert({anchor:K,text:a.title,font_size:a.titleFontSize??.18,color:a.titleColor??"#000000",position:{x:U,y:J},rotation:0})}}},H9e=class extends Qn{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0);q(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:WAe}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.children.filter(A=>A.componentName==="SchematicRow");if(s.length===0)return;let l=[],d=0;for(let A of s){let B=A.children.filter(w=>w.componentName==="SchematicCell");d=Math.max(d,B.length)}for(let A=0;A<s.length;A++)l[A]=[];for(let A=0;A<s.length;A++){let w=s[A].children.filter(j=>j.componentName==="SchematicCell"),P=0;for(let j=0;j<w.length;j++){for(;l[A][P];)P++;let O=w[j],z=O._parsedProps.colSpan??1,ee=O._parsedProps.rowSpan??1;for(let W=0;W<ee;W++)for(let re=0;re<z;re++)l[A+W]||(l[A+W]=[]),l[A+W][P+re]=O;P+=z}}d=Math.max(0,...l.map(A=>A.length));let x=s.map((A,B)=>A._parsedProps.height??1),f=Array.from({length:d},(A,B)=>{let w=0;for(let P=0;P<s.length;P++){let j=l[P]?.[B];if(j){let O=j._parsedProps.text??j._parsedProps.children,z=j._parsedProps.width??(O?.length??2)*.5;z>w&&(w=z)}}return w||10}),m=this._getGlobalSchematicPositionBeforeLayout(),D=e.schematic_table.insert({anchor_position:m,column_widths:f,row_heights:x,cell_padding:a.cellPadding,border_width:a.borderWidth,anchor:a.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=D.schematic_table_id;let b=new Set,E=0;for(let A=0;A<s.length;A++){let B=0;for(let w=0;w<d;w++){let P=l[A]?.[w];if(P&&!b.has(P)){b.add(P);let j=P._parsedProps,O=j.rowSpan??1,z=j.colSpan??1,ee=0;for(let re=0;re<z;re++)ee+=f[w+re];let W=0;for(let re=0;re<O;re++)W+=x[A+re];e.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:A,end_row_index:A+O-1,start_column_index:w,end_column_index:w+z-1,text:j.text??j.children,center:{x:m.x+B+ee/2,y:m.y-E-W/2},width:ee,height:W,horizontal_align:j.horizontalAlign,vertical_align:j.verticalAlign,font_size:j.fontSize??a.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}f[w]&&(B+=f[w])}E+=x[A]}}},W9e=class extends Qn{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:KAe}}},K9e=class extends Qn{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0);q(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:JAe}}},FXt={name:"@tscircuit/core",type:"module",version:"0.0.734",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"'},devDependencies:{"@biomejs/biome":"^1.8.3","@tscircuit/capacity-autorouter":"^0.0.107","@tscircuit/checks":"^0.0.75","@tscircuit/circuit-json-util":"^0.0.67","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.21","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"0.0.334","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^0.0.37","@tscircuit/simple-3d-svg":"^0.0.41","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.260","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-simple-3d":"^0.0.8","circuit-to-svg":"^0.0.194",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.201","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.37","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},Kg=class{constructor({platform:r,projectUrl:e}={}){q(this,"firstChild",null);q(this,"children");q(this,"db");q(this,"root",null);q(this,"isRoot",!0);q(this,"schematicDisabled",!1);q(this,"pcbDisabled",!1);q(this,"pcbRoutingDisabled",!1);q(this,"_featureMspSchematicTraceRouting",!0);q(this,"name");q(this,"platform");q(this,"projectUrl");q(this,"_hasRenderedAtleastOnce",!1);q(this,"_eventListeners",{});this.children=[],this.db=ua([]),this.root=this,this.platform=r,this.projectUrl=e,this.pcbDisabled=r?.pcbDisabled??!1}add(r){let e;(0,J9e.isValidElement)(r)?e=YBe(r):e=r,this.children.push(e)}_getBoard(){return this.children.find(r=>r.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 r=new Wg({subcircuit:!0});r.parent=this,r.addAll(this.children),this.children=[r],this.firstChild=r}render(){this.firstChild||this._guessRootComponent();let{firstChild:r,db:e}=this;if(!r)throw new Error("RootCircuit has no root component");r.parent=this,r.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(e=>setTimeout(e,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(r=>r._hasIncompleteAsyncEffects()?!0:r.children.some(e=>e._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(r){let e=await Promise.resolve().then(()=>(DBe(),gBe)).catch(a=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
|
|
1037
|
+
${s.stack}`),a.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:r,componentDisplayName:this.getString(),phase:a.phase,error:s.toString()})})}_emitRenderLifecycleEvent(r,e){yVt(`${r}:${e} ${this.getString()}`);let a=`renderable:renderLifecycle:${r}:${e}`,s={renderId:this._renderId,componentDisplayName:this.getString(),type:a};"root"in this&&this.root&&(this.root.emit(a,s),this.root.emit("renderable:renderLifecycle:anyEvent",{...s,type:a}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(r=>!r.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(r){for(let e of this._asyncEffects)if(!e.complete&&e.phase===r)return!0;for(let e of this.children)if(e._hasIncompleteAsyncEffectsInSubtreeForPhase(r))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(r=>r.getRenderGraph())}}runRenderCycle(){for(let r of ld)this.runRenderPhaseForChildren(r),this.runRenderPhase(r)}runRenderPhase(r){this._currentRenderPhase=r;let e=this.renderPhaseStates[r],a=e.initialized,s=e.dirty;if(!a&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&a){this._emitRenderLifecycleEvent(r,"start"),this?.[`remove${r}`]?.(),e.initialized=!1,e.dirty=!1,this._emitRenderLifecycleEvent(r,"end");return}let l=ld.indexOf(r)-1;if(l>=0){let x=ld[l];if(this._asyncEffects.filter(m=>m.phase===x).some(m=>!m.complete))return}let d=bVt[r]||[];for(let x of d)if(this._hasIncompleteAsyncEffectsInSubtreeForPhase(x))return;if(this._emitRenderLifecycleEvent(r,"start"),a){s&&(this?.[`update${r}`]?.(),e.dirty=!1),this._emitRenderLifecycleEvent(r,"end");return}e.dirty=!1,this?.[`doInitial${r}`]?.(),e.initialized=!0,this._emitRenderLifecycleEvent(r,"end")}runRenderPhaseForChildren(r){for(let e of this.children)e.runRenderPhaseForChildren(r),e.runRenderPhase(r)}renderError(r){throw typeof r=="string"?new Error(r):new Error(JSON.stringify(r,null,2))}},VS={},XBe=r=>{let e=Object.fromEntries(Object.entries(r).map(([a,s])=>[a.toLowerCase(),s]));Object.assign(VS,r),Object.assign(VS,e)},EVt=class extends Error{constructor(r,e,a){let s,l=Object.keys(a).filter(m=>m!=="_errors"),d=[],x=e.pinLabels;if(x)for(let[m,D]of Object.entries(x)){let b=Array.isArray(D)?D:[D];for(let E of b)typeof E=="string"&&(E.startsWith(" ")||E.endsWith(" "))&&d.push(`pinLabels.${m} ("${E}" has leading or trailing spaces)`)}let f=l.map(m=>m==="pinLabels"&&d.length>0?d.join(", "):a[m]._errors[0]?`${m} (${a[m]._errors[0]})`:`${m} (${JSON.stringify(a[m])})`).join(", ");"name"in e?s=`Invalid props for ${r} "${e.name}": ${f}`:"footprint"in e&&typeof e.footprint=="string"?s=`Invalid props for ${r} (unnamed ${e.footprint} component): ${f}`:s=`Invalid props for ${r} (unnamed): ${f}`,super(s),this.componentName=r,this.originalProps=e,this.formattedError=a}};function VW(r,e){let a=e.match(/^#(\w+)/);if(a)return r.props.id===a[1];let s=e.match(/^\.(\w+)/);if(s)return r.isMatchingNameOrAlias(s[1]);let[l,...d]=e.split(/(?=[#.[])/);return l==="pin"&&(l="port"),l&&l!=="*"&&r.lowercaseComponentName!==l.toLowerCase()?!1:d.every(x=>{if(x.startsWith("#"))return r.props.id===x.slice(1);if(x.startsWith("."))return r.isMatchingNameOrAlias(x.slice(1));let f=x.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!f)return!0;let[,m,D]=f;return r.props[m].toString()===D})}var iK={isTag:r=>!0,getParent:r=>r.parent,getChildren:r=>r.children,getName:r=>r.lowercaseComponentName,getAttributeValue:(r,e)=>{if(e==="class"&&"getNameAndAliases"in r)return r.getNameAndAliases().join(" ");if(e==="name"&&r._parsedProps?.name)return r._parsedProps.name;if(r._parsedProps&&e in r._parsedProps){let s=r._parsedProps[e];return typeof s=="string"?s:s!=null?String(s):null}if(e in r){let s=r[e];return typeof s=="string"?s:s!=null?String(s):null}let a=r._attributeLowerToCamelNameMap;if(a){let s=a[e];if(s&&s in r){let l=r[s];return typeof l=="string"?l:l!=null?String(l):null}}return null},hasAttrib:(r,e)=>{if(e==="class")return!!r._parsedProps?.name;if(r._parsedProps&&e in r._parsedProps||e in r)return!0;let a=r._attributeLowerToCamelNameMap;if(a){let s=a[e];if(s&&s in r)return!0}return!1},getSiblings:r=>r.parent?r.parent.children:[],prevElementSibling:r=>{if(!r.parent)return null;let e=r.parent.children,a=e.indexOf(r);return a>0?e[a-1]:null},getText:()=>"",removeSubsets:r=>r.filter((e,a)=>!r.some((s,l)=>a!==l&&s!==e&&s.getDescendants().includes(e))),existsOne:(r,e)=>e.some(r),findAll:(r,e)=>{let a=[],s=l=>{r(l)&&a.push(l);for(let d of l.children)s(d)};for(let l of e)s(l);return a},findOne:(r,e)=>{for(let a of e){if(r(a))return a;let s=a.children;if(s.length>0){let l=iK.findOne(r,s);if(l)return l}}return null},equals:(r,e)=>r._renderId===e._renderId,isHovered:r=>!1,isVisited:r=>!1,isActive:r=>!1},vVt={...iK,getChildren:r=>r.children.filter(e=>!e.isSubcircuit)},yBe={...iK,getChildren:r=>r.children.filter(e=>e.isSubcircuit)},bBe=r=>{if(/net\.[^\s>]*\./.test(r))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(r))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(r)){let e=r.match(/net\.([^ >]+)/),a=e?e[1]:"";throw new Error(`Net name "${a}" cannot start with a number, try using a prefix like "VBUS1"`)}return r.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,(e,a,s,l)=>{let d=/^\d+$/.test(l)?`pin${l}`:l;return`${a}.${s} > .${d}`}).trim()},GW={adapter:vVt,cacheResults:!0},Qn=class extends sK{constructor(e){super(e);q(this,"parent",null);q(this,"children");q(this,"childrenPendingRemoval");q(this,"props");q(this,"_parsedProps");q(this,"externallyAddedAliases");q(this,"isPrimitiveContainer",!1);q(this,"canHaveTextChildren",!1);q(this,"source_group_id",null);q(this,"source_component_id",null);q(this,"schematic_component_id",null);q(this,"pcb_component_id",null);q(this,"cad_component_id",null);q(this,"fallbackUnassignedName");q(this,"_cachedSelectAllQueries",new Map);q(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=e??{},this.externallyAddedAliases=[];let s=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(e??{});if(s.success)this._parsedProps=s.data;else throw new EVt(this.lowercaseComponentName,this.props,s.error.format())}get config(){return{componentName:"",zodProps:v.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(e){let a=this;for(;a;){if(a._parsedProps&&e in a._parsedProps)return a._parsedProps[e];a=a.parent}if(this.root?.platform&&e in this.root.platform)return this.root.platform[e]}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(e){let a=this.config.zodProps.parse({...this.props,...e}),s=this.props;this.props=a,this._parsedProps=this.config.zodProps.parse(e),this.onPropsChange({oldProps:s,newProps:a,changedProps:Object.keys(e)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation:e}=this.props;return typeof e=="string"?parseFloat(e):e??null}computePcbPropsTransform(){let{_parsedProps:e}=this,a=this._getPcbRotationBeforeLayout()??0;return js(Ma(e.pcbX??0,e.pcbY??0),Ip(a*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let e=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(e&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let a=this._getPcbRotationBeforeLayout()??0;return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),js(Ma(e.x,e.y),Ip(a*Math.PI/180)))}if(this.isPcbPrimitive){let a=this.getPrimitiveContainer();if(a&&a._parsedProps.layer==="bottom")return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),P3e(),this.computePcbPropsTransform())}return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let e=this.getPrimitiveContainer(),a=e?e._parsedProps.layer==="bottom":!1;return{isFlipped:a,maybeFlipLayer:l=>a?l==="top"?"bottom":"top":l}}_setPositionFromLayout(e){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:e}=this;return js(Ma(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){let e=this._getSchematicGlobalManualPlacementTransform(this);return e||js(this.parent?.computeSchematicGlobalTransform?.()??Si(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:e}=this,a=this.config.schematicSymbolName,s={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},l=e.schOrientation!==void 0?s[e.schOrientation]:e.schRotation;if(l===void 0&&(l=0),l=l%360,l<0&&(l+=360),e.schRotation!==void 0&&l%90!==0)throw new Error(`Schematic rotation ${e.schRotation} is not supported for ${this.componentName}`);let d=`${a}_horz`,x=`${a}_vert`,f=`${a}_up`,m=`${a}_down`,D=`${a}_left`,b=`${a}_right`;if(b in ks&&l===0)return b;if(f in ks&&l===90)return f;if(D in ks&&l===180)return D;if(m in ks&&l===270)return m;if(d in ks&&(l===0||l===180))return d;if(x in ks&&(l===90||l===270))return x;if(a in ks)return a}_getSchematicSymbolNameOrThrow(){let e=this._getSchematicSymbolName();if(!e)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return e}getSchematicSymbol(){let e=this._getSchematicSymbolName();return e?ks[e]??null:null}_getPcbManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let a=this.props.manualEdits;if(!a)return null;let s=a?.pcb_placements;if(!s)return null;for(let l of s)if(VW(e,l.selector)||e.props.name===l.selector)return as(this._computePcbGlobalTransformBeforeLayout(),l.center);return null}_getSchematicManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let a=this.props.manualEdits;if(!a)return null;let s=a.schematic_placements;if(!s)return null;for(let l of s)if(VW(e,l.selector)||e.props.name===l.selector)return as(this.computeSchematicGlobalTransform(),l.center);return null}_getSchematicGlobalManualPlacementTransform(e){let a=this.getSubcircuit()?._parsedProps.manualEdits;if(!a)return null;for(let s of a.schematic_placements??[])if((VW(e,s.selector)||e.props.name===s.selector)&&s.relative_to==="group_center")return js(this.parent?._computePcbGlobalTransformBeforeLayout()??Si(),Ma(s.center.x,s.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return as(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return as(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(e){this.parent=e}onPropsChange(e){}onChildChanged(e){this.parent?.onChildChanged?.(e)}add(e){let a=e.__text;if(typeof a=="string"){if(this.canHaveTextChildren||a.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${a}"`)}if(Object.keys(e).length!==0){if(this.lowercaseComponentName==="board"&&e.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(!e.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(e)}"`);e.onAddToParent(this),e.parent=this,this.children.push(e)}}addAll(e){for(let a of e)this.add(a)}remove(e){this.children=this.children.filter(a=>a!==e),this.childrenPendingRemoval.push(e),e.shouldBeRemoved=!0}getSubcircuitSelector(){let e=this.name,a=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?a:`${this.parent.getSubcircuitSelector()} > ${a}`}getFullPathSelector(){let e=this.name,a=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName,s=this.parent?.getFullPathSelector?.();return s?`${s} > ${a}`:a}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(e){return this.getNameAndAliases().includes(e)}isMatchingAnyOf(e){return this.getNameAndAliases().some(a=>e.map(s=>s.toString()).includes(a))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(e){let a=[this.componentName,this.lowercaseComponentName],s=[this.name].filter(Boolean),l=e.trim().split(/\> /)[0],d=l[0];return l.length>1?!1:!!(e==="*"||e[0]==="#"&&e.slice(1)===this.props.id||e[0]==="."&&s.includes(e.slice(1))||/^[a-zA-Z0-9_]/.test(d)&&a.includes(d))}getSubcircuit(){if(this.isSubcircuit)return this;let e=this.parent?.getSubcircuit?.();if(!e)throw new Error("Component is not inside an opaque group (no board?)");return e}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let e=this.selectAll("port");for(let a of e){let s=a.parent?.getNameAndAliases(),l=a.getNameAndAliases();if(s)for(let d of s)for(let x of l){let f=[`.${d} > .${x}`,`.${d} .${x}`];for(let m of f){let D=this._cachedSelectAllQueries.get(m);D?D.push(a):this._cachedSelectAllQueries.set(m,[a])}}}for(let[a,s]of this._cachedSelectAllQueries.entries())s.length===1&&this._cachedSelectOneQueries.set(a,s[0])}selectAll(e){if(this._cachedSelectAllQueries.has(e))return this._cachedSelectAllQueries.get(e);let a=bBe(e),s=lY(a,this,GW);if(s.length>0)return this._cachedSelectAllQueries.set(e,s),s;let[l,...d]=a.split(" "),x=e5(l,this,{adapter:yBe});if(!x)return[];let f=x.selectAll(d.join(" "));return this._cachedSelectAllQueries.set(e,f),f}selectOne(e,a){if(this._cachedSelectOneQueries.has(e))return this._cachedSelectOneQueries.get(e);let s=bBe(e);a?.port&&(a.type="port");let l=null;if(a?.type&&(l=lY(s,this,GW).find(D=>D.lowercaseComponentName===a.type)),l??(l=e5(s,this,GW)),l)return this._cachedSelectOneQueries.set(e,l),l;let[d,...x]=s.split(" "),f=e5(d,this,{adapter:yBe});return f?(l=f.selectOne(x.join(" "),a),this._cachedSelectOneQueries.set(e,l),l):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:e}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[e(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?this.root?._getBoard()?.allLayers??["top","bottom"]:[]}return[]}getDescendants(){let e=[];for(let a of this.children)e.push(a),e.push(...a.getDescendants());return e}getSelectableDescendants(){let e=[];for(let a of this.children)a.isSubcircuit?e.push(a):(e.push(a),e.push(...a.getSelectableDescendants()));return e}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this;return{schWidth:e.schWidth,schHeight:e.schHeight}}renderError(e){if(typeof e=="string")return super.renderError(e);this.root?.db.pcb_placement_error.insert(e)}getString(){let{lowercaseComponentName:e,_parsedProps:a,parent:s}=this;return a?.pinNumber!==void 0&&s?.props?.name&&a?.name?`<${e}#${this._renderId}(pin:${a.pinNumber} .${s?.props.name}>.${a.name}) />`:s?.props?.name&&a?.name?`<${e}#${this._renderId}(.${s?.props.name}>.${a?.name}) />`:a?.from&&a?.to?`<${e}#${this._renderId}(from:${a.from} to:${a?.to}) />`:a?.name?`<${e}#${this._renderId} name=".${a?.name}" />`:a?.portHints?`<${e}#${this._renderId}(${a.portHints.map(l=>`.${l}`).join(", ")}) />`:`<${e}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},CVt=class extends Qn{constructor(r,e){super(r),this._parsedProps={...r,error:e,type:r.type||"unknown",component_name:r.name,error_type:"source_failed_to_create_component_error",message:e instanceof Error?e.message:String(e),pcbX:r.pcbX,pcbY:r.pcbY,schX:r.schX,schY:r.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:v.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let r=this._getGlobalPcbPositionBeforeLayout(),e=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:r,schematic_center:e})}}};function _Vt(r,e){return new CVt(r,e)}function AVt(r,e){let a=r;return a.__tsci={...e},r}var RVt={supportsMutation:!0,createInstance(r,e){let a=VS[r];if(!a)throw Object.keys(VS).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 "${r}". 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 AVt(new a(e),{})}catch(s){return _Vt({...e,componentType:r},s)}},createTextInstance(r){return{__text:r}},appendInitialChild(r,e){r.add(e)},appendChild(r,e){r.add(e)},appendChildToContainer(r,e){r.add(e)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(r){return r},preparePortalMount(r){throw new Error("Function not implemented.")},scheduleTimeout(r,e){throw new Error("Function not implemented.")},cancelTimeout(r){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(r){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(r,e)=>{throw new Error("Function not implemented.")},getInstanceFromScope:r=>{throw new Error("Function not implemented.")},detachDeletedInstance:r=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>zS.DefaultEventPriority,getCurrentUpdatePriority:()=>zS.DefaultEventPriority,resolveUpdatePriority:()=>zS.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},OS=(0,VBe.default)(RVt),YBe=r=>{let e={children:[],props:{name:"$root"},add(d){d.parent=this,this.children.push(d)},computePcbGlobalTransform(){return Si()}},a=[],s=OS.createContainer(e,0,null,!1,null,"tsci",d=>{console.log("Error in createContainer"),console.error(d),a.push(d)},null);if(OS.updateContainerSync(r,s,null,()=>{}),OS.flushSyncWork(),a.length>0)throw a[0];let l=OS.getPublicRootInstance(s);return l||e.children[0]},YF=(r,e)=>{if(typeof r=="number")return r;if(r.startsWith("pin"))return Number(r.slice(3));if(!e)throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`);for(let a in e)if((Array.isArray(e[a])?e[a]:[e[a]]).includes(r))return Number(a.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`)},SVt=(r,e)=>{if(!r)return;let a={},s={};for(let[l,d]of Object.entries(r)){let x=YF(l,e);s[x]={...s[x],...d}}for(let[l,d]of Object.entries(s)){let x=`pin${l}`;a[x]={bottom_margin:d.bottomMargin,left_margin:d.leftMargin,right_margin:d.rightMargin,top_margin:d.topMargin}}return a},BVt=r=>{if(r){if("leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r)return{left_side:r.leftSide,right_side:r.rightSide,top_side:r.topSide,bottom_side:r.bottomSide};if("leftPinCount"in r||"rightPinCount"in r||"topPinCount"in r||"bottomPinCount"in r)return{left_size:r.leftPinCount,right_size:r.rightPinCount,top_size:r.topPinCount,bottom_size:r.bottomPinCount};if("leftSize"in r||"rightSize"in r||"topSize"in r||"bottomSize"in r)return{left_size:r.leftSize,right_size:r.rightSize,top_size:r.topSize,bottom_size:r.bottomSize}}};function HBe(r){let e=[];for(let a=0;a<r.length-1;a++)e.push([r[a],r[a+1]]);return e}var wVt=v.object({name:v.string().refine(r=>!/[+-]/.test(r),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),oK=class extends Qn{constructor(){super(...arguments);q(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:wVt}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=a.name.startsWith("GND"),l=a.name.startsWith("V"),d=e.source_net.insert({name:a.name,member_source_group_ids:[],is_ground:s,is_power:l,is_positive_voltage_source:l});this.source_net_id=d.source_net_id}doInitialSourceParentAttachment(){let e=this.getSubcircuit();if(!e)return;let{db:a}=this.root;a.source_net.update(this.source_net_id,{subcircuit_id:e.subcircuit_id})}getAllConnectedPorts(){let e=this.getSubcircuit().selectAll("port"),a=[];for(let s of e){let l=s._getDirectlyConnectedTraces();for(let d of l)if(d._isExplicitlyConnectedToNet(this)){a.push(s);break}}return a}_getAllDirectlyConnectedTraces(){let e=this.getSubcircuit().selectAll("trace"),a=[];for(let s of e)s._isExplicitlyConnectedToNet(this)&&a.push(s);return a}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getAllDirectlyConnectedTraces().filter(x=>(x._portsRoutedOnPcb?.length??0)>0),l=[];for(let x of s){let f=x._portsRoutedOnPcb,m=l.find(D=>f.some(b=>D.ports.includes(b)));if(!m){l.push({ports:[...f],traces:[x]});continue}m.traces.push(x),m.ports.push(...f)}if(l.length===0)return;let d=HBe(l);for(let[x,f]of d){let m=x.ports.map(O=>O._getGlobalPcbPositionBeforeLayout()),D=f.ports.map(O=>O._getGlobalPcbPositionBeforeLayout()),b=1/0,E=[-1,-1];for(let O=0;O<m.length;O++){let z=m[O];for(let ee=0;ee<D.length;ee++){let W=D[ee],re=Math.sqrt((z.x-W.x)**2+(z.y-W.y)**2);re<b&&(b=re,E=[O,ee])}}let A=x.ports[E[0]],B=f.ports[E[1]],w=e.toArray().filter(O=>O.type==="pcb_smtpad"||O.type==="pcb_trace"||O.type==="pcb_plated_hole"||O.type==="pcb_hole"||O.type==="source_port"||O.type==="pcb_port"),{solution:P}=Z_e(w.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[A.source_port_id,B.source_port_id]}])),j=P[0];if(!j){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[A.pcb_component_id,B.pcb_component_id].filter(Boolean),pcb_port_ids:[A.pcb_port_id,B.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}e.pcb_trace.insert(j)}}renderError(e){if(typeof e=="string")return super.renderError(e);this.root?.db.pcb_trace_error.insert(e)}},uK=(r,e)=>{for(let a of e)if(typeof a=="string"&&a.startsWith("net.")){if(/net\.[^\s>]*\./.test(a))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(a))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(a)){let l=a.split("net.")[1];throw new Error(`Net name "${l}" cannot start with a number, try using a prefix like "VBUS1"`)}let s=r.getSubcircuit();if(!s.selectOne(a)){let l=new oK({name:a.split("net.")[1]});s.add(l)}}},GS=class extends Qn{constructor(){super(...arguments);q(this,"pcb_smtpad_id",null);q(this,"matchedPort",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:FAe}}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="polygon"){let a=e.points,s=a.map(D=>D.x),l=a.map(D=>D.y),d=Math.min(...s),x=Math.max(...s),f=Math.min(...l),m=Math.max(...l);return{width:x-d,height:m-f}}if(e.shape==="pill")return{width:e.width,height:e.height};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let a of e)if(a.isMatchingAnyOf(this.props.portHints)){this.matchedPort=a,a.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this;if(!a.portHints)return;let s=this.getPrimitiveContainer(),l=this.getSubcircuit(),d=this._getGlobalPcbPositionBeforeLayout(),x=s?._getGlobalPcbPositionBeforeLayout(),f=i4(this._computePcbGlobalTransformBeforeLayout()),m=Math.abs(f.rotation.angle*(180/Math.PI)-90)%180<.01,{maybeFlipLayer:D}=this._getPcbPrimitiveFlippedHelpers(),b=s?._parsedProps.pcbRotation??0,E=null,A=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;a.shape==="circle"?(E=e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"circle",radius:a.radius,port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,x:d.x,y:d.y,subcircuit_id:l?.subcircuit_id??void 0}),e.pcb_solder_paste.insert({layer:E.layer,shape:"circle",radius:E.radius*.7,x:E.x,y:E.y,pcb_component_id:E.pcb_component_id,pcb_smtpad_id:E.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):a.shape==="rect"?(E=b===0||m?e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"rect",width:m?a.height:a.width,height:m?a.width:a.height,port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,x:d.x,y:d.y,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):e.pcb_smtpad.insert({pcb_component_id:A,layer:D(a.layer??"top"),shape:"rotated_rect",width:a.width,height:a.height,x:d.x,y:d.y,ccw_rotation:b,port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),E.shape==="rect"&&e.pcb_solder_paste.insert({layer:D(a.layer??"top"),shape:"rect",width:E.width*.7,height:E.height*.7,x:E.x,y:E.y,pcb_component_id:E.pcb_component_id,pcb_smtpad_id:E.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),E.shape==="rotated_rect"&&e.pcb_solder_paste.insert({layer:D(a.layer??"top"),shape:"rotated_rect",width:E.width*.7,height:E.height*.7,x:E.x,y:E.y,ccw_rotation:b,pcb_component_id:E.pcb_component_id,pcb_smtpad_id:E.pcb_smtpad_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})):a.shape==="polygon"?E=e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"polygon",points:a.points.map(B=>({x:B.x+d.x,y:B.y+d.y})),port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):a.shape==="pill"&&(E=e.pcb_smtpad.insert({pcb_component_id:A,pcb_port_id:this.matchedPort?.pcb_port_id,layer:D(a.layer??"top"),shape:"pill",x:d.x,y:d.y,radius:a.radius,height:a.height,width:a.width,port_hints:a.portHints.map(B=>B.toString()),is_covered_with_solder_mask:a.coveredWithSolderMask??!1,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})),E&&(this.pcb_smtpad_id=E.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_smtpad.get(this.pcb_smtpad_id);if(a.shape==="rect")return{center:{x:a.x,y:a.y},bounds:{left:a.x-a.width/2,top:a.y+a.height/2,right:a.x+a.width/2,bottom:a.y-a.height/2},width:a.width,height:a.height};if(a.shape==="rotated_rect"){let s=a.ccw_rotation*Math.PI/180,l=Math.cos(s),d=Math.sin(s),x=a.width/2,f=a.height/2,m=Math.abs(x*l)+Math.abs(f*d),D=Math.abs(x*d)+Math.abs(f*l);return{center:{x:a.x,y:a.y},bounds:{left:a.x-m,right:a.x+m,top:a.y-D,bottom:a.y+D},width:m*2,height:D*2}}if(a.shape==="circle")return{center:{x:a.x,y:a.y},bounds:{left:a.x-a.radius,top:a.y-a.radius,right:a.x+a.radius,bottom:a.y+a.radius},width:a.radius*2,height:a.radius*2};if(a.shape==="polygon"){let s=a.points,l=s.map(b=>b.x),d=s.map(b=>b.y),x=Math.min(...l),f=Math.max(...l),m=Math.min(...d),D=Math.max(...d);return{center:{x:(x+f)/2,y:(m+D)/2},bounds:{left:x,top:D,right:f,bottom:m},width:f-x,height:D-m}}if(a.shape==="pill"){let s=a.width/2,l=a.height/2;return{center:{x:a.x,y:a.y},bounds:{left:a.x-s,top:a.y-l,right:a.x+s,bottom:a.y+l},width:a.width,height:a.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${a.shape}"`)}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_smtpad.update(this.pcb_smtpad_id,{x:e.x,y:e.y});let s=a.pcb_solder_paste.list().find(l=>l.pcb_smtpad_id===this.pcb_smtpad_id);a.pcb_solder_paste.update(s?.pcb_solder_paste_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}},cK=class extends Qn{constructor(){super(...arguments);q(this,"pcb_silkscreen_path_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:QAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenPath. Must be "top" or "bottom".`);let d=this._computePcbGlobalTransformBeforeLayout(),x=this.getSubcircuit(),f=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=e.pcb_silkscreen_path.insert({pcb_component_id:f,layer:l,route:a.route.map(D=>{let b=as(d,{x:D.x,y:D.y});return{...D,x:b.x,y:b.y}}),stroke_width:a.strokeWidth??.1,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=m.pcb_silkscreen_path_id}_setPositionFromLayout(e){let{db:a}=this.root,{_parsedProps:s}=this,l=a.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!l)return;let d=0,x=0;for(let b of l.route)d+=b.x,x+=b.y;d/=l.route.length,x/=l.route.length;let f=e.x-d,m=e.y-x,D=l.route.map(b=>({...b,x:b.x+f,y:b.y+m}));a.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:D})}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let a=1/0,s=-1/0,l=1/0,d=-1/0;for(let x of e.route)a=Math.min(a,x.x),s=Math.max(s,x.x),l=Math.min(l,x.y),d=Math.max(d,x.y);return{width:s-a,height:d-l}}},TVt=v.object({route:v.array(UA),source_trace_id:v.string().optional()}),lK=class extends Qn{constructor(){super(...arguments);q(this,"pcb_trace_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:TVt}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer(),l=this.getSubcircuit(),{maybeFlipLayer:d}=this._getPcbPrimitiveFlippedHelpers(),x=this._computePcbGlobalTransformBeforeLayout(),f=a.route.map(D=>{let{x:b,y:E,...A}=D,B=as(x,{x:b,y:E});return D.route_type==="wire"&&D.layer?{...B,...A,layer:d(D.layer)}:{...B,...A}}),m=e.pcb_trace.insert({pcb_component_id:s.pcb_component_id,source_trace_id:a.source_trace_id,route:f,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=m.pcb_trace_id}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let a=1/0,s=-1/0,l=1/0,d=-1/0;for(let x of e.route)a=Math.min(a,x.x),s=Math.max(s,x.x),l=Math.min(l,x.y),d=Math.max(d,x.y),x.route_type==="wire"&&(a=Math.min(a,x.x-x.width/2),s=Math.max(s,x.x+x.width/2),l=Math.min(l,x.y-x.width/2),d=Math.max(d,x.y+x.width/2));return a===1/0||s===-1/0||l===1/0||d===-1/0?{width:0,height:0}:{width:s-a,height:d-l}}},Yg=class extends Qn{constructor(){super(...arguments);q(this,"pcb_plated_hole_id",null);q(this,"matchedPort",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:dAe}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.outerDiameter,height:e.outerDiameter};if(e.shape==="oval"||e.shape==="pill")return{width:e.outerWidth,height:e.outerHeight};if(e.shape==="circular_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};if(e.shape==="pill_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_plated_hole.get(this.pcb_plated_hole_id),s=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-s.width/2,top:a.y+s.height/2,right:a.x+s.width/2,bottom:a.y-s.height/2},width:s.width,height:s.height}}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let a of e)if(a.isMatchingAnyOf(this.props.portHints)){this.matchedPort=a,a.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalPcbPositionBeforeLayout(),l=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,d=this.getSubcircuit();if(a.shape==="circle"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:a.outerDiameter,hole_diameter:a.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:a.outerDiameter/2,x:s.x,y:s.y,subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:a.outerDiameter/2,x:s.x,y:s.y,subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(a.shape==="pill"&&a.rectPad){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:a.outerWidth,outer_height:a.outerHeight,hole_width:a.holeWidth,hole_height:a.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:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:a.pcbRotation??0,rect_ccw_rotation:a.pcbRotation??0,rect_pad_width:a.outerWidth,rect_pad_height:a.outerHeight,hole_offset_x:a.holeOffsetX,hole_offset_y:a.holeOffsetY});this.pcb_plated_hole_id=x.pcb_plated_hole_id}else if(a.shape==="pill"||a.shape==="oval"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:a.outerWidth,outer_height:a.outerHeight,hole_width:a.holeWidth,hole_height:a.holeHeight,shape:a.shape,port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:a.pcbRotation??0});this.pcb_plated_hole_id=x.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:a.shape,width:a.outerWidth,height:a.outerHeight,x:s.x,y:s.y,subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:a.shape,width:a.outerWidth,height:a.outerHeight,x:s.x,y:s.y,subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(a.shape==="circular_hole_with_rect_pad"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:a.holeDiameter,rect_pad_width:a.rectPadWidth,rect_pad_height:a.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:a.holeOffsetX,hole_offset_y:a.holeOffsetY,rect_border_radius:a.rectBorderRadius??0});this.pcb_plated_hole_id=x.pcb_plated_hole_id}else if(a.shape==="pill_hole_with_rect_pad"){let x=e.pcb_plated_hole.insert({pcb_component_id:l,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:a.holeWidth,hole_height:a.holeHeight,rect_pad_width:a.rectPadWidth,rect_pad_height:a.rectPadHeight,hole_offset_x:a.holeOffsetX,hole_offset_y:a.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:s.x,y:s.y,layers:["top","bottom"],subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=x.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},XS=class extends Qn{constructor(){super(...arguments);q(this,"pcb_keepout_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:qAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let e=this.getSubcircuit(),{db:a}=this.root,{_parsedProps:s}=this,l=this._getGlobalPcbPositionBeforeLayout(),d=i4(this._computePcbGlobalTransformBeforeLayout()),x=Math.abs(d.rotation.angle*(180/Math.PI)-90)%180<.01,f=null;s.shape==="circle"?f=a.pcb_keepout.insert({layers:["top"],shape:"circle",radius:s.radius,center:{x:l.x,y:l.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0}):s.shape==="rect"&&(f=a.pcb_keepout.insert({layers:["top"],shape:"rect",...x?{width:s.height,height:s.width}:{width:s.width,height:s.height},center:{x:l.x,y:l.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0})),f&&(this.pcb_keepout_id=f.pcb_keepout_id)}},dK=class extends Qn{constructor(){super(...arguments);q(this,"pcb_hole_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:EAe}}getPcbSize(){let{_parsedProps:e}=this,a=e.shape==="pill";return{width:a?e.width:e.diameter,height:a?e.height:e.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=this._getGlobalPcbPositionBeforeLayout(),d=e.pcb_hole.insert({hole_shape:"circle",hole_diameter:a.diameter,x:l.x,y:l.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:s?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=d.pcb_hole_id}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_hole.get(this.pcb_hole_id),s=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-s.width/2,top:a.y-s.height/2,right:a.x+s.width/2,bottom:a.y+s.height/2},width:s.width,height:s.height}}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_hole.update(this.pcb_hole_id,{x:e.x,y:e.y})}},JS=class extends Qn{constructor(){super(...arguments);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:ZAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer(),l=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:d}=this._getPcbPrimitiveFlippedHelpers(),x=this.getSubcircuit(),f=new Set(a.layers);a.layer&&f.add(a.layer);let m=f.size>0?Array.from(f):["top"];for(let D of m)e.pcb_silkscreen_text.insert({anchor_alignment:a.anchorAlignment,anchor_position:{x:l.x,y:l.y},font:a.font??"tscircuit2024",font_size:a.fontSize??1,layer:d(D),text:a.text??"",ccw_rotation:a.pcbRotation,pcb_component_id:s.pcb_component_id,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:e}=this,a=e.fontSize??1,l=(e.text??"").length*a,d=a;return{width:l*a,height:d*a}}},XF=class extends Qn{constructor(){super(...arguments);q(this,"pcb_cutout_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:bAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=this.getGroup()?.pcb_group_id??void 0,d=this._getGlobalPcbPositionBeforeLayout(),f=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,m;if(a.shape==="rect"){let D=typeof f=="string"?parseInt(f.replace("deg",""),10):f,b=Math.abs(D%180)===90,E={shape:"rect",center:d,width:b?a.height:a.width,height:b?a.width:a.height,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:l};m=e.pcb_cutout.insert(E)}else if(a.shape==="circle"){let D={shape:"circle",center:d,radius:a.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:l};m=e.pcb_cutout.insert(D)}else if(a.shape==="polygon"){let D=this._computePcbGlobalTransformBeforeLayout(),E={shape:"polygon",points:a.points.map(A=>as(D,A)),subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:l};m=e.pcb_cutout.insert(E)}m&&(this.pcb_cutout_id=m.pcb_cutout_id)}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="polygon"){if(e.points.length===0)return{width:0,height:0};let a=1/0,s=-1/0,l=1/0,d=-1/0;for(let x of e.points)a=Math.min(a,x.x),s=Math.max(s,x.x),l=Math.min(l,x.y),d=Math.max(d,x.y);return{width:s-a,height:d-l}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,a=e.pcb_cutout.get(this.pcb_cutout_id);if(!a)return super._getPcbCircuitJsonBounds();if(a.shape==="rect")return{center:a.center,bounds:{left:a.center.x-a.width/2,top:a.center.y+a.height/2,right:a.center.x+a.width/2,bottom:a.center.y-a.height/2},width:a.width,height:a.height};if(a.shape==="circle")return{center:a.center,bounds:{left:a.center.x-a.radius,top:a.center.y+a.radius,right:a.center.x+a.radius,bottom:a.center.y-a.radius},width:a.radius*2,height:a.radius*2};if(a.shape==="polygon"){if(a.points.length===0)return super._getPcbCircuitJsonBounds();let s=1/0,l=-1/0,d=1/0,x=-1/0;for(let f of a.points)s=Math.min(s,f.x),l=Math.max(l,f.x),d=Math.min(d,f.y),x=Math.max(x,f.y);return{center:{x:(s+l)/2,y:(d+x)/2},bounds:{left:s,top:x,right:l,bottom:d},width:l-s,height:x-d}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(e){if(!this.pcb_cutout_id)return;let{db:a}=this.root,s=a.pcb_cutout.get(this.pcb_cutout_id);if(s){if(s.shape==="rect"||s.shape==="circle")a.pcb_cutout.update(this.pcb_cutout_id,{...s,center:e});else if(s.shape==="polygon"){let l=this._getPcbCircuitJsonBounds().center,d=e.x-l.x,x=e.y-l.y,f=s.points.map(m=>({x:m.x+d,y:m.y+x}));a.pcb_cutout.update(this.pcb_cutout_id,{...s,points:f})}}}},PVt=({elm:r,pinLabels:e,layer:a,readableRotation:s,anchorAlignment:l})=>{let d=r.text.replace(/[{}]/g,"").toLowerCase(),x=d;if(Array.isArray(e)){let f=parseInt(d.replace(/[^\d]/g,""),10)-1;x=String(e[f]??d)}else typeof e=="object"&&(x=String(e[d]??d));return new JS({anchorAlignment:l||"center",text:x??d,layer:a||"top",fontSize:r.font_size+.2,pcbX:isNaN(r.anchor_position.x)?0:r.anchor_position.x,pcbY:r.anchor_position.y,pcbRotation:s??0})},IVt=(r,e)=>((-parseInt(r||"0",10)+(e??0))%360+360)%360,qS=({componentName:r,componentRotation:e,footprint:a,pinLabels:s,pcbPinLabels:l},d)=>{let x=[];for(let f of d)if(f.type==="pcb_smtpad"&&f.shape==="rect")x.push(new GS({pcbX:f.x,pcbY:f.y,layer:f.layer,shape:"rect",height:f.height,width:f.width,portHints:f.port_hints,rectBorderRadius:f.rect_border_radius}));else if(f.type==="pcb_smtpad"&&f.shape==="circle")x.push(new GS({pcbX:f.x,pcbY:f.y,layer:f.layer,shape:"circle",radius:f.radius,portHints:f.port_hints}));else if(f.type==="pcb_silkscreen_path")x.push(new cK({layer:f.layer,route:f.route,strokeWidth:f.stroke_width}));else if(f.type==="pcb_plated_hole")f.shape==="circle"?x.push(new Yg({pcbX:f.x,pcbY:f.y,shape:"circle",holeDiameter:f.hole_diameter,outerDiameter:f.outer_diameter,portHints:f.port_hints})):f.shape==="circular_hole_with_rect_pad"?x.push(new Yg({pcbX:f.x,pcbY:f.y,shape:"circular_hole_with_rect_pad",holeDiameter:f.hole_diameter,rectPadHeight:f.rect_pad_height,rectPadWidth:f.rect_pad_width,portHints:f.port_hints,rectBorderRadius:f.rect_border_radius,holeOffsetX:f.hole_offset_x,holeOffsetY:f.hole_offset_y})):f.shape==="pill"||f.shape==="oval"?x.push(new Yg({pcbX:f.x,pcbY:f.y,shape:f.shape,holeWidth:f.hole_width,holeHeight:f.hole_height,outerWidth:f.outer_width,outerHeight:f.outer_height,portHints:f.port_hints})):f.shape==="pill_hole_with_rect_pad"&&x.push(new Yg({pcbX:f.x,pcbY:f.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:f.hole_width,holeHeight:f.hole_height,rectPadWidth:f.rect_pad_width,rectPadHeight:f.rect_pad_height,portHints:f.port_hints,holeOffsetX:f.hole_offset_x,holeOffsetY:f.hole_offset_y}));else if(f.type==="pcb_keepout"&&f.shape==="circle")x.push(new XS({pcbX:f.center.x,pcbY:f.center.y,shape:"circle",radius:f.radius}));else if(f.type==="pcb_keepout"&&f.shape==="rect")x.push(new XS({pcbX:f.center.x,pcbY:f.center.y,shape:"rect",width:f.width,height:f.height}));else if(f.type==="pcb_hole"&&f.hole_shape==="circle")x.push(new dK({pcbX:f.x,pcbY:f.y,diameter:f.hole_diameter}));else if(f.type==="pcb_cutout")f.shape==="rect"?x.push(new XF({pcbX:f.center.x,pcbY:f.center.y,shape:"rect",width:f.width,height:f.height})):f.shape==="circle"?x.push(new XF({pcbX:f.center.x,pcbY:f.center.y,shape:"circle",radius:f.radius})):f.shape==="polygon"&&x.push(new XF({shape:"polygon",points:f.points}));else if(f.type==="pcb_silkscreen_text"){let m=IVt(e,f.ccw_rotation);a.includes("pinrow")&&f.text.includes("PIN")?x.push(PVt({elm:f,pinLabels:l??s,layer:f.layer,readableRotation:m,anchorAlignment:f.anchor_alignment})):x.push(new JS({anchorAlignment:f.anchor_alignment||"center",text:r,fontSize:f.font_size+.2,pcbX:Number.isNaN(f.anchor_position.x)?0:f.anchor_position.x,pcbY:f.anchor_position.y,pcbRotation:m??0}))}else f.type==="pcb_trace"&&x.push(new lK({route:f.route}));return x};function ZS(r){let e=1/0,a=1/0,s=-1/0,l=-1/0,d=!1;for(let m of r)if(m.isPcbPrimitive&&!m.componentName.startsWith("Silkscreen")){let{x:D,y:b}=m._getGlobalPcbPositionBeforeLayout(),{width:E,height:A}=m.getPcbSize();e=Math.min(e,D-E/2),a=Math.min(a,b-A/2),s=Math.max(s,D+E/2),l=Math.max(l,b+A/2),d=!0}else if(m.children.length>0){let D=ZS(m.children);(D.width>0||D.height>0)&&(e=Math.min(e,D.minX),a=Math.min(a,D.minY),s=Math.max(s,D.maxX),l=Math.max(l,D.maxY),d=!0)}if(!d)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let x=s-e,f=l-a;return x<0&&(x=0),f<0&&(f=0),{minX:e,minY:a,maxX:s,maxY:l,width:x,height:f}}function jVt(r,e){let a=e.x-r.x,s=e.y-r.y;return Math.abs(a)>Math.abs(s)?a>=0?"right":"left":s>=0?"up":"down"}var FBe=r=>{if(r.length<=1)return!0;let e=r.map(d=>{let x=d._getPcbCircuitJsonBounds();return{left:x.bounds.left,right:x.bounds.right,top:x.bounds.top,bottom:x.bounds.bottom}}),a=Array(e.length).fill(!1).map(()=>Array(e.length).fill(!1));for(let d=0;d<e.length;d++)for(let x=d+1;x<e.length;x++){let f=e[d],m=e[x];a[d][x]=a[x][d]=!(f.right<m.left||f.left>m.right||f.bottom>m.top||f.top<m.bottom)}let s=new Set,l=d=>{s.add(d);for(let x=0;x<e.length;x++)a[d][x]&&!s.has(x)&&l(x)};return l(0),s.size===e.length},EBe=r=>{if(r.length===0)throw new Error("Cannot get center of empty PCB primitives array");let e=r.map(l=>l._getPcbCircuitJsonBounds().center).filter(Boolean),a=e.reduce((l,d)=>l+d.x,0),s=e.reduce((l,d)=>l+d.y,0);return{x:a/e.length,y:s/e.length}},kVt=v.object({name:v.string().optional(),pinNumber:v.number().optional(),aliases:v.array(v.string()).optional(),layer:v.string().optional(),layers:v.array(v.string()).optional()}),Ni=class extends Qn{constructor(e,a={}){if(!e.name&&e.pinNumber!==void 0&&(e.name=`pin${e.pinNumber}`),!e.name)throw new Error("Port must have a name or a pinNumber");super(e);q(this,"source_port_id",null);q(this,"pcb_port_id",null);q(this,"schematic_port_id",null);q(this,"schematicSymbolPortDef",null);q(this,"matchedComponents");q(this,"facingDirection",null);q(this,"originDescription",null);a.originDescription&&(this.originDescription=a.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:kVt}}_isBoardPinoutFromAttributes(){let e=this.parent;if(e?._parsedProps?.pinAttributes){let a=e._parsedProps.pinAttributes;for(let s of this.getNameAndAliases())if(a[s]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let e=this.matchedComponents.find(s=>s.isPcbPrimitive),a=this.parent;if(a&&!a.props.footprint)throw new Error(`${a.componentName} "${a.props.name}" does not have a footprint. Add a footprint prop, e.g. <${a.componentName.toLowerCase()} footprint="..." />`);if(!e)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return e?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,a=e.pcb_port.get(this.pcb_port_id);return{center:{x:a.x,y:a.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let e=this.parent;if(!e||!e._getInternallyConnectedPins)return[];let a=e._getInternallyConnectedPins();for(let s of a)if(s.some(l=>l===this))return s;return[]}_hasSchematicPort(){if(this.parent?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(l=>l.schematicSymbolPortDef));let a=this?.parent?._getSchematicBoxDimensions();return!!(a&&this.props.pinNumber!==void 0&&a.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let e=this.parent?.getSchematicSymbol();if(e){let s=this.schematicSymbolPortDef;if(!s&&(s=this._getPortsInternallyConnectedToThisPort().find(d=>d.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 l=js(this.parent.computeSchematicGlobalTransform(),Ma(-e.center.x,-e.center.y));return as(l,s)}let a=this?.parent?._getSchematicBoxDimensions();if(a&&this.props.pinNumber!==void 0){let s=a.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 as(this.parent.computeSchematicGlobalTransform(),s)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:e}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let a=e.schematic_port.get(this.schematic_port_id);if(!a)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return a.center}registerMatch(e){this.matchedComponents.push(e)}getNameAndAliases(){let{_parsedProps:e}=this;return Array.from(new Set([...e.name?[e.name]:[],...e.aliases??[],...typeof e.pinNumber=="number"?[`pin${e.pinNumber}`,e.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let e=this.parent?._parsedProps?.pinAttributes;if(!e)return[];let a=[];for(let s of this.getNameAndAliases()){let l=e[s];l&&a.push(l)}return a}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(e=>e.includeInBoardPinout===!0)}isMatchingPort(e){return this.isMatchingAnyOf(e.getNameAndAliases())}getPortSelector(){return`.${this.parent?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:e,layers:a}=this._parsedProps;return a||(e?[e]:Array.from(new Set(this.matchedComponents.flatMap(s=>s.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(s=>!s._couldNotFindPort).filter(s=>s._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getNameAndAliases(),l=e.source_port.insert({name:a.name,pin_number:a.pinNumber,port_hints:s,source_component_id:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=l.source_port_id}doInitialSourceParentAttachment(){let{db:e}=this.root;if(!this.parent?.source_component_id)throw new Error(`${this.getString()} has no parent source component (parent: ${this.parent?.getString()})`);e.source_port.update(this.source_port_id,{source_component_id:this.parent?.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=this.parent?.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{matchedComponents:a}=this;if(!this.parent?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()})`);let s=a.filter(d=>d.isPcbPrimitive);if(s.length===0)return;let l=null;if(s.length===1&&(l=s[0]._getPcbCircuitJsonBounds().center),s.length>1){if(!FBe(s))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${s.map(d=>d.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)`);l=EBe(s)}if(l){let d=this.getSubcircuit(),x=this._shouldIncludeInBoardPinout(),f=e.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...x?{is_board_pinout:!0}:{},...l,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=f.pcb_port_id}else{let d=s[0];throw new Error(`${d.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;if(this.pcb_port_id)return;let a=this.matchedComponents.filter(f=>f.isPcbPrimitive);if(a.length===0)return;let s=null;if(a.length===1&&(s=a[0]._getPcbCircuitJsonBounds().center),a.length>1)try{FBe(a)&&(s=EBe(a))}catch{}if(!s)return;let l=this.getSubcircuit(),d=this._shouldIncludeInBoardPinout(),x=e.pcb_port.insert({pcb_component_id:this.parent?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...d?{is_board_pinout:!0}:{},...s,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=x.pcb_port_id}doInitialSchematicPortRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getPrimitiveContainer();if(!s||!this._hasSchematicPort())return;let l=s._getGlobalSchematicPositionBeforeLayout(),d=this._getGlobalSchematicPositionBeforeLayout(),x=null,f=s._getSchematicBoxDimensions();f&&a.pinNumber!==void 0&&(x=f.getPortPositionByPinNumber(a.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&e.schematic_debug_object.insert({shape:"rect",center:d,size:{width:.1,height:.1},label:"obstacle"}),x?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[x.side]:this.facingDirection=jVt(l,d);let m=e.source_port.get(this.source_port_id),D=[];for(let w of m?.port_hints??[])w.match(/^(pin)?\d+$/)||w.match(/^(left|right)/)&&!m?.name.match(/^(left|right)/)||D.push(w);let b;this.parent?.props?.showPinAliases&&D.length>0?b=D.join("/"):D.length>0&&(b=D[0]);let A={type:"schematic_port",schematic_component_id:this.parent?.schematic_component_id,center:d,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:x?.side,pin_number:a.pinNumber,true_ccw_index:x?.trueIndex,display_pin_label:b,is_connected:!1};for(let w of this._getMatchingPinAttributes())w.requiresPower&&(A.has_input_arrow=!0),w.providesPower&&(A.has_output_arrow=!0);let B=e.schematic_port.insert(A);this.schematic_port_id=B.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(e){let{db:a}=this.root;this.pcb_port_id&&a.pcb_port.update(this.pcb_port_id,{x:e.x,y:e.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(e=>e.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},WBe=r=>{let e=r.find(a=>/^(pin)?\d+$/.test(a));return e?Number.parseInt(e.replace(/^pin/,"")):null};function qF(r,e){let a=WBe(r);if(!a)return null;let l=[...r.filter(d=>d.toString()!==a.toString()&&d!==`pin${a}`),...e?.additionalAliases?.[`pin${a}`]??[]];return new Ni({pinNumber:a,aliases:l})}var NVt=r=>{for(let e of["leftSide","rightSide","topSide","bottomSide"])if(e in r&&typeof r[e]=="number")throw new Error(`A number was specified for "${e}", you probably meant to use "size" not "side"`);return"leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r},MVt=r=>{if(NVt(r))return{leftSize:r.leftSide?.pins.length??0,rightSize:r.rightSide?.pins.length??0,topSize:r.topSide?.pins.length??0,bottomSize:r.bottomSide?.pins.length??0};let{leftSize:e=0,rightSize:a=0,topSize:s=0,bottomSize:l=0}=r;return{leftSize:e,rightSize:a,topSize:s,bottomSize:l}};function KBe(r){let e=r;return e.leftSide!==void 0||e.rightSide!==void 0||e.topSide!==void 0||e.bottomSide!==void 0}var OVt=r=>{let e=r.portDistanceFromEdge??.4,a=r.schPortArrangement?MVt(r.schPortArrangement):null,s={left:0,right:0,top:0,bottom:0},l=r.pinCount??null;if(l===null)if(a)l=a.leftSize+a.rightSize+a.topSize;else throw new Error("Could not determine pin count for the schematic box");if(l&&!a){let w=Math.floor(l/2);a={leftSize:l-w,rightSize:w,topSize:0,bottomSize:0}}a||(a={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let d=({side:w,sideIndex:P,truePinIndex:j})=>{if(!r.schPortArrangement||!KBe(r.schPortArrangement))return j+1;let O={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[w],z=r.schPortArrangement?.[`${w}Side`]?.direction??O,ee=r.schPortArrangement?.[`${w}Side`]?.pins,W=P;return z!==O&&(W=ee.length-P-1),YF(ee[W],r.pinLabels)},x=[],f=0,m=0;for(let w=0;w<a.leftSize;w++){let P=d({side:"left",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.topMargin&&(f+=j.topMargin),x.push({trueIndex:m,pinNumber:P,side:"left",distanceFromOrthogonalEdge:f}),j?.bottomMargin&&(f+=j.bottomMargin),w===a.leftSize-1?s.left=f:f+=r.schPinSpacing,m++}f=0;for(let w=0;w<a.bottomSize;w++){let P=d({side:"bottom",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.leftMargin&&(f+=j.leftMargin),x.push({trueIndex:m,pinNumber:P,side:"bottom",distanceFromOrthogonalEdge:f}),j?.rightMargin&&(f+=j.rightMargin),w===a.bottomSize-1?s.bottom=f:f+=r.schPinSpacing,m++}f=0;for(let w=0;w<a.rightSize;w++){let P=d({side:"right",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.bottomMargin&&(f+=j.bottomMargin),x.push({trueIndex:m,pinNumber:P,side:"right",distanceFromOrthogonalEdge:f}),j?.topMargin&&(f+=j.topMargin),w===a.rightSize-1?s.right=f:f+=r.schPinSpacing,m++}f=0;for(let w=0;w<a.topSize;w++){let P=d({side:"top",sideIndex:w,truePinIndex:m}),j=r.numericSchPinStyle?.[`pin${P}`]??r.numericSchPinStyle?.[P];j?.rightMargin&&(f+=j.rightMargin),x.push({trueIndex:m,pinNumber:P,side:"top",distanceFromOrthogonalEdge:f}),j?.leftMargin&&(f+=j.leftMargin),w===a.topSize-1?s.top=f:f+=r.schPinSpacing,m++}let D=r.schWidth;if(D===void 0){D=Math.max(s.top+r.schPinSpacing*2,s.bottom+r.schPinSpacing*2);let w=r.pinLabels?Math.max(...Object.values(r.pinLabels).map(j=>j.length*.1)):0,P=w>0?1.1:0;D=Math.max(D,w+P)}let b=r.schHeight;b||(b=Math.max(s.left+r.schPinSpacing*2,s.right+r.schPinSpacing*2));let E={left:{x:-D/2-e,y:s.left/2},bottom:{x:-s.bottom/2,y:-b/2-e},right:{x:D/2+e,y:-s.right/2},top:{x:s.top/2,y:b/2+e}},A={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},B=x.map(w=>{let{distanceFromOrthogonalEdge:P,side:j}=w,O=E[j],z=A[j];return{x:O.x+P*z.x,y:O.y+P*z.y,...w}});return{getPortPositionByPinNumber(w){let P=B.find(j=>j.pinNumber.toString()===w.toString());return P||null},getSize(){return{width:D,height:b}},getSizeIncludingPins(){return{width:D+(a.leftSize||a.rightSize?.4:0),height:b+(a.topSize||a.bottomSize?.4:0)}},pinCount:l}},LVt=(0,JBe.default)("tscircuit:core:footprint"),ZBe=class extends Qn{get config(){return{componentName:"Footprint",zodProps:CAe}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let r=this.children.filter(E=>E.componentName==="Constraint");if(r.length===0)return;let{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers(),a=E=>e&&"left"in E&&"right"in E?{...E,left:E.right,right:E.left}:E,s=r.flatMap(E=>E._getAllReferencedComponents().componentsWithSelectors).map(({component:E,selector:A,componentSelector:B,edge:w})=>({component:E,selector:A,componentSelector:B,edge:w,bounds:E._getPcbCircuitJsonBounds()}));if(s.some(E=>E.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function l(E){return s.find(({selector:A})=>A===E)}let d=new ug,x={};function f(E){return E in x||(x[E]=new rd(E),d.addEditVariable(x[E],Oa.weak)),x[E]}for(let{selector:E,bounds:A}of s){let B=f(`${E}_x`),w=f(`${E}_y`);d.suggestValue(B,A.center.x),d.suggestValue(w,A.center.y)}for(let E of r){let A=E._parsedProps;if("xDist"in A){let{xDist:B,left:w,right:P,edgeToEdge:j,centerToCenter:O}=a(A),z=f(`${w}_x`),ee=f(`${P}_x`),W=l(w)?.bounds,re=l(P)?.bounds;if(O){let L=new Xa(ee,[-1,z]);d.addConstraint(new Vs(L,Ds.Eq,A.xDist,Oa.required))}else if(j){let L=new Xa(ee,-re.width/2,[-1,z],-W.width/2);d.addConstraint(new Vs(L,Ds.Eq,A.xDist,Oa.required))}}else if("yDist"in A){let{yDist:B,top:w,bottom:P,edgeToEdge:j,centerToCenter:O}=A,z=f(`${w}_y`),ee=f(`${P}_y`),W=l(w)?.bounds,re=l(P)?.bounds;if(O){let L=new Xa(z,[-1,ee]);d.addConstraint(new Vs(L,Ds.Eq,A.yDist,Oa.required))}else if(j){let L=new Xa(z,W.height/2,[-1,ee],-re.height/2);d.addConstraint(new Vs(L,Ds.Eq,A.yDist,Oa.required))}}else if("sameY"in A){let{for:B}=A;if(B.length<2)continue;let w=B.map(j=>f(`${j}_y`)),P=new Xa(...w.slice(1));d.addConstraint(new Vs(P,Ds.Eq,w[0],Oa.required))}else if("sameX"in A){let{for:B}=A;if(B.length<2)continue;let w=B.map(j=>f(`${j}_x`)),P=new Xa(...w.slice(1));d.addConstraint(new Vs(P,Ds.Eq,w[0],Oa.required))}}d.updateVariables(),LVt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(x).map(([E,A])=>({var:E,val:A.value()}))));let m={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:E,bounds:{width:A,height:B}}of s){let w=f(`${E}_x`),P=f(`${E}_y`),j=w.value()-A/2,O=w.value()+A/2,z=P.value()+B/2,ee=P.value()-B/2;m.left=Math.min(m.left,j),m.right=Math.max(m.right,O),m.top=Math.max(m.top,z),m.bottom=Math.min(m.bottom,ee)}let D={x:-(m.right+m.left)/2,y:-(m.top+m.bottom)/2},b=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();D.x+=b.x,D.y+=b.y;for(let{component:E,selector:A}of s){let B=f(`${A}_x`),w=f(`${A}_y`);E._setPositionFromLayout({x:B.value()+D.x,y:w.value()+D.y})}}},XW=v.union([v.number(),v.string()]),vBe=v.object({x:XW,y:XW,z:XW}),QBe=class extends Qn{get config(){return{componentName:"CadModel",zodProps:GAe}}doInitialCadModelRender(){let r=this._findParentWithPcbComponent();if(!r||!r.pcb_component_id)return;let{db:e}=this.root,{boardThickness:a=0}=this.root?._getBoard()??{},s=r._getPcbCircuitJsonBounds(),l=e.pcb_component.get(r.pcb_component_id),d=this._parsedProps;if(!d||typeof d.modelUrl!="string")return;let x=vBe.parse({x:0,y:0,z:0});if(typeof d.rotationOffset=="number")x.z=Number(d.rotationOffset);else if(typeof d.rotationOffset=="object"){let A=vBe.parse(d.rotationOffset);x.x=Number(A.x),x.y=Number(A.y),x.z=Number(A.z)}let f=l5.parse({x:d.pcbX??0,y:d.pcbY??0,z:d.pcbZ??0,...typeof d.positionOffset=="object"?d.positionOffset:{}}),m=r.props.layer==="bottom"?"bottom":"top",D=new URL(d.modelUrl).pathname.split(".").pop()?.toLowerCase(),b={};D==="stl"?b.model_stl_url=this._addCachebustToModelUrl(d.modelUrl):D==="obj"?b.model_obj_url=this._addCachebustToModelUrl(d.modelUrl):D==="gltf"?b.model_gltf_url=this._addCachebustToModelUrl(d.modelUrl):D==="glb"?b.model_glb_url=this._addCachebustToModelUrl(d.modelUrl):D==="step"||D==="stp"?b.model_step_url=this._addCachebustToModelUrl(d.modelUrl):D==="wrl"||D==="vrml"?b.model_wrl_url=this._addCachebustToModelUrl(d.modelUrl):b.model_stl_url=this._addCachebustToModelUrl(d.modelUrl);let E=e.cad_component.insert({position:{x:s.center.x+Number(f.x),y:s.center.y+Number(f.y),z:(m==="bottom"?-a/2:a/2)+Number(f.z)},rotation:{x:Number(x.x),y:(m==="top"?0:180)+Number(x.y),z:m==="bottom"?-((l?.rotation??0)+Number(x.z))+180:(l?.rotation??0)+Number(x.z)},pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,model_unit_to_mm_scale_factor:typeof d.modelUnitToMmScale=="number"?d.modelUnitToMmScale:void 0,...b});this.cad_component_id=E.cad_component_id}_findParentWithPcbComponent(){let r=this.parent;for(;r&&!r.pcb_component_id;)r=r.parent;return r}_addCachebustToModelUrl(r){if(!r||!r.includes("modelcdn.tscircuit.com"))return r;let e=this.root?.getClientOrigin()??"";return`${r}${r.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(e)}`}},e9e=class extends Qn{constructor(){super(...arguments);q(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:VAe}}},$Vt=(r,e)=>{if(!r)return;let a={};for(let[s,l]of Object.entries(r)){let d=YF(s,e),x={leftMargin:l.marginLeft??l.leftMargin,rightMargin:l.marginRight??l.rightMargin,topMargin:l.marginTop??l.topMargin,bottomMargin:l.marginBottom??l.bottomMargin};a[`pin${d}`]={...a[`pin${d}`],...x}}return a},CBe=class{constructor({input:r}){q(this,"input");this.input=r}solveAndMapToTraces(){let r=[];for(let e of this.input.connections){if(e.pointsToConnect.length!==2)continue;let[a,s]=e.pointsToConnect,l={type:"pcb_trace",pcb_trace_id:"",connection_name:e.name,route:[{route_type:"wire",x:a.x,y:a.y,layer:"top",width:.1},{route_type:"wire",x:s.x,y:s.y,layer:"top",width:.1}]};r.push(l)}return r}},zVt=r=>{let e=Math.min(...r.map(d=>d.center.x)),a=Math.max(...r.map(d=>d.center.x)),s=Math.min(...r.map(d=>d.center.y)),l=Math.max(...r.map(d=>d.center.y));return{minX:e,maxX:a,minY:s,maxY:l}},_Be=["top","bottom","inner1","inner2"],US=(r,e=[])=>{let a=[];if(e.length===0){let f=r[0].layers;for(let m of f)a.push(...US(r.slice(1),[m]));return a}if(r.length===0)return[];let s=r[0],l=s.via||s.optional_via,d=e[e.length-1];if(r.length===1){let f=s;return f.layers&&l?f.layers.map(m=>({layer_path:[...e,m]})):f.layers?.includes(d)?[{layer_path:[...e,d]}]:[]}if(!l)return s.layers&&!s.layers.includes(d)?[]:US(r.slice(1),e.concat([d]));let x=(s.optional_via?_Be:_Be.filter(f=>f!==d)).filter(f=>!s.layers||s.layers?.includes(f));for(let f of x)a.push(...US(r.slice(1),e.concat(f)));return a};function ABe(r){let e={x:r.to.x-r.from.x,y:r.to.y-r.from.y},a=Math.abs(e.x),s=Math.abs(e.y);return a>s?e.x>0?"right":"left":e.y>0?"down":"up"}function qg(r,e){return Math.hypot(r.x-e.x,r.y-e.y)}var qVt=r=>{if(r.length===1)return r[0];if(r.some(m=>m.length===0))throw new Error("Cannot merge routes with zero length");let e=[],a=r[0][0],s=r[0][r[0].length-1],l=r[1][0],d=r[1][r[1].length-1],x=Math.min(qg(a,l),qg(a,d)),f=Math.min(qg(s,l),qg(s,d));x<f?e.push(...r[0].reverse()):e.push(...r[0]);for(let m=1;m<r.length;m++){let D=e[e.length-1],b=r[m],E=b[0],A=b[b.length-1],B=qg(D,E),w=qg(D,A);B<w?e.push(...b):e.push(...b.reverse())}for(let m=1;m<e.length-1;m++){let D=e[m-1],b=e[m];D.route_type==="wire"&&b.route_type==="wire"&&D.layer!==b.layer&&e.splice(m,0,{x:D.x,y:D.y,from_layer:D.layer,to_layer:b.layer,route_type:"via"})}return e},UVt=(r,e)=>{let a="_getGlobalPcbPositionBeforeLayout"in r?r._getGlobalPcbPositionBeforeLayout():r,s="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((a.x-s.x)**2+(a.y-s.y)**2)};function VVt(r,e){if(e.length===0)throw new Error("No candidates given to getClosest method");let a=e[0],s=1/0;for(let l of e){let d=UVt(r,l);d<s&&(a=l,s=d)}return a}var GVt=(r,e)=>{let a=0;a+=r.length??0,a+=e.filter(s=>s.is_crossing).length;for(let s=1;s<e.length;s++){let l=e[s-1],d=e[s],x=Math.abs(l.from.x-l.to.x)<.01,f=Math.abs(d.from.x-d.to.x)<.01;x!==f&&a++}return a},HF=r=>({up:"bottom",down:"top",left:"right",right:"left"})[r]??null,ZW=({firstEdge:r,firstEdgePort:e,firstDominantDirection:a,lastEdge:s,lastEdgePort:l,lastDominantDirection:d})=>{if(r&&e)return ZW({lastEdge:{from:r.to,to:r.from},lastEdgePort:e,lastDominantDirection:a}).reverse().map(f=>({from:f.to,to:f.from}));let x=[];if(s&&l){let f={x:s.to.x,y:s.to.y};d==="left"||d==="right"?(f.x=l.position.x,x.push({from:s.to,to:{...f}}),x.push({from:f,to:{...l.position}})):(f.y=l.position.y,x.push({from:s.to,to:{...f}}),x.push({from:f,to:{...l.position}}))}return x=x.filter(f=>wi(f.from,f.to)>.01),x};function XVt(r){try{return[r(),null]}catch(e){return[null,e]}}var YVt=(r,{db:e})=>{let a=r.map(s=>{let l=e.source_port.get(s.source_port_id);if(!l?.source_component_id)return null;let d=e.source_component.get(l.source_component_id);return d?.ftype==="simple_capacitor"?d.max_decoupling_trace_length:null}).filter(s=>s!==null);if(a.length!==0)return Math.min(...a)};function HVt({ports:r,nets:e}){if(r.length>=2)return`${r[0]?.selector} to ${r[1]?.selector}`;if(r.length===1&&e.length===1)return`${r[0]?.selector} to net.${e[0]._parsedProps.name}`}var WVt=(r,{db:e})=>{let a=e.pcb_board.list()[0];if(a.outline){let m=a.outline,D=(b,E)=>{let A=!1;for(let B=0,w=E.length-1;B<E.length;w=B++){let P=E[B].x,j=E[B].y,O=E[w].x,z=E[w].y;j>b.y!=z>b.y&&b.x<(O-P)*(b.y-j)/(z-j)+P&&(A=!A)}return A};return r.some(b=>!D(b,m))}let s=a.width,l=a.height,d=a.center.x,x=a.center.y;return r.some(m=>m.x<d-s/2||m.y<x-l/2||m.x>d+s/2||m.y>x+l/2)},RBe=(r,e)=>Math.abs(r-e)<1e-4,KVt=(r,e,{viaDiameter:a=.5}={})=>{let s=[];for(let l=0;l<r.length-1;l++){let[d,x]=[r[l],r[l+1]],f=l-1>=0?r[l-1]:null,m=RBe(d.y,x.y),D=RBe(d.x,x.x);if(!m&&!D)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${d.x}, ${d.y}), end: (${x.x}, ${x.y})`);let b={type:"rect",layers:[d.layer],center:{x:(d.x+x.x)/2,y:(d.y+x.y)/2},width:m?Math.abs(d.x-x.x):.1,height:D?Math.abs(d.y-x.y):.1,connectedTo:[e]};if(s.push(b),f&&f.layer===d.layer&&d.layer!==x.layer){let E={type:"rect",layers:[d.layer,x.layer],center:{x:d.x,y:d.y},connectedTo:[e],width:a,height:a};s.push(E)}}return s};function t9e(r,e=4){let{center:a,width:s,height:l,rotation:d}=r,x=[],f=d*Math.PI/180,m=Math.cos(f),D=Math.sin(f),b=(d%360+360)%360;if(l<=s?b>=45&&b<135||b>=225&&b<315:b>=135&&b<225||b>=315||b<45){let A=s/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*m,j=-w*D,O=A*1.1,z=Math.abs(l*m)+Math.abs(A*D);x.push({center:{x:a.x+P,y:a.y+j},width:O,height:z})}}else{let A=l/e;for(let B=0;B<e;B++){let w=(B-e/2+.5)*A,P=-w*D,j=w*m,O=Math.abs(s*m)+Math.abs(A*D),z=A*1.1;x.push({center:{x:a.x+P,y:a.y+j},width:O,height:z})}}return x}function JVt(r,e={}){if(r.length<3)return[];let{rectHeight:a=.1}=e,s=[],l=r.map(f=>f.y),d=Math.min(...l),x=Math.max(...l);for(let f=d;f<x;f+=a){let m=f+a/2,D=[];for(let b=0;b<r.length;b++){let E=r[b],A=r[(b+1)%r.length];if(E.y<=m&&A.y>m||A.y<=m&&E.y>m){let B=(m-E.y)*(A.x-E.x)/(A.y-E.y)+E.x;D.push(B)}}D.sort((b,E)=>b-E);for(let b=0;b<D.length;b+=2)if(b+1<D.length){let E=D[b],B=D[b+1]-E;B>1e-6&&s.push({center:{x:E+B/2,y:m},width:B,height:a})}}return s}function ZVt(r,e={}){let{center:a,radius:s}=r,{rectHeight:l=.1}=e,d=[],x=Math.ceil(s*2/l);for(let f=0;f<x;f++){let m=a.y-s+(f+.5)*l,D=m-a.y,b=Math.sqrt(s*s-D*D);b>0&&d.push({center:{x:a.x,y:m},width:b*2,height:l})}return d}var nx=["top","inner1","inner2","bottom"],pK=(r,e)=>{let a=l=>e?l.concat(l.map(d=>e?.getNetConnectedToId(d)).filter(Boolean)):l,s=[];for(let l of r)if(l.type==="pcb_smtpad"){if(l.shape==="circle")s.push({type:"oval",layers:[l.layer],center:{x:l.x,y:l.y},width:l.radius*2,height:l.radius*2,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rect")s.push({type:"rect",layers:[l.layer],center:{x:l.x,y:l.y},width:l.width,height:l.height,connectedTo:a([l.pcb_smtpad_id])});else if(l.shape==="rotated_rect"){let d={center:{x:l.x,y:l.y},width:l.width,height:l.height,rotation:l.ccw_rotation},x=t9e(d);for(let f of x)s.push({type:"rect",layers:[l.layer],center:f.center,width:f.width,height:f.height,connectedTo:a([l.pcb_smtpad_id])})}}else if(l.type==="pcb_keepout")l.shape==="circle"?s.push({type:"oval",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.radius*2,height:l.radius*2,connectedTo:[]}):l.shape==="rect"&&s.push({type:"rect",layers:l.layers,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.type==="pcb_cutout"){if(l.shape==="rect")s.push({type:"rect",layers:nx,center:{x:l.center.x,y:l.center.y},width:l.width,height:l.height,connectedTo:[]});else if(l.shape==="circle"){let d=ZVt({center:l.center,radius:l.radius},{rectHeight:.6});for(let x of d)s.push({type:"rect",layers:nx,center:x.center,width:x.width,height:x.height,connectedTo:[]})}else if(l.shape==="polygon"){let d=JVt(l.points,{rectHeight:.6});for(let x of d)s.push({type:"rect",layers:nx,center:x.center,width:x.width,height:x.height,connectedTo:[]})}}else if(l.type==="pcb_hole")l.hole_shape==="oval"?s.push({type:"oval",center:{x:l.x,y:l.y},width:l.hole_width,height:l.hole_height,connectedTo:[]}):l.hole_shape==="square"?s.push({type:"rect",layers:nx,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]}):(l.hole_shape==="round"||l.hole_shape==="circle")&&s.push({type:"rect",layers:nx,center:{x:l.x,y:l.y},width:l.hole_diameter,height:l.hole_diameter,connectedTo:[]});else if(l.type==="pcb_plated_hole")l.shape==="circle"?s.push({type:"oval",layers:nx,center:{x:l.x,y:l.y},width:l.outer_diameter,height:l.outer_diameter,connectedTo:a([l.pcb_plated_hole_id])}):l.shape==="circular_hole_with_rect_pad"?s.push({type:"rect",layers:nx,center:{x:l.x,y:l.y},width:l.rect_pad_width,height:l.rect_pad_height,connectedTo:a([l.pcb_plated_hole_id])}):(l.shape==="oval"||l.shape==="pill")&&s.push({type:"oval",layers:nx,center:{x:l.x,y:l.y},width:l.outer_width,height:l.outer_height,connectedTo:a([l.pcb_plated_hole_id])});else if(l.type==="pcb_trace"){let d=KVt(l.route.map(x=>({x:x.x,y:x.y,layer:"layer"in x?x.layer:x.from_layer})),l.source_trace_id);s.push(...d)}else l.type==="pcb_via"&&s.push({type:"rect",layers:l.layers,center:{x:l.x,y:l.y},connectedTo:[],width:l.outer_diameter,height:l.outer_diameter});return s},ax=({anchor_position:r,anchor_side:e,text:a,font_size:s=.18})=>{let l=.1*(s/.18),d=a.length*l,x=s,f={...r};switch(e){case"right":f.x-=d/2;break;case"left":f.x+=d/2;break;case"top":f.y-=x/2;break;case"bottom":f.y+=x/2;break}return f},xK=({db:r,source_trace_id:e,sameNetOnly:a,differentNetOnly:s})=>{!a&&!s&&(s=!0);let l=r.source_trace.get(e),d=[];for(let x of r.schematic_trace.list()){if(x.source_trace_id===e)continue;let m=r.source_trace.get(x.source_trace_id)?.subcircuit_connectivity_map_key===l.subcircuit_connectivity_map_key;s&&m||a&&!m||d.push(x)}return d},QVt=({edges:r,otherEdges:e})=>{let a=[...r];for(let s=0;s<a.length;s++){if(s>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let l=a[s],d=Math.abs(l.from.x-l.to.x)<.01?"vertical":l.from.y===l.to.y?"horizontal":"not-orthogonal";if(d==="not-orthogonal")continue;let x=[];for(let P of e){let j=P.from.x===P.to.x?"vertical":P.from.y===P.to.y?"horizontal":"not-orthogonal";if(j==="not-orthogonal"||d===j)continue;if(zp([l.from,l.to],[P.from,P.to],{lineThickness:.01})){let z=d==="vertical"?l.from.x:P.from.x,ee=d==="vertical"?P.from.y:l.from.y,W={x:z,y:ee};x.push({otherEdge:P,crossingPoint:W,distanceFromEdgeFrom:wi(l.from,W)})}}if(x.length===0)continue;let f=x[0];for(let P of x)P.distanceFromEdgeFrom<f.distanceFromEdgeFrom&&(f=P);let m=f.crossingPoint,D=.075;if(m.x===l.from.x&&m.y===l.from.y)continue;let b=F5(l.from,m),E={x:m.x-b.x*D/2,y:m.y-b.y*D/2},A={x:m.x+b.x*D/2,y:m.y+b.y*D/2},B=wi(A,l.to)<D,w=[{from:l.from,to:E},{from:E,to:A,is_crossing:!0},{from:A,to:l.to}];a.splice(s,1,...w),s+=w.length-2,B&&s++}return a},QW=.001,Ug=(r,e)=>{let a=Math.min(e.from.x,e.to.x),s=Math.max(e.from.x,e.to.x),l=Math.min(e.from.y,e.to.y),d=Math.max(e.from.y,e.to.y);return r.x>=a&&r.x<=s&&r.y>=l&&r.y<=d},SBe=r=>{let e=Math.abs(r.from.x-r.to.x)<QW,a=Math.abs(r.from.y-r.to.y)<QW;return e?"vertical":a?"horizontal":"diagonal"},eGt=(r,e)=>{let a=SBe(r),s=SBe(e);if(a===s)return null;if(a==="vertical"&&s==="horizontal"||a==="horizontal"&&s==="vertical"){let E=a==="vertical"?r:e,A=a==="horizontal"?r:e,B=E.from.x,w=A.from.y,P={x:B,y:w};return Ug(P,r)&&Ug(P,e)?P:null}if(a==="vertical"||s==="vertical"){let E=a==="vertical"?r:e,A=a==="vertical"?e:r,B=E.from.x,w=(A.to.y-A.from.y)/(A.to.x-A.from.x),P=A.from.y-w*A.from.x,j=w*B+P,O={x:B,y:j};return Ug(O,r)&&Ug(O,e)?O:null}let l=(r.to.y-r.from.y)/(r.to.x-r.from.x),d=r.from.y-l*r.from.x,x=(e.to.y-e.from.y)/(e.to.x-e.from.x),f=e.from.y-x*e.from.x;if(Math.abs(l-x)<QW)return null;let m=(f-d)/(l-x),D=l*m+d,b={x:m,y:D};return Ug(b,r)&&Ug(b,e)?b:null},tGt=({edges:r,db:e,source_trace_id:a})=>{let s=xK({db:e,source_trace_id:a,sameNetOnly:!0}).flatMap(d=>d.edges),l=new Map;for(let d of r)for(let x of s){let f=eGt(d,x);if(f){let m=`${f.x.toFixed(6)},${f.y.toFixed(6)}`;l.has(m)||l.set(m,f)}}return Array.from(l.values())};function rGt(r){let e=1/0,a=1/0,s=-1/0,l=-1/0;for(let d of r){let x,f,m,D;d.type==="schematic_component"?(x=d.center?.x,f=d.center?.y,m=d.size?.width,D=d.size?.height):d.type==="schematic_box"?(x=d.x,f=d.y,m=d.width,D=d.height):d.type==="schematic_port"?(x=d.center?.x,f=d.center?.y,m=.2,D=.2):d.type==="schematic_text"&&(x=d.position?.x,f=d.position?.y,m=(d.text?.length??0)*.1,D=.2),typeof x=="number"&&typeof f=="number"&&typeof m=="number"&&typeof D=="number"&&(e=Math.min(e,x-m/2),s=Math.max(s,x+m/2),a=Math.min(a,f-D/2),l=Math.max(l,f+D/2))}return{minX:e,maxX:s,minY:a,maxY:l}}function nGt(r,e={}){let{minX:a,maxX:s,minY:l,maxY:d}=r,x=e.padding??1;if(!isFinite(a)||!isFinite(s)||!isFinite(l)||!isFinite(d))return[];let f=a-x,m=s+x,D=d+x,b=l-x,E=.01;return[{type:"rect",layers:["top"],center:{x:(f+m)/2,y:D},width:m-f,height:E,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(f+m)/2,y:b},width:m-f,height:E,connectedTo:[]},{type:"rect",layers:["top"],center:{x:f,y:(D+b)/2},width:E,height:D-b,connectedTo:[]},{type:"rect",layers:["top"],center:{x:m,y:(D+b)/2},width:E,height:D-b,connectedTo:[]}]}var aGt=r=>{let e=r.root.db,a=r._findConnectedPorts().ports??[],s=new Set(a.map(x=>x.schematic_port_id)),l=[];for(let x of e.toArray()){if(x.type==="schematic_component"){let f=!!x.symbol_name,m=x.size.width>x.size.height?"horz":"vert";l.push({type:"rect",layers:["top"],center:x.center,width:x.size.width+(f&&m==="horz"?-.5:0),height:x.size.height+(f&&m==="vert"?-.5:0),connectedTo:[]})}if(x.type==="schematic_port"){if(s.has(x.schematic_port_id))continue;let f=x.facing_direction?E5(x.facing_direction):{x:0,y:0};l.push({type:"rect",layers:["top"],center:{x:x.center.x-f.x*.1,y:x.center.y-f.y*.1},width:.1+Math.abs(f.x)*.3,height:.1+Math.abs(f.y)*.3,connectedTo:[]})}x.type==="schematic_text"&&l.push({type:"rect",layers:["top"],center:x.position,width:(x.text?.length??0)*.1,height:.2,connectedTo:[]}),x.type==="schematic_box"&&l.push({type:"rect",layers:["top"],center:{x:x.x,y:x.y},width:x.width,height:x.height,connectedTo:[]})}let d=rGt(e.toArray());return l.push(...nGt(d,{padding:1})),l},sGt=({edges:r,db:e,source_trace_id:a})=>{let s=e.source_trace.get(a),l=xK({db:e,source_trace_id:a,differentNetOnly:!0}).flatMap(x=>x.edges),d=x=>{let{from:f,to:m}=x;return f.x===m.x?"vertical":"horizontal"};for(let x of r){let f=d(x),m=()=>l.find(b=>d(b)===f&&zp([x.from,x.to],[b.from,b.to],{lineThickness:.05})),D=m();for(;D;)f==="horizontal"?(x.from.y+=.1,x.to.y+=.1):(x.from.x+=.1,x.to.x+=.1),D=m()}},eK=r=>{switch(r){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},iGt=D4e.version??"unknown",UF=class extends Error{constructor(r){super(`${r} (capacity-autorouter@${iGt})`),this.name="AutorouterError"}},YS=class extends Error{constructor(r){super(r.message),this.errorData=r,this.name="TraceConnectionError"}},oGt=r=>{if(r.root?._featureMspSchematicTraceRouting||r._couldNotFindPort||r.root?.schematicDisabled)return;let{db:e}=r.root,{_parsedProps:a,parent:s}=r;if(!s)throw new Error("Trace has no parent");let l,d;try{let Me=r._findConnectedPorts();l=Me.allPortsFound,d=Me.portsWithSelectors??[]}catch(Me){if(Me instanceof YS){e.source_trace_not_connected_error.insert({...Me.errorData,error_type:"source_trace_not_connected_error"});return}throw Me}let{netsWithSelectors:x}=r._findConnectedNets();if(!l)return;let m=d.map(Me=>Me.port.schematic_port_id).sort().join(","),D=r.root?._getBoard();if(D?._connectedSchematicPortPairs&&D._connectedSchematicPortPairs.has(m))return;let b={name:r.source_trace_id,pointsToConnect:[]},E=aGt(r),A=d.filter(({port:Me})=>Me.schematic_port_id!==null).map(({port:Me})=>({port:Me,position:Me._getGlobalSchematicPositionAfterLayout(),schematic_port_id:Me.schematic_port_id??void 0,facingDirection:Me.facingDirection}));if(A.length===1&&x.length===1){let Me=x[0].net,{port:Ge,position:et}=A[0],dt=r.getSubcircuit().selectAll("netlabel").find(ut=>{let it=ut._parsedProps.connection??ut._parsedProps.connectsTo;return it?Array.isArray(it)?it.some(It=>r.getSubcircuit().selectOne(It,{port:!0})===Ge):r.getSubcircuit().selectOne(it,{port:!0})===Ge:!1});if(!dt){let ut=e.schematic_net_label.getWhere({source_trace_id:r.source_trace_id});ut&&(dt=ut)}if(dt){let ut="_getGlobalSchematicPositionBeforeLayout"in dt?dt._getGlobalSchematicPositionBeforeLayout():dt.anchor_position,it=[];et.x===ut.x||et.y===ut.y?it.push({from:et,to:ut}):(it.push({from:et,to:{x:ut.x,y:et.y}}),it.push({from:{x:ut.x,y:et.y},to:ut}));let Ut=e.schematic_trace.insert({source_trace_id:r.source_trace_id,edges:it,junctions:[],subcircuit_connectivity_map_key:r.subcircuit_connectivity_map_key??void 0});r.schematic_trace_id=Ut.schematic_trace_id;return}if(r.props.schDisplayLabel){let ut=HF(Ge.facingDirection)??"bottom";e.schematic_net_label.insert({text:r.props.schDisplayLabel,source_net_id:Me.source_net_id,anchor_position:et,center:ax({anchor_position:et,anchor_side:ut,text:r.props.schDisplayLabel}),anchor_side:ut});return}let $t=HF(Ge.facingDirection)??"bottom",bt=e.schematic_net_label.insert({text:Me._parsedProps.name,source_net_id:Me.source_net_id,anchor_position:et,center:ax({anchor_position:et,anchor_side:$t,text:Me._parsedProps.name}),anchor_side:$t});return}if(r.props.schDisplayLabel&&("from"in r.props&&"to"in r.props||"path"in r.props)){r._doInitialSchematicTraceRenderWithDisplayLabel();return}if(A.length<2)return;let P=(()=>{let Me=[];for(let et=0;et<A.length-1;et++){let dt=A[et],$t=A[et+1],bt=dg({x:dt.position.x,y:dt.position.y,facingDirection:eK(dt.facingDirection)},{x:$t.position.x,y:$t.position.y,facingDirection:eK($t.facingDirection)});for(let ut=0;ut<bt.length-1;ut++)Me.push({from:bt[ut],to:bt[ut+1]})}let Ge=(et,dt)=>{let $t=dt.width/2,bt=dt.height/2,ut=dt.center.x-$t,it=dt.center.x+$t,Ut=dt.center.y-bt,It=dt.center.y+bt,tr=vt=>vt.x>=ut&&vt.x<=it&&vt.y>=Ut&&vt.y<=It;return tr(et.from)||tr(et.to)?!0:[[{x:ut,y:Ut},{x:it,y:Ut}],[{x:it,y:Ut},{x:it,y:It}],[{x:it,y:It},{x:ut,y:It}],[{x:ut,y:It},{x:ut,y:Ut}]].some(vt=>zp([et.from,et.to],vt,{lineThickness:0}))};for(let et of Me)for(let dt of E)if(Ge(et,dt))return null;return Me})();P&&P.length===0&&(P=null),b.pointsToConnect=A.map(({position:Me})=>({...Me,layer:"top"}));let j=zVt(E),O=2,z={minTraceWidth:.1,obstacles:E,connections:[b],bounds:{minX:j.minX-O,maxX:j.maxX+O,minY:j.minY-O,maxY:j.maxY+O},layerCount:1},ee=o5,W=!1;if(r.getSubcircuit().props._schDirectLineRoutingEnabled&&(ee=CBe,W=!0),!P){let Ge=new ee({input:z,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(Ge.length===0){if(r._isSymbolToChipConnection()||r._isSymbolToSymbolConnection()||r._isChipToChipConnection()){r._doInitialSchematicTraceRenderWithDisplayLabel();return}Ge=new CBe({input:z}).solveAndMapToTraces(),W=!0}let[{route:et}]=Ge;P=[];for(let dt=0;dt<et.length-1;dt++)P.push({from:et[dt],to:et[dt+1]})}let re=r.source_trace_id,L=[];if(!W){sGt({edges:P,db:e,source_trace_id:re});let Me=xK({db:e,source_trace_id:re,differentNetOnly:!0}).flatMap(Ge=>Ge.edges);P=QVt({edges:P,otherEdges:Me}),L=tGt({edges:P,db:e,source_trace_id:r.source_trace_id})}if(!P||P.length===0)return;let K=P[P.length-1],U=A[A.length-1],J=ABe(K);P.push(...ZW({lastEdge:K,lastEdgePort:U,lastDominantDirection:J}));let Q=P[0],de=A[0],oe=ABe(Q);if(P.unshift(...ZW({firstEdge:Q,firstEdgePort:de,firstDominantDirection:oe})),!r.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(r.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&GVt(L,P)>=5&&(r._isSymbolToChipConnection()||r._isSymbolToSymbolConnection()||r._isChipToChipConnection())){r._doInitialSchematicTraceRenderWithDisplayLabel();return}let Te=e.schematic_trace.insert({source_trace_id:r.source_trace_id,edges:P,junctions:L,subcircuit_connectivity_map_key:r.subcircuit_connectivity_map_key??void 0});r.schematic_trace_id=Te.schematic_trace_id;for(let{port:Me}of d)Me.schematic_port_id&&e.schematic_port.update(Me.schematic_port_id,{is_connected:!0});D?._connectedSchematicPortPairs&&D._connectedSchematicPortPairs.add(m)};function r9e(r){let e=0;for(let a=0;a<r.length;a++){let s=r[a];if(s.route_type==="wire"){let l=r[a+1];if(l){let d=l.x-s.x,x=l.y-s.y;e+=Math.sqrt(d*d+x*x)}}else s.route_type==="via"&&(e+=1.6)}return e}var LS=r=>({...r._getGlobalPcbPositionAfterLayout(),layers:r.getAvailablePcbLayers()}),uGt=!1;function cGt(r){if(r.root?.pcbDisabled)return;let{db:e}=r.root,{_parsedProps:a,parent:s}=r,l=r.getSubcircuit();if(!s)throw new Error("Trace has no parent");if(l._parsedProps.routingDisabled)return;let d=l._parsedProps.pcbRouteCache?.pcbTraces;if(d){let J=e.pcb_trace.insert({route:d.flatMap(Q=>Q.route),source_trace_id:r.source_trace_id,subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0});r.pcb_trace_id=J.pcb_trace_id;return}if(a.pcbPath&&a.pcbPath.length>0||!l._shouldUseTraceByTraceRouting())return;let{allPortsFound:x,ports:f}=r._findConnectedPorts(),m=[];if(!x)return;let D=[];for(let J of f)J._hasMatchedPcbPrimitive()||D.push(J);if(D.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:r.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, ${r} wasn't routed. Missing ports: ${D.map(J=>J.getString()).join(", ")}`,pcb_trace_id:r.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:D.map(J=>J.pcb_port_id).filter(Boolean)});return}let b=r._findConnectedNets().netsWithSelectors;if(f.length===0&&b.length===2){r.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(f.length===1&&b.length===1){let J=f[0],de=b[0].net.getAllConnectedPorts().filter(Te=>Te!==J);if(de.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let oe=VVt(J,de);m.push(oe),f.push(oe)}else if(f.length>1&&b.length>=1){r.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 E=f.flatMap(J=>J.matchedComponents.filter(Q=>Q.componentName==="TraceHint")),A=(r._parsedProps.pcbRouteHints??[]).concat(E.flatMap(J=>J.getPcbRouteHints()));if(f.length>2){r.renderError(`Trace has more than two ports (${f.map(J=>J.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(r.getSubcircuit().selectAll("trace").filter(J=>J.renderPhaseStates.PcbTraceRender.initialized).some(J=>J._portsRoutedOnPcb.length===f.length&&J._portsRoutedOnPcb.every(Q=>f.includes(Q))))return;let P=[];A.length===0?P=[LS(f[0]),LS(f[1])]:P=[LS(f[0]),...A,LS(f[1])];let j=US(P);if(uGt&&j.length===0){r.renderError(`Could not find a common layer (using hints) for trace ${r.getString()}`);return}let O=eu(r.root.db.toArray()),[z,ee]=XVt(()=>pK(r.root.db.toArray()));if(ee){r.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:r.pcb_trace_id,message:`Error getting obstacles for autorouting: ${ee.message}`,source_trace_id:r.source_trace_id,center:{x:0,y:0},pcb_port_ids:f.map(J=>J.pcb_port_id),pcb_trace_id:r.pcb_trace_id,pcb_component_ids:[]});return}for(let J of z)if(J.connectedTo.length>0){let de=O.getNetConnectedToId(J.connectedTo[0]);de&&J.connectedTo.push(de)}let W=[];if(j.length===0)W=P;else{let J=j[0].layer_path;W=P.map((Q,de)=>Q.via?{...Q,via_to_layer:J[de]}:{...Q,layers:[J[de]]})}W[0].pcb_port_id=f[0].pcb_port_id,W[W.length-1].pcb_port_id=f[1].pcb_port_id;let re=[];for(let[J,Q]of HBe(W)){let de="via_to_layer"in J?J.via_to_layer:null,oe=2,Te="layers"in J&&J.layers.length===1?J.layers[0]:de??"top",Me="layers"in Q&&Q.layers.length===1?Q.layers[0]:de??"top",Ge="pcb_port_id"in J?J.pcb_port_id:null,et="pcb_port_id"in Q?Q.pcb_port_id:null,dt=r.getSubcircuit()._parsedProps.minTraceWidth??.16,$t=new o5({OBSTACLE_MARGIN:dt*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(Ge&&et),connMap:O,input:{obstacles:z,minTraceWidth:dt,connections:[{name:r.source_trace_id,pointsToConnect:[{...J,layer:Te,pcb_port_id:Ge},{...Q,layer:Me,pcb_port_id:et}]}],layerCount:r.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(J.x,Q.x)-oe,maxX:Math.max(J.x,Q.x)+oe,minY:Math.min(J.y,Q.y)-oe,maxY:Math.max(J.y,Q.y)+oe}}}),bt=null;try{bt=$t.solveAndMapToTraces()}catch(Ut){r.renderError({type:"pcb_trace_error",pcb_trace_error_id:r.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${Ut.message}`,source_trace_id:r.pcb_trace_id,center:{x:(J.x+Q.x)/2,y:(J.y+Q.y)/2},pcb_port_ids:f.map(It=>It.pcb_port_id),pcb_trace_id:r.pcb_trace_id,pcb_component_ids:f.map(It=>It.pcb_component_id)})}if(!bt)return;if(bt.length===0){r.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:r.pcb_trace_id,message:`Could not find a route for ${r}`,source_trace_id:r.source_trace_id,center:{x:(J.x+Q.x)/2,y:(J.y+Q.y)/2},pcb_port_ids:f.map(Ut=>Ut.pcb_port_id),pcb_trace_id:r.pcb_trace_id,pcb_component_ids:f.map(Ut=>Ut.pcb_component_id)});return}let[ut]=bt;de&&(ut.route=ut.route.map(Ut=>(Ut.route_type==="wire"&&!Ut.layer&&(Ut.layer=de),Ut))),Ge&&ut.route[0].route_type==="wire"&&(ut.route[0].start_pcb_port_id=Ge);let it=ut.route[ut.route.length-1];et&&it.route_type==="wire"&&(it.end_pcb_port_id=et),re.push(ut.route)}let L=qVt(re),K=r9e(L),U=e.pcb_trace.insert({route:L,source_trace_id:r.source_trace_id,subcircuit_id:r.getSubcircuit()?.subcircuit_id,trace_length:K});r._portsRoutedOnPcb=f,r.pcb_trace_id=U.pcb_trace_id;for(let J of L)J.route_type==="via"&&e.pcb_via.insert({pcb_trace_id:U.pcb_trace_id,x:J.x,y:J.y,hole_diameter:.3,outer_diameter:.6,layers:[J.from_layer,J.to_layer],from_layer:J.from_layer,to_layer:J.to_layer});r._insertErrorIfTraceIsOutsideBoard(L,f)}function lGt(r){if(r.root?.pcbDisabled)return;let{db:e}=r.root,{_parsedProps:a}=r,s=r.getSubcircuit();if(!a.pcbPath||a.pcbPath.length===0)return;let{allPortsFound:l,ports:d,portsWithSelectors:x}=r._findConnectedPorts();if(!l)return;let f=[];for(let z of d)z._hasMatchedPcbPrimitive()||f.push(z);if(f.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:r.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, ${r} wasn't routed. Missing ports: ${f.map(z=>z.getString()).join(", ")}`,pcb_trace_id:r.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:f.map(z=>z.pcb_port_id).filter(Boolean)});return}let m;a.pcbPathRelativeTo&&(m=x.find(z=>z.selector===a.pcbPathRelativeTo)?.port,m||(m=r.getSubcircuit().selectOne(a.pcbPathRelativeTo))),m||(m=d[0]);let D=d.find(z=>z!==m)??d[1],b=m.getAvailablePcbLayers()[0]||"top",E=a.thickness??r.getSubcircuit()._parsedProps.minTraceWidth??.16,A=m._getGlobalPcbPositionAfterLayout(),B=D._getGlobalPcbPositionAfterLayout(),w=[];w.push({route_type:"wire",x:A.x,y:A.y,width:E,layer:b,start_pcb_port_id:m.pcb_port_id});let P=m?._computePcbGlobalTransformBeforeLayout?.()||Si();for(let z of a.pcbPath){let ee=as(P,{x:z.x,y:z.y});w.push({route_type:"wire",x:ee.x,y:ee.y,width:E,layer:b})}w.push({route_type:"wire",x:B.x,y:B.y,width:E,layer:b,end_pcb_port_id:D.pcb_port_id});let j=r9e(w),O=e.pcb_trace.insert({route:w,source_trace_id:r.source_trace_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0,trace_length:j});r._portsRoutedOnPcb=d,r.pcb_trace_id=O.pcb_trace_id,r._insertErrorIfTraceIsOutsideBoard(w,d)}function dGt(r){if(r.root?.schematicDisabled)return;let{db:e}=r.root,{_parsedProps:a,parent:s}=r;if(!s)throw new Error("Trace has no parent");let{allPortsFound:l,portsWithSelectors:d}=r._findConnectedPorts();if(!l)return;let x=d.map(({port:W})=>({port:W,position:W._getGlobalSchematicPositionAfterLayout(),schematic_port_id:W.schematic_port_id,facingDirection:W.facingDirection}));if(x.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let f,m,D=x[0].position,b=x[0].port;if("path"in r.props){if(r.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[f,m]=r.props.path}else{if(!("from"in r.props&&"to"in r.props))throw new Error("Missing 'from' or 'to' properties in props.");f=r.props.from,m=r.props.to}if(!b.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${f}).`);let E=x[1].position,A=x[1].port;if(!A.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${m}).`);let B=e.schematic_net_label.list().find(W=>W.source_net_id===b.source_port_id),w=e.schematic_net_label.list().find(W=>W.source_net_id===A.source_port_id),[P,j]=d.map(({port:W})=>W),z=P.parent?.config.shouldRenderAsSchematicBox?`${P?.parent?.props.name}_${P?.props.name}`:`${j?.parent?.props.name}_${j?.props.name}`,ee=r.props.schDisplayLabel??z;if(B&&B.text!==ee&&(B.text=`${ee} / ${B.text}`),w&&w?.text!==ee&&(w.text=`${ee} / ${w.text}`),!w){let W=HF(A.facingDirection)??"bottom";e.schematic_net_label.insert({text:r.props.schDisplayLabel??z,source_net_id:A.source_port_id,anchor_position:E,center:ax({anchor_position:E,anchor_side:W,text:r.props.schDisplayLabel??z}),anchor_side:W})}if(!B){let W=HF(b.facingDirection)??"bottom";e.schematic_net_label.insert({text:r.props.schDisplayLabel??z,source_net_id:b.source_port_id,anchor_position:D,center:ax({anchor_position:D,anchor_side:W,text:r.props.schDisplayLabel??z}),anchor_side:W})}}function pGt(r){let{_parsedProps:e,parent:a}=r;if(!a)throw new Error("Trace has no parent");let l=r.getTracePortPathSelectors().map(d=>({selector:d,port:r.getSubcircuit().selectOne(d,{type:"port"})??null}));for(let{selector:d,port:x}of l)if(!x){let f,m,D=d.lastIndexOf(".");if(D!==-1&&D>d.lastIndexOf(" "))f=d.slice(0,D),m=d.slice(D+1);else{let W=d.match(/^(.*[ >])?([^ >]+)$/);f=W?.[1]?.trim()??"",m=W?.[2]??d}let b=f?r.getSubcircuit().selectOne(f):null;if(!b&&f&&!/[.#\[]/.test(f)&&(b=r.getSubcircuit().selectOne(`.${f}`)),!b){let W=f?`Could not find port for selector "${d}". Component "${f}" not found`:`Could not find port for selector "${d}"`,re=r.getSubcircuit(),L=re.getGroup();throw new YS({error_type:"source_trace_not_connected_error",message:W,subcircuit_id:re.subcircuit_id??void 0,source_group_id:L?.source_group_id??void 0,source_trace_id:r.source_trace_id??void 0,selectors_not_found:[d]})}let E=b.children.filter(W=>W.componentName==="Port"),A=m.includes(".")?m.split(".").pop()??"":m,B=E.flatMap(W=>W.getNameAndAliases()),w=B.some(W=>!/^(pin\d+|\d+)$/.test(W)),P=Array.from(new Set(B)).join(", "),j;E.length===0?j="It has no ports":w?j=`It has [${P}]`:j=`It has ${E.length} pins and no pinLabels (consider adding pinLabels)`;let O=`Could not find port for selector "${d}". Component "${b.props.name??f}" found, but does not have pin "${A}". ${j}`,z=r.getSubcircuit(),ee=z.getGroup();throw new YS({error_type:"source_trace_not_connected_error",message:O,subcircuit_id:z.subcircuit_id??void 0,source_group_id:ee?.source_group_id??void 0,source_trace_id:r.source_trace_id??void 0,selectors_not_found:[d]})}return l.some(d=>!d.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:l,ports:l.map(({port:d})=>d)}}var qc=class extends Qn{constructor(e){super(e);q(this,"source_trace_id",null);q(this,"pcb_trace_id",null);q(this,"schematic_trace_id",null);q(this,"_portsRoutedOnPcb");q(this,"subcircuit_connectivity_map_key",null);q(this,"_traceConnectionHash",null);q(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}get config(){return{zodProps:vAe,componentName:"Trace"}}_getTracePortOrNetSelectorListFromProps(){return"from"in this.props&&"to"in this.props?[typeof this.props.from=="string"?this.props.from:this.props.from.getPortSelector(),typeof this.props.to=="string"?this.props.to:this.props.to.getPortSelector()]:"path"in this.props?this.props.path.map(e=>typeof e=="string"?e:e.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>!e.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>e.includes("net."))}_findConnectedPorts(){return pGt(this)}_resolveNet(e){let a=this.getSubcircuit().selectOne(e,{type:"net"});if(a)return a;let s=e.match(/^net\.(.+)$/),l=s?s[1]:null;return l&&this.root._getBoard().getDescendants().find(x=>x.componentName==="Net"&&x._parsedProps.name===l)||null}_findConnectedNets(){let e=this.getTracePathNetSelectors().map(s=>({selector:s,net:this._resolveNet(s)})),a=e.filter(s=>!s.net);return a.length>0&&this.renderError(`Could not find net for selector "${a[0].selector}" inside ${this}`),{netsWithSelectors:e,nets:e.map(s=>s.net)}}_getAllTracesConnectedToSameNet(){let e=this.getSubcircuit().selectAll("trace"),a=this._findConnectedNets().nets,s=this._findConnectedPorts().ports??[];return e.filter(l=>{if(l===this)return!1;let d=l._findConnectedNets().nets,x=l._findConnectedPorts().ports??[];return d.some(f=>a.includes(f))||x.some(f=>s.includes(f))})}_isExplicitlyConnectedToPort(e){let{allPortsFound:a,portsWithSelectors:s}=this._findConnectedPorts();return a?s.map(d=>d.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){uK(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();return!e||!a?null:[...a].sort((d,x)=>(d.pcb_port_id||"").localeCompare(x.pcb_port_id||"")).map(d=>d.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:e}=this.root,{_parsedProps:a,parent:s}=this;if(!s){this.renderError("Trace has no parent");return}let l,d;try{let E=this._findConnectedPorts();l=E.allPortsFound,d=E.portsWithSelectors??[]}catch(E){if(E instanceof YS){e.source_trace_not_connected_error.insert({...E.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw E}if(!l)return;this._traceConnectionHash=this._computeTraceConnectionHash();let f=e.source_trace.list().find(E=>E.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&E.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(f){this.source_trace_id=f.source_trace_id;return}let m=this._findConnectedNets().nets,D=HVt({ports:d,nets:m}),b=e.source_trace.insert({connected_source_port_ids:d.map(E=>E.port.source_port_id),connected_source_net_ids:m.map(E=>E.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:YVt(d.map(E=>E.port),{db:e})??a.maxLength,display_name:D,min_trace_thickness:a.thickness});this.source_trace_id=b.source_trace_id}_insertErrorIfTraceIsOutsideBoard(e,a){let{db:s}=this.root;WVt(e,{db:s})&&s.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:a.map(d=>d.pcb_port_id)})}doInitialPcbManualTraceRender(){lGt(this)}doInitialPcbTraceRender(){cGt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){dGt(this)}_isSymbolToChipConnection(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();if(!e||a.length!==2)return!1;let[s,l]=a;if(!s?.parent||!l?.parent)return!1;let d=s.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return d&&!x||!d&&x}_isSymbolToSymbolConnection(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();if(!e||a.length!==2)return!1;let[s,l]=a;if(!s?.parent||!l?.parent)return!1;let d=!s.parent.config.shouldRenderAsSchematicBox,x=!l.parent.config.shouldRenderAsSchematicBox;return d&&x}_isChipToChipConnection(){let{allPortsFound:e,ports:a}=this._findConnectedPorts();if(!e||a.length!==2)return!1;let[s,l]=a;if(!s?.parent||!l?.parent)return!1;let d=s.parent.config.shouldRenderAsSchematicBox,x=l.parent.config.shouldRenderAsSchematicBox;return d&&x}doInitialSchematicTraceRender(){oGt(this)}},xGt=r=>{let{db:e}=r.root;if(r.pcb_component_id){let a=e.pcb_component.get(r.pcb_component_id);return a?{width:a.width,height:a.height}:null}if(r.pcb_group_id){let a=e.pcb_group.get(r.pcb_group_id);return a?{width:a.width,height:a.height}:null}return null},fGt=(r,e)=>{let{db:a}=r.root,s=a.toArray();if(r.pcb_component_id){C5(s,r.pcb_component_id,e);return}if(r.source_group_id){_5(s,r.source_group_id,e);return}throw new Error(`Cannot reposition component ${r.getString()}: no pcb_component_id or source_group_id`)},hGt=r=>{let{db:e}=r.root;if(!r.source_component_id)return;let a=r.selectAll("port"),s=e.source_trace.list(),l=new Set;for(let x of s)for(let f of x.connected_source_port_ids)l.add(f);let d=r._getInternallyConnectedPins();for(let x of d)if(x.some(f=>f.source_port_id&&l.has(f.source_port_id)))for(let f of x)f.source_port_id&&l.add(f.source_port_id);for(let x of a)x.source_port_id&&mGt(r,x)&&(l.has(x.source_port_id)||e.source_pin_missing_trace_warning.insert({message:`Port ${x.getNameAndAliases()[0]} on ${r.props.name} is missing a trace`,source_component_id:r.source_component_id,source_port_id:x.source_port_id,subcircuit_id:r.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},mGt=(r,e)=>{if(r.config.componentName==="Chip"){let a=r.props.pinAttributes;if(!a)return!1;for(let s of e.getNameAndAliases()){let l=a[s];if(l?.requiresPower||l?.requiresGround||l?.requiresVoltage!==void 0)return!0}return!1}return!0};function gGt(r){let e=r.font_size,a=r.text.length*e*.6,s=e,l=r.anchor_alignment||"center",d=r.anchor_position.x,x=r.anchor_position.y;switch(l){case"top_left":d=r.anchor_position.x+a/2,x=r.anchor_position.y+s/2;break;case"top_center":d=r.anchor_position.x,x=r.anchor_position.y+s/2;break;case"top_right":d=r.anchor_position.x-a/2,x=r.anchor_position.y+s/2;break;case"center_left":d=r.anchor_position.x+a/2,x=r.anchor_position.y;break;case"center":d=r.anchor_position.x,x=r.anchor_position.y;break;case"center_right":d=r.anchor_position.x-a/2,x=r.anchor_position.y;break;case"bottom_left":d=r.anchor_position.x+a/2,x=r.anchor_position.y-s/2;break;case"bottom_center":d=r.anchor_position.x,x=r.anchor_position.y-s/2;break;case"bottom_right":d=r.anchor_position.x-a/2,x=r.anchor_position.y-s/2;break;default:d=r.anchor_position.x,x=r.anchor_position.y;break}return{x:d-a/2,y:x-s/2,width:a,height:s}}function DGt(r){if(!r._adjustSilkscreenTextAutomatically||r.root?.pcbDisabled||!r.pcb_component_id)return;let{db:e}=r.root,s=r._getPcbCircuitJsonBounds().center,l=e.pcb_silkscreen_text.list({pcb_component_id:r.pcb_component_id}).filter(m=>m.text===r.name);if(l.length===0)return;let f=r.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(m=>m!==r&&m.pcb_component_id).map(m=>{let D=m._getPcbCircuitJsonBounds(),b={center:D.center,width:D.width,height:D.height};return td(b)});for(let m of l){let D=m.anchor_position,b=gGt(m),E={center:{x:b.x+b.width/2,y:b.y+b.height/2},width:b.width,height:b.height},A=td(E);if(!f.some(ee=>Yb(A,ee)))continue;let w=2*s.x-D.x,P=2*s.y-D.y,j={center:{x:w,y:P},width:b.width,height:b.height},O=td(j);f.some(ee=>Yb(O,ee))||e.pcb_silkscreen_text.update(m.pcb_silkscreen_text_id,{anchor_position:{x:w,y:P}})}}function yGt(r){if(!r)return{validPinLabels:r,invalidPinLabelsMessages:[]};let e={},a=[];for(let[s,l]of Object.entries(r)){let d=Array.isArray(l)?l.slice():[l],x=[];for(let f of d)bGt(s,f)?x.push(f):a.push(`Invalid pin label: ${s} = '${f}' - excluding from component. Please use a valid pin label.`);x.length>0&&(e[s]=Array.isArray(l)?x:x[0])}return{validPinLabels:Object.keys(e).length>0?e:void 0,invalidPinLabelsMessages:a}}function bGt(r,e){try{let a={name:"test",footprint:"test",pinLabels:{[r]:e}};return og.safeParse(a).success}catch{return!1}}var HS=r=>r.startsWith("http://")||r.startsWith("https://"),rK=r=>{if(HS(r))return null;let e=r.indexOf(":");if(e<=0)return null;let a=r.slice(0,e),s=r.slice(e+1);return!a||!s?null:{footprintLib:a,footprintName:s}};function FGt(r,e){let{footprint:a}=r.props;if(a??(a=r._getImpliedFootprintString?.()),!a)return;let{pcbRotation:s,pinLabels:l,pcbPinLabels:d}=r.props;if(typeof a=="string"&&HS(a)){if(r._hasStartedFootprintUrlLoad)return;r._hasStartedFootprintUrlLoad=!0;let x=a;e("load-footprint-url",async()=>{try{let f=await fetch(x);if(!f.ok)throw new Error(`Failed to fetch footprint: ${f.status}`);let m=await f.json(),D=qS({componentName:r.name,componentRotation:s,footprint:x,pinLabels:l,pcbPinLabels:d},m);r.addAll(D),r._markDirty("InitializePortsFromChildren")}catch(f){let m=r.root?.db;if(m&&r.source_component_id&&r.pcb_component_id){let D=r.getSubcircuit(),b=`${r.getString()} failed to load external footprint "${x}": `+(f instanceof Error?f.message:String(f)),E=yb.parse({type:"external_footprint_load_error",message:b,pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,subcircuit_id:D.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0,footprinter_string:x});m.external_footprint_load_error.insert(E)}throw f}});return}if(typeof a=="string"){let x=rK(a);if(!x||r._hasStartedFootprintUrlLoad)return;r._hasStartedFootprintUrlLoad=!0;let m=r.root?.platform?.footprintLibraryMap?.[x.footprintLib],D;if(typeof m=="function"&&(D=m),!D)return;e("load-lib-footprint",async()=>{try{let b=await D(x.footprintName),E=null;if(Array.isArray(b)?E=b:Array.isArray(b.footprintCircuitJson)&&(E=b.footprintCircuitJson),!E)return;let A=qS({componentName:r.name,componentRotation:s,footprint:a,pinLabels:l,pcbPinLabels:d},E);r.addAll(A),!Array.isArray(b)&&b.cadModel&&(r._asyncFootprintCadModel=b.cadModel);for(let B of r.children)B.componentName==="Port"&&B._markDirty?.("PcbPortRender");r._markDirty("InitializePortsFromChildren")}catch(b){let E=r.root?.db;if(E&&r.source_component_id&&r.pcb_component_id){let A=r.getSubcircuit(),B=`${r.getString()} failed to load external footprint "${a}": `+(b instanceof Error?b.message:String(b)),w=yb.parse({type:"external_footprint_load_error",message:B,pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,subcircuit_id:A.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0,footprinter_string:a});E.external_footprint_load_error.insert(w)}throw b}});return}if(!(0,tK.isValidElement)(a)&&a.componentName==="Footprint"&&r.add(a),Array.isArray(a)&&!(0,tK.isValidElement)(a)&&a.length>0){try{let x=qS({componentName:r.name,componentRotation:s,footprint:"",pinLabels:l,pcbPinLabels:d},a);r.addAll(x)}catch(x){let f=r.root?.db;if(f&&r.source_component_id&&r.pcb_component_id){let m=r.getSubcircuit(),D=`${r.getString()} failed to load json footprint: `+(x instanceof Error?x.message:String(x)),b=VA.parse({type:"circuit_json_footprint_load_error",message:D,pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,subcircuit_id:m.subcircuit_id??void 0,pcb_group_id:r.getGroup()?.pcb_group_id??void 0});f.circuit_json_footprint_load_error.insert(b)}throw x}return}}function EGt(r){if(r.root?.pcbDisabled||!r.pcb_component_id)return;let{pcbX:e,pcbY:a}=r._parsedProps,s=r.props?.pcbPositionAnchor;if(!s||e===void 0&&a===void 0)return;let l=ZS(r.children);if(l.width===0||l.height===0)return;let x={...{x:(l.minX+l.maxX)/2,y:(l.minY+l.maxY)/2}},f=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(s)){let b={left:l.minX,right:l.maxX,top:l.minY,bottom:l.maxY};switch(s){case"center":f=x;break;case"top_left":f={x:b.left,y:b.top};break;case"top_center":f={x:x.x,y:b.top};break;case"top_right":f={x:b.right,y:b.top};break;case"center_left":f={x:b.left,y:x.y};break;case"center_right":f={x:b.right,y:x.y};break;case"bottom_left":f={x:b.left,y:b.bottom};break;case"bottom_center":f={x:x.x,y:b.bottom};break;case"bottom_right":f={x:b.right,y:b.bottom};break}}else try{let b=r.portMap[s];b&&(f=b._getGlobalPcbPositionBeforeLayout())}catch{}if(!f)return;let D={...x};e!==void 0&&(D.x+=e-f.x),a!==void 0&&(D.y+=a-f.y),(Math.abs(D.x-x.x)>1e-6||Math.abs(D.y-x.y)>1e-6)&&r._repositionOnPcb(D)}var vGt=(0,UBe.default)("tscircuit:core"),CGt=v.object({x:Vn,y:Vn,z:Vn}),es=class extends Qn{constructor(e){let a={...e},s=[];if(a.pinLabels&&!Array.isArray(a.pinLabels)){let{validPinLabels:l,invalidPinLabelsMessages:d}=yGt(a.pinLabels);a.pinLabels=l,s=d}super(a);q(this,"reactSubtrees",[]);q(this,"_impliedFootprint");q(this,"isPrimitiveContainer",!0);q(this,"_isNormalComponent",!0);q(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});q(this,"_asyncSupplierPartNumbers");q(this,"_asyncFootprintCadModel");q(this,"_isCadModelChild");q(this,"pcb_missing_footprint_error_id");q(this,"_hasStartedFootprintUrlLoad",!1);q(this,"_invalidPinLabelMessages",[]);q(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=s,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(a=>a.map(s=>typeof s=="number"?`pin${s}`:s))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let e=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(l=>l!==this&&l._isNormalComponent&&l.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let l=this._getGlobalPcbPositionBeforeLayout(),d=this._getGlobalSchematicPositionBeforeLayout();e.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:l,schematic_center:d}),this.shouldBeRemoved=!0;let x=[...this.children];for(let f of x)this.remove(f)}}initPorts(e={}){if(this.root?.schematicDisabled)return;let{config:a}=this,s=[],l=this._getSchematicPortArrangement();if(l&&!this._parsedProps.pinLabels){for(let D in l){let b=l[D].pins;if(Array.isArray(b))for(let E of b){let A=YF(E,this._parsedProps.pinLabels);s.push(new Ni({pinNumber:A,aliases:e.additionalAliases?.[`pin${A}`]??[]},{originDescription:`schPortArrangement:${D}`}))}}let f=["left","right","top","bottom"],m=1;for(let D of f){let b=l[`${D}Size`];for(let E=0;E<b;E++)s.push(new Ni({pinNumber:m++,aliases:e.additionalAliases?.[`pin${m}`]??[]},{originDescription:`schPortArrangement:${D}`}))}}let d=this._parsedProps.pinLabels;if(d)for(let[f,m]of Object.entries(d)){f=f.replace("pin","");let D=s.find(A=>A._parsedProps.pinNumber===Number(f)),b=Array.isArray(m)?m[0]:m,E=Array.isArray(m)?m.slice(1):[];D?(D.externallyAddedAliases.push(b,...E),D.props.name=b):(D=new Ni({pinNumber:parseInt(f),name:b,aliases:[...E,...e.additionalAliases?.[`pin${parseInt(f)}`]??[]]},{originDescription:`pinLabels:pin${f}`}),s.push(D))}if(a.schematicSymbolName&&!e.ignoreSymbolPorts){let f=ks[this._getSchematicSymbolNameOrThrow()];if(!f)return;for(let m of f.ports){let D=WBe(m.labels);if(!D)continue;let b=s.find(E=>E._parsedProps.pinNumber===Number(D));if(b)b.schematicSymbolPortDef=m;else{let E=qF(m.labels.concat(e.additionalAliases?.[`pin${D}`]??[]));E&&(E.originDescription=`schematicSymbol:labels[0]:${m.labels[0]}`,E.schematicSymbolPortDef=m,s.push(E))}}this.addAll(s)}if(!this._getSchematicPortArrangement()){let f=this.getPortsFromFootprint(e);for(let m of f)s.some(D=>D.isMatchingAnyOf(m.getNameAndAliases()))||s.push(m)}let x=e.pinCount??this._getPinCount()??0;for(let f=1;f<=x;f++){if(s.find(D=>D._parsedProps.pinNumber===f))continue;if(!l){s.push(new Ni({pinNumber:f,aliases:e.additionalAliases?.[`pin${f}`]??[]}));continue}let m=[...l.leftSide?.pins??[],...l.rightSide?.pins??[],...l.topSide?.pins??[],...l.bottomSide?.pins??[]].map(D=>YF(D,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(D=>D in l)&&(m=Array.from({length:this._getPinCount()},(D,b)=>b+1)),m.includes(f)&&s.push(new Ni({pinNumber:f,aliases:e.additionalAliases?.[`pin${f}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${f}`}))}s.length>0&&this.addAll(s)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:e,pinLabels:a,pcbPinLabels:s}=this.props,{footprint:l}=this.props;if(l??(l=this._getImpliedFootprintString?.()),!!l&&typeof l=="string"){if(HS(l)||rK(l))return;let d=Vq.string(l).soup(),x=qS({componentName:this.name??this.componentName,componentRotation:e,footprint:l,pinLabels:a,pcbPinLabels:s},d);this.addAll(x)}}get portMap(){return new Proxy({},{get:(e,a)=>{let s=this.children.find(l=>l.componentName==="Port"&&l.isMatchingNameOrAlias(a));if(!s)throw new Error(`There was an issue finding the port "${a.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return s}})}getInstanceForReactElement(e){for(let a of this.reactSubtrees)if(a.element===e)return a.component;return null}doInitialSourceRender(){let e=this.config.sourceFtype;if(!e)return;let{db:a}=this.root,{_parsedProps:s}=this,l=a.source_component.insert({ftype:e,name:this.name,manufacturer_part_number:s.manufacturerPartNumber??s.mfn,supplier_part_numbers:s.supplierPartNumbers});this.source_component_id=l.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let l of this._invalidPinLabelMessages){let d="pinLabels",x=l.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);x&&(d=`pinLabels['${x[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:d,message:l,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:a}=this.config;a?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let s=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&s){if(!this.schematic_component_id)return;let l=qA.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});e.schematic_manual_edit_conflict_warning.insert(l)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let e=[];for(let a of this.internallyConnectedPinNames){let s=[];for(let l of a)s.push(this.portMap[l]);e.push(s)}return e}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getSchematicSymbolNameOrThrow(),l=ks[s],d=this._getGlobalSchematicPositionBeforeLayout();if(l){let x=e.schematic_component.insert({center:d,size:l.size,source_component_id:this.source_component_id,symbol_name:s,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=x.schematic_component_id}}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getSchematicBoxDimensions(),l={};if(Array.isArray(a.pinLabels))a.pinLabels.forEach((B,w)=>{l[String(w+1)]=B});else for(let[B,w]of Object.entries(a.pinLabels??{}))l[B]=Array.isArray(w)?w[0]:w;let d=this._getGlobalSchematicPositionBeforeLayout(),x=this._getSchematicPortArrangement(),f=e.schematic_component.insert({center:d,rotation:a.schRotation??0,size:s.getSize(),port_arrangement:BVt(x),pin_spacing:a.schPinSpacing??.2,pin_styles:SVt(a.schPinStyle,a.pinLabels),port_labels:l,source_component_id:this.source_component_id}),m=x?.topSide!==void 0||x?.bottomSide!==void 0,D=s?.getSize().width,b=s?.getSize().height,E=e.schematic_text.insert({text:a.manufacturerPartNumber??"",schematic_component_id:f.schematic_component_id,anchor:"left",rotation:0,position:{x:m?d.x+(D??0)/2+.1:d.x-(D??0)/2,y:m?d.y+(b??0)/2+.35:d.y-(b??0)/2-.13},color:"#006464",font_size:.18}),A=e.schematic_text.insert({text:a.name??"",schematic_component_id:f.schematic_component_id,anchor:"left",rotation:0,position:{x:m?d.x+(D??0)/2+.1:d.x-(D??0)/2,y:m?d.y+(b??0)/2+.55:d.y+(b??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=f.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit(),l=e.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:s.subcircuit_id??void 0});if(!(a.footprint??this._getImpliedFootprintString())&&!this.isGroup){let f=e.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=f.pcb_missing_footprint_error_id}this.pcb_component_id=l.pcb_component_id;let x=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&x){let f=GA.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:s.subcircuit_id??void 0});e.pcb_manual_edit_conflict_warning.insert(f)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:e}=this.root,{_parsedProps:a}=this,s=ZS(this.children);if(s.width===0||s.height===0)return;let l={x:(s.minX+s.maxX)/2,y:(s.minY+s.maxY)/2};e.pcb_component.update(this.pcb_component_id,{center:l,width:s.width,height:s.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){EGt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(e){let a=YBe(e);return{element:e,component:a}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let e=this.props.footprint;(0,B1.isValidElement)(e)&&(this.children.some(l=>l.componentName==="Footprint")||this.add(e));let a=this.props.cadModel;if((0,B1.isValidElement)(a)){this._isCadModelChild=!0;let s=this.children.some(d=>d.componentName==="CadAssembly"),l=this.children.some(d=>d.componentName==="CadModel");!s&&!l&&this.add(a)}}doInitialPcbFootprintStringRender(){FGt(this,(e,a)=>this._queueAsyncEffect(e,a))}_hasExistingPortExactly(e){return this.children.filter(s=>s.componentName==="Port").some(s=>{let l=e.getNameAndAliases(),d=s.getNameAndAliases();return l.length===d.length&&l.every(x=>d.includes(x))})}add(e){let a;if((0,B1.isValidElement)(e)){let s=this._renderReactSubtree(e);this.reactSubtrees.push(s),a=s.component}else a=e;if(a.componentName==="Port"){if(this._hasExistingPortExactly(a))return;let l=this.children.filter(d=>d.componentName==="Port").find(d=>d.isMatchingAnyOf(a.getNameAndAliases()));l&&vGt(`Similar ports added. Port 1: ${l}, Port 2: ${a}`)}super.add(a)}getPortsFromFootprint(e){let{footprint:a}=this.props;if((!a||(0,B1.isValidElement)(a))&&(a=this.children.find(l=>l.componentName==="Footprint")),typeof a=="string"){if(HS(a))return[];if(rK(a))return[];let l=Vq.string(a).soup(),d=[];for(let x of l)if("port_hints"in x&&x.port_hints){let f=qF(x.port_hints,e);if(!f)continue;f.originDescription=`footprint:string:${a}:port_hints[0]:${x.port_hints[0]}`,d.push(f)}return d}if(!(0,B1.isValidElement)(a)&&a&&a.componentName==="Footprint"){let l=a,d=1,x=[];for(let f of l.children){if(!f.props.portHints)continue;let m=f.props.portHints;m.some(E=>E.startsWith("pin"))||(m=[...m,`pin${d}`]),d++;let b=qF(m);b&&(b.originDescription=`footprint:${a}`,x.push(b))}return x}let s=[];if(!a){for(let l of this.children)if(l.props.portHints&&l.isPcbPrimitive){let d=qF(l.props.portHints);d&&s.push(d)}}return s}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:e}=this;if(!e.schematicSymbolName)return[];let a=ks[e.schematicSymbolName];if(!a)return[];let s=[];for(let l of a.ports){let d=qF(l.labels);d&&(d.schematicSymbolPortDef=l,s.push(d))}return s}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:e}=this,a=[];if(e.connections)for(let[s,l]of Object.entries(e.connections)){let d=Array.isArray(l)?l:[l];for(let x of d)a.push(x)}return a}_createNetsFromProps(e){uK(this,e)}_getPcbCircuitJsonBounds(){let{db:e}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let a=e.pcb_component.get(this.pcb_component_id);return{center:{x:a.center.x,y:a.center.y},bounds:{left:a.center.x-a.width/2,top:a.center.y-a.height/2,right:a.center.x+a.width/2,bottom:a.center.y+a.height/2},width:a.width,height:a.height}}_getPinCountFromSchematicPortArrangement(){let e=this._getSchematicPortArrangement();if(!e)return 0;if(!KBe(e))return(e.leftSize??e.leftPinCount??0)+(e.rightSize??e.rightPinCount??0)+(e.topSize??e.topPinCount??0)+(e.bottomSize??e.bottomPinCount??0);let{leftSide:s,rightSide:l,topSide:d,bottomSide:x}=e;return Math.max(...s?.pins??[],...l?.pins??[],...d?.pins??[],...x?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let a=this.getPortsFromFootprint();if(a.length>0)return a.length;let{pinLabels:s}=this._parsedProps;if(s){if(Array.isArray(s))return s.length;let l=Object.keys(s).map(d=>d.startsWith("pin")?parseInt(d.slice(3)):parseInt(d)).filter(d=>!Number.isNaN(d));return l.length>0?Math.max(...l):Object.keys(s).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this,a=this._getPinCount(),s=e.schPinSpacing??.2;return OVt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:s,numericSchPinStyle:$Vt(e.schPinStyle,e.pinLabels),pinCount:a,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:e.pinLabels})}doInitialCadModelRender(){if(this._isCadModelChild)return;let{db:e}=this.root,{boardThickness:a=0}=this.root?._getBoard()??{},s=this._parsedProps.cadModel,l=s===void 0?this._asyncFootprintCadModel:s,d=this.props.footprint??this._getImpliedFootprintString();if(!this.pcb_component_id||!l&&!d||l===null)return;let x=this._getPcbCircuitJsonBounds(),f=e.pcb_component.get(this.pcb_component_id);if(typeof l=="string")throw new Error("String cadModel not yet implemented");let m=CGt.parse({x:0,y:0,z:typeof l?.rotationOffset=="number"?l.rotationOffset:0,...typeof l?.rotationOffset=="object"?l.rotationOffset??{}:{}}),D=Vf.parse({x:0,y:0,z:0,...typeof l?.positionOffset=="object"?l.positionOffset:{}}),b=this.props.layer==="bottom"?"bottom":"top",E=e.cad_component.insert({position:{x:x.center.x+D.x,y:x.center.y+D.y,z:(b==="bottom"?-a/2:a/2)+D.z},rotation:{x:m.x,y:(b==="top"?0:180)+m.y,z:b==="bottom"?-((f?.rotation??0)+m.z)+180:(f?.rotation??0)+m.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(l??{})?this._addCachebustToModelUrl(l.stlUrl):void 0,model_obj_url:"objUrl"in(l??{})?this._addCachebustToModelUrl(l.objUrl):void 0,model_mtl_url:"mtlUrl"in(l??{})?this._addCachebustToModelUrl(l.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(l??{})?this._addCachebustToModelUrl(l.gltfUrl):void 0,model_glb_url:"glbUrl"in(l??{})?this._addCachebustToModelUrl(l.glbUrl):void 0,model_step_url:"stepUrl"in(l??{})?this._addCachebustToModelUrl(l.stepUrl):void 0,model_wrl_url:"wrlUrl"in(l??{})?this._addCachebustToModelUrl(l.wrlUrl):void 0,model_jscad:"jscad"in(l??{})?l.jscad:void 0,model_unit_to_mm_scale_factor:typeof l?.modelUnitToMmScale=="number"?l.modelUnitToMmScale:void 0,footprinter_string:typeof d=="string"&&!l?d:void 0});this.cad_component_id=E.cad_component_id}_addCachebustToModelUrl(e){if(!e||!e.includes("modelcdn.tscircuit.com"))return e;let a=this.root?.getClientOrigin()??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(a)}`}_getPartsEngineCacheKey(e,a){return JSON.stringify({ftype:e.ftype,name:e.name,manufacturer_part_number:e.manufacturer_part_number,footprinterString:a})}async _getSupplierPartNumbers(e,a,s){if(this.props.doNotPlace)return{};let l=this.root?.platform?.localCacheEngine,d=this._getPartsEngineCacheKey(a,s);if(l){let m=await l.getItem(d);if(m)try{return JSON.parse(m)}catch{}}let x=await Promise.resolve(e.findPart({sourceComponent:a,footprinterString:s})),f=x==="Not found"?{}:x;if(l)try{await l.setItem(d,JSON.stringify(f))}catch{}return f}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let e=this.getInheritedProperty("partsEngine");if(!e)return;let{db:a}=this.root,s=a.source_component.get(this.source_component_id);if(!s||s.supplier_part_numbers)return;let l;this.props.footprint&&typeof this.props.footprint=="string"&&(l=this.props.footprint);let d=this._getSupplierPartNumbers(e,s,l);if(!(d instanceof Promise)){a.source_component.update(this.source_component_id,{supplier_part_numbers:d});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await d,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:e}=this.root,a=e.source_component.get(this.source_component_id);if(a&&!a.supplier_part_numbers&&this._asyncSupplierPartNumbers){e.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:e}=this;e.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:e}=this;if(e.connections)for(let[a,s]of Object.entries(e.connections)){let l=Array.isArray(s)?s:[s];for(let d of l)this.add(new qc({from:`${this.getSubcircuitSelector()} > port.${a}`,to:d}))}}doInitialSourceDesignRuleChecks(){hGt(this)}_getMinimumFlexContainerSize(){return xGt(this)}_repositionOnPcb(e){return fGt(this,e)}doInitialSilkscreenOverlapAdjustment(){return DGt(this)}},_Gt=class{constructor(r,e={}){q(this,"input");q(this,"isRouting",!1);q(this,"solver");q(this,"eventHandlers",{complete:[],error:[],progress:[]});q(this,"cycleCount",0);q(this,"stepDelay");q(this,"timeoutId");this.input=r;let{capacityDepth:a,targetMinCapacity:s,stepDelay:l=0}=e;this.solver=new R6e(r,{capacityDepth:a,targetMinCapacity:s,cacheProvider:null}),this.stepDelay=l}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 UF(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let r=Date.now(),e=this.solver.iterations;for(;Date.now()-r<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let a=(this.solver.iterations-e)/(Date.now()-r)*1e3;this.cycleCount++;let s=this.solver?.preview()||void 0,l=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:a,progress:l,phase:this.solver.getCurrentPhase(),debugGraphics:s}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(r){this.emitEvent({type:"error",error:r instanceof Error?new UF(r.message):new UF(String(r))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(r,e){r==="complete"?this.eventHandlers.complete.push(e):r==="error"?this.eventHandlers.error.push(e):r==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(r){if(r.type==="complete")for(let e of this.eventHandlers.complete)e(r);else if(r.type==="error")for(let e of this.eventHandlers.error)e(r);else if(r.type==="progress")for(let e of this.eventHandlers.progress)e(r)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new UF(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},fK=class extends Qn{constructor(){super(...arguments);q(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:n4e}}doInitialPortMatching(){let{db:e}=this.root,{_parsedProps:a,parent:s}=this;if(!s)return;if(s.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!s)throw new Error("TraceHint has no parent");if(!a.for){this.renderError(`TraceHint has no for property (${this})`);return}let l=s.selectOne(a.for,{type:"port"});l||this.renderError(`${this} could not find port for selector "${a.for}"`),this.matchedPort=l,l.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:e}=this,a=e.offset?[e.offset]:e.offsets;if(!a)return[];let s=this._computePcbGlobalTransformBeforeLayout();return a.map(l=>({...as(s,l),via:l.via,to_layer:l.to_layer,trace_width:l.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this;e.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},n9e=({circuitJson:r,editEvents:e,manualEditsFile:a})=>{let s={...a,pcb_placements:[...a.pcb_placements??[]]};for(let l of e)if(l.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:d,new_center:x}=l,f=ua(r).pcb_component.get(d);if(!f)continue;let m=ua(r).source_component.get(f.source_component_id);if(!m)continue;let D=s.pcb_placements?.findIndex(E=>E.selector===m.name),b={selector:m.name,center:x,relative_to:"group_center"};D>=0?s.pcb_placements[D]=b:s.pcb_placements.push(b)}return s},a9e=({circuitJson:r,editEvents:e,manualEditsFile:a})=>{let s={...a,schematic_placements:[...a.schematic_placements??[]]};for(let l of e)if(l.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:d,new_center:x}=l,f=ua(r).schematic_component.get(d);if(!f||!f.source_component_id)continue;let m=ua(r).source_component.get(f.source_component_id);if(!m)continue;let D=s.schematic_placements?.findIndex(E=>E.selector===m.name),b={selector:m.name,center:x,relative_to:"group_center"};D>=0?s.schematic_placements[D]=b:s.schematic_placements.push(b)}return s},AGt=({circuitJson:r,editEvents:e,manualEditsFile:a})=>{let s=e.filter(x=>x.edit_event_type==="edit_schematic_component_location"),l=e.filter(x=>x.edit_event_type==="edit_pcb_component_location"),d=a;return s.length>0&&(d=a9e({circuitJson:r,editEvents:s,manualEditsFile:d})),l.length>0&&(d=n9e({circuitJson:r,editEvents:l,manualEditsFile:d})),d},RGt=(r,e)=>{if(ua(r).pcb_trace_hint.get(e.pcb_trace_hint_id))r=r.map(s=>s.pcb_trace_hint_id===e.pcb_trace_hint_id?{...s,route:e.route}:s);else{let s=ua(r).pcb_port.get(e.pcb_port_id);r=r.filter(l=>!(l.type==="pcb_trace_hint"&&l.pcb_port_id===e.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:e.pcb_trace_hint_id,route:e.route,pcb_port_id:e.pcb_port_id,pcb_component_id:s?.pcb_component_id}])}return r},SGt=({circuitJson:r,editEvents:e})=>{r=JSON.parse(JSON.stringify(r));for(let a of e)if(a.edit_event_type==="edit_pcb_component_location"){let s=r.find(d=>d.type==="pcb_component"&&d.pcb_component_id===a.pcb_component_id);if((!s||s.center.x!==a.new_center.x||s.center.y!==a.new_center.y)&&a.original_center){let d=Ma(a.new_center.x-a.original_center.x,a.new_center.y-a.original_center.y);r=r.map(x=>x.pcb_component_id!==a.pcb_component_id?x:IY(x,d))}}else a.edit_event_type==="edit_schematic_component_location"?r=r.map(s=>s.type==="schematic_component"&&s.schematic_component_id===a.schematic_component_id?{...s,center:a.new_center}:s):a.edit_event_type==="edit_pcb_trace_hint"&&(r=RGt(r,a));return r},s9e=(r,e)=>{let a=r.source_group.list(),s=[],l=d=>{let x=a.filter(f=>f.parent_subcircuit_id===d);for(let f of x)f.subcircuit_id&&(s.push(f.subcircuit_id),l(f.subcircuit_id))};return l(e),s},nK=({db:r,circuitJson:e,subcircuit_id:a,minTraceWidth:s=.1})=>{if(!r&&e&&(r=ua(e)),!r)throw new Error("db or circuitJson is required");let l=r.pcb_trace_hint.list(),d=a?new Set([a]):null;if(a){let K=s9e(r,a);for(let U of K)d.add(U)}let x=(e??r.toArray()).filter(K=>!a||"subcircuit_id"in K&&d.has(K.subcircuit_id)),f=r.pcb_board.list()[0];r=ua(x);let m=eu(x),D=pK([...r.pcb_component.list(),...r.pcb_smtpad.list(),...r.pcb_plated_hole.list(),...r.pcb_hole.list(),...r.pcb_via.list(),...r.pcb_cutout.list()].filter(K=>!a||d?.has(K.subcircuit_id)),m);for(let K of D){let U=K.connectedTo.flatMap(J=>m.getIdsConnectedToNet(J));K.connectedTo.push(...U)}let b=D.flatMap(K=>[{x:K.center.x-K.width/2,y:K.center.y-K.height/2},{x:K.center.x+K.width/2,y:K.center.y+K.height/2}]),E;if(f?E={minX:f.center.x-f.width/2,maxX:f.center.x+f.width/2,minY:f.center.y-f.height/2,maxY:f.center.y+f.height/2}:E={minX:Math.min(...b.map(K=>K.x))-1,maxX:Math.max(...b.map(K=>K.x))+1,minY:Math.min(...b.map(K=>K.y))-1,maxY:Math.max(...b.map(K=>K.y))+1},a){let K=r.pcb_group.getWhere({subcircuit_id:a});if(K){let U={minX:K.center.x-K.width/2,maxX:K.center.x+K.width/2,minY:K.center.y-K.height/2,maxY:K.center.y+K.height/2};E={minX:Math.min(E.minX,U.minX),maxX:Math.max(E.maxX,U.maxX),minY:Math.min(E.minY,U.minY),maxY:Math.max(E.maxY,U.maxY)}}}let A=new Set(r.pcb_trace.list().map(K=>K.source_trace_id).filter(K=>!!K)),B=r.source_trace.list().filter(K=>!A.has(K.source_trace_id)).map(K=>{let U=K.connected_source_port_ids.map(Ge=>{let et=r.source_port.get(Ge),dt=r.pcb_port.getWhere({source_port_id:Ge});return{...et,...dt}});if(U.length<2)return null;let[J,Q]=U,de=J.layers?.[0]??"top",oe=Q.layers?.[0]??"top",Te=l.filter(Ge=>Ge.pcb_port_id===J.pcb_port_id||Ge.pcb_port_id===Q.pcb_port_id),Me=[];for(let Ge of Te){let dt=r.pcb_port.get(Ge.pcb_port_id)?.layers?.[0]??"top";for(let $t of Ge.route)Me.push({x:$t.x,y:$t.y,layer:dt})}return{name:K.source_trace_id??m.getNetConnectedToId(K.source_trace_id)??"",source_trace_id:K.source_trace_id,pointsToConnect:[{x:J.x,y:J.y,layer:de,pointId:J.pcb_port_id,pcb_port_id:J.pcb_port_id},...Me,{x:Q.x,y:Q.y,layer:oe,pointId:Q.pcb_port_id,pcb_port_id:Q.pcb_port_id}]}}).filter(K=>K!==null),w=new Map(B.map(K=>[K.source_trace_id,K])),P=r.source_net.list().filter(K=>!a||d?.has(K.subcircuit_id)),j=[];for(let K of P){let U=r.source_trace.list().filter(J=>J.connected_source_net_ids?.includes(K.source_net_id));j.push({name:K.source_net_id??m.getNetConnectedToId(K.source_net_id),pointsToConnect:U.flatMap(J=>r.pcb_port.list().filter(de=>J.connected_source_port_ids.includes(de.source_port_id)).map(de=>({x:de.x,y:de.y,layer:de.layers?.[0]??"top",pointId:de.pcb_port_id,pcb_port_id:de.pcb_port_id})))})}let O=r.pcb_breakout_point.list().filter(K=>!a||d?.has(K.subcircuit_id)),z=[],ee=new Map;for(let K of O){let U={x:K.x,y:K.y,layer:"top"};if(K.source_trace_id){let J=w.get(K.source_trace_id)??ee.get(K.source_trace_id);if(J)J.pointsToConnect.push(U);else{let Q={name:K.source_trace_id,source_trace_id:K.source_trace_id,pointsToConnect:[U]};z.push(Q),ee.set(K.source_trace_id,Q)}}else if(K.source_net_id){let J=j.find(Q=>Q.name===K.source_net_id);J?J.pointsToConnect.push(U):z.push({name:K.source_net_id,pointsToConnect:[U]})}else if(K.source_port_id){let J=r.pcb_port.getWhere({source_port_id:K.source_port_id});J&&z.push({name:K.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:J.x,y:J.y,layer:J.layers?.[0]??"top",pointId:J.pcb_port_id,pcb_port_id:J.pcb_port_id},U]})}}let W=[...B,...j,...z],re=new Map;for(let K of W)for(let U of K.pointsToConnect)U.pointId&&re.set(U.pointId,K);let L=r.pcb_trace.list().filter(K=>!a||d?.has(K.subcircuit_id));for(let K of L){let U=new Set;for(let de of K.route)de.start_pcb_port_id&&U.add(de.start_pcb_port_id),de.end_pcb_port_id&&U.add(de.end_pcb_port_id);if(U.size<2)continue;let J=U.values().next().value;if(!J)continue;let Q=re.get(J);Q&&[...U].every(de=>re.get(de)===Q)&&(Q.externallyConnectedPointIds??(Q.externallyConnectedPointIds=[]),Q.externallyConnectedPointIds.push([...U]))}return{simpleRouteJson:{bounds:E,obstacles:D,connections:W,layerCount:f?.num_layers??2,minTraceWidth:s},connMap:m}},BGt=r=>{let e={};if(!r)return e;for(let s of ld)e[s]=0;let a=new Map;for(let s of r){let[,,l,d]=s.type.split(":");if(d==="start"){a.set(`${l}:${s.renderId}`,s);continue}if(d==="end"){let x=a.get(`${l}:${s.renderId}`);if(x){let f=s.createdAt-x.createdAt;e[l]=(e[l]||0)+f}}}return e},wGt=r=>{let e=r.map(m=>[...new Set(m)]),a=e.map(()=>[]),s=e.map(()=>null);for(let m=0;m<e.length;m++)for(let D of e[m])if(/^\d+$/.test(D)){s[m]=Number.parseInt(D);break}let l=0,d=new Set;for(let m=0;m<s.length;m++){let D=s[m];if(D===null||D<1)continue;if(!d.has(D)){d.add(D),a[m].push(`pin${D}`),l=Math.max(l,D);continue}let b=0;for(let E of a[m])E.startsWith(`pin${D}_alt`)&&b++;a[m].push(`pin${D}_alt${b+1}`)}for(let m=0;m<a.length;m++)a[m][0]?.includes("_alt")&&(l++,a[m].unshift(`pin${l}`));for(let m=0;m<a.length;m++)a[m].length===0&&(l++,a[m].push(`pin${l}`));let x={};for(let m of e)for(let D of m)/^\d+$/.test(D)||(x[D]=(x[D]??0)+1);let f={};for(let m=0;m<e.length;m++){let D=e[m];for(let b of D)/^\d+$/.test(b)||(x[b]===1?a[m].push(b):(f[b]=(f[b]??0)+1,a[m].push(`${b}${f[b]}`)))}return a},BBe=(0,i9e.default)("Group_doInitialSchematicLayoutMatchAdapt");function TGt(r){let{db:e}=r.root,a=Hb(e.toArray(),{source_group_id:r.source_group_id}),s=uH(a);BBe.enabled&&global.debugGraphics?.push(Wp(s,{title:`floatingBpcGraph-${r.name}`}));let l=uH(a),d={boxes:l.boxes,pins:l.pins.map(m=>({...m,color:m.color.replace("not_connected","normal")}))},{result:x}=r5e([{variantName:"default",floatingGraph:l},{variantName:"noNotConnected",floatingGraph:d}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(l.boxes.filter(m=>l.pins.filter(E=>E.boxId===m.boxId).filter(E=>!E.color.includes("center")).length<=2).map(m=>m.boxId)),corpus:{}});BBe.enabled&&global.debugGraphics?.push(Wp(x,{title:`laidOutBpcGraph-${r.name}`}));let f=r._getGlobalSchematicPositionBeforeLayout();for(let m of x.boxes){if(!m.center)continue;let D=e.schematic_component.get(m.boxId);if(D){let E={x:m.center.x+f.x,y:m.center.y+f.y},A=e.schematic_port.list({schematic_component_id:D.schematic_component_id}),B=e.schematic_text.list({schematic_component_id:D.schematic_component_id}),w={x:E.x-D.center.x,y:E.y-D.center.y};for(let P of A)P.center.x+=w.x,P.center.y+=w.y;for(let P of B)P.position.x+=w.x,P.position.y+=w.y;D.center=E;continue}let b=e.schematic_net_label.get(m.boxId);if(b){let E=x.pins.find(B=>B.boxId===m.boxId&&B.color==="netlabel_center");if(!E)throw new Error(`No pin found for net label: ${m.boxId}`);let A={x:m.center.x+f.x,y:m.center.y+f.y};b.center=A,b.anchor_position={x:A.x+E.offset.x,y:A.y+E.offset.y};continue}console.error(`No schematic element found for box: ${m.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var an=(0,o9e.default)("Group_doInitialSchematicLayoutMatchpack");function wBe(r){switch(r){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function TBe(r,e){let a=["right","up","left","down"],s=a.indexOf(r);if(s===-1)return r;let l=Math.round(e/90),d=(s+l)%4;return a[d<0?d+4:d]}function PGt(r,e,a){let s={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};an(`[${a.name}] Processing ${r.childNodes.length} child nodes for input problem`),r.childNodes.forEach((d,x)=>{if(an(`[${a.name}] Processing child ${x}: nodeType=${d.nodeType}`),d.nodeType==="component"?an(`[${a.name}] - Component: ${d.sourceComponent?.name}`):d.nodeType==="group"&&an(`[${a.name}] - Group: ${d.sourceGroup?.name}`),d.nodeType==="component"&&d.sourceComponent){let f=d.sourceComponent.name||`chip_${x}`,m=e.schematic_component.getWhere({source_component_id:d.sourceComponent.source_component_id});if(!m)return;let D=a.children.find(z=>z.source_component_id===d.sourceComponent?.source_component_id),b=[0,90,180,270];D?._parsedProps?.schOrientation&&(b=[0]),D?._parsedProps?.schRotation!==void 0&&(b=[0]);let E=D?._parsedProps?.schMarginLeft??D?._parsedProps?.schMarginX??0,A=D?._parsedProps?.schMarginRight??D?._parsedProps?.schMarginX??0,B=D?._parsedProps?.schMarginTop??D?._parsedProps?.schMarginY??0,w=D?._parsedProps?.schMarginBottom??D?._parsedProps?.schMarginY??0;D?.config.shouldRenderAsSchematicBox&&(B+=.4,w+=.4);let P=(A-E)/2,j=(B-w)/2;s.chipMap[f]={chipId:f,pins:[],size:{x:(m.size?.width||1)+E+A,y:(m.size?.height||1)+B+w},availableRotations:b};let O=e.schematic_port.list({schematic_component_id:m.schematic_component_id});for(let z of O){let ee=e.source_port.get(z.source_port_id);if(!ee)continue;let W=`${f}.${ee.pin_number||ee.name||z.schematic_port_id}`;s.chipMap[f].pins.push(W);let re=wBe(z.facing_direction);s.chipPinMap[W]={pinId:W,offset:{x:(z.center?.x||0)-(m.center.x||0)+P,y:(z.center?.y||0)-(m.center.y||0)+j},side:re}}}else if(d.nodeType==="group"&&d.sourceGroup){let f=d.sourceGroup.name||`group_${x}`;an(`[${a.name}] Processing nested group: ${f}`);let m=e.schematic_group?.getWhere?.({source_group_id:d.sourceGroup.source_group_id}),D=a.children.find(b=>b.source_group_id===d.sourceGroup?.source_group_id);if(an(`[${a.name}] Found schematic_group for ${f}:`,m),m){an(`[${a.name}] Treating group ${f} as composite chip`);let b=e.schematic_component.list({schematic_group_id:m.schematic_group_id});an(`[${a.name}] Group ${f} has ${b.length} components:`,b.map(J=>J.source_component_id));let E=1/0,A=-1/0,B=1/0,w=-1/0,P=!1;for(let J of b)if(J.center&&J.size){P=!0;let Q=J.size.width/2,de=J.size.height/2;E=Math.min(E,J.center.x-Q),A=Math.max(A,J.center.x+Q),B=Math.min(B,J.center.y-de),w=Math.max(w,J.center.y+de)}let j=D?._parsedProps?.schMarginLeft??D?._parsedProps?.schMarginX??0,O=D?._parsedProps?.schMarginRight??D?._parsedProps?.schMarginX??0,z=D?._parsedProps?.schMarginTop??D?._parsedProps?.schMarginY??0,ee=D?._parsedProps?.schMarginBottom??D?._parsedProps?.schMarginY??0,W=(O-j)/2,re=(z-ee)/2,L=(P?A-E:2)+j+O,K=(P?w-B:2)+z+ee;an(`[${a.name}] Group ${f} computed size: ${L} x ${K}`);let U=[];for(let J of b){let Q=e.schematic_port.list({schematic_component_id:J.schematic_component_id});for(let de of Q){let oe=e.source_port.get(de.source_port_id);if(!oe)continue;let Te=`${f}.${oe.pin_number||oe.name||de.schematic_port_id}`;U.push(Te);let Me=m.center||{x:0,y:0},Ge=wBe(de.facing_direction);s.chipPinMap[Te]={pinId:Te,offset:{x:(de.center?.x||0)-Me.x+W,y:(de.center?.y||0)-Me.y+re},side:Ge}}}an(`[${a.name}] Group ${f} has ${U.length} pins:`,U),s.chipMap[f]={chipId:f,pins:U,size:{x:L,y:K}},an(`[${a.name}] Added group ${f} to chipMap`)}else an(`[${a.name}] Warning: No schematic_group found for group ${f}`)}}),an(`[${a.name}] Creating connections using connectivity keys`);let l=new Map;for(let[d,x]of Object.entries(s.chipMap))for(let f of x.pins){let m=f.split(".").pop(),D=r.childNodes.find(b=>b.nodeType==="component"&&b.sourceComponent?b.sourceComponent.name===d:b.nodeType==="group"&&b.sourceGroup?`group_${r.childNodes.indexOf(b)}`===d:!1);if(D?.nodeType==="group"&&D.sourceGroup){let b=e.schematic_group?.getWhere?.({source_group_id:D.sourceGroup.source_group_id});if(b){let E=e.schematic_component.list({schematic_group_id:b.schematic_group_id});for(let A of E){let B=e.source_port.list({source_component_id:A.source_component_id});for(let w of B){let P=w.pin_number||w.name;if(String(P)===String(m))if(w.subcircuit_connectivity_map_key){let j=w.subcircuit_connectivity_map_key;l.has(j)||l.set(j,[]),l.get(j).push(f),an(`[${a.name}] \u2713 Pin ${f} has connectivity key: ${j}`)}else an(`[${a.name}] Pin ${f} has no connectivity key`)}}}}else if(D?.nodeType==="component"&&D.sourceComponent){let b=e.source_port.list({source_component_id:D.sourceComponent.source_component_id});for(let E of b){let A=E.pin_number||E.name;if(String(A)===String(m)&&E.subcircuit_connectivity_map_key){let B=E.subcircuit_connectivity_map_key;l.has(B)||l.set(B,[]),l.get(B).push(f),an(`[${a.name}] Pin ${f} has connectivity key: ${B}`)}}}}an(`[${a.name}] Found ${l.size} connectivity groups:`,Array.from(l.entries()).map(([d,x])=>({key:d,pins:x})));for(let[d,x]of l)if(x.length>=2){let f=e.source_trace.list().filter(b=>b.subcircuit_connectivity_map_key===d),m=f.some(b=>b.connected_source_net_ids&&b.connected_source_net_ids.length>0),D=f.some(b=>b.connected_source_port_ids&&b.connected_source_port_ids.length>=2);if(an(`[${a.name}] Connectivity ${d}: hasNetConnections=${m}, hasDirectConnections=${D}`),D){for(let b of f)if(b.connected_source_port_ids&&b.connected_source_port_ids.length>=2){let E=[];for(let A of b.connected_source_port_ids)for(let B of x){let w=B.split(".").pop(),P=e.source_port.get(A);if(P&&String(P.pin_number||P.name)===String(w)){let j=B.split(".")[0],O=r.childNodes.find(z=>z.nodeType==="component"&&z.sourceComponent?z.sourceComponent.name===j:z.nodeType==="group"&&z.sourceGroup?`group_${r.childNodes.indexOf(z)}`===j:!1);O?.nodeType==="component"&&O.sourceComponent&&e.source_port.list({source_component_id:O.sourceComponent.source_component_id}).some(ee=>ee.source_port_id===A)&&E.push(B)}}for(let A=0;A<E.length;A++)for(let B=A+1;B<E.length;B++){let w=E[A],P=E[B];s.pinStrongConnMap[`${w}-${P}`]=!0,s.pinStrongConnMap[`${P}-${w}`]=!0,an(`[${a.name}] Created strong connection: ${w} <-> ${P}`)}}}if(m){let b=e.source_net.getWhere({subcircuit_connectivity_map_key:d}),E=b?.is_ground??!1,A=b?.is_power??!1;s.netMap[d]={netId:d,isGround:E,isPositiveVoltageSource:A};for(let B of x)s.netConnMap[`${B}-${d}`]=!0;an(`[${a.name}] Created net ${d} with ${x.length} pins:`,x)}}return s}function IGt(r){let{db:e}=r.root,a=xg(e.toArray(),{source_group_id:r.source_group_id});if(an(`[${r.name}] Starting matchpack layout with ${a.childNodes.length} children`),an(`[${r.name}] Tree structure:`,JSON.stringify(a,null,2)),a.childNodes.length<=1){an(`[${r.name}] Only ${a.childNodes.length} children, skipping layout`);return}an("Converting circuit tree to InputProblem...");let s=PGt(a,e,r);an.enabled&&r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${r.name}`,content:JSON.stringify(s,null,2)});let l=new sSe(s);if(an("Starting LayoutPipelineSolver..."),an.enabled&&global.debugGraphics){let m=l.visualize();global.debugGraphics.push({...m,title:`matchpack-initial-${r.name}`})}if(l.solve(),an(`Solver completed in ${l.iterations} iterations`),an(`Solved: ${l.solved}, Failed: ${l.failed}`),l.failed)throw an(`Solver failed with error: ${l.error}`),new Error(`Matchpack layout solver failed: ${l.error}`);let d=l.getOutputLayout();if(an("OutputLayout:",JSON.stringify(d,null,2)),an("Solver completed successfully:",!l.failed),an.enabled&&global.debugGraphics){let m=l.visualize();global.debugGraphics.push({...m,title:`matchpack-final-${r.name}`})}let x=l.checkForOverlaps(d);if(x.length>0){an(`Warning: Found ${x.length} overlapping components:`);for(let m of x)an(` ${m.chip1} overlaps ${m.chip2} (area: ${m.overlapArea})`)}let f=r._getGlobalSchematicPositionBeforeLayout();an(`Group offset: x=${f.x}, y=${f.y}`),an(`Applying layout results for ${Object.keys(d.chipPlacements).length} chip placements`);for(let[m,D]of Object.entries(d.chipPlacements)){an(`Processing placement for chip: ${m} at (${D.x}, ${D.y})`);let b=a.childNodes.find(A=>{if(A.nodeType==="component"&&A.sourceComponent){let B=A.sourceComponent.name===m;return an(` Checking component ${A.sourceComponent.name}: matches=${B}`),B}if(A.nodeType==="group"&&A.sourceGroup){let B=A.sourceGroup.name,w=`group_${a.childNodes.indexOf(A)}`,P=w===m;return an(` Checking group ${B} (expected chipId: ${w}): matches=${P}`),P}return!1});if(!b){an(`Warning: No tree node found for chip: ${m}`),an("Available tree nodes:",a.childNodes.map((A,B)=>({type:A.nodeType,name:A.nodeType==="component"?A.sourceComponent?.name:A.sourceGroup?.name,expectedChipId:A.nodeType==="group"?`group_${B}`:A.sourceComponent?.name})));continue}let E={x:D.x+f.x,y:D.y+f.y};if(b.nodeType==="component"&&b.sourceComponent){let A=e.schematic_component.getWhere({source_component_id:b.sourceComponent.source_component_id});if(A){an(`Moving component ${m} to (${E.x}, ${E.y})`);let B=e.schematic_port.list({schematic_component_id:A.schematic_component_id}),w=e.schematic_text.list({schematic_component_id:A.schematic_component_id}),P={x:E.x-A.center.x,y:E.y-A.center.y};for(let j of B)j.center.x+=P.x,j.center.y+=P.y;for(let j of w)j.position.x+=P.x,j.position.y+=P.y;if(A.center=E,D.ccwRotationDegrees!==0){an(`Component ${m} has rotation: ${D.ccwRotationDegrees}\xB0`);let j=D.ccwRotationDegrees*Math.PI/180,O=Math.cos(j),z=Math.sin(j);for(let ee of B){let W=ee.center.x-E.x,re=ee.center.y-E.y,L=W*O-re*z,K=W*z+re*O;ee.center.x=E.x+L,ee.center.y=E.y+K;let U=ee.facing_direction||"right";ee.facing_direction=TBe(U,D.ccwRotationDegrees)}for(let ee of w){let W=ee.position.x-E.x,re=ee.position.y-E.y,L=W*O-re*z,K=W*z+re*O;ee.position.x=E.x+L,ee.position.y=E.y+K}if(A.symbol_name){let ee=A.symbol_name.match(/_(right|left|up|down)$/);ee&&(A.symbol_name=A.symbol_name.replace(ee[0],`_${TBe(ee[1],D.ccwRotationDegrees)}`))}}}}else if(b.nodeType==="group"&&b.sourceGroup){let A=e.schematic_group?.getWhere?.({source_group_id:b.sourceGroup.source_group_id});if(A){an(`Moving group ${m} to (${E.x}, ${E.y}) from (${A.center?.x}, ${A.center?.y})`);let B=e.schematic_component.list({schematic_group_id:A.schematic_group_id});an(`Group ${m} has ${B.length} components to move`);let w=A.center||{x:0,y:0},P={x:E.x-w.x,y:E.y-w.y};an(`Position delta for group ${m}: (${P.x}, ${P.y})`);for(let j of B)if(j.center){let O={...j.center};j.center.x+=P.x,j.center.y+=P.y,an(`Moved component ${j.source_component_id} from (${O.x}, ${O.y}) to (${j.center.x}, ${j.center.y})`);let z=e.schematic_port.list({schematic_component_id:j.schematic_component_id}),ee=e.schematic_text.list({schematic_component_id:j.schematic_component_id});for(let W of z)W.center&&(W.center.x+=P.x,W.center.y+=P.y);for(let W of ee)W.position&&(W.position.x+=P.x,W.position.y+=P.y)}A.center=E,an(`Updated group ${m} center to (${E.x}, ${E.y})`)}}}an("Matchpack layout completed successfully")}function jGt(r){if(!r.isSubcircuit)return;let{db:e}=r.root,a=r.selectAll("trace"),s=new $b({});s.addConnections(a.map(f=>{let m=e.source_trace.get(f.source_trace_id);return m?[m.source_trace_id,...m.connected_source_port_ids,...m.connected_source_net_ids]:null}).filter(f=>f!==null));let{name:l}=r._parsedProps;for(let f of a){if(!f.source_trace_id)continue;let m=s.getNetConnectedToId(f.source_trace_id);m&&(f.subcircuit_connectivity_map_key=`${l??`unnamedsubcircuit${r._renderId}`}_${m}`,e.source_trace.update(f.source_trace_id,{subcircuit_connectivity_map_key:f.subcircuit_connectivity_map_key}))}let d=new Set;for(let f of a){if(!f.source_trace_id)continue;let m=e.source_trace.get(f.source_trace_id);if(m)for(let D of m.connected_source_port_ids)d.add(D)}for(let f of d){let m=s.getNetConnectedToId(f);if(!m)continue;let D=`${l??`unnamedsubcircuit${r._renderId}`}_${m}`;e.source_port.update(f,{subcircuit_connectivity_map_key:D})}let x=new Set;for(let f of a){if(!f.source_trace_id)continue;let m=e.source_trace.get(f.source_trace_id);if(m)for(let D of m.connected_source_net_ids)x.add(D)}for(let f of x){let m=s.getNetConnectedToId(f);if(!m)continue;let D=`${l??`unnamedsubcircuit${r._renderId}`}_${m}`;e.source_net.update(f,{subcircuit_connectivity_map_key:D})}}function kGt(r){let{db:e}=r.root,a=r._parsedProps,s=r.children.filter(re=>{let L=re._parsedProps?.schX!==void 0||re._parsedProps?.schY!==void 0;return re.schematic_component_id&&!L});if(s.length===0)return;let l=0,d=0;for(let re of s){let L=e.schematic_component.get(re.schematic_component_id);L?.size&&(l=Math.max(l,L.size.width),d=Math.max(d,L.size.height))}l===0&&s.length>0&&(l=1),d===0&&s.length>0&&(d=1);let x=a.gridCols,f,m=a.gridGap,D=a.gridRowGap,b=a.gridColumnGap;a.schLayout?.grid&&(x=a.schLayout.grid.cols??x,f=a.schLayout.grid.rows,m=a.schLayout.gridGap??m,D=a.schLayout.gridRowGap??D,b=a.schLayout.gridColumnGap??b);let E,A;x!==void 0&&f!==void 0?(E=x,A=f):x!==void 0?(E=x,A=Math.ceil(s.length/E)):f!==void 0?(A=f,E=Math.ceil(s.length/A)):(E=Math.ceil(Math.sqrt(s.length)),A=Math.ceil(s.length/E)),E===0&&s.length>0&&(E=1),A===0&&s.length>0&&(A=s.length);let B,w,P=re=>{if(re!==void 0)return typeof re=="number"?re:pe.parse(re)};if(D!==void 0||b!==void 0){let re=typeof m=="object"&&m!==null?m.x:m,L=typeof m=="object"&&m!==null?m.y:m;B=P(b??re)??1,w=P(D??L)??1}else if(typeof m=="number")B=m,w=m;else if(typeof m=="string"){let re=pe.parse(m);B=re,w=re}else if(typeof m=="object"&&m!==null){let re=m.x,L=m.y;B=typeof re=="number"?re:pe.parse(re??"0mm"),w=typeof L=="number"?L:pe.parse(L??"0mm")}else B=1,w=1;let j=E*l+Math.max(0,E-1)*B,O=A*d+Math.max(0,A-1)*w,z=r._getGlobalSchematicPositionBeforeLayout(),ee=z.x-j/2+l/2,W=z.y+O/2-d/2;for(let re=0;re<s.length;re++){let L=s[re];if(!L.schematic_component_id)continue;let K=Math.floor(re/E),U=re%E;if(K>=A||U>=E){console.warn(`Schematic grid layout: Child ${L.getString()} at index ${re} (row ${K}, col ${U}) exceeds specified grid dimensions (${A}x${E}). Skipping placement.`);continue}let J=ee+U*(l+B),Q=W-K*(d+w),de=e.schematic_component.get(L.schematic_component_id);if(de){let oe=de.center,Te={x:J,y:Q};e.schematic_component.update(L.schematic_component_id,{center:Te});let Me=Te.x-oe.x,Ge=Te.y-oe.y,et=e.schematic_port.list({schematic_component_id:L.schematic_component_id});for(let $t of et)e.schematic_port.update($t.schematic_port_id,{center:{x:$t.center.x+Me,y:$t.center.y+Ge}});let dt=e.schematic_text.list({schematic_component_id:L.schematic_component_id});for(let $t of dt)e.schematic_text.update($t.schematic_text_id,{position:{x:$t.position.x+Me,y:$t.position.y+Ge}})}}r.schematic_group_id&&e.schematic_group.update(r.schematic_group_id,{width:j,height:O,center:z})}var PBe=(r,e)=>{let{sourceComponent:a,sourceGroup:s}=e;if(e.nodeType==="component"){let l=r.schematic_component.getWhere({source_component_id:a?.source_component_id});return l?.size?{width:l.size.width,height:l.size.height}:null}if(e.nodeType==="group"){let l=r.schematic_group.getWhere({source_group_id:s?.source_group_id});if(l?.width&&l?.height)return{width:l.width,height:l.height};let d=r.schematic_component.list({schematic_group_id:l?.schematic_group_id}),x=1/0,f=-1/0,m=1/0,D=-1/0;for(let A of d)if(A.center&&A.size){let B=A.size.width/2,w=A.size.height/2;x=Math.min(x,A.center.x-B),f=Math.max(f,A.center.x+B),m=Math.min(m,A.center.y-w),D=Math.max(D,A.center.y+w)}let b=f-x,E=D-m;return{width:b,height:E}}return null},NGt=r=>{let{db:e}=r.root,a=r._parsedProps,s=xg(e.toArray(),{source_group_id:r.source_group_id}),l=a.schJustifyContent??a.justifyContent,d=a.schAlignItems??a.alignItems,x=a.schFlexGap??a.schGap??a.gap,f=a.schFlexDirection??"row",m={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"}[l??"space-between"],D={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[d??"center"];if(!m)throw new Error(`Invalid justifyContent value: "${l}"`);if(!D)throw new Error(`Invalid alignItems value: "${d}"`);let b=0,E=0;typeof x=="object"?(b=x.y??0,E=x.x??0):typeof x=="number"?(b=x,E=x):typeof x=="string"&&(b=pe.parse(x),E=pe.parse(x));let A,B=a.width??a.schWidth??void 0,w=a.height??a.schHeight??void 0;(B===void 0||w===void 0)&&(A=A5(s.childNodes.map(W=>PBe(e,W)).filter(W=>W!==null),{alignItems:D,justifyContent:m,direction:f,rowGap:b,columnGap:E}),B=A.width,w=A.height);let j=new _S(B,w,{alignItems:D,justifyContent:m,direction:f,rowGap:b,columnGap:E});for(let W of s.childNodes){let re=PBe(e,W);j.addChild({metadata:W,width:re?.width??0,height:re?.height??0,flexBasis:re?f==="row"?re.width:re.height:void 0})}j.build();let O={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let W of j.children)O.minX=Math.min(O.minX,W.position.x),O.minY=Math.min(O.minY,W.position.y),O.maxX=Math.max(O.maxX,W.position.x+W.size.width),O.maxY=Math.max(O.maxY,W.position.y+W.size.height);O.width=O.maxX-O.minX,O.height=O.maxY-O.minY;let z={x:-(O.maxX+O.minX)/2,y:-(O.maxY+O.minY)/2},ee=e.toArray();for(let W of j.children){let{sourceComponent:re,sourceGroup:L}=W.metadata;if(re){let K=e.schematic_component.getWhere({source_component_id:re.source_component_id});if(!K)continue;S4e(ee,K.schematic_component_id,{x:W.position.x+W.size.width/2+z.x,y:W.position.y+W.size.height/2+z.y})}if(L){if(!e.schematic_group.getWhere({source_group_id:L.source_group_id}))continue;w4e(ee,L.source_group_id,{x:W.position.x+W.size.width/2+z.x,y:W.position.y+W.size.height/2+z.y})}}r.schematic_group_id&&e.schematic_group.update(r.schematic_group_id,{width:O.width,height:O.height})},YW=1;function MGt(r){let{db:e}=r.root,a=r._parsedProps,s=OGt(r);if(s.length===0)return;let l=LGt({db:e,pcbChildren:s}),d=$Gt(a),x=zGt({props:a,pcbChildren:s,childDimensions:l,gridConfig:d}),f=VGt({pcbChildren:s,childDimensions:l,gridLayout:x,gridConfig:d}),{itemCoordinates:m}=f.layout();GGt({db:e,group:r,pcbChildren:s,itemCoordinates:m,gridLayout:x}),XGt({db:e,group:r,props:a,gridLayout:x})}function OGt(r){return r.children.filter(e=>e.pcb_component_id||e.pcb_group_id)}function LGt(r){let{db:e,pcbChildren:a}=r,s=0,l=0;for(let d of a){let x=0,f=0;if(d.pcb_group_id){let m=e.pcb_group.get(d.pcb_group_id);x=m?.width??0,f=m?.height??0}else if(d.pcb_component_id){let m=e.pcb_component.get(d.pcb_component_id);x=m?.width??0,f=m?.height??0}s=Math.max(s,x),l=Math.max(l,f)}return{width:s,height:l}}function $Gt(r){let e=r.pcbGridCols??r.gridCols??r.pcbLayout?.grid?.cols,a=r.pcbGridRows??r.pcbLayout?.grid?.rows,s=r.pcbGridTemplateColumns,l=r.pcbGridTemplateRows,d=E=>E===void 0?YW:typeof E=="number"?E:pe.parse(E),x=r.pcbGridGap??r.gridGap??r.pcbLayout?.gridGap,f=r.pcbGridRowGap??r.gridRowGap??r.pcbLayout?.gridRowGap,m=r.pcbGridColumnGap??r.gridColumnGap??r.pcbLayout?.gridColumnGap,D=YW,b=YW;if(f!==void 0||m!==void 0){let E=typeof x=="object"?x?.x:x,A=typeof x=="object"?x?.y:x;D=d(m??E),b=d(f??A)}else if(typeof x=="object"&&x!==null)D=d(x.x),b=d(x.y);else{let E=d(x);D=E,b=E}return{cols:e,rows:a,gapX:D,gapY:b,templateColumns:s,templateRows:l}}function zGt(r){let{props:e,pcbChildren:a,childDimensions:s,gridConfig:l}=r;return e.pcbGridTemplateColumns||e.pcbGridTemplateRows?qGt({props:e,gridConfig:l,pcbChildren:a,childDimensions:s}):UGt({gridConfig:l,pcbChildren:a,childDimensions:s})}function qGt(r){let{props:e,gridConfig:a,pcbChildren:s,childDimensions:l}=r,d=e.pcbGridTemplateColumns??"",x=e.pcbGridTemplateRows??"",f=A=>{let B=A.match(/repeat\((\d+),/);return B?parseInt(B[1]):Math.ceil(Math.sqrt(s.length))},m=e.pcbGridTemplateColumns?f(d):Math.ceil(Math.sqrt(s.length)),D=e.pcbGridTemplateRows?f(x):Math.ceil(s.length/m),b=m*l.width+Math.max(0,m-1)*a.gapX,E=D*l.height+Math.max(0,D-1)*a.gapY;return{gridTemplateColumns:d,gridTemplateRows:x,containerWidth:b,containerHeight:E}}function UGt(r){let{gridConfig:e,pcbChildren:a,childDimensions:s}=r,l,d;e.cols!==void 0&&e.rows!==void 0?(l=e.cols,d=e.rows):e.cols!==void 0?(l=e.cols,d=Math.ceil(a.length/l)):e.rows!==void 0?(d=e.rows,l=Math.ceil(a.length/d)):(l=Math.ceil(Math.sqrt(a.length)),d=Math.ceil(a.length/l)),l=Math.max(1,l),d=Math.max(1,d);let x=l*s.width+Math.max(0,l-1)*e.gapX,f=d*s.height+Math.max(0,d-1)*e.gapY,m=`repeat(${l}, ${s.width}px)`,D=`repeat(${d}, ${s.height}px)`;return{gridTemplateColumns:m,gridTemplateRows:D,containerWidth:x,containerHeight:f}}function VGt(r){let{pcbChildren:e,childDimensions:a,gridLayout:s,gridConfig:l}=r,d=e.map((x,f)=>({key:x.getString()||`child-${f}`,contentWidth:a.width,contentHeight:a.height}));return new fSe({containerWidth:s.containerWidth,containerHeight:s.containerHeight,gridTemplateColumns:s.gridTemplateColumns,gridTemplateRows:s.gridTemplateRows,gap:[l.gapY,l.gapX],children:d})}function GGt(r){let{db:e,group:a,pcbChildren:s,itemCoordinates:l,gridLayout:d}=r,x=a._getGlobalPcbPositionBeforeLayout(),f=e.toArray();for(let m=0;m<s.length;m++){let D=s[m],b=D.getString()||`child-${m}`,E=l[b];if(!E){console.warn(`PCB grid layout: No coordinates found for child ${b}`);continue}let A=x.x-d.containerWidth/2+E.x+E.width/2,B=x.y+d.containerHeight/2-E.y-E.height/2;if(D.pcb_component_id)C5(f,D.pcb_component_id,{x:A,y:B});else{let w=D;w.pcb_group_id&&w.source_group_id&&_5(f,w.source_group_id,{x:A,y:B})}}}function XGt(r){let{db:e,group:a,props:s,gridLayout:l}=r;if(a.pcb_group_id){let d=a._getGlobalPcbPositionBeforeLayout();e.pcb_group.update(a.pcb_group_id,{width:s.width??l.containerWidth,height:s.height??l.containerHeight,center:d})}}function YGt(r){let e={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof r=="object"&&!r.preset)return{local:!(r.serverUrl||r.serverMode||r.serverCacheEnabled),...e,...r};let a=typeof r=="object"?r.preset:r,s=typeof r=="object"?r:{};switch(a){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:l,local:d,groupMode:x,...f}=s;return{local:!1,groupMode:"subcircuit",...e,...f}}default:return{local:!0,groupMode:"subcircuit"}}}var HGt=(r,e)=>{let a=r.children.filter(E=>E.componentName==="Constraint"&&E._parsedProps.pcb),s=new Map,l={},d=E=>(l[E]!==E&&(l[E]=d(l[E])),l[E]),x=(E,A)=>{let B=d(E),w=d(A);B!==w&&(l[w]=B)},f=E=>{E in l||(l[E]=E)},m=E=>{let A=E.startsWith(".")?E.slice(1):E;return r.children.find(w=>w.name===A)?.pcb_component_id??void 0};for(let E of a){let A=E._parsedProps;if("left"in A&&"right"in A){let B=m(A.left),w=m(A.right);B&&w&&(f(B),f(w),x(B,w))}else if("top"in A&&"bottom"in A){let B=m(A.top),w=m(A.bottom);B&&w&&(f(B),f(w),x(B,w))}else if("for"in A&&Array.isArray(A.for)){let B=A.for.map(w=>m(w)).filter(w=>!!w);for(let w of B)f(w);for(let w=1;w<B.length;w++)x(B[0],B[w])}}for(let E of Object.keys(l)){let A=d(E);s.has(A)||s.set(A,{componentIds:[],constraints:[]}),s.get(A).componentIds.push(E)}for(let E of a){let A=E._parsedProps,B;if("left"in A?B=m(A.left):"top"in A?B=m(A.top):"for"in A&&(B=m(A.for[0])),!B)continue;let w=d(B);s.get(w)?.constraints.push(E)}let D={},b=Object.fromEntries(e.components.map(E=>[E.componentId,E]));for(let[E,A]of s.entries()){if(A.componentIds.length<=1)continue;let B=new ug,w={},P=(J,Q)=>{let de=`${J}_${Q}`;return w[de]||(w[de]=new rd(de)),w[de]},j=A.componentIds[0];B.addConstraint(new Vs(P(j,"x"),Ds.Eq,0,Oa.required)),B.addConstraint(new Vs(P(j,"y"),Ds.Eq,0,Oa.required));for(let J of A.constraints){let Q=J._parsedProps;if("xDist"in Q){let de=m(Q.left),oe=m(Q.right);de&&oe&&B.addConstraint(new Vs(new Xa(P(oe,"x"),[-1,P(de,"x")]),Ds.Eq,Q.xDist,Oa.required))}else if("yDist"in Q){let de=m(Q.top),oe=m(Q.bottom);de&&oe&&B.addConstraint(new Vs(new Xa(P(de,"y"),[-1,P(oe,"y")]),Ds.Eq,Q.yDist,Oa.required))}else if("sameX"in Q&&Array.isArray(Q.for)){let de=Q.for.map(oe=>m(oe)).filter(oe=>!!oe);if(de.length>1){let oe=P(de[0],"x");for(let Te=1;Te<de.length;Te++)B.addConstraint(new Vs(new Xa(P(de[Te],"x"),[-1,oe]),Ds.Eq,0,Oa.required))}}else if("sameY"in Q&&Array.isArray(Q.for)){let de=Q.for.map(oe=>m(oe)).filter(oe=>!!oe);if(de.length>1){let oe=P(de[0],"y");for(let Te=1;Te<de.length;Te++)B.addConstraint(new Vs(new Xa(P(de[Te],"y"),[-1,oe]),Ds.Eq,0,Oa.required))}}}B.updateVariables();let O={};for(let J of A.componentIds)O[J]={x:P(J,"x").value(),y:P(J,"y").value()};let z=1/0,ee=1/0,W=-1/0,re=-1/0;for(let J of A.componentIds){let Q=b[J],de=O[J];if(Q)for(let oe of Q.pads){let Te=de.x+oe.offset.x,Me=de.y+oe.offset.y;z=Math.min(z,Te-oe.size.x/2),W=Math.max(W,Te+oe.size.x/2),ee=Math.min(ee,Me-oe.size.y/2),re=Math.max(re,Me+oe.size.y/2)}}let L={x:(z+W)/2,y:(ee+re)/2},K=[],U={};for(let J of A.componentIds){let Q=b[J],de=O[J];if(Q){U[J]={x:de.x-L.x,y:de.y-L.y};for(let oe of Q.pads)K.push({padId:oe.padId,networkId:oe.networkId,type:oe.type,size:oe.size,offset:{x:de.x+oe.offset.x-L.x,y:de.y+oe.offset.y-L.y}})}}e.components=e.components.filter(J=>!A.componentIds.includes(J.componentId)),e.components.push({componentId:A.componentIds[0],pads:K,availableRotationDegrees:[0]}),A.relativeCenters=U,D[A.componentIds[0]]=A}return D},VF=(r,e,a)=>{if(e===a)return!0;let s=r.source_group.get(e);return!s||!s.parent_source_group_id?!1:VF(r,s.parent_source_group_id,a)},WGt=(r,e,a)=>{let{db:s}=r.root;for(let l of e.components){let{center:d,componentId:x,ccwRotationOffset:f,ccwRotationDegrees:m}=l,D=a[x];if(D){let O=(m??f??0)*Math.PI/180;for(let z of D.componentIds){let ee=D.relativeCenters[z];if(!ee)continue;let W={x:ee.x*Math.cos(O)-ee.y*Math.sin(O),y:ee.x*Math.sin(O)+ee.y*Math.cos(O)},re=s.pcb_component.get(z);if(!re)continue;let L=re.center,K=js(r._computePcbGlobalTransformBeforeLayout(),Ma(d.x+W.x,d.y+W.y),Ip(O),Ma(-L.x,-L.y)),U=s.toArray().filter(J=>"pcb_component_id"in J&&J.pcb_component_id===z);pg(U,K)}continue}let b=s.pcb_component.get(x);if(b){let j=r.source_group_id,z=s.source_component.get(b.source_component_id)?.source_group_id;if(z!==void 0&&!VF(s,z,j))continue;let ee=b.center,W=m??f??0,re=js(r._computePcbGlobalTransformBeforeLayout(),Ma(d.x,d.y),Ip(W*Math.PI/180),Ma(-ee.x,-ee.y)),L=s.toArray().filter(K=>"pcb_component_id"in K&&K.pcb_component_id===x);pg(L,re);continue}let E=s.pcb_group.list().find(j=>j.source_group_id===x);if(!E)continue;let A=E.center,B=m??f??0,w=js(r._computePcbGlobalTransformBeforeLayout(),Ma(d.x,d.y),Ip(B*Math.PI/180),Ma(-A.x,-A.y)),P=s.toArray().filter(j=>{if("source_group_id"in j&&j.source_group_id&&(j.source_group_id===x||VF(s,j.source_group_id,x)))return!0;if("source_component_id"in j&&j.source_component_id){let O=s.source_component.get(j.source_component_id);if(O?.source_group_id&&(O.source_group_id===x||VF(s,O.source_group_id,x)))return!0}if("pcb_component_id"in j&&j.pcb_component_id){let O=s.pcb_component.get(j.pcb_component_id);if(O?.source_component_id){let z=s.source_component.get(O.source_component_id);if(z?.source_group_id&&(z.source_group_id===x||VF(s,z.source_group_id,x)))return!0}}return!1});pg(P,w),s.pcb_group.update(E.pcb_group_id,{center:d})}},KGt="1mm",IBe=(0,u9e.default)("Group_doInitialPcbLayoutPack"),JGt=r=>{let{db:e}=r.root,{_parsedProps:a}=r,{packOrderStrategy:s,packPlacementStrategy:l,gap:d,pcbGap:x,pcbPackGap:f}=a,m=f??x??d,D=pe.parse(m??KGt),b={},E=P=>{if(P?.pcb_component_id&&P?._parsedProps){let j=P._parsedProps,O=pe.parse(j.pcbMarginLeft??j.pcbMarginX??0),z=pe.parse(j.pcbMarginRight??j.pcbMarginX??0),ee=pe.parse(j.pcbMarginTop??j.pcbMarginY??0),W=pe.parse(j.pcbMarginBottom??j.pcbMarginY??0);(O||z||ee||W)&&(b[P.pcb_component_id]={left:O,right:z,top:ee,bottom:W})}P?.children&&P.children.forEach(E)};E(r);let A={...nSe(rSe(e.toArray(),{source_group_id:r.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:b})),orderStrategy:s??"largest_to_smallest",placementStrategy:l??"minimum_sum_squared_distance_to_network",minGap:D},B=HGt(r,A);IBe.enabled&&(r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${r.name}`,content:JSON.stringify(e.toArray())}),r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${r.name}`,content:A}));let w=ES(A);if(IBe.enabled){let P=yW(w);P.title=`packOutput-${r.name}`,global.debugGraphics?.push(P)}WGt(r,w,B)},ZGt=r=>{let{db:e}=r.root,{_parsedProps:a}=r,s=r.children.filter(re=>re.pcb_component_id||re.pcb_group_id);if(s.some(re=>{let L=re._parsedProps;return L?.pcbX!==void 0||L?.pcbY!==void 0}))return;let d=a.pcbJustifyContent??a.justifyContent,x=a.pcbAlignItems??a.alignItems,f=a.pcbFlexGap??a.pcbGap??a.gap,m=a.pcbFlexDirection??"row",D={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"}[d??"space-between"],b={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[x??"center"];if(!D)throw new Error(`Invalid justifyContent value: "${d}"`);if(!b)throw new Error(`Invalid alignItems value: "${x}"`);let E=0,A=0;typeof f=="object"?(E=f.y??0,A=f.x??0):typeof f=="number"?(E=f,A=f):typeof f=="string"&&(E=pe.parse(f),A=pe.parse(f));let B,w=a.width??a.pcbWidth??void 0,P=a.height??a.pcbHeight??void 0;(w===void 0||P===void 0)&&(B=A5(s.map(re=>re._getMinimumFlexContainerSize()).filter(re=>re!==null),{alignItems:b,justifyContent:D,direction:m,rowGap:E,columnGap:A}),w=B.width,P=B.height);let O=new _S(w,P,{alignItems:b,justifyContent:D,direction:m,rowGap:E,columnGap:A});for(let re of s){let L=re._getMinimumFlexContainerSize();O.addChild({metadata:re,width:L?.width??0,height:L?.height??0,flexBasis:L?m==="row"?L.width:L.height:void 0})}O.build();let z={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let re of O.children)z.minX=Math.min(z.minX,re.position.x),z.minY=Math.min(z.minY,re.position.y),z.maxX=Math.max(z.maxX,re.position.x+re.size.width),z.maxY=Math.max(z.maxY,re.position.y+re.size.height);z.width=z.maxX-z.minX,z.height=z.maxY-z.minY;let ee=r._getGlobalPcbPositionBeforeLayout(),W={x:ee.x-(z.maxX+z.minX)/2,y:ee.y-(z.maxY+z.minY)/2};for(let re of O.children)re.metadata._repositionOnPcb({x:re.position.x+re.size.width/2+W.x,y:re.position.y+re.size.height/2+W.y});e.pcb_group.update(r.pcb_group_id,{width:z.width,height:z.height,center:ee})};function QGt(r){let{db:e}=r.root,a=new Map,s=new Map,l=new Set,x=r.selectAll("trace").filter(Q=>Q._parsedProps?.schDisplayLabel),f=r.selectAll("group"),m=[r.schematic_group_id,...f.map(Q=>Q.schematic_group_id)],D=e.schematic_component.list().filter(Q=>m.includes(Q.schematic_group_id)),b=[],E=new Map,A=new Map;for(let Q of D){let de=Q.schematic_component_id,oe=[],Te=e.source_component.getWhere({source_component_id:Q.source_component_id}),Me=e.schematic_port.list({schematic_component_id:Q.schematic_component_id});for(let Ge of Me){let et=`${Te?.name??Q.schematic_component_id}.${Ge.pin_number}`;E.set(et,Ge.schematic_port_id),A.set(Ge.schematic_port_id,et)}for(let Ge of Me){let et=A.get(Ge.schematic_port_id);oe.push({pinId:et,x:Ge.center.x,y:Ge.center.y})}b.push({chipId:de,center:Q.center,width:Q.size.width,height:Q.size.height,pins:oe})}let B=new Set,w=new Map,P=new Map,j=new Map;for(let Q of D){let de=e.schematic_port.list({schematic_component_id:Q.schematic_component_id});for(let oe of de)B.add(oe.schematic_port_id),oe.source_port_id&&(w.set(oe.schematic_port_id,oe.source_port_id),P.set(oe.source_port_id,oe.schematic_port_id))}let O=new Set;r.subcircuit_id&&O.add(r.subcircuit_id);for(let Q of f)Q.subcircuit_id&&O.add(Q.subcircuit_id);let ee=e.source_trace.list().filter(Q=>{if(Q.subcircuit_id===r.subcircuit_id)return!0;for(let de of Q.connected_source_port_ids)if(P.has(de))return!0;return!1}).flatMap(Q=>Q.connected_source_net_ids);for(let Q of ee){let de=e.source_net.get(Q);de?.subcircuit_id&&O.add(de.subcircuit_id)}let W=[],re=new Map;for(let Q of e.source_trace.list()){if(Q.subcircuit_id&&!O.has(Q.subcircuit_id))continue;let de=(Q.connected_source_port_ids??[]).map(oe=>P.get(oe)).filter(oe=>!!oe&&B.has(oe));if(de.length>=2){let[oe,Te]=de.slice(0,2),Me=[oe,Te].sort().join("::");if(!re.has(Me)){re.set(Me,Q.source_trace_id);let Ge=Q.display_name??Q.source_trace_id;Q.subcircuit_connectivity_map_key&&(l.add(Q.subcircuit_connectivity_map_key),j.set(Ge,Q.subcircuit_connectivity_map_key),s.set(Q.subcircuit_connectivity_map_key,Ge)),W.push({pinIds:[oe,Te].map(et=>A.get(et)),netId:Ge})}}}let L=[];for(let Q of e.source_net.list().filter(de=>!de.subcircuit_id||O.has(de.subcircuit_id)))Q.subcircuit_connectivity_map_key&&(l.add(Q.subcircuit_connectivity_map_key),a.set(Q.subcircuit_connectivity_map_key,Q));let K=new Map;for(let[Q,de]of w){let oe=e.source_port.get(de);if(!oe?.subcircuit_connectivity_map_key)continue;let Te=oe.subcircuit_connectivity_map_key;l.add(Te),K.has(Te)||K.set(Te,[]),K.get(Te).push(Q)}for(let[Q,de]of K){let oe=a.get(Q);if(oe&&de.length>=2){let Te=String(oe.name||oe.source_net_id||Q);j.set(Te,Q),s.set(Q,Te);let Ge=.1*(.18/.18),et=Number((String(Te).length*Ge).toFixed(2));L.push({netId:Te,pinIds:de.map(dt=>A.get(dt)),netLabelWidth:et})}}let U=(()=>{let Q={},de=new Set(L.map(oe=>oe.netId));for(let oe of e.source_net.list().filter(Te=>!Te.subcircuit_id||O.has(Te.subcircuit_id)))oe.name&&de.has(oe.name)&&(oe.is_ground||oe.name.toLowerCase().startsWith("gnd")?Q[oe.name]=["y-"]:oe.is_power||oe.name.toLowerCase().startsWith("v")?Q[oe.name]=["y+"]:Q[oe.name]=["x-","x+"]);return Q})();return{inputProblem:{chips:b,directConnections:W,netConnections:L,availableNetLabelOrientations:U,maxMspPairDistance:r._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:E,pairKeyToSourceTraceId:re,sckToSourceNet:a,sckToUserNetId:s,userNetIdToSck:j,allSourceAndSchematicPortIdsInScope:B,schPortIdToSourcePortId:w,displayLabelTraces:x,allScks:l}}var Qi=1e-6;function jBe(r){let e=Math.abs(r.to.x-r.from.x),a=Math.abs(r.to.y-r.from.y);return e>=a}function WS(r,e){return Math.hypot(e.x-r.x,e.y-r.y)}function kBe(r,e,a){return{x:r.x+(e.x-r.x)*a,y:r.y+(e.y-r.y)*a}}function NBe(r,e,a){let s=WS(r,e);if(s<Qi)return 0;let l=((a.x-r.x)*(e.x-r.x)+(a.y-r.y)*(e.y-r.y))/((e.x-r.x)*(e.x-r.x)+(e.y-r.y)*(e.y-r.y));return Math.max(0,Math.min(1,l))*s}function $S(r,e,a,s){return r*s-e*a}function eXt(r,e,a,s){let l={x:e.x-r.x,y:e.y-r.y},d={x:s.x-a.x,y:s.y-a.y},x=$S(l.x,l.y,d.x,d.y),f={x:a.x-r.x,y:a.y-r.y},m=$S(f.x,f.y,l.x,l.y);if(Math.abs(x)<Qi&&Math.abs(m)<Qi||Math.abs(x)<Qi&&Math.abs(m)>=Qi)return null;let D=$S(f.x,f.y,d.x,d.y)/x,b=$S(f.x,f.y,l.x,l.y)/x;return D<-Qi||D>1+Qi||b<-Qi||b>1+Qi?null:{x:r.x+D*l.x,y:r.y+D*l.y}}function tXt(r,e=Qi){if(r.length===0)return r;r.sort((l,d)=>l.start-d.start);let a=[],s={...r[0]};for(let l=1;l<r.length;l++){let d=r[l];d.start<=s.end+e?s.end=Math.max(s.end,d.end):(a.push(s),s={...d})}return a.push(s),a}function rXt(r,e,a){let s=WS(r.from,r.to);if(s<Qi||e.length===0)return[r];let l=a/2,d=e.map(E=>({start:Math.max(0,E-l),end:Math.min(s,E+l)})).filter(E=>E.end-E.start>Qi),x=tXt(d),f=[],m=0,D={x:r.to.x-r.from.x,y:r.to.y-r.from.y},b=(E,A,B)=>{if(A-E<=Qi)return;let w=E/s,P=A/s;f.push({from:kBe(r.from,r.to,w),to:kBe(r.from,r.to,P),...B?{is_crossing:!0}:{}})};for(let E of x)E.start-m>Qi&&b(m,E.start,!1),b(E.start,E.end,!0),m=E.end;return s-m>Qi&&b(m,s,!1),f.length>0?f:[r]}function nXt(r,e={}){let a=e.crossSegmentLength??.075,s=e.tolerance??Qi,l=new Map,d=m=>`${m.traceIdx}:${m.edgeIdx}`,x=m=>r[m.traceIdx].edges[m.edgeIdx];for(let m=0;m<r.length;m++){let D=r[m];for(let b=0;b<D.edges.length;b++){let E=D.edges[b];for(let A=m;A<r.length;A++){let B=r[A];for(let w=A===m?b+1:0;w<B.edges.length;w++){let P=B.edges[w],j=eXt(E.from,E.to,P.from,P.to);if(!j)continue;let O=WS(E.from,E.to),z=WS(P.from,P.to);if(O<s||z<s)continue;let ee=NBe(E.from,E.to,j),W=NBe(P.from,P.to,j),re=ee<=s||Math.abs(O-ee)<=s||Number.isNaN(ee),L=W<=s||Math.abs(z-W)<=s||Number.isNaN(W);if(!re&&!L){let K=jBe(E),U=jBe(P),J;if(K!==U)J=K;else{let oe=Math.abs(E.to.x-E.from.x),Te=Math.abs(E.to.y-E.from.y),Me=Math.abs(P.to.x-P.from.x),Ge=Math.abs(P.to.y-P.from.y),et=oe-Te,dt=Me-Ge;J=et===dt?!0:et>dt}let Q=d({traceIdx:J?m:A,edgeIdx:J?b:w}),de=l.get(Q)??[];de.push(J?ee:W),l.set(Q,de)}}}}}let f=r.map(m=>({source_trace_id:m.source_trace_id,edges:[]}));for(let m=0;m<r.length;m++){let D=r[m];for(let b=0;b<D.edges.length;b++){let E=d({traceIdx:m,edgeIdx:b}),A=l.get(E)??[];if(A.length===0){f[m].edges.push(D.edges[b]);continue}let B=Array.from(new Set(A.map(P=>Number(P.toFixed(6))))).sort((P,j)=>P-j),w=rXt(D.edges[b],B,a);f[m].edges.push(...w)}}return f}var al=1e-6;function KS(r,e,a=al){return Math.abs(r-e)<=a}function Hg(r,e,a=al){return KS(r.x,e.x,a)&&KS(r.y,e.y,a)}function MBe(r,e,a,s=al){let l=Math.min(e.x,a.x)-s,d=Math.max(e.x,a.x)+s,x=Math.min(e.y,a.y)-s,f=Math.max(e.y,a.y)+s;return r.x<l||r.x>d||r.y<x||r.y>f?!1:Math.abs((a.x-e.x)*(r.y-e.y)-(a.y-e.y)*(r.x-e.x))<=s}function OBe(r,e=al){let a=new Map;for(let s of r){let l=`${s.x.toFixed(6)},${s.y.toFixed(6)}`;a.has(l)||a.set(l,s)}return Array.from(a.values())}function LBe(r){return{x:r.to.x-r.from.x,y:r.to.y-r.from.y}}function HW(r,e,a=al){let s=LBe(r),l=LBe(e),d=Math.hypot(s.x,s.y),x=Math.hypot(l.x,l.y);if(d<a||x<a)return!0;let f=s.x*l.y-s.y*l.x;return Math.abs(f)<=a*d*x}function GF(r,e,a=al){return r.edges.filter(s=>Hg(s.from,e,a)||Hg(s.to,e,a))}function $Be(r,e,a=al){for(let s of r.edges){if(Hg(s.from,e,a))return s.from;if(Hg(s.to,e,a))return s.to}return null}function aXt(r,e,a=al){let s=Hg(r.from,e,a)||KS(r.from.x,e.x,a)&&KS(r.from.y,e.y,a)?r.to:r.from,l=s.x-e.x,d=s.y-e.y;return Math.abs(l)<a&&Math.abs(d)<a?null:Math.abs(l)>=Math.abs(d)?l>=0?"right":"left":d>=0?"up":"down"}function Vg(r,e,a=al){let s=GF(r,e,a);if(s.length<2)return null;let l=s.map(E=>aXt(E,e,a)),d=l.includes("up"),x=l.includes("down"),f=l.includes("left"),m=l.includes("right"),D=d?"up":x?"down":null,b=m?"right":f?"left":null;return D&&b?`${D}-${b}`:null}function sXt(r,e={}){let a=e.tolerance??al,s={};for(let d of r)s[d.source_trace_id]=[];let l=r.map(d=>{let x=[];for(let f of d.edges)x.push(f.from,f.to);return OBe(x,a)});for(let d=0;d<r.length;d++){let x=r[d],f=l[d];for(let m=d+1;m<r.length;m++){let D=r[m],b=l[m];for(let E of f)for(let A of b)if(Hg(E,A,a)){let B=GF(x,E,a),w=GF(D,A,a),P=B.some(ee=>w.some(W=>!HW(ee,W,a))),j=Vg(x,E,a),O=Vg(D,A,a);P&&!(j!==null&&O!==null&&j===O)&&(s[x.source_trace_id].push(E),x.source_trace_id!==D.source_trace_id&&s[D.source_trace_id].push(A))}for(let E of f)for(let A of D.edges)if(MBe(E,A.from,A.to,a)){let w=GF(x,E,a).some(ee=>!HW(ee,A,a)),P=Vg(x,E,a),j=$Be(D,E,a*1e3),O=j?Vg(D,j,a):null;w&&!(P!==null&&O!==null&&P===O)&&(s[x.source_trace_id].push(E),x.source_trace_id!==D.source_trace_id&&s[D.source_trace_id].push(E))}for(let E of b)for(let A of x.edges)if(MBe(E,A.from,A.to,a)){let w=GF(D,E,a).some(ee=>!HW(A,ee,a)),P=Vg(D,E,a),j=$Be(x,E,a*1e3),O=j?Vg(x,j,a):null;w&&!(O!==null&&P!==null&&O===P)&&(s[D.source_trace_id].push(E),x.source_trace_id!==D.source_trace_id&&s[x.source_trace_id].push(E))}}}for(let d of Object.keys(s))s[d]=OBe(s[d],a);return s}var WW=(0,l9e.default)("Group_doInitialSchematicTraceRender");function iXt(r){let{group:e,solver:a,pinIdToSchematicPortId:s,userNetIdToSck:l}=r,{db:d}=e.root,x=a.traceOverlapShiftSolver?.correctedTraceMap,f=[];WW(`Traces inside SchematicTraceSolver output: ${Object.values(x??{}).length}`);for(let b of Object.values(x??{})){let E=b?.tracePath;if(!Array.isArray(E)||E.length<2){WW(`Skipping trace ${b?.pinIds.join(",")} because it has less than 2 points`);continue}let A=[];for(let P=0;P<E.length-1;P++)A.push({from:{x:E[P].x,y:E[P].y},to:{x:E[P+1].x,y:E[P+1].y}});let B=null,w;if(Array.isArray(b?.pins)&&b.pins.length===2){let P=s.get(b.pins[0]?.pinId),j=s.get(b.pins[1]?.pinId);if(P&&j){for(let O of[P,j])d.schematic_port.get(O)&&d.schematic_port.update(O,{is_connected:!0});w=l.get(String(b.userNetId))}}B||(B=`solver_${b?.mspPairId}`,w=l.get(String(b.userNetId))),f.push({source_trace_id:B,edges:A,subcircuit_connectivity_map_key:w})}WW(`Applying ${f.length} traces from SchematicTraceSolver output`);let m=nXt(f.map(b=>({source_trace_id:b.source_trace_id,edges:b.edges}))),D=sXt(m);for(let b of m)d.schematic_trace.insert({source_trace_id:b.source_trace_id,edges:b.edges,junctions:D[b.source_trace_id]??[],subcircuit_connectivity_map_key:f.find(E=>E.source_trace_id===b.source_trace_id)?.subcircuit_connectivity_map_key})}var oXt=r=>{switch(r){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"}},uXt=r=>{for(let a of r){let s=a._getDirectlyConnectedTraces();for(let l of s){let d=l._parsedProps.schDisplayLabel;if(d)return{name:d,wasAssignedDisplayLabel:!0}}}return{name:r.map(a=>a._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},KW=(0,d9e.default)("Group_doInitialSchematicTraceRender");function cXt(r){let{group:e,solver:a,sckToSourceNet:s,allScks:l,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,userNetIdToSck:f,pinIdToSchematicPortId:m,schematicPortIdsWithPreExistingNetLabels:D,schematicPortIdsWithRoutedTraces:b}=r,{db:E}=e.root,A=a.netLabelPlacementSolver?.netLabelPlacements??[],B=a.mspConnectionPairSolver.globalConnMap;for(let w of A){KW(`processing placement: ${w.netId}`);let P=B.getIdsConnectedToNet(w.globalConnNetId).find(Q=>f.get(Q)),j=f.get(P),O=w.anchorPoint,z=w.orientation,ee=oXt(z),W=j?s.get(j):void 0,re=w.pinIds.map(Q=>m.get(Q));if(re.some(Q=>D.has(Q))){KW(`skipping net label placement for "${w.netId}" REASON:schematic port has pre-existing net label`);continue}if(W){let Q=W.name,de=ax({anchor_position:O,anchor_side:ee,text:Q});E.schematic_net_label.insert({text:Q,anchor_position:O,center:de,anchor_side:ee,...W?.source_net_id?{source_net_id:W.source_net_id}:{}});continue}let L=e.selectAll("port").filter(Q=>Q._getSubcircuitConnectivityKey()===j),{name:K,wasAssignedDisplayLabel:U}=uXt(L);if(!U&&re.some(Q=>b.has(Q))){KW(`skipping net label placement for "${w.netId}" REASON:schematic port has routed traces and no display label`);continue}let J=ax({anchor_position:O,anchor_side:ee,text:K});E.schematic_net_label.insert({text:K,anchor_position:O,center:J,anchor_side:ee})}}var lXt=({allSourceAndSchematicPortIdsInScope:r,group:e,schPortIdToSourcePortId:a,sckToSourceNet:s,pinIdToSchematicPortId:l,schematicPortIdsWithPreExistingNetLabels:d})=>{let{db:x}=e.root;for(let f of Array.from(r)){let m=x.schematic_port.get(f);if(!m||m.is_connected)continue;let D=a.get(f);if(!D)continue;let E=x.source_port.get(D)?.subcircuit_connectivity_map_key;if(!E)continue;let A=s.get(E);if(!A||x.schematic_net_label.list().some(O=>Math.abs(O.anchor_position.x-m.center.x)<.1&&Math.abs(O.anchor_position.y-m.center.y)<.1?A.source_net_id&&O.source_net_id?O.source_net_id===A.source_net_id:O.text===(A.name||E):!1))continue;let w=A.name||A.source_net_id||E,P=HF(m.facing_direction||"right")||"right",j=ax({anchor_position:m.center,anchor_side:P,text:w});x.schematic_net_label.insert({text:w,anchor_position:m.center,center:j,anchor_side:P,...A.source_net_id?{source_net_id:A.source_net_id}:{}})}},dXt=r=>{let e=new Set,a=r.selectAll("netlabel");for(let s of a){let l=s._getConnectedPorts();for(let d of l)d.schematic_port_id&&e.add(d.schematic_port_id)}return e},pXt=({solver:r,pinIdToSchematicPortId:e})=>{let a=r.schematicTraceLinesSolver.solvedTracePaths,s=new Set;for(let l of a)for(let d of l.pinIds){let x=e.get(d);x&&s.add(x)}return s},xXt=(0,c9e.default)("Group_doInitialSchematicTraceRender"),fXt=r=>{if(!r.root?._featureMspSchematicTraceRouting||!r.isSubcircuit||r.root?.schematicDisabled)return;let{inputProblem:e,pinIdToSchematicPortId:a,pairKeyToSourceTraceId:s,sckToSourceNet:l,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,displayLabelTraces:f,allScks:m,userNetIdToSck:D}=QGt(r),b=dXt(r);xXt.enabled&&r.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(e,null,2)});let E=new RSe(e);E.solve();let A=pXt({solver:E,pinIdToSchematicPortId:a});iXt({group:r,solver:E,pinIdToSchematicPortId:a,userNetIdToSck:D}),cXt({group:r,solver:E,sckToSourceNet:l,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,pinIdToSchematicPortId:a,allScks:m,userNetIdToSck:D,schematicPortIdsWithPreExistingNetLabels:b,schematicPortIdsWithRoutedTraces:A}),lXt({group:r,allSourceAndSchematicPortIdsInScope:d,schPortIdToSourcePortId:x,sckToSourceNet:l,pinIdToSchematicPortId:a,schematicPortIdsWithPreExistingNetLabels:b})},Wg=class extends es{constructor(){super(...arguments);q(this,"pcb_group_id",null);q(this,"schematic_group_id",null);q(this,"subcircuit_id",null);q(this,"_hasStartedAsyncAutorouting",!1);q(this,"_asyncAutoroutingResult",null);q(this,"unnamedElementCounter",{})}get config(){return{zodProps:oAe,componentName:"Group"}}doInitialSourceGroupRender(){let{db:e}=this.root,a=e.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit});this.source_group_id=a.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${a.source_group_id}`,e.source_group.update(a.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:e}=this.root;for(let a of this.children)e.source_component.update(a.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:e}=this.root,a=this.parent?.getGroup?.();if(a?.source_group_id&&e.source_group.update(this.source_group_id,{parent_source_group_id:a.source_group_id}),!this.isSubcircuit)return;let s=this.parent?.getSubcircuit?.()?.subcircuit_id;s&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:s})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.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:a.autorouter?{trace_clearance:a.autorouter.traceClearance}:void 0});this.pcb_group_id=s.pcb_group_id;for(let l of this.children)e.pcb_component.update(l.pcb_component_id,{pcb_group_id:s.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,a=this._parsedProps,s=ZS(this.children);if(this.pcb_group_id){let l=s.width,d=s.height,x=(s.minX+s.maxX)/2,f=(s.minY+s.maxY)/2;if(this.isSubcircuit){let{padLeft:b,padRight:E,padTop:A,padBottom:B}=this._resolvePcbPadding();l+=b+E,d+=A+B,x+=(E-b)/2,f+=(A-B)/2}let D=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0?e.pcb_group.get(this.pcb_group_id)?.center??{x,y:f}:{x,y:f};e.pcb_group.update(this.pcb_group_id,{width:Number(a.width??l),height:Number(a.height??d),center:D})}}getNextAvailableName(e){var a,s;return(a=this.unnamedElementCounter)[s=e.lowercaseComponentName]??(a[s]=1),`unnamed_${e.lowercaseComponentName}${this.unnamedElementCounter[e.lowercaseComponentName]++}`}_resolvePcbPadding(){let e=this._parsedProps,a=e.pcbLayout,s=E=>{let A=a?.[E],B=e[E];if(typeof A=="number")return A;if(typeof B=="number")return B},l=s("padding")??0,d=s("paddingX"),x=s("paddingY"),f=s("paddingLeft")??d??l,m=s("paddingRight")??d??l,D=s("paddingTop")??x??l,b=s("paddingBottom")??x??l;return{padLeft:f,padRight:m,padTop:D,padBottom:b}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:e}=this,{db:a}=this.root,s=e;if(!this.isSubcircuit)return;let l=s.manualEdits?.manual_trace_hints;if(l)for(let d of l)this.add(new fK({for:d.pcb_port_selector,offsets:d.offsets}))}doInitialSourceAddConnectivityMapKey(){jGt(this)}_areChildSubcircuitsRouted(){let e=this.selectAll("group").filter(a=>a.isSubcircuit);for(let a of e)if(a._shouldRouteAsync()&&!a._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let e=this._getAutorouterConfig();return e.groupMode==="sequential-trace"?!1:!!(e.local&&e.groupMode==="subcircuit"||!e.local)}_hasTracesToRoute(){let e=(0,Gg.default)("tscircuit:core:_hasTracesToRoute"),a=this.selectAll("trace");return e(`[${this.getString()}] has ${a.length} traces to route`),a.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:e}=this.root,a=(0,Gg.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),s=this._parsedProps,l=this._getAutorouterConfig(),d=l.serverUrl,x=l.serverMode,f=(b,E)=>(a("fetching",b),E.headers&&(E.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(b,E)),m=this.root.db.toArray().filter(b=>b.type.startsWith("source_")||b.type.startsWith("pcb_"));if(x==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:E}=await f(`${d}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:nK({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(A=>A.json());this._asyncAutoroutingResult=E,this._markDirty("PcbTraceRender");return}let{autorouting_result:b}=await f(`${d}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:m,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(E=>E.json());this._asyncAutoroutingResult=b,this._markDirty("PcbTraceRender");return}let{autorouting_job:D}=await f(`${d}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:m,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:l.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(b=>b.json());for(;;){let{autorouting_job:b}=await f(`${d}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:D.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(E=>E.json());if(b.is_finished){let{autorouting_job_output:E}=await f(`${d}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:D.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(A=>A.json());this._asyncAutoroutingResult={output_pcb_traces:E.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(b.has_error){let E=new UF(`Autorouting job failed: ${JSON.stringify(b.error)}`);throw e.pcb_autorouting_error.insert({pcb_error_id:D.autorouting_job_id,error_type:"pcb_autorouting_error",message:E.message}),E}await new Promise(E=>setTimeout(E,100))}}async _runLocalAutorouting(){let{db:e}=this.root,a=this._parsedProps,s=(0,Gg.default)("tscircuit:core:_runLocalAutorouting");s(`[${this.getString()}] starting local autorouting`);let l=this._getAutorouterConfig(),{simpleRouteJson:d}=nK({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(s.enabled){let m=aH(d);m.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(m)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:d});let x;l.algorithmFn?x=await l.algorithmFn(d):x=new _Gt(d,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity});let f=new Promise((m,D)=>{x.on("complete",b=>{s(`[${this.getString()}] local autorouting complete`),m(b.traces)}),x.on("error",b=>{s(`[${this.getString()}] local autorouting error: ${b.error.message}`),D(b.error)})});x.on("progress",m=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...m})}),x.start();try{let m=await f;this._asyncAutoroutingResult={output_pcb_traces:m},this._markDirty("PcbTraceRender")}catch(m){let{db:D}=this.root;throw D.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:m instanceof Error?m.message:String(m)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:m instanceof Error?m.message:String(m)},simpleRouteJson:d}),m}finally{x.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let e=(0,Gg.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){e(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}e(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){fXt(this)}updatePcbTraceRender(){let e=(0,Gg.default)("tscircuit:core:updatePcbTraceRender");if(e(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(e(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:a}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){e(`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){e(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:e}=this.root,{traces:a}=this._asyncAutoroutingResult.output_simple_route_json;if(a)for(let s of a){let l=e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:s.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;let{db:a}=this.root;for(let s of e)if(s.type==="pcb_trace"){if(s.subcircuit_id=this.subcircuit_id,s.connection_name){let l=s.connection_name;s.source_trace_id=l}a.pcb_trace.insert(s)}for(let s of e)if(s.type!=="pcb_via"&&s.type==="pcb_trace")for(let l of s.route)l.route_type==="via"&&a.pcb_via.insert({pcb_trace_id:s.pcb_trace_id,x:l.x,y:l.y,hole_diameter:.3,outer_diameter:.6,layers:[l.from_layer,l.to_layer],from_layer:l.from_layer,to_layer:l.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=s.schematic_group_id;for(let l of this.children)l.schematic_component_id&&e.schematic_component.update(l.schematic_component_id,{schematic_group_id:s.schematic_group_id})}_getSchematicLayoutMode(){let e=this._parsedProps;if(e.schLayout?.layoutMode==="none"||e.schLayout?.layoutMode==="relative")return"relative";if(e.schLayout?.matchAdapt)return"match-adapt";if(e.schLayout?.flex)return"flex";if(e.schLayout?.grid)return"grid";if(e.schMatchAdapt)return"match-adapt";if(e.schFlex)return"flex";if(e.schGrid)return"grid";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";if(e.relative||e.schRelative)return"relative";let a=this.children.some(l=>{let d=l._parsedProps;return d?.schX!==void 0||d?.schY!==void 0}),s=(e.manualEdits?.schematic_placements?.length??0)>0;return!a&&!s?"match-adapt":"relative"}doInitialSchematicLayout(){let e=this._getSchematicLayoutMode();e==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),e==="grid"&&this._doInitialSchematicLayoutGrid(),e==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){TGt(this)}_doInitialSchematicLayoutMatchpack(){IGt(this)}_doInitialSchematicLayoutGrid(){kGt(this)}_doInitialSchematicLayoutFlex(){NGt(this)}_getPcbLayoutMode(){let e=this._parsedProps;if(e.pcbRelative)return"none";if(e.pcbLayout?.matchAdapt)return"match-adapt";if(e.pcbLayout?.flex)return"flex";if(e.pcbLayout?.grid)return"grid";if(e.pcbLayout?.pack)return"pack";if(e.pcbFlex)return"flex";if(e.pcbGrid)return"grid";if(e.pcbPack||e.pack)return"pack";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";let a=e.pcbX!==void 0||e.pcbY!==void 0,s=(e.manualEdits?.pcb_placements?.length??0)>0;if(this.children.some(x=>{let f=x._parsedProps;return f?.pcbX!==void 0||f?.pcbY!==void 0}))return"none";let d=this.children.reduce((x,f)=>{let m=f._parsedProps,D=m?.pcbX!==void 0||m?.pcbY!==void 0;return x+(D?0:1)},0);return!a&&!s&&d>1?"pack":"none"}doInitialPcbLayout(){let e=this._getPcbLayoutMode();e==="grid"?this._doInitialPcbLayoutGrid():e==="pack"?this._doInitialPcbLayoutPack():e==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){MGt(this)}_doInitialPcbLayoutPack(){JGt(this)}_doInitialPcbLayoutFlex(){ZGt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,a=this._parsedProps;if(!a.border)return;let s=typeof a.schWidth=="number"?a.schWidth:void 0,l=typeof a.schHeight=="number"?a.schHeight:void 0,d=typeof a.schPadding=="number"?a.schPadding:0,x=typeof a.schPaddingLeft=="number"?a.schPaddingLeft:d,f=typeof a.schPaddingRight=="number"?a.schPaddingRight:d,m=typeof a.schPaddingTop=="number"?a.schPaddingTop:d,D=typeof a.schPaddingBottom=="number"?a.schPaddingBottom:d,b=this.schematic_group_id?e.schematic_group.get(this.schematic_group_id):null;if(b&&(s===void 0&&typeof b.width=="number"&&(s=b.width),l===void 0&&typeof b.height=="number"&&(l=b.height)),s===void 0||l===void 0)return;let E=b?.center??this._getGlobalSchematicPositionBeforeLayout(),A=E.x-s/2-x,B=E.y-l/2-D,w=s+x+f,P=l+m+D;e.schematic_box.insert({width:w,height:P,x:A,y:B,is_dashed:a.border?.dashed??!1})}_determineSideFromPosition(e,a){if(!e.center||!a.center)return"left";let s=e.center.x-a.center.x,l=e.center.y-a.center.y;return Math.abs(s)>Math.abs(l)?s>0?"right":"left":l>0?"bottom":"top"}_calculateSchematicBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let a=1/0,s=-1/0,l=1/0,d=-1/0;for(let f of e)a=Math.min(a,f.centerX),s=Math.max(s,f.centerX),l=Math.min(l,f.centerY),d=Math.max(d,f.centerY);let x=2;return{minX:a-x,maxX:s+x,minY:l-x,maxY:d+x}}_getAutorouterConfig(){let e=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return YGt(e)}_getSubcircuitLayerCount(){let e=this.getInheritedProperty("layers");return typeof e=="number"?e:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(this.isSubcircuit){let a=new Map;for(let s of this.children)if(!s.isSubcircuit&&s._parsedProps.name){let l=a.get(s._parsedProps.name)||[];l.push(s),a.set(s._parsedProps.name,l)}for(let[s,l]of a.entries())l.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${s}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:l.map(d=>d.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:e}=this.root,a=e;for(let s of a.schematic_net_label.list()){let l=a.source_net.get(s.source_net_id),d=s.text||l?.name||"";if(s.anchor_side==="top"&&/^gnd/i.test(d)){a.schematic_net_label.update(s.schematic_net_label_id,{symbol_name:"rail_down"});continue}s.anchor_side==="bottom"&&/^v/i.test(d)&&a.schematic_net_label.update(s.schematic_net_label_id,{symbol_name:"rail_up"})}}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(e){return super._repositionOnPcb(e)}},zBe=(r,e,a)=>{let s=Math.min(a,r/2,e/2),l=Math.max(1,Math.ceil(Math.PI/2*s)),d=Math.PI/2/l,x=r/2,f=e/2,m=[];m.push({x:-x+s,y:-f}),m.push({x:x-s,y:-f});for(let D=1;D<=l;D++){let b=-Math.PI/2+D*d;m.push({x:x-s+s*Math.cos(b),y:-f+s+s*Math.sin(b)})}m.push({x,y:f-s});for(let D=1;D<=l;D++){let b=0+D*d;m.push({x:x-s+s*Math.cos(b),y:f-s+s*Math.sin(b)})}m.push({x:-x+s,y:f});for(let D=1;D<=l;D++){let b=Math.PI/2+D*d;m.push({x:-x+s+s*Math.cos(b),y:f-s+s*Math.sin(b)})}m.push({x:-x,y:-f+s});for(let D=1;D<=l;D++){let b=Math.PI+D*d;m.push({x:-x+s+s*Math.cos(b),y:-f+s+s*Math.sin(b)})}return m},p9e=class extends Wg{constructor(){super(...arguments);q(this,"pcb_board_id",null);q(this,"_drcChecksComplete",!1);q(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:SY}}get boardThickness(){let{_parsedProps:e}=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:e}=this.root,{_parsedProps:a}=this;if(a.width&&a.height)return;let s=1/0,l=1/0,d=-1/0,x=-1/0,f=s9e(e,this.subcircuit_id),m=new Set([this.subcircuit_id,...f]),D=e.pcb_component.list().filter(re=>re.subcircuit_id&&m.has(re.subcircuit_id)),b=e.pcb_group.list().filter(re=>re.subcircuit_id&&m.has(re.subcircuit_id)),E=!1,A=(re,L,K)=>{L===0||K===0||(E=!0,s=Math.min(s,re.x-L/2),l=Math.min(l,re.y-K/2),d=Math.max(d,re.x+L/2),x=Math.max(x,re.y+K/2))};for(let re of D)A(re.center,re.width,re.height);for(let re of b)A(re.center,re.width,re.height);let B=2,w=E?d-s+B*2:0,P=E?x-l+B*2:0,j={x:E?(s+d)/2+(a.outlineOffsetX??0):a.outlineOffsetX??0,y:E?(l+x)/2+(a.outlineOffsetY??0):a.outlineOffsetY??0},O=a.width??w,z=a.height??P,ee=a.outline;!ee&&a.borderRadius!=null&&O>0&&z>0&&(ee=zBe(O,z,a.borderRadius));let W={width:O,height:z,center:j};ee&&(W.outline=ee.map(re=>({x:re.x+(a.outlineOffsetX??0),y:re.y+(a.outlineOffsetY??0)}))),e.pcb_board.update(this.pcb_board_id,W)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let e=this.root?.platform;if(!e?.printBoardInformationToSilkscreen)return;let a=this.root.db.pcb_board.get(this.pcb_board_id);if(!a)return;let s=[];if(e.projectName&&s.push(e.projectName),e.version&&s.push(`v${e.version}`),e.url&&s.push(e.url),s.length===0)return;let l=s.join(`
|
|
1038
|
+
`),f={x:a.center.x+a.width/2-.25,y:a.center.y-a.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:l,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:f})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=a.width??0,l=a.height??0,d={x:(a.pcbX??0)+(a.outlineOffsetX??0),y:(a.pcbY??0)+(a.outlineOffsetY??0)};if(a.outline){let m=a.outline.map(w=>w.x),D=a.outline.map(w=>w.y),b=Math.min(...m),E=Math.max(...m),A=Math.min(...D),B=Math.max(...D);s=E-b,l=B-A,d={x:(b+E)/2+(a.outlineOffsetX??0),y:(A+B)/2+(a.outlineOffsetY??0)}}let x=a.outline;!x&&a.borderRadius!=null&&s>0&&l>0&&(x=zBe(s,l,a.borderRadius));let f=e.pcb_board.insert({center:d,thickness:this.boardThickness,num_layers:this.allLayers.length,width:s,height:l,outline:x?.map(m=>({x:m.x+(a.outlineOffsetX??0),y:m.y+(a.outlineOffsetY??0)})),material:a.material});this.pcb_board_id=f.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:e}=this.root;this.pcb_board_id&&(e.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return Si()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let a=TSe(e.toArray());for(let d of a)e.pcb_trace_error.insert(d);let s=wSe(e.toArray());for(let d of s)e.pcb_port_not_connected_error.insert(d);let l=jSe(e.toArray());for(let d of l)e.pcb_component_outside_board_error.insert(d)}_emitRenderLifecycleEvent(e,a){super._emitRenderLifecycleEvent(e,a),a==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e})}},hXt=new Proxy({},{get:(r,e)=>e}),dd=hXt,x9e=class extends es{constructor(){super(...arguments);q(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:gAe,sourceFtype:dd.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let e=this.props.capacitance,a=typeof e=="string"?e:`${Ns(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${a}/${Ns(this._parsedProps.maxVoltageRating)}V`:a}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new qc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new qc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,capacitance:a.capacitance,max_voltage_rating:a.maxVoltageRating,max_decoupling_trace_length:a.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!a.polarized});this.source_component_id=s.source_component_id}},QS=class extends es{constructor(e){super(e);q(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:og,shouldRenderAsSchematicBox:!0}}initPorts(e={}){super.initPorts(e);let{_parsedProps:a}=this;if(a.externallyConnectedPins){let s=new Set;for(let[l,d]of a.externallyConnectedPins)s.add(l),s.add(d);for(let l of s)if(!this.children.find(x=>x instanceof Ni&&x.isMatchingAnyOf([l]))){let x=l.match(/^pin(\d+)$/);if(x){let f=parseInt(x[1]);this.add(new Ni({pinNumber:f,aliases:[l]}))}else this.add(new Ni({name:l,aliases:[l]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:e}=this;e?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=s.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:e}=this;if(e.externallyConnectedPins)for(let[a,s]of e.externallyConnectedPins)this.add(new qc({from:`${this.getSubcircuitSelector()} > port.${a}`,to:`${this.getSubcircuitSelector()} > port.${s}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:e}=this.root,{pinAttributes:a}=this.props;if(!a)return;let s=null,l=null,d,x=this.selectAll("port");for(let E of x)for(let A of E.getNameAndAliases())if(a[A]){let B=a[A];B.providesPower&&(s=E,d=B.providesVoltage),B.providesGround&&(l=E)}if(!s||!l||d===void 0)return;let f=e.source_port.get(s.source_port_id);if(!f?.subcircuit_connectivity_map_key)return;let m=e.source_port.get(l.source_port_id);if(!m?.subcircuit_connectivity_map_key)return;let D=e.source_net.getWhere({subcircuit_connectivity_map_key:f.subcircuit_connectivity_map_key}),b=e.source_net.getWhere({subcircuit_connectivity_map_key:m.subcircuit_connectivity_map_key});!D||!b||e.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:s.source_port_id,positive_source_net_id:D.source_net_id,negative_source_port_id:l.source_port_id,negative_source_net_id:b.source_net_id,voltage:d})}},f9e=class extends QS{constructor(r){super(r)}get config(){return{...super.config,componentName:"Pinout",zodProps:uAe}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:e.manufacturerPartNumber,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=a.source_component_id}},h9e=class extends es{constructor(){super(...arguments);q(this,"pos",this.portMap.pin1);q(this,"anode",this.portMap.pin1);q(this,"neg",this.portMap.pin2);q(this,"cathode",this.portMap.pin2)}get config(){let e={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},a=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:a?e[a]:this.props.symbolName??"diode",componentName:"Diode",zodProps:PAe,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=s.source_component_id}},m9e=class extends es{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:lAe,sourceFtype:dd.simple_fuse}}_getSchematicSymbolDisplayValue(){let r=this._parsedProps.currentRating,e=this._parsedProps.voltageRating,a=typeof r=="string"?parseFloat(r):r,s=typeof e=="string"?parseFloat(e):e;return`${Ns(a)}A / ${Ns(s)}V`}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=typeof e.currentRating=="string"?parseFloat(e.currentRating):e.currentRating,s=typeof e.voltageRating=="string"?parseFloat(e.voltageRating):e.voltageRating,l=r.source_component.insert({name:this.name,ftype:dd.simple_fuse,current_rating_amps:a,voltage_rating_volts:s,display_current_rating:`${Ns(a)}A`,display_voltage_rating:`${Ns(s)}V`});this.source_component_id=l.source_component_id}},g9e=class extends es{constructor(){super(...arguments);q(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:BY,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let a=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),s=this._parsedProps.schDirection??"right";return{leftSize:s==="left"?a:0,rightSize:s==="right"?a:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,a=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),s={};for(let x=0;x<a.length;x++){let f=a[x],m=e.source_port.get(f.source_port_id),D="";if(typeof m?.pin_number=="number")D=m.pin_number.toString();else if(Array.isArray(m?.port_hints)){let b=m.port_hints.find(E=>/^(pin)?\d+$/.test(E));b&&(/^pin\d+$/.test(b)?D=b.replace(/^pin/,""):D=b)}s[D]=f.pcb_port_id}let l=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),d=x=>{if(x&&typeof x=="string"&&x.startsWith("{PIN")){let f=x.replace("{PIN","").replace("}","");return s[f]||x}return x};for(let x of l)if(x.route)for(let f of x.route)f.route_type==="wire"&&(f.start_pcb_port_id=d(f.start_pcb_port_id),f.end_pcb_port_id=d(f.end_pcb_port_id))}},D9e=class extends es{constructor(){super(...arguments);q(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(e){return this.selectOne(`port.${e}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let e=this.children.filter(a=>a.componentName==="Port").map(a=>a.name);return e.length>0?[e]:[]}return this._parsedProps.bridgedPins??[]}get config(){let e=this._parsedProps??this.props,a=e.pinCount;if(e.pinCount==null&&!e.footprint&&(a=2),e.pinCount==null){let d=(e.bridgedPins??[]).flat().map(D=>this._getPinNumberFromBridgedPinName(D)).filter(D=>D!==null),x=d.length>0?Math.max(...d):0,f=e.pinLabels?Object.keys(e.pinLabels).length:0,m=Math.max(x,f);(m===2||m===3)&&(a=m),a==null&&e.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(a=this.getPortsFromFootprint().length)}let s="";a?s+=`solderjumper${a}`:s="solderjumper";let l=[];return Array.isArray(e.bridgedPins)&&e.bridgedPins.length>0?l=Array.from(new Set(e.bridgedPins.flat().map(d=>this._getPinNumberFromBridgedPinName(d)).filter(d=>d!==null))).sort((d,x)=>d-x):e.bridged&&a&&(l=Array.from({length:a},(d,x)=>x+1)),l.length>0&&(s+=`_bridged${l.join("")}`),{schematicSymbolName:e.symbolName??s,componentName:"SolderJumper",zodProps:cAe,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let a=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);a==null&&!this._parsedProps.footprint&&(a=2);let s=this._parsedProps.schDirection??"right";return{leftSize:s==="left"?a:0,rightSize:s==="right"?a:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:a.manufacturerPartNumber,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=e.pcb_component.insert({center:{x:a.pcbX??0,y:a.pcbY??0},width:2,height:3,layer:a.layer??"top",rotation:a.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=s.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,a=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),s={};for(let x=0;x<a.length;x++){let f=a[x],m=e.source_port.get(f.source_port_id),D="";if(typeof m?.pin_number=="number")D=m.pin_number.toString();else if(Array.isArray(m?.port_hints)){let b=m.port_hints.find(E=>/^(pin)?\d+$/.test(E));b&&(/^pin\d+$/.test(b)?D=b.replace(/^pin/,""):D=b)}s[D]=f.pcb_port_id}let l=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),d=x=>{if(x&&typeof x=="string"&&x.startsWith("{PIN")){let f=x.replace("{PIN","").replace("}","");return s[f]||x}return x};for(let x of l)if(x.route)for(let f of x.route)f.route_type==="wire"&&(f.start_pcb_port_id=d(f.start_pcb_port_id),f.end_pcb_port_id=d(f.end_pcb_port_id))}},y9e=class extends es{constructor(){super(...arguments);q(this,"pos",this.portMap.pin1);q(this,"anode",this.portMap.pin1);q(this,"neg",this.portMap.pin2);q(this,"cathode",this.portMap.pin2)}get config(){let e={laser:"laser_diode"},a=this.props.laser?"laser":null;return{schematicSymbolName:a?e[a]:this.props.symbolName??"led",componentName:"Led",zodProps:jAe,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_led",name:this.name,wave_length:a.wavelength,color:a.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=s.source_component_id}},b9e=class extends es{constructor(){super(...arguments);q(this,"pos",this.portMap.pin1);q(this,"positive",this.portMap.pin1);q(this,"neg",this.portMap.pin2);q(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:XAe,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Ni({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Ni({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:a.voltage,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=s.source_component_id}},mXt=gs.extend({voltage:Us.optional(),frequency:Oc.optional(),peakToPeakVoltage:Us.optional(),waveShape:v.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:Vn.optional(),dutyCycle:v.number().optional()}),F9e=class extends es{constructor(){super(...arguments);q(this,"terminal1",this.portMap.terminal1);q(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:mXt,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(e){if(!e.startsWith("Pcb"))for(let a of this.children)a.runRenderPhaseForChildren(e),a.runRenderPhase(e)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:a.voltage,frequency:a.frequency,peak_to_peak_voltage:a.peakToPeakVoltage,wave_shape:a.waveShape,phase:a.phase,duty_cycle:a.dutyCycle,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}doInitialSimulationRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.portMap.terminal1,l=this.portMap.terminal2;e.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:s.source_port_id,terminal2_source_port_id:l.source_port_id,voltage:a.voltage,frequency:a.frequency,peak_to_peak_voltage:a.peakToPeakVoltage,wave_shape:a.waveShape,phase:a.phase,duty_cycle:a.dutyCycle})}},E9e=class extends es{constructor(){super(...arguments);q(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:pAe,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${Ns(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 qc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new qc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new qc({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new qc({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:a.manufacturerPartNumber??a.mfn,supplier_part_numbers:a.supplierPartNumbers,resistance:a.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}},gXt=["leftedge","rightedge","topedge","bottomedge","center"],v9e=class extends Qn{get config(){return{componentName:"Constraint",zodProps:yAe}}constructor(r){if(super(r),("xdist"in r||"ydist"in r)&&!("edgeToEdge"in r)&&!("centerToCenter"in r))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in r&&r.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let r=[],e=this.getPrimitiveContainer();function a(s){let l=s.split(" ").pop(),d=gXt.includes(l)?l:void 0,x=d?s.replace(` ${d}`,""):s,f=e.selectOne(x,{pcbPrimitive:!0});f&&r.push({selector:s,component:f,componentSelector:x,edge:d})}for(let s of["left","right","top","bottom"])s in this._parsedProps&&a(this._parsedProps[s]);if("for"in this._parsedProps)for(let s of this._parsedProps.for)a(s);return{componentsWithSelectors:r}}},C9e=class extends Qn{constructor(){super(...arguments);q(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:OAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,a=this.getSubcircuit(),{_parsedProps:s}=this,l=s.layer??"top";if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenPath. Must be "top" or "bottom".`);let d=this._computePcbGlobalTransformBeforeLayout(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,f=e.pcb_fabrication_note_path.insert({pcb_component_id:x,layer:l,color:s.color,route:s.route.map(m=>{let D=as(d,{x:m.x,y:m.y});return{...m,x:D.x,y:D.y}}),stroke_width:s.strokeWidth??.1,subcircuit_id:a?.subcircuit_id??void 0});this.fabrication_note_path_id=f.pcb_fabrication_note_path_id}},_9e=class extends Qn{get config(){return{componentName:"FabricationNoteText",zodProps:MAe}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:r}=this.root,{_parsedProps:e}=this,a=this.getPrimitiveContainer(),s=this.getSubcircuit();r.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:e.pcbX??0,y:e.pcbY??0},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:e.text??"",pcb_component_id:a.pcb_component_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},A9e=class extends Wg{constructor(r){super({...r,subcircuit:!0})}},R9e=class extends Wg{constructor(r){super({...r,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:r}=this.root,e=this._parsedProps;if(!this.pcb_group_id)return;let a=r.pcb_group.get(this.pcb_group_id),s=e.paddingLeft??e.padding??0,l=e.paddingRight??e.padding??0,d=e.paddingTop??e.padding??0,x=e.paddingBottom??e.padding??0;r.pcb_group.update(this.pcb_group_id,{width:a.width+s+l,height:a.height+d+x,center:{x:a.center.x+(l-s)/2,y:a.center.y+(d-x)/2}})}},S9e=class extends Qn{constructor(){super(...arguments);q(this,"pcb_breakout_point_id",null);q(this,"matchedPort",null);q(this,"matchedNet",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:zAe}}_matchConnection(){let{connection:e}=this._parsedProps,a=this.getSubcircuit();a&&(this.matchedPort=a.selectOne(e,{type:"port"}),this.matchedPort||(this.matchedNet=a.selectOne(e,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${e}"`))}_getSourceTraceIdForPort(e){let{db:a}=this.root;return a.source_trace.list().find(l=>l.connected_source_port_ids.includes(e.source_port_id))?.source_trace_id}_getSourceNetIdForPort(e){let{db:a}=this.root;return a.source_trace.list().find(l=>l.connected_source_port_ids.includes(e.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;this._matchConnection();let{pcbX:a=0,pcbY:s=0}=this._parsedProps,l=this.parent?.getGroup(),d=this.getSubcircuit();if(!l||!l.pcb_group_id)return;let x=e.pcb_breakout_point.insert({pcb_group_id:l.pcb_group_id,subcircuit_id:d?.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:a,y:s});this.pcb_breakout_point_id=x.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:e=0,pcbY:a=0}=this._parsedProps;return{center:{x:e,y:a},bounds:{left:e,top:a,right:e,bottom:a},width:0,height:0}}_setPositionFromLayout(e){let{db:a}=this.root;this.pcb_breakout_point_id&&a.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:e.x,y:e.y})}getPcbSize(){return{width:0,height:0}}},B9e=class extends Qn{constructor(){super(...arguments);q(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:RAe}}_getAnchorSide(){let{_parsedProps:e}=this;if(e.anchorSide)return e.anchorSide;if(!this._resolveConnectsTo())return"right";let s=this._getGlobalSchematicPositionBeforeLayout(),l=this._getConnectedPorts();if(l.length===0)return"right";let d=l[0]._getGlobalSchematicPositionBeforeLayout(),x=d.x-s.x,f=d.y-s.y;if(Math.abs(x)>Math.abs(f)){if(x>0)return"right";if(x<0)return"left"}else{if(f>0)return"top";if(f<0)return"bottom"}return"right"}_getConnectedPorts(){let e=this._resolveConnectsTo();if(!e)return[];let a=[];for(let s of e){let l=this.getSubcircuit().selectOne(s);l&&a.push(l)}return a}computeSchematicPropsTransform(){let{_parsedProps:e}=this;if(e.schX===void 0&&e.schY===void 0){let a=this._getConnectedPorts();if(a.length>0){let s=a[0]._getGlobalSchematicPositionBeforeLayout(),l=as(this.parent?.computeSchematicGlobalTransform?.()??Si(),{x:0,y:0});return Ma(s.x-l.x,s.y-l.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalSchematicPositionBeforeLayout(),l=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),d=a.anchorSide??"right",x=ax({anchor_position:s,anchor_side:d,text:a.net}),f=e.schematic_net_label.insert({text:a.net,source_net_id:l.source_net_id,anchor_position:s,center:x,anchor_side:this._getAnchorSide()});this.source_net_label_id=f.source_net_id}_resolveConnectsTo(){let{_parsedProps:e}=this,a=e.connectsTo??e.connection;if(Array.isArray(a))return a;if(typeof a=="string")return[a]}_getNetName(){let{_parsedProps:e}=this;return e.net}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;e.net&&uK(this,[`net.${e.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let e=this._resolveConnectsTo();if(e)for(let a of e)this.add(new qc({from:a,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:e}=this.root,a=this._resolveConnectsTo();if(!a||a.length===0)return;let s=this._getGlobalSchematicPositionBeforeLayout(),l=this._getAnchorSide(),x={left:"x-",right:"x+",top:"y+",bottom:"y-"}[l],f=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let m of a){let D=this.getSubcircuit().selectOne(m,{type:"port"});if(!D||!D.schematic_port_id)continue;let b=!1;if(f?.source_net_id){let O=e.source_trace.list().find(z=>z.connected_source_net_ids?.includes(f.source_net_id)&&z.connected_source_port_ids?.includes(D.source_port_id??""));if(O&&(b=e.schematic_trace.list().some(z=>z.source_trace_id===O.source_trace_id)),b)continue}let E=D._getGlobalSchematicPositionAfterLayout(),A=eK(D.facingDirection??"right")??"x+",B=dg({x:E.x,y:E.y,facingDirection:A},{x:s.x,y:s.y,facingDirection:x});if(!Array.isArray(B)||B.length<2)continue;let w=[];for(let O=0;O<B.length-1;O++)w.push({from:{x:B[O].x,y:B[O].y},to:{x:B[O+1].x,y:B[O+1].y}});let P,j;if(f?.source_net_id&&D.source_port_id){let O=e.source_trace.list().find(z=>z.connected_source_net_ids?.includes(f.source_net_id)&&z.connected_source_port_ids?.includes(D.source_port_id));P=O?.source_trace_id,j=O?.subcircuit_connectivity_map_key||e.source_net.get(f.source_net_id)?.subcircuit_connectivity_map_key}e.schematic_trace.insert({source_trace_id:P,edges:w,junctions:[],subcircuit_connectivity_map_key:j}),e.schematic_port.update(D.schematic_port_id,{is_connected:!0})}}},w9e=class extends Qn{constructor(){super(...arguments);q(this,"pcb_silkscreen_circle_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:r4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenCircle. Must be "top" or "bottom".`);let d=this._computePcbGlobalTransformBeforeLayout(),x=this.getSubcircuit(),f=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,m=e.pcb_silkscreen_circle.insert({pcb_component_id:f,layer:l,center:{x:a.pcbX??0,y:a.pcbY??0},radius:a.radius,subcircuit_id:x?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:a.strokeWidth??.1});this.pcb_silkscreen_circle_id=m.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:e}=this,a=e.radius*2;return{width:a,height:a}}},T9e=class extends Qn{constructor(){super(...arguments);q(this,"pcb_silkscreen_rect_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:t4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenRect. Must be "top" or "bottom".`);let d=this.getSubcircuit(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,f=e.pcb_silkscreen_rect.insert({pcb_component_id:x,layer:l,center:{x:a.pcbX??0,y:a.pcbY??0},width:a.width,height:a.height,subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:a.strokeWidth??.1});this.pcb_silkscreen_rect_id=f.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},P9e=class extends Qn{constructor(){super(...arguments);q(this,"pcb_silkscreen_line_id",null);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:e4e}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),l=s(a.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for SilkscreenLine. Must be "top" or "bottom".`);let d=this.getSubcircuit(),x=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,f=e.pcb_silkscreen_line.insert({pcb_component_id:x,layer:l,x1:a.x1,y1:a.y1,x2:a.x2,y2:a.y2,stroke_width:a.strokeWidth??.1,subcircuit_id:d?.subcircuit_id??void 0,pcb_group_id:d?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=f.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:e}=this,a=Math.abs(e.x2-e.x1),s=Math.abs(e.y2-e.y1);return{width:a,height:s}}},I9e=class extends Qn{constructor(e){super(e);q(this,"pcb_via_id",null);q(this,"matchedPort",null);q(this,"isPcbPrimitive",!0);q(this,"source_manually_placed_via_id",null);let a=this._getLayers();this._parsedProps.layers=a,this.initPorts()}get config(){return{componentName:"Via",zodProps:LAe}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:e}=this;return{width:e.outerDiameter,height:e.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:e}=this.root,a=e.pcb_via.get(this.pcb_via_id),s=this.getPcbSize();return{center:{x:a.x,y:a.y},bounds:{left:a.x-s.width/2,top:a.y-s.height/2,right:a.x+s.width/2,bottom:a.y+s.height/2},width:s.width,height:s.height}}_setPositionFromLayout(e){let{db:a}=this.root;a.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}_getLayers(){let{fromLayer:e="top",toLayer:a="bottom"}=this._parsedProps;return e===a?[e]:[e,a]}initPorts(){let e=this._parsedProps.layers;for(let s of e){let l=new Ni({name:s,layer:s});l.registerMatch(this),this.add(l)}let a=new Ni({name:"pin1"});a.registerMatch(this),this.add(a)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalPcbPositionBeforeLayout(),l=this.getSubcircuit(),d=e.pcb_component.insert({center:s,width:a.outerDiameter,height:a.outerDiameter,layer:a.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:l?.subcircuit_id??void 0});this.pcb_component_id=d.pcb_component_id}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=this.getGroup(),l=this.getSubcircuit(),d=e.source_manually_placed_via.insert({source_group_id:s?.source_group_id,source_net_id:a.net??"",subcircuit_id:l?.subcircuit_id??void 0});this.source_component_id=d.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalPcbPositionBeforeLayout(),l=this.getSubcircuit(),d=e.pcb_via.insert({x:s.x,y:s.y,hole_diameter:a.holeDiameter,outer_diameter:a.outerDiameter,layers:["bottom","top"],from_layer:a.fromLayer||"bottom",to_layer:a.toLayer||"top",subcircuit_id:l?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_via_id=d.pcb_via_id}},j9e=class extends Qn{constructor(){super(...arguments);q(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:UAe}}getPcbSize(){return{width:0,height:0}}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:e}=this.root,{_parsedProps:a}=this,s=this.getSubcircuit().selectOne(a.connectsTo);if(!s||!s.source_net_id){this.renderError(`Net "${a.connectsTo}" not found for copper pour`);return}let l=e.pcb_board.list()[0];if(!l){this.renderError("No board found for copper pour");return}let d;l.outline&&l.outline.length>0?d=new se.Polygon(l.outline.map(B=>se.point(B.x,B.y))):d=new se.Polygon(new se.Box(l.center.x-l.width/2,l.center.y-l.height/2,l.center.x+l.width/2,l.center.y+l.height/2).toPoints());let x=eu(e.toArray()),f=pK(e.toArray(),x).filter(B=>B.layers.includes(a.layer));for(let B of e.pcb_trace.list())if(B.route)for(let w=0;w<B.route.length-1;w++){let P=B.route[w],j=B.route[w+1];if(P.route_type!=="wire"||j.route_type!=="wire"||P.layer!==a.layer)continue;let O=P.width;if(O===0)continue;let z=Math.hypot(P.x-j.x,P.y-j.y);if(z===0)continue;let ee=(P.x+j.x)/2,W=(P.y+j.y)/2,re=Math.atan2(j.y-P.y,j.x-P.x)*180/Math.PI,K=t9e({center:{x:ee,y:W},width:z,height:O,rotation:re});for(let U of K)f.push({type:"rect",layers:[P.layer],center:U.center,width:U.width,height:U.height,connectedTo:B.source_trace_id?[B.source_trace_id]:[],obstacle_type:"trace"})}let m=[],D=[],b=a.traceMargin??.2,E=a.padMargin??.2;for(let B of f){if(B.connectedTo.some(O=>x.areIdsConnected(O,s.source_net_id)))continue;if(B.type==="oval"&&B.width===B.height){let O=B.width/2+E;D.push({center:B.center,radius:O});continue}if(B.type==="rect"&&B.width===B.height&&B.connectedTo.length===0){let O=B.width/2;D.push({center:B.center,radius:O});continue}let P=b,j=new se.Box(B.center.x-B.width/2-P,B.center.y-B.height/2-P,B.center.x+B.width/2+P,B.center.y+B.height/2+P);m.push(new se.Polygon(j.toPoints()))}let A=d;if(m.length>0){let B=m.reduce((w,P)=>se.BooleanOperations.unify(w,P));B&&!B.isEmpty()&&(A=se.BooleanOperations.subtract(d,B))}Array.isArray(A)||(A=[A]);for(let B of A){let w=B.splitToIslands();for(let P of w){if(P.isEmpty())continue;let j=[...P.faces],O=j.find(L=>L.orientation()===se.ORIENTATION.CCW),z=j.filter(L=>L.orientation()===se.ORIENTATION.CW);if(!O)continue;if(!e.pcb_copper_pour){this.renderError("db.pcb_copper_pour not found. The database schema may be outdated.");return}let ee=L=>L.edges.map(K=>{let U={x:K.start.x,y:K.start.y};if(K.isArc){let J=Math.tan(K.shape.sweep/4);Math.abs(J)>1e-9&&(U.bulge=J)}return U});O.reverse();let W=ee(O),re=z.map(L=>(L.reverse(),{vertices:ee(L)}));for(let L of D){let K=se.point(L.center.x,L.center.y);P.contains(K)&&re.push({vertices:[{x:L.center.x,y:L.center.y-L.radius,bulge:1},{x:L.center.x,y:L.center.y+L.radius,bulge:1}]})}e.pcb_copper_pour.insert({shape:"brep",layer:a.layer,brep_shape:{outer_ring:{vertices:W},inner_rings:re},source_net_id:s.source_net_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id??void 0})}}})}},k9e=class extends es{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:_Ae,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=a.source_component_id}},N9e=class extends es{_getPcbRotationBeforeLayout(){let r=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+r}get config(){return{componentName:"PinHeader",zodProps:AAe,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let r=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),e=this._parsedProps.holeDiameter,a=this._parsedProps.platedDiameter,s=this._parsedProps.pitch,l=this._parsedProps.showSilkscreenPinLabels;if(r>0){let d;if(s)!e&&!a?d=`pinrow${r}_p${s}`:d=`pinrow${r}_p${s}_id${e}_od${a}`;else if(!e&&!a)d=`pinrow${r}`;else return null;return l!==!0&&(d+="_nopinlabels"),d}return null}initPorts(){let r=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let e=1;e<=r;e++){let a=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[e-1]:this._parsedProps.pinLabels?.[`pin${e}`];if(a){let s=Array.isArray(a)?a[0]:a,l=Array.isArray(a)?a.slice(1):[];this.add(new Ni({pinNumber:e,name:s,aliases:[`pin${e}`,...l]}))}else this.add(new Ni({pinNumber:e,name:`pin${e}`}))}}_getSchematicPortArrangement(){let r=this._parsedProps.pinCount??1,e=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",a=this._parsedProps.schPinArrangement;return e==="left"?{leftSide:{direction:a?.leftSide?.direction??"top-to-bottom",pins:a?.leftSide?.pins??Array.from({length:r},(s,l)=>`pin${l+1}`)}}:{rightSide:{direction:a?.rightSide?.direction??"top-to-bottom",pins:a?.rightSide?.pins??Array.from({length:r},(s,l)=>`pin${l+1}`)}}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:e.supplierPartNumbers,pin_count:e.pinCount,gender:e.gender,are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}};function DXt(r){switch(r){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var M9e=class extends es{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??DXt(this.props.pinVariant),zodProps:mAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=e.pinVariant||"no_ground",s=r.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:a,are_pins_interchangeable:a==="no_ground"||a==="ground_pin"});this.source_component_id=s.source_component_id}_getSchematicSymbolDisplayValue(){let r=`${Ns(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${r} / ${Ns(this._parsedProps.loadCapacitance)}F`:r}},O9e=class extends es{constructor(){super(...arguments);q(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:TAe,sourceFtype:dd.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${Ns(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({name:this.name,ftype:dd.simple_inductor,inductance:a.inductance,supplier_part_numbers:a.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=s.source_component_id}};function yXt(r){switch(r){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var L9e=class extends es{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??yXt(this.props.pinVariant),zodProps:fAe,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${Ns(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=e.pinVariant||"two_pin",s=r.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:e.maxResistance,pin_variant:a,are_pins_interchangeable:a==="two_pin"});this.source_component_id=s.source_component_id}},$9e=class extends es{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:SAe,sourceFtype:dd.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let r=ks[this._getSchematicSymbolNameOrThrow()],e=r.ports.find(D=>D.labels.includes("1")),a=r.ports.find(D=>D.labels.includes("2")),s=this.selectAll("port"),l=s.find(D=>D.props.pinNumber===1),d=s.find(D=>D.props.pinNumber===2),x=s.find(D=>D.props.pinNumber===3),f=s.find(D=>D.props.pinNumber===4),{internallyConnectedPins:m}=this._parsedProps;l.schematicSymbolPortDef=e,(!m||m.length===0)&&(d.schematicSymbolPortDef=a);for(let[D,b]of[[2,d],[3,x],[4,f]]){let E=m?.find(([B,w])=>B===`pin${D}`||w===`pin${D}`);if(!E){b.schematicSymbolPortDef=a;break}(E?.[0]===`pin${D}`?E[1]:E?.[0])!=="pin1"&&(b.schematicSymbolPortDef=a)}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({name:this.name,ftype:dd.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=a.source_component_id}},z9e=class extends es{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:hAe,sourceFtype:"simple_crystal"}}initPorts(){let r=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:r})}_getSchematicSymbolDisplayValue(){let r=`${Ns(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${r} / ${Ns(this._parsedProps.loadCapacitance)}F`:r}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:e.frequency,load_capacitance:e.loadCapacitance,pin_variant:e.pinVariant||"two_pin",are_pins_interchangeable:(e.pinVariant||"two_pin")==="two_pin"});this.source_component_id=a.source_component_id}},q9e=class extends es{constructor(){super(...arguments);q(this,"emitter",this.portMap.pin1);q(this,"collector",this.portMap.pin2);q(this,"base",this.portMap.pin3)}get config(){let e=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??e,zodProps:BAe,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let e={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:e})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:a}=this,s=e.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:a.type});this.source_component_id=s.source_component_id}},U9e=class extends es{get config(){let r=this.props.mosfetMode==="depletion"?"d":"e",a=`${this.props.channelType}_channel_${r}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??a,zodProps:wAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=a.source_component_id}},V9e=class extends es{_getSwitchType(){let{spst:r,spdt:e,dpst:a,dpdt:s,type:l}=this._parsedProps??{};return s?"dpdt":r?"spst":e?"spdt":a?"dpst":l??"spst"}get config(){let r=this._getSwitchType(),{isNormallyClosed:e}=this._parsedProps??{},s={spst:e?"spst_normally_closed_switch":"spst_switch",spdt:e?"spdt_normally_closed_switch":"spdt_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"}[r]??"spst_switch";return{componentName:"Switch",schematicSymbolName:this.props.symbolName??s,zodProps:NAe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,a=r.source_component.insert({ftype:"simple_switch",name:this.name,switch_type:e.type,is_normally_closed:e.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=a.source_component_id}},JW={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},G9e=class extends es{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:$Ae,sourceFtype:dd.simple_test_point}}_getPropsWithDefaults(){let{padShape:r,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:d}=this._parsedProps;return!a&&e&&(a="through_hole"),a??(a="through_hole"),r??(r="circle"),a==="pad"?r==="circle"?s??(s=JW.SMT_CIRCLE_DIAMETER):r==="rect"&&(l??(l=JW.SMT_RECT_SIZE),d??(d=l)):a==="through_hole"&&(e??(e=JW.HOLE_DIAMETER)),{padShape:r,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:d}}_getImpliedFootprintString(){let{padShape:r,holeDiameter:e,footprintVariant:a,padDiameter:s,width:l,height:d}=this._getPropsWithDefaults();if(a==="through_hole")return`platedhole_d${e}`;if(a==="pad"){if(r==="circle")return`smtpad_circle_d${s}`;if(r==="rect")return`smtpad_rect_w${l}_h${d}`}throw new Error(`Footprint variant "${a}" with pad shape "${r}" not implemented`)}doInitialSourceRender(){let{db:r}=this.root,{_parsedProps:e}=this,{padShape:a,holeDiameter:s,footprintVariant:l,padDiameter:d,width:x,height:f}=this._getPropsWithDefaults(),m=r.source_component.insert({ftype:dd.simple_test_point,name:this.name,supplier_part_numbers:e.supplierPartNumbers,footprint_variant:l,pad_shape:a,pad_diameter:d,hole_diameter:s,width:x,height:f,are_pins_interchangeable:!0});this.source_component_id=m.source_component_id}},X9e=class extends Qn{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:HAe}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this._getGlobalSchematicPositionBeforeLayout();e.schematic_text.insert({anchor:a.anchor??"center",text:a.text,font_size:a.fontSize,color:a.color||"#000000",position:{x:s.x,y:s.y},rotation:a.schRotation??0})}};function bXt({anchor:r,x:e,y:a,width:s,height:l,isInside:d}){switch(r){case"top_left":return{x:e,y:a+l,textAnchor:d?"top_left":"bottom_left"};case"top_center":return{x:e+s/2,y:a+l,textAnchor:d?"top_center":"bottom_center"};case"top_right":return{x:e+s,y:a+l,textAnchor:d?"top_right":"bottom_right"};case"center_left":return{x:e,y:a+l/2,textAnchor:d?"center_left":"center_right"};case"center":return{x:e+s/2,y:a+l/2,textAnchor:"center"};case"center_right":return{x:e+s,y:a+l/2,textAnchor:d?"center_right":"center_left"};case"bottom_left":return{x:e,y:a,textAnchor:d?"bottom_left":"top_left"};case"bottom_center":return{x:e+s/2,y:a,textAnchor:d?"bottom_center":"top_center"};case"bottom_right":return{x:e+s,y:a,textAnchor:d?"bottom_right":"top_right"};default:return{x:e+s/2,y:a+l,textAnchor:"center"}}}var Y9e=class extends Qn{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:YAe,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=.6,l=typeof a.padding=="number"?a.padding:0,d=typeof a.paddingTop=="number"?a.paddingTop:l,x=typeof a.paddingBottom=="number"?a.paddingBottom:l,f=typeof a.paddingLeft=="number"?a.paddingLeft:l,m=typeof a.paddingRight=="number"?a.paddingRight:l,D=a.overlay&&a.overlay.length>0,b=typeof a.width=="number"&&typeof a.height=="number",E,A,B,w,P,j;if(D){let z=a.overlay.map(it=>({selector:it,port:this.getSubcircuit().selectOne(it,{type:"port"})})).filter(({port:it})=>it!=null).map(({port:it})=>({position:it._getGlobalSchematicPositionAfterLayout()}));if(z.length===0)return;let ee=z.map(it=>it.position.x),W=z.map(it=>it.position.y),re=Math.min(...ee),L=Math.max(...ee),K=Math.min(...W),U=Math.max(...W),J=L-re,Q=U-K,de=J===0?s:0,oe=Q===0?s:0,Te=f+de/2,Me=m+de/2,Ge=d+oe/2,et=x+oe/2,dt=re-Te,$t=L+Me,bt=K-et,ut=U+Ge;E=$t-dt,A=ut-bt,B=dt+(a.schX??0),w=bt+(a.schY??0),P=B+E/2,j=w+A/2}else if(b){E=a.width,A=a.height;let O=this._getGlobalSchematicPositionBeforeLayout();P=O.x,j=O.y,B=P-E/2,w=j-A/2}else return;if(e.schematic_box.insert({height:A,width:E,x:B,y:w,is_dashed:a.strokeStyle==="dashed"}),a.title){let O=a.titleInside,z=.1,ee=a.titleAlignment,W=bXt({anchor:ee,x:B,y:w,width:E,height:A,isInside:O}),re,L,K=W.textAnchor;O?(re=ee.includes("top")?-z:ee.includes("bottom")?z:0,L=ee.includes("left")?z:ee.includes("right")?-z:0):(re=ee.includes("top")?z:ee.includes("bottom")?-z:0,L=ee.includes("center_left")?-z:ee.includes("center_right")?z:0);let U=W.x+L,J=W.y+re;e.schematic_text.insert({anchor:K,text:a.title,font_size:a.titleFontSize??.18,color:a.titleColor??"#000000",position:{x:U,y:J},rotation:0})}}},H9e=class extends Qn{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0);q(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:WAe}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:a}=this,s=this.children.filter(A=>A.componentName==="SchematicRow");if(s.length===0)return;let l=[],d=0;for(let A of s){let B=A.children.filter(w=>w.componentName==="SchematicCell");d=Math.max(d,B.length)}for(let A=0;A<s.length;A++)l[A]=[];for(let A=0;A<s.length;A++){let w=s[A].children.filter(j=>j.componentName==="SchematicCell"),P=0;for(let j=0;j<w.length;j++){for(;l[A][P];)P++;let O=w[j],z=O._parsedProps.colSpan??1,ee=O._parsedProps.rowSpan??1;for(let W=0;W<ee;W++)for(let re=0;re<z;re++)l[A+W]||(l[A+W]=[]),l[A+W][P+re]=O;P+=z}}d=Math.max(0,...l.map(A=>A.length));let x=s.map((A,B)=>A._parsedProps.height??1),f=Array.from({length:d},(A,B)=>{let w=0;for(let P=0;P<s.length;P++){let j=l[P]?.[B];if(j){let O=j._parsedProps.text??j._parsedProps.children,z=j._parsedProps.width??(O?.length??2)*.5;z>w&&(w=z)}}return w||10}),m=this._getGlobalSchematicPositionBeforeLayout(),D=e.schematic_table.insert({anchor_position:m,column_widths:f,row_heights:x,cell_padding:a.cellPadding,border_width:a.borderWidth,anchor:a.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=D.schematic_table_id;let b=new Set,E=0;for(let A=0;A<s.length;A++){let B=0;for(let w=0;w<d;w++){let P=l[A]?.[w];if(P&&!b.has(P)){b.add(P);let j=P._parsedProps,O=j.rowSpan??1,z=j.colSpan??1,ee=0;for(let re=0;re<z;re++)ee+=f[w+re];let W=0;for(let re=0;re<O;re++)W+=x[A+re];e.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:A,end_row_index:A+O-1,start_column_index:w,end_column_index:w+z-1,text:j.text??j.children,center:{x:m.x+B+ee/2,y:m.y-E-W/2},width:ee,height:W,horizontal_align:j.horizontalAlign,vertical_align:j.verticalAlign,font_size:j.fontSize??a.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}f[w]&&(B+=f[w])}E+=x[A]}}},W9e=class extends Qn{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:KAe}}},K9e=class extends Qn{constructor(){super(...arguments);q(this,"isSchematicPrimitive",!0);q(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:JAe}}},FXt={name:"@tscircuit/core",type:"module",version:"0.0.735",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"'},devDependencies:{"@biomejs/biome":"^1.8.3","@tscircuit/capacity-autorouter":"^0.0.107","@tscircuit/checks":"^0.0.75","@tscircuit/circuit-json-util":"^0.0.67","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.21","@tscircuit/miniflex":"^0.0.4","@tscircuit/props":"0.0.334","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^0.0.37","@tscircuit/simple-3d-svg":"^0.0.41","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.260","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-simple-3d":"^0.0.8","circuit-to-svg":"^0.0.194",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.201","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.37","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},Kg=class{constructor({platform:r,projectUrl:e}={}){q(this,"firstChild",null);q(this,"children");q(this,"db");q(this,"root",null);q(this,"isRoot",!0);q(this,"schematicDisabled",!1);q(this,"pcbDisabled",!1);q(this,"pcbRoutingDisabled",!1);q(this,"_featureMspSchematicTraceRouting",!0);q(this,"name");q(this,"platform");q(this,"projectUrl");q(this,"_hasRenderedAtleastOnce",!1);q(this,"_eventListeners",{});this.children=[],this.db=ua([]),this.root=this,this.platform=r,this.projectUrl=e,this.pcbDisabled=r?.pcbDisabled??!1}add(r){let e;(0,J9e.isValidElement)(r)?e=YBe(r):e=r,this.children.push(e)}_getBoard(){return this.children.find(r=>r.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 r=new Wg({subcircuit:!0});r.parent=this,r.addAll(this.children),this.children=[r],this.firstChild=r}render(){this.firstChild||this._guessRootComponent();let{firstChild:r,db:e}=this;if(!r)throw new Error("RootCircuit has no root component");r.parent=this,r.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(e=>setTimeout(e,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(r=>r._hasIncompleteAsyncEffects()?!0:r.children.some(e=>e._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(r){let e=await Promise.resolve().then(()=>(DBe(),gBe)).catch(a=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
|
|
1039
1039
|
|
|
1040
1040
|
"${a.message}"`)});if(r.view==="pcb")return e.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(r.view==="schematic")return e.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${r.view}`)}getCoreVersion(){let[r,e,a]=FXt.version.split(".").map(Number);return`${r}.${e}.${a+1}`}async preview(r){let e=typeof r=="object"?r:{previewName:r};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return Si()}_computePcbGlobalTransformBeforeLayout(){return Si()}selectAll(r){return this._guessRootComponent(),this.firstChild?.selectAll(r)??[]}selectOne(r,e){return this._guessRootComponent(),this.firstChild?.selectOne(r,e)??null}emit(r,...e){if(this._eventListeners[r])for(let a of this._eventListeners[r])a(...e)}on(r,e){this._eventListeners[r]||(this._eventListeners[r]=[]),this._eventListeners[r].push(e)}removeListener(r,e){this._eventListeners[r]&&(this._eventListeners[r]=this._eventListeners[r].filter(a=>a!==e))}enableDebug(r){typeof r=="string"?aK.default.enable(r):(r===null||r===!1)&&aK.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},EXt=Kg,vXt=Kg,CXt=r=>{let[e,a]=Xg.default.useState(!0),[s,l]=Xg.default.useState(null),[d,x]=Xg.default.useState(),[f,m]=Xg.default.useState();return Xg.default.useEffect(()=>{a(!0),l(null),r&&setTimeout(()=>{try{let D=new Kg;D.add(r),x(D),m(D.toJson())}catch(D){l(D)}a(!1)},1)},[r]),{isLoading:e,error:s,circuit:d,circuitJson:f}},Jg=(r,e)=>(a,s)=>{let l=[];Array.isArray(e)?l.push(...e.flat()):typeof e=="object"&&l.push(...Object.values(e).flat(),...Object.keys(e));let d=x=>{if(x?.name&&x.name!==a)throw new Error(`Component name mismatch. Hook name: ${a}, Component prop name: ${x.name}`);let f={...s,...x,name:a},m=[];for(let D of l)if(f[D]){let b=`.${a} > .${D}`,E=f[D];m.push({from:b,to:E}),delete f[D]}return(0,w1.jsxs)(w1.Fragment,{children:[(0,w1.jsx)(r,{...f}),m.map((D,b)=>(0,w1.jsx)("trace",{...D},b))]})};for(let x of l)d[x]=`.${a} > .${x}`;return d},_Xt=Jg(r=>(0,Z9e.jsx)("capacitor",{...r}),DAe),AXt=r=>Jg(e=>(0,Q9e.jsx)("chip",{pinLabels:r,...e}),r),RXt=Jg(r=>(0,e7e.jsx)("diode",{...r}),IAe),SXt=Jg(r=>(0,t7e.jsx)("led",{...r}),kAe),BXt=Jg(r=>(0,r7e.jsx)("resistor",{...r}),xAe),wXt=new Proxy(r=>new Proxy({},{get:(e,a)=>`.${r} > .${a}`}),{get:(r,e)=>{let a=(...s)=>{let l=s[0];return new Proxy({},{get:(d,x)=>`.${e} > .${x}`})};return new Proxy(a,{get:(s,l)=>e==="net"?`net.${l}`:e==="subcircuit"?new Proxy({},{get:(d,x)=>new Proxy({},{get:(f,m)=>`subcircuit.${l} > .${x} > .${m}`})}):`.${e} > .${l}`,apply:(s,l,d)=>e==="net"?new Proxy({},{get:(x,f)=>`net.${f}`}):new Proxy({},{get:(x,f)=>{let m=`.${e} > .${f}`;return["U","J","CN"].some(b=>e.startsWith(b))?m:new Proxy(new String(m),{get:(b,E)=>typeof E=="symbol"||E==="toString"?()=>m:`.${e} > .${f} > .${E}`})}})})}});XBe(qBe);XBe({Bug:QS});var i7e=Or(kc(),1);var hK=new Map,Co=async(r,e)=>{let a=new URLSearchParams({...e,json:"true"}).toString();if(hK.has(a))return hK.get(a);let l=await(await fetch(`https://jlcsearch.tscircuit.com/${r}/list?${a}`)).json();return hK.set(a,l),l},a7e={findPart:async({sourceComponent:r,footprinterString:e})=>{if(r.type==="source_component"&&r.ftype==="simple_resistor"){let{resistors:a}=await Co("resistors",{resistance:r.display_resistance??r.resistance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_capacitor"){e?.includes("cap")&&(e=e.replace("cap",""));let{capacitors:a}=await Co("capacitors",{capacitance:r.display_capacitance??r.capacitance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_pin_header"){let a;e?.includes("_p")&&(a=Number(e.split("_p")[1]));let{headers:s}=await Co("headers",a?{pitch:a,num_pins:r.pin_count,gender:r.gender}:{num_pins:r.pin_count,gender:r.gender});return{jlcpcb:(s??[]).map(l=>`C${l.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_potentiometer"){let{potentiometers:a}=await Co("potentiometers",{resistance:r.max_resistance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_diode"){let{diodes:a}=await Co("diodes",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_chip"){let{chips:a}=await Co("chips",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_transistor"){let{transistors:a}=await Co("transistors",{package:e,transistor_type:r.transistor_type});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_power_source"){let{power_sources:a}=await Co("power_sources",{voltage:r.voltage,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_inductor"){let{inductors:a}=await Co("inductors",{inductance:r.inductance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_crystal"){let{crystals:a}=await Co("crystals",{frequency:r.frequency,load_capacitance:r.load_capacitance,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_mosfet"){let{mosfets:a}=await Co("mosfets",{package:e,mosfet_mode:r.mosfet_mode,channel_type:r.channel_type});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_resonator"){let{resonators:a}=await Co("resonators",{frequency:r.frequency,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_switch"){let{switches:a}=await Co("switches",{switch_type:r.type,package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_led"){let{leds:a}=await Co("leds",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(r.type==="source_component"&&r.ftype==="simple_fuse"){let{fuses:a}=await Co("fuses",{package:e});return{jlcpcb:(a??[]).map(s=>`C${s.lcsc}`).slice(0,3)}}return{}}};var TXt="https://kicad-mod-cache.tscircuit.com",s7e=()=>({partsEngine:a7e,footprintLibraryMap:{kicad:async r=>{let e=`${TXt}/${r}`,a=`${e}.circuit.json`,l=await(await fetch(a)).json(),d=Array.isArray(l)?l.filter(f=>f?.type==="pcb_silkscreen_text"?f?.text==="REF**":!0):l,x=`${e}.wrl`;return{footprintCircuitJson:d,cadModel:{wrlUrl:x,modelUnitToMmScale:2.54}}}}});var mK=Or(fs(),1),xyr=(0,mK.default)("tsci:eval:execution-context");function tB(r,e={}){globalThis.React=i7e;let a=e.platform||s7e(),s=e.projectConfig?{...a,...e.projectConfig}:a,l=new Kg({platform:s});return e.name&&(l.name=e.name),e.debugNamespace&&l.enableDebug(e.debugNamespace),{fsMap:{},entrypoint:"",preSuppliedImports:{"@tscircuit/core":eB,tscircuit:eB,"@tscircuit/math-utils":TY,react:i7e,debug:mK.default,"@tscircuit/props":{}},circuit:l,...r}}function WF(r){let e=r;return e=e.replace(/\\/g,"/"),e=e.trim(),e.startsWith("./")&&(e=e.slice(2)),e.startsWith("/")&&(e=e.slice(1)),e}function o7e(r){let e={};for(let[a,s]of Object.entries(r))e[WF(a)]=s;return e}function Uc(r){if(!r)return".";let a=r.replace(/\\/g,"/").replace(/\/+$/,"");return a.indexOf("/")===-1?".":a.substring(0,a.lastIndexOf("/"))||"/"}function gK(r,e){if(r.startsWith("../")){let a=Uc(e);return gK(r.slice(3),a)}return r.startsWith("./")?gK(r.slice(2),e):r.startsWith("/")?r.slice(1):`${e}/${r}`}var KF=(r,e,a)=>{let s=a?gK(r,a):r,l=new Set(Array.isArray(e)?e:Object.keys(e));if(l.has(s))return s;let d=new Map;for(let m of l)d.set(WF(m),m);let x=WF(s);if(d.has(x))return d.get(x);let f=["tsx","ts","json","js","jsx","obj","gltf","glb"];for(let m of f){let D=`${x}.${m}`;if(d.has(D))return d.get(D)}if(!r.startsWith("./")&&!r.startsWith("../")){let m=WF(r);if(d.has(m))return d.get(m);for(let D of f){let b=`${m}.${D}`;if(d.has(b))return d.get(b)}}return null},rB=(r,e)=>{let a=KF(r,e);if(!a)throw new Error(`File not found "${r}", available paths:
|
|
1041
1041
|
|