tscircuit 0.0.1840-libonly → 0.0.1841-libonly
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/browser.min.js +2 -2
- package/dist/webworker.min.js +4 -4
- package/package.json +3 -3
package/dist/webworker.min.js
CHANGED
|
@@ -334,7 +334,7 @@ ${face.svg()}`;return svgStr+=`" >
|
|
|
334
334
|
`).map(x4=>x4.match(/\(([^)]+)\)/)[1]).map(parseSinglePoint)}function parseArrayOfLineStrings(str){return str.split(`
|
|
335
335
|
`).map(x4=>x4.match(/\(([^)]+)\)/)[1]).map(parseLineString).reduce((acc,x4)=>[...acc,...x4],[])}function parseWKT(str){if(str.startsWith("POINT")){let pointStr=str.replace(/^POINT \(/,"").replace(/\)$/,"");return parseSinglePoint(pointStr)}else if(str.startsWith("MULTIPOINT")){let multiPointStr=str.replace(/^MULTIPOINT \(/,"").replace(/\)$/,"");return parseMultiPoint(multiPointStr)}else if(str.startsWith("LINESTRING")){let lineStr=str.replace(/^LINESTRING \(/,"").replace(/\)$/,"");return parseLineString(lineStr)}else if(str.startsWith("MULTILINESTRING")){let multilineStr=str.replace(/^MULTILINESTRING /,"");return parseMultiLineString(multilineStr)}else{if(str.startsWith("POLYGON")||str.startsWith("MULTIPOLYGON"))return parsePolygon(str);if(str.startsWith("GEOMETRYCOLLECTION")){let regex=/(?<type>POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON) \((?:[^\(\)]|\([^\)]*\))*\)/g,wktArray=str.match(regex);return wktArray[0].startsWith("GEOMETRYCOLLECTION")&&(wktArray[0]=wktArray[0].replace("GEOMETRYCOLLECTION (","")),wktArray.map(parseWKT).map(x4=>x4 instanceof Array?x4:[x4]).reduce((acc,x4)=>[...acc,...x4],[])}else{if(isArrayOfPoints(str))return parseArrayOfPoints(str);if(isArrayOfLines(str))return parseArrayOfLineStrings(str)}}return[]}function isArrayOfPoints(str){return str.split(`
|
|
336
336
|
`)?.every(str2=>str2.includes("POINT"))}function isArrayOfLines(str){return str.split(`
|
|
337
|
-
`)?.every(str2=>str2.includes("LINESTRING"))}function isWktString(str){return str.startsWith("POINT")||isArrayOfPoints(str)||str.startsWith("LINESTRING")||isArrayOfLines(str)||str.startsWith("MULTILINESTRING")||str.startsWith("POLYGON")||str.startsWith("MULTIPOINT")||str.startsWith("MULTIPOLYGON")||str.startsWith("GEOMETRYCOLLECTION")}Flatten.isWktString=isWktString;Flatten.parseWKT=parseWKT;Flatten.BooleanOperations=BooleanOperations;Flatten.Relations=Relations;init_dist();init_dist5();var package_default={name:"@tscircuit/capacity-autorouter",main:"./dist/index.js",version:"0.0.529",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","run-sample":"bun scripts/run-sample.ts","repomix:lib":"repomix --ignore 'testing/**,**/TwoRouteHighDensitySolver/**,**/RouteStitchingSolver/**,solvers/CapacitySegmentPointOptimizer/CapacitySegmentPointOptimizer.ts' lib","bug-report":"bun run scripts/download-bug-report.ts","bug-report-with-test":"bun run scripts/create-bug-report-test.ts"},devDependencies:{"@biomejs/biome":"^1.9.4","@radix-ui/react-icons":"^1.3.2","@radix-ui/react-menubar":"^1.1.14","@react-hook/resize-observer":"^2.0.2","@resvg/resvg-js":"^2.6.2","@tsci/seveibar.dataset-srj13":"git+https://github.com/tscircuit/dataset-srj13.git#56db70039aeb28a76540fe951b5a96be60f9e949","@tsci/tscircuit.dataset-srj16-bga-breakouts":"git+https://github.com/tscircuit/dataset-srj16-bga-breakouts.git","@tsci/tscircuit.dataset-srj12-bus-routing":"git+https://github.com/tscircuit/dataset-srj12-bus-routing.git#ba82f86a7d1288566b7144eb8661ad2549c5f328","@tscircuit/autorouting-dataset-01":"^1.0.32","@tscircuit/checks":"^0.0.126","@tscircuit/circuit-json-util":"^0.0.94","@tscircuit/core":"^0.0.337","@tscircuit/curvy-trace-solver":"^0.0.10","@tscircuit/dataset-srj05":"git+https://github.com/tscircuit/dataset-srj05.git#9a49c126a89c083dc4d2b72cd17184735f637762","@tscircuit/fixed-via-hypergraph-solver":"https://codeload.github.com/tscircuit/fixed-via-hypergraph-solver/tar.gz/bed37a6201b5dd07c9cc68b828917ecc20d6d049","@tscircuit/hypergraph":"^0.0.71","@tscircuit/jumper-topology-generator":"^0.0.4","@tscircuit/krt-wasm":"^0.1.0","@tscircuit/math-utils":"^0.0.36","@tscircuit/rectdiff":"git+https://github.com/tscircuit/rectdiff.git#4af388d","@tscircuit/solver-utils":"^0.0.16","@types/bun":"^1.2.23","@types/fast-json-stable-stringify":"^2.1.2","@types/object-hash":"^3.0.6","@types/rbush":"^4.0.0","@types/react":"^19.0.8","@types/react-dom":"^19.0.3","@vercel/node":"^5.1.7","@vitejs/plugin-react":"^4.3.4","bun-match-svg":"^0.0.14","circuit-json-to-connectivity-map":"^0.0.19","circuit-json":"^0.0.419","circuit-to-svg":"^0.0.220",clsx:"^2.1.1","dataset-srj11-45-degree":"git+https://github.com/tscircuit/dataset-srj11-45-degree.git#0add61e6a0e6b59f6defc36f257052f773e2d685",flatbush:"^4.4.0","graphics-debug":"0.0.94","high-density-dataset-z04":"git+https://github.com/tscircuit/high-density-dataset-z04.git#b9128ed52f5a50102b6526319be1d4ec33dca2c2",kleur:"^4.1.5","looks-same":"9","pcb-poly-hyper-graph":"https://codeload.github.com/tscircuit/pcb-poly-hyper-graph/tar.gz/80db1463c4a47506eeda15b2c14d59679de900f8",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","tiny-hypergraph":"git+https://github.com/tscircuit/tiny-hypergraph.git#78db8cb1dc78bfb3569ea6cb86bacc86d04c7338","tiny-hypergraph-poly":"git+https://github.com/tscircuit/tiny-hypergraph.git#7b93b4c",tsup:"^8.3.6",typescript:"^5.9.3","use-mouse-matrix-transform":"^1.3.0",vite:"^6.0.11","vite-tsconfig-paths":"^5.1.4","zdwiel-dataset":"git+https://github.com/dwiel/tscircuit-benchmark.git#be36518b5bf51755dae92c230061ab3cf4e3e063","high-density-repair01":"git+https://github.com/tscircuit/high-density-repair01.git#f4804e26d6da845cb985e4681ebd528b7c5f2ce8","high-density-repair02":"https://codeload.github.com/tscircuit/high-density-repair02/tar.gz/2afc0cbba3bf2f7eb6b9cd33615d21e9ad9352d4","high-density-repair03":"git+https://github.com/tscircuit/high-density-repair03.git#db73a5f"},dependencies:{"@tscircuit/high-density-a01":"^0.0.37","fast-json-stable-stringify":"^2.1.0","object-hash":"^3.0.0"}};init_dist();init_dist3();var import_react=__toESM(require_react(),1),import_react_reconciler=__toESM(require_react_reconciler(),1),import_constants=__toESM(require_constants(),1);init_zod();init_dist();init_dist();init_zod();init_dist();init_dist();init_zod();init_dist();var e2={a:1,b:0,c:0,d:1,e:0,f:0,m11:1,m12:0,m13:0,m14:0,m21:0,m22:1,m23:0,m24:0,m31:0,m32:0,m33:1,m34:0,m41:0,m42:0,m43:0,m44:1,is2D:!0,isIdentity:!0},t=e5=>(e5 instanceof Float64Array||e5 instanceof Float32Array||Array.isArray(e5)&&e5.every(e6=>typeof e6=="number"))&&[6,16].some(t52=>e5.length===t52),n=t52=>t52 instanceof DOMMatrix||t52 instanceof h||typeof t52=="object"&&Object.keys(e2).every(e5=>t52&&e5 in t52),r3=e5=>{let n4=new h,r5=Array.from(e5);if(!t(r5))throw TypeError(`CSSMatrix: "${r5.join(",")}" must be an array with 6/16 numbers.`);if(r5.length===16){let[e6,t52,i3,a3,o4,s3,c4,l4,u5,d4,f3,p4,m4,h6,g6,_4]=r5;n4.m11=e6,n4.a=e6,n4.m21=o4,n4.c=o4,n4.m31=u5,n4.m41=m4,n4.e=m4,n4.m12=t52,n4.b=t52,n4.m22=s3,n4.d=s3,n4.m32=d4,n4.m42=h6,n4.f=h6,n4.m13=i3,n4.m23=c4,n4.m33=f3,n4.m43=g6,n4.m14=a3,n4.m24=l4,n4.m34=p4,n4.m44=_4}else if(r5.length===6){let[e6,t52,i3,a3,o4,s3]=r5;n4.m11=e6,n4.a=e6,n4.m12=t52,n4.b=t52,n4.m21=i3,n4.c=i3,n4.m22=a3,n4.d=a3,n4.m41=o4,n4.e=o4,n4.m42=s3,n4.f=s3}return n4},i=e5=>{if(n(e5))return r3([e5.m11,e5.m12,e5.m13,e5.m14,e5.m21,e5.m22,e5.m23,e5.m24,e5.m31,e5.m32,e5.m33,e5.m34,e5.m41,e5.m42,e5.m43,e5.m44]);throw TypeError(`CSSMatrix: "${JSON.stringify(e5)}" is not a DOMMatrix / CSSMatrix / JSON compatible object.`)},a=e5=>{if(typeof e5!="string")throw TypeError(`CSSMatrix: "${JSON.stringify(e5)}" is not a string.`);let t52=String(e5).replace(/\s/g,""),n4=new h,i3=`CSSMatrix: invalid transform string "${e5}"`;return t52.split(")").filter(e6=>e6).forEach(e6=>{let[t53,a3]=e6.split("(");if(!a3)throw TypeError(i3);let o4=a3.split(",").map(e7=>e7.includes("rad")?180/Math.PI*parseFloat(e7):parseFloat(e7)),[s3,c4,l4,u5]=o4,d4=[s3,c4,l4],f3=[s3,c4,l4,u5];if(t53==="perspective"&&s3&&[c4,l4].every(e7=>e7===void 0))n4.m34=-1/s3;else if(t53.includes("matrix")&&[6,16].includes(o4.length)&&o4.every(e7=>!Number.isNaN(+e7))){let e7=o4.map(e8=>Math.abs(e8)<1e-6?0:e8);n4.multiplySelf(r3(e7))}else if(t53==="translate3d"&&d4.every(e7=>!Number.isNaN(+e7)))n4.translateSelf(s3,c4,l4);else if(t53==="translate"&&s3&&l4===void 0)n4.translateSelf(s3,c4||0,0);else if(t53==="rotate3d"&&f3.every(e7=>!Number.isNaN(+e7))&&u5)n4.rotateAxisAngleSelf(s3,c4,l4,u5);else if(t53==="rotate"&&s3&&[c4,l4].every(e7=>e7===void 0))n4.rotateSelf(0,0,s3);else if(t53==="scale3d"&&d4.every(e7=>!Number.isNaN(+e7))&&d4.some(e7=>e7!==1))n4.scaleSelf(s3,c4,l4);else if(t53==="scale"&&!Number.isNaN(s3)&&(s3!==1||c4!==1)&&l4===void 0){let e7=Number.isNaN(+c4)?s3:c4;n4.scaleSelf(s3,e7,1)}else if(t53==="skew"&&(s3||!Number.isNaN(s3)&&c4)&&l4===void 0)n4.skewSelf(s3,c4||0);else if(["translate","rotate","scale","skew"].some(e7=>t53.includes(e7))&&/[XYZ]/.test(t53)&&s3&&[c4,l4].every(e7=>e7===void 0))if(t53==="skewX"||t53==="skewY")n4[t53==="skewX"?"skewXSelf":"skewYSelf"](s3);else{let e7=t53.replace(/[XYZ]/,""),r5=t53.replace(e7,""),i4=["X","Y","Z"].indexOf(r5),a4=e7==="scale"?1:0,o6=e7+"Self",c5=[i4===0?s3:a4,i4===1?s3:a4,i4===2?s3:a4];n4[o6](...c5)}else throw TypeError(i3)}),n4},o=(e5,t52)=>t52?[e5.a,e5.b,e5.c,e5.d,e5.e,e5.f]:[e5.m11,e5.m12,e5.m13,e5.m14,e5.m21,e5.m22,e5.m23,e5.m24,e5.m31,e5.m32,e5.m33,e5.m34,e5.m41,e5.m42,e5.m43,e5.m44],s=(e5,t52,n4)=>{let r5=new h;return r5.m41=e5,r5.e=e5,r5.m42=t52,r5.f=t52,r5.m43=n4,r5},c=(e5,t52,n4)=>{let r5=new h,i3=Math.PI/180,a3=e5*i3,o4=t52*i3,s3=n4*i3,c4=Math.cos(a3),l4=-Math.sin(a3),u5=Math.cos(o4),d4=-Math.sin(o4),f3=Math.cos(s3),p4=-Math.sin(s3),m4=u5*f3,g6=-u5*p4;r5.m11=m4,r5.a=m4,r5.m12=g6,r5.b=g6,r5.m13=d4;let _4=l4*d4*f3+c4*p4;r5.m21=_4,r5.c=_4;let v4=c4*f3-l4*d4*p4;return r5.m22=v4,r5.d=v4,r5.m23=-l4*u5,r5.m31=l4*p4-c4*d4*f3,r5.m32=l4*f3+c4*d4*p4,r5.m33=c4*u5,r5},l=(e5=0,t52=0,n4=0,r5=0)=>{let i3=new h,a3=Math.sqrt(e5*e5+t52*t52+n4*n4);if(a3===0)return i3;let o4=e5/a3,s3=t52/a3,c4=n4/a3,l4=Math.PI/360*r5,u5=Math.sin(l4),d4=Math.cos(l4),f3=u5*u5,p4=o4*o4,m4=s3*s3,g6=c4*c4,_4=1-2*(m4+g6)*f3;i3.m11=_4,i3.a=_4;let v4=2*(o4*s3*f3+c4*u5*d4);i3.m12=v4,i3.b=v4,i3.m13=2*(o4*c4*f3-s3*u5*d4);let y4=2*(s3*o4*f3-c4*u5*d4);i3.m21=y4,i3.c=y4;let b3=1-2*(g6+p4)*f3;return i3.m22=b3,i3.d=b3,i3.m23=2*(s3*c4*f3+o4*u5*d4),i3.m31=2*(c4*o4*f3+s3*u5*d4),i3.m32=2*(c4*s3*f3-o4*u5*d4),i3.m33=1-2*(p4+m4)*f3,i3},u3=(e5,t52,n4)=>{let r5=new h;return r5.m11=e5,r5.a=e5,r5.m22=t52,r5.d=t52,r5.m33=n4,r5},d=(e5,t52)=>{let n4=new h;if(e5){let t53=e5*Math.PI/180,r5=Math.tan(t53);n4.m21=r5,n4.c=r5}if(t52){let e6=t52*Math.PI/180,r5=Math.tan(e6);n4.m12=r5,n4.b=r5}return n4},f=e5=>d(e5,0),p=e5=>d(0,e5),m=(e5,t52)=>r3([t52.m11*e5.m11+t52.m12*e5.m21+t52.m13*e5.m31+t52.m14*e5.m41,t52.m11*e5.m12+t52.m12*e5.m22+t52.m13*e5.m32+t52.m14*e5.m42,t52.m11*e5.m13+t52.m12*e5.m23+t52.m13*e5.m33+t52.m14*e5.m43,t52.m11*e5.m14+t52.m12*e5.m24+t52.m13*e5.m34+t52.m14*e5.m44,t52.m21*e5.m11+t52.m22*e5.m21+t52.m23*e5.m31+t52.m24*e5.m41,t52.m21*e5.m12+t52.m22*e5.m22+t52.m23*e5.m32+t52.m24*e5.m42,t52.m21*e5.m13+t52.m22*e5.m23+t52.m23*e5.m33+t52.m24*e5.m43,t52.m21*e5.m14+t52.m22*e5.m24+t52.m23*e5.m34+t52.m24*e5.m44,t52.m31*e5.m11+t52.m32*e5.m21+t52.m33*e5.m31+t52.m34*e5.m41,t52.m31*e5.m12+t52.m32*e5.m22+t52.m33*e5.m32+t52.m34*e5.m42,t52.m31*e5.m13+t52.m32*e5.m23+t52.m33*e5.m33+t52.m34*e5.m43,t52.m31*e5.m14+t52.m32*e5.m24+t52.m33*e5.m34+t52.m34*e5.m44,t52.m41*e5.m11+t52.m42*e5.m21+t52.m43*e5.m31+t52.m44*e5.m41,t52.m41*e5.m12+t52.m42*e5.m22+t52.m43*e5.m32+t52.m44*e5.m42,t52.m41*e5.m13+t52.m42*e5.m23+t52.m43*e5.m33+t52.m44*e5.m43,t52.m41*e5.m14+t52.m42*e5.m24+t52.m43*e5.m34+t52.m44*e5.m44]),_a3,h=(_a3=class{constructor(e5){return this.a=1,this.b=0,this.c=0,this.d=1,this.e=0,this.f=0,this.m11=1,this.m12=0,this.m13=0,this.m14=0,this.m21=0,this.m22=1,this.m23=0,this.m24=0,this.m31=0,this.m32=0,this.m33=1,this.m34=0,this.m41=0,this.m42=0,this.m43=0,this.m44=1,e5?this.setMatrixValue(e5):this}get isIdentity(){return this.m11===1&&this.m12===0&&this.m13===0&&this.m14===0&&this.m21===0&&this.m22===1&&this.m23===0&&this.m24===0&&this.m31===0&&this.m32===0&&this.m33===1&&this.m34===0&&this.m41===0&&this.m42===0&&this.m43===0&&this.m44===1}get is2D(){return this.m31===0&&this.m32===0&&this.m33===1&&this.m34===0&&this.m43===0&&this.m44===1}setMatrixValue(e5){return typeof e5=="string"&&e5.length&&e5!=="none"?a(e5):Array.isArray(e5)||e5 instanceof Float64Array||e5 instanceof Float32Array?r3(e5):typeof e5=="object"?i(e5):this}toFloat32Array(e5){return Float32Array.from(o(this,e5))}toFloat64Array(e5){return Float64Array.from(o(this,e5))}toString(){let{is2D:e5}=this,t52=this.toFloat64Array(e5).join(", ");return`${e5?"matrix":"matrix3d"}(${t52})`}toJSON(){let{is2D:e5,isIdentity:t52}=this;return{...this,is2D:e5,isIdentity:t52}}multiply(e5){return m(this,e5)}translate(e5,t52,n4){return this.multiply(s(e5,t52??0,n4??0))}scale(e5,t52,n4){return this.multiply(u3(e5,t52??e5,n4??1))}rotate(e5,t52,n4){let r5=e5,i3=t52||0,a3=n4||0;return typeof e5=="number"&&t52===void 0&&n4===void 0&&(a3=r5,r5=0,i3=0),this.multiply(c(r5,i3,a3))}rotateAxisAngle(e5=0,t52=0,n4=0,r5=0){if([e5,t52,n4,r5].some(e6=>!Number.isFinite(e6)))throw TypeError("CSSMatrix: expecting 4 values");return Math.sqrt(e5*e5+t52*t52+n4*n4)===0?i(this):this.multiply(l(e5,t52,n4,r5))}skewX(e5){return this.multiply(f(e5))}skewY(e5){return this.multiply(p(e5))}skew(e5,t52){return this.multiply(d(e5,t52))}multiplySelf(e5){let t52=m(this,e5);return Object.assign(this,t52),this}translateSelf(e5,t52,n4){return this.multiplySelf(s(e5,t52??0,n4??0))}scaleSelf(e5,t52,n4){return this.multiplySelf(u3(e5,t52??e5,n4??1))}rotateSelf(e5,t52,n4){let r5=e5,i3=t52||0,a3=n4||0;return typeof e5=="number"&&t52===void 0&&n4===void 0&&(a3=r5,r5=0,i3=0),this.multiplySelf(c(r5,i3,a3))}rotateAxisAngleSelf(e5=0,t52=0,n4=0,r5=0){if([e5,t52,n4,r5].some(e6=>!Number.isFinite(e6)))throw TypeError("CSSMatrix: expecting 4 values");return Math.sqrt(e5*e5+t52*t52+n4*n4)===0?this:this.multiplySelf(l(e5,t52,n4,r5))}skewXSelf(e5){return this.multiplySelf(f(e5))}skewYSelf(e5){return this.multiplySelf(p(e5))}skewSelf(e5,t52){return this.multiplySelf(d(e5,t52))}transformPoint(e5){let t52=this.m11*e5.x+this.m21*e5.y+this.m31*e5.z+this.m41*e5.w,n4=this.m12*e5.x+this.m22*e5.y+this.m32*e5.z+this.m42*e5.w,r5=this.m13*e5.x+this.m23*e5.y+this.m33*e5.z+this.m43*e5.w,i3=this.m14*e5.x+this.m24*e5.y+this.m34*e5.z+this.m44*e5.w;return e5 instanceof DOMPoint?new DOMPoint(t52,n4,r5,i3):{x:t52,y:n4,z:r5,w:i3}}},__publicField(_a3,"Translate",s),__publicField(_a3,"Rotate",c),__publicField(_a3,"RotateAxisAngle",l),__publicField(_a3,"Scale",u3),__publicField(_a3,"SkewX",f),__publicField(_a3,"SkewY",p),__publicField(_a3,"Skew",d),__publicField(_a3,"Multiply",m),__publicField(_a3,"fromArray",r3),__publicField(_a3,"fromMatrix",i),__publicField(_a3,"fromString",a),__publicField(_a3,"toArray",o),__publicField(_a3,"isCompatibleArray",t),__publicField(_a3,"isCompatibleObject",n),_a3);var version="2.2.1",midPoint=([ax3,ay3],[bx3,by3],t52)=>[ax3+(bx3-ax3)*t52,ay3+(by3-ay3)*t52],distanceSquareRoot=(a3,b3)=>Math.sqrt((a3[0]-b3[0])*(a3[0]-b3[0])+(a3[1]-b3[1])*(a3[1]-b3[1])),getLineLength=(x12,y12,x22,y22)=>distanceSquareRoot([x12,y12],[x22,y22]),getPointAtLineLength=(x12,y12,x22,y22,distance8)=>{let point7={x:x12,y:y12};if(typeof distance8=="number"){let length4=distanceSquareRoot([x12,y12],[x22,y22]);if(distance8<=0)point7={x:x12,y:y12};else if(distance8>=length4)point7={x:x22,y:y22};else{let[x4,y4]=midPoint([x12,y12],[x22,y22],distance8/length4);point7={x:x4,y:y4}}}return point7},getLineBBox=(x12,y12,x22,y22)=>{let{min,max}=Math;return[min(x12,x22),min(y12,y22),max(x12,x22),max(y12,y22)]},lineTools={getLineBBox,getLineLength,getPointAtLineLength},arcLength=(rx3,ry3,theta)=>{let halfTheta=theta/2,sinHalfTheta=Math.sin(halfTheta),cosHalfTheta=Math.cos(halfTheta),term1=rx3**2*sinHalfTheta**2,term2=ry3**2*cosHalfTheta**2,length4=Math.sqrt(term1+term2)*theta;return Math.abs(length4)},arcPoint=(cx3,cy3,rx3,ry3,alpha,theta)=>{let{sin:sin6,cos:cos6}=Math,cosA=cos6(alpha),sinA=sin6(alpha),x4=rx3*cos6(theta),y4=ry3*sin6(theta);return[cx3+cosA*x4-sinA*y4,cy3+sinA*x4+cosA*y4]},angleBetween=(v02,v12)=>{let{x:v0x,y:v0y}=v02,{x:v1x,y:v1y}=v12,p4=v0x*v1x+v0y*v1y,n4=Math.sqrt((v0x**2+v0y**2)*(v1x**2+v1y**2));return(v0x*v1y-v0y*v1x<0?-1:1)*Math.acos(p4/n4)},getArcProps=(x12,y12,RX,RY2,angle,LAF,SF,x4,y4)=>{let{abs,sin:sin6,cos:cos6,sqrt,PI:PI7}=Math,rx3=abs(RX),ry3=abs(RY2),xRotRad=(angle%360+360)%360*(PI7/180);if(x12===x4&&y12===y4)return{rx:rx3,ry:ry3,startAngle:0,endAngle:0,center:{x:x4,y:y4}};if(rx3===0||ry3===0)return{rx:rx3,ry:ry3,startAngle:0,endAngle:0,center:{x:(x4+x12)/2,y:(y4+y12)/2}};let dx3=(x12-x4)/2,dy3=(y12-y4)/2,transformedPoint={x:cos6(xRotRad)*dx3+sin6(xRotRad)*dy3,y:-sin6(xRotRad)*dx3+cos6(xRotRad)*dy3},radiiCheck=transformedPoint.x**2/rx3**2+transformedPoint.y**2/ry3**2;radiiCheck>1&&(rx3*=sqrt(radiiCheck),ry3*=sqrt(radiiCheck));let cRadicand=(rx3**2*ry3**2-rx3**2*transformedPoint.y**2-ry3**2*transformedPoint.x**2)/(rx3**2*transformedPoint.y**2+ry3**2*transformedPoint.x**2);cRadicand=cRadicand<0?0:cRadicand;let cCoef=(LAF!==SF?1:-1)*sqrt(cRadicand),transformedCenter={x:cCoef*(rx3*transformedPoint.y/ry3),y:cCoef*(-(ry3*transformedPoint.x)/rx3)},center2={x:cos6(xRotRad)*transformedCenter.x-sin6(xRotRad)*transformedCenter.y+(x12+x4)/2,y:sin6(xRotRad)*transformedCenter.x+cos6(xRotRad)*transformedCenter.y+(y12+y4)/2},startVector={x:(transformedPoint.x-transformedCenter.x)/rx3,y:(transformedPoint.y-transformedCenter.y)/ry3},startAngle=angleBetween({x:1,y:0},startVector),sweepAngle=angleBetween(startVector,{x:(-transformedPoint.x-transformedCenter.x)/rx3,y:(-transformedPoint.y-transformedCenter.y)/ry3});return!SF&&sweepAngle>0?sweepAngle-=2*PI7:SF&&sweepAngle<0&&(sweepAngle+=2*PI7),sweepAngle%=2*PI7,{center:center2,startAngle,endAngle:startAngle+sweepAngle,rx:rx3,ry:ry3}},getArcLength=(x12,y12,RX,RY2,angle,LAF,SF,x4,y4)=>{let{rx:rx3,ry:ry3,startAngle,endAngle}=getArcProps(x12,y12,RX,RY2,angle,LAF,SF,x4,y4);return arcLength(rx3,ry3,endAngle-startAngle)},getPointAtArcLength=(x12,y12,RX,RY2,angle,LAF,SF,x4,y4,distance8)=>{let point7={x:x12,y:y12},{center:center2,rx:rx3,ry:ry3,startAngle,endAngle}=getArcProps(x12,y12,RX,RY2,angle,LAF,SF,x4,y4);if(typeof distance8=="number"){let length4=arcLength(rx3,ry3,endAngle-startAngle);if(distance8<=0)point7={x:x12,y:y12};else if(distance8>=length4)point7={x:x4,y:y4};else{if(x12===x4&&y12===y4)return{x:x4,y:y4};if(rx3===0||ry3===0)return getPointAtLineLength(x12,y12,x4,y4,distance8);let{PI:PI7,cos:cos6,sin:sin6}=Math,sweepAngle=endAngle-startAngle,xRotRad=(angle%360+360)%360*(PI7/180),alpha=startAngle+sweepAngle*(distance8/length4),ellipseComponentX=rx3*cos6(alpha),ellipseComponentY=ry3*sin6(alpha);point7={x:cos6(xRotRad)*ellipseComponentX-sin6(xRotRad)*ellipseComponentY+center2.x,y:sin6(xRotRad)*ellipseComponentX+cos6(xRotRad)*ellipseComponentY+center2.y}}}return point7},getArcBBox=(x12,y12,RX,RY2,angle,LAF,SF,x4,y4)=>{let{center:center2,rx:rx3,ry:ry3,startAngle,endAngle}=getArcProps(x12,y12,RX,RY2,angle,LAF,SF,x4,y4),deltaAngle=endAngle-startAngle,{min,max,tan:tan6,atan2,PI:PI7}=Math,{x:cx3,y:cy3}=center2,alpha=angle*PI7/180,tangent=tan6(alpha),theta=atan2(-ry3*tangent,rx3),angle1=theta,angle2=theta+PI7,angle3=atan2(ry3,rx3*tangent),angle4=angle3+PI7,xArray=[x4],yArray=[y4],xMin=min(x12,x4),xMax=max(x12,x4),yMin=min(y12,y4),yMax=max(y12,y4),pP2=arcPoint(cx3,cy3,rx3,ry3,alpha,endAngle-deltaAngle*1e-5),pP3=arcPoint(cx3,cy3,rx3,ry3,alpha,endAngle-deltaAngle*.99999);if(pP2[0]>xMax||pP3[0]>xMax){let p12=arcPoint(cx3,cy3,rx3,ry3,alpha,angle1);xArray.push(p12[0]),yArray.push(p12[1])}if(pP2[0]<xMin||pP3[0]<xMin){let p22=arcPoint(cx3,cy3,rx3,ry3,alpha,angle2);xArray.push(p22[0]),yArray.push(p22[1])}if(pP2[1]<yMin||pP3[1]<yMin){let p4=arcPoint(cx3,cy3,rx3,ry3,alpha,angle4);xArray.push(p4[0]),yArray.push(p4[1])}if(pP2[1]>yMax||pP3[1]>yMax){let p32=arcPoint(cx3,cy3,rx3,ry3,alpha,angle3);xArray.push(p32[0]),yArray.push(p32[1])}return xMin=min.apply([],xArray),yMin=min.apply([],yArray),xMax=max.apply([],xArray),yMax=max.apply([],yArray),[xMin,yMin,xMax,yMax]},arcTools={angleBetween,arcLength,arcPoint,getArcBBox,getArcLength,getArcProps,getPointAtArcLength},Tvalues=[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213],Cvalues=[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872],deriveBezier=points=>{let dpoints=[];for(let p4=points,d4=p4.length,c4=d4-1;d4>1;d4-=1,c4-=1){let list=[];for(let j4=0;j4<c4;j4+=1)list.push({x:c4*(p4[j4+1].x-p4[j4].x),y:c4*(p4[j4+1].y-p4[j4].y),t:0});dpoints.push(list),p4=list}return dpoints},computeBezier=(points,t52)=>{if(t52===0)return points[0].t=0,points[0];let order=points.length-1;if(t52===1)return points[order].t=1,points[order];let mt3=1-t52,p4=points;if(order===0)return points[0].t=t52,points[0];if(order===1)return{x:mt3*p4[0].x+t52*p4[1].x,y:mt3*p4[0].y+t52*p4[1].y,t:t52};let mt22=mt3*mt3,t210=t52*t52,a3=0,b3=0,c4=0,d4=0;return order===2?(p4=[p4[0],p4[1],p4[2],{x:0,y:0}],a3=mt22,b3=mt3*t52*2,c4=t210):order===3&&(a3=mt22*mt3,b3=mt22*t52*3,c4=mt3*t210*3,d4=t52*t210),{x:a3*p4[0].x+b3*p4[1].x+c4*p4[2].x+d4*p4[3].x,y:a3*p4[0].y+b3*p4[1].y+c4*p4[2].y+d4*p4[3].y,t:t52}},calculateBezier=(derivativeFn,t52)=>{let d4=derivativeFn(t52),l4=d4.x*d4.x+d4.y*d4.y;return Math.sqrt(l4)},bezierLength=derivativeFn=>{let len=Tvalues.length,sum=0;for(let i3=0,t52;i3<len;i3++)t52=.5*Tvalues[i3]+.5,sum+=Cvalues[i3]*calculateBezier(derivativeFn,t52);return .5*sum},getBezierLength=curve=>{let points=[];for(let idx=0,len=curve.length,step=2;idx<len;idx+=step)points.push({x:curve[idx],y:curve[idx+1]});let dpoints=deriveBezier(points);return bezierLength(t52=>computeBezier(dpoints[0],t52))},CBEZIER_MINMAX_EPSILON=1e-8,minmaxQ=([v12,cp2,v22])=>{let min=Math.min(v12,v22),max=Math.max(v12,v22);if(cp2>=v12?v22>=cp2:v22<=cp2)return[min,max];let E3=(v12*v22-cp2*cp2)/(v12-2*cp2+v22);return E3<min?[E3,max]:[min,E3]},minmaxC=([v12,cp1,cp2,v22])=>{let K3=v12-3*cp1+3*cp2-v22;if(Math.abs(K3)<1e-8)return v12===v22&&v12===cp1?[v12,v22]:minmaxQ([v12,-.5*v12+1.5*cp1,v12-3*cp1+3*cp2]);let T4=-v12*cp2+v12*v22-cp1*cp2-cp1*v22+cp1*cp1+cp2*cp2;if(T4<=0)return[Math.min(v12,v22),Math.max(v12,v22)];let S3=Math.sqrt(T4),min=Math.min(v12,v22),max=Math.max(v12,v22),L3=v12-2*cp1+cp2;for(let R3=(L3+S3)/K3,i3=1;i3<=2;R3=(L3-S3)/K3,i3++)if(R3>0&&R3<1){let Q4=v12*(1-R3)*(1-R3)*(1-R3)+cp1*3*(1-R3)*(1-R3)*R3+cp2*3*(1-R3)*R3*R3+v22*R3*R3*R3;Q4<min&&(min=Q4),Q4>max&&(max=Q4)}return[min,max]},bezierTools={bezierLength,calculateBezier,CBEZIER_MINMAX_EPSILON,computeBezier,Cvalues,deriveBezier,getBezierLength,minmaxC,minmaxQ,Tvalues},getPointAtCubicSegmentLength=([x12,y12,c1x,c1y,c2x,c2y,x22,y22],t52)=>{let t110=1-t52;return{x:t110**3*x12+3*t110**2*t52*c1x+3*t110*t52**2*c2x+t52**3*x22,y:t110**3*y12+3*t110**2*t52*c1y+3*t110*t52**2*c2y+t52**3*y22}},getCubicLength=(x12,y12,c1x,c1y,c2x,c2y,x22,y22)=>getBezierLength([x12,y12,c1x,c1y,c2x,c2y,x22,y22]),getPointAtCubicLength=(x12,y12,c1x,c1y,c2x,c2y,x22,y22,distance8)=>{let distanceIsNumber=typeof distance8=="number",point7={x:x12,y:y12};if(distanceIsNumber){let currentLength=getBezierLength([x12,y12,c1x,c1y,c2x,c2y,x22,y22]);distance8<=0||(distance8>=currentLength?point7={x:x22,y:y22}:point7=getPointAtCubicSegmentLength([x12,y12,c1x,c1y,c2x,c2y,x22,y22],distance8/currentLength))}return point7},getCubicBBox=(x12,y12,c1x,c1y,c2x,c2y,x22,y22)=>{let cxMinMax=minmaxC([x12,c1x,c2x,x22]),cyMinMax=minmaxC([y12,c1y,c2y,y22]);return[cxMinMax[0],cyMinMax[0],cxMinMax[1],cyMinMax[1]]},cubicTools={getCubicBBox,getCubicLength,getPointAtCubicLength,getPointAtCubicSegmentLength},getPointAtQuadSegmentLength=([x12,y12,cx3,cy3,x22,y22],t52)=>{let t110=1-t52;return{x:t110**2*x12+2*t110*t52*cx3+t52**2*x22,y:t110**2*y12+2*t110*t52*cy3+t52**2*y22}},getQuadLength=(x12,y12,cx3,cy3,x22,y22)=>getBezierLength([x12,y12,cx3,cy3,x22,y22]),getPointAtQuadLength=(x12,y12,cx3,cy3,x22,y22,distance8)=>{let distanceIsNumber=typeof distance8=="number",point7={x:x12,y:y12};if(distanceIsNumber){let currentLength=getBezierLength([x12,y12,cx3,cy3,x22,y22]);distance8<=0||(distance8>=currentLength?point7={x:x22,y:y22}:point7=getPointAtQuadSegmentLength([x12,y12,cx3,cy3,x22,y22],distance8/currentLength))}return point7},getQuadBBox=(x12,y12,cx3,cy3,x22,y22)=>{let cxMinMax=minmaxQ([x12,cx3,x22]),cyMinMax=minmaxQ([y12,cy3,y22]);return[cxMinMax[0],cyMinMax[0],cxMinMax[1],cyMinMax[1]]},quadTools={getPointAtQuadLength,getPointAtQuadSegmentLength,getQuadBBox,getQuadLength},polygonArea=polygon2=>{let n4=polygon2.length,i3=-1,a3,b3=polygon2[n4-1],area=0;for(;++i3<n4;)a3=b3,b3=polygon2[i3],area+=a3[1]*b3[0]-a3[0]*b3[1];return area/2},polygonLength=polygon2=>polygon2.reduce((length4,point7,i3)=>i3?length4+distanceSquareRoot(polygon2[i3-1],point7):0,0),polygonCentroid=polygon2=>{if(polygon2.length===0)return[0,0];let sumX=0,sumY=0;for(let[x4,y4]of polygon2)sumX+=x4,sumY+=y4;let count=polygon2.length;return[sumX/count,sumY/count]},polygonTools={polygonArea,polygonLength,polygonCentroid},rotateVector=(x4,y4,rad)=>{let{sin:sin6,cos:cos6}=Math;return{x:x4*cos6(rad)-y4*sin6(rad),y:x4*sin6(rad)+y4*cos6(rad)}},roundTo=(n4,round)=>{let pow=round>=1?10**round:1;return round>0?Math.round(n4*pow)/pow:Math.round(n4)},defaultOptions2={origin:[0,0,0],round:4},paramsCounts={a:7,c:6,h:1,l:2,m:2,r:4,q:4,s:4,t:2,v:1,z:0},finalizeSegment=path=>{let pathCommand=path.pathValue[path.segmentStart],relativeCommand=pathCommand.toLowerCase(),{data}=path;for(;data.length>=paramsCounts[relativeCommand]&&(relativeCommand==="m"&&data.length>2?(path.segments.push([pathCommand].concat(data.splice(0,2))),relativeCommand="l",pathCommand=pathCommand==="m"?"l":"L"):path.segments.push([pathCommand].concat(data.splice(0,paramsCounts[relativeCommand]))),!!paramsCounts[relativeCommand]););},error="SVGPathCommanderError",scanFlag=path=>{let{index,pathValue}=path,code=pathValue.charCodeAt(index);if(code===48){path.param=0,path.index+=1;return}if(code===49){path.param=1,path.index+=1;return}path.err=`${error}: invalid Arc flag "${pathValue[index]}", expecting 0 or 1 at index ${index}`},isDigit=code=>code>=48&&code<=57,invalidPathValue="Invalid path value",scanParam=path=>{let{max,pathValue,index:start}=path,index=start,zeroFirst=!1,hasCeiling=!1,hasDecimal=!1,hasDot=!1,ch3;if(index>=max){path.err=`${error}: ${invalidPathValue} at index ${index}, "pathValue" is missing param`;return}if(ch3=pathValue.charCodeAt(index),(ch3===43||ch3===45)&&(index+=1,ch3=pathValue.charCodeAt(index)),!isDigit(ch3)&&ch3!==46){path.err=`${error}: ${invalidPathValue} at index ${index}, "${pathValue[index]}" is not a number`;return}if(ch3!==46){if(zeroFirst=ch3===48,index+=1,ch3=pathValue.charCodeAt(index),zeroFirst&&index<max&&ch3&&isDigit(ch3)){path.err=`${error}: ${invalidPathValue} at index ${start}, "${pathValue[start]}" illegal number`;return}for(;index<max&&isDigit(pathValue.charCodeAt(index));)index+=1,hasCeiling=!0;ch3=pathValue.charCodeAt(index)}if(ch3===46){for(hasDot=!0,index+=1;isDigit(pathValue.charCodeAt(index));)index+=1,hasDecimal=!0;ch3=pathValue.charCodeAt(index)}if(ch3===101||ch3===69){if(hasDot&&!hasCeiling&&!hasDecimal){path.err=`${error}: ${invalidPathValue} at index ${index}, "${pathValue[index]}" invalid float exponent`;return}if(index+=1,ch3=pathValue.charCodeAt(index),(ch3===43||ch3===45)&&(index+=1),index<max&&isDigit(pathValue.charCodeAt(index)))for(;index<max&&isDigit(pathValue.charCodeAt(index));)index+=1;else{path.err=`${error}: ${invalidPathValue} at index ${index}, "${pathValue[index]}" invalid integer exponent`;return}}path.index=index,path.param=+path.pathValue.slice(start,index)},isSpace=ch3=>[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279,10,13,8232,8233,32,9,11,12,160].includes(ch3),skipSpaces=path=>{let{pathValue,max}=path;for(;path.index<max&&isSpace(pathValue.charCodeAt(path.index));)path.index+=1},isPathCommand=code=>{switch(code|32){case 109:case 122:case 108:case 104:case 118:case 99:case 115:case 113:case 116:case 97:return!0;default:return!1}},isDigitStart=code=>isDigit(code)||code===43||code===45||code===46,isArcCommand=code=>(code|32)===97,isMoveCommand=code=>{switch(code|32){case 109:case 77:return!0;default:return!1}},scanSegment=path=>{let{max,pathValue,index,segments}=path,cmdCode=pathValue.charCodeAt(index),reqParams=paramsCounts[pathValue[index].toLowerCase()];if(path.segmentStart=index,!isPathCommand(cmdCode)){path.err=`${error}: ${invalidPathValue} "${pathValue[index]}" is not a path command at index ${index}`;return}let lastSegment=segments[segments.length-1];if(!isMoveCommand(cmdCode)&&lastSegment?.[0]?.toLocaleLowerCase()==="z"){path.err=`${error}: ${invalidPathValue} "${pathValue[index]}" is not a MoveTo path command at index ${index}`;return}if(path.index+=1,skipSpaces(path),path.data=[],!reqParams){finalizeSegment(path);return}for(;;){for(let i3=reqParams;i3>0;i3-=1){if(isArcCommand(cmdCode)&&(i3===3||i3===4)?scanFlag(path):scanParam(path),path.err.length)return;path.data.push(path.param),skipSpaces(path),path.index<max&&pathValue.charCodeAt(path.index)===44&&(path.index+=1,skipSpaces(path))}if(path.index>=path.max||!isDigitStart(pathValue.charCodeAt(path.index)))break}finalizeSegment(path)},PathParser=class{constructor(pathString){this.segments=[],this.pathValue=pathString,this.max=pathString.length,this.index=0,this.param=0,this.segmentStart=0,this.data=[],this.err=""}},parsePathString=pathInput=>{if(typeof pathInput!="string")return pathInput.slice(0);let path=new PathParser(pathInput);for(skipSpaces(path);path.index<path.max&&!path.err.length;)scanSegment(path);if(!path.err.length)path.segments.length&&(path.segments[0][0]="M");else throw TypeError(path.err);return path.segments},absolutizeSegment=(segment2,index,lastX,lastY)=>{let[pathCommand]=segment2,absCommand=pathCommand.toUpperCase();if(index===0||absCommand===pathCommand)return segment2;if(absCommand==="A")return[absCommand,segment2[1],segment2[2],segment2[3],segment2[4],segment2[5],segment2[6]+lastX,segment2[7]+lastY];if(absCommand==="V")return[absCommand,segment2[1]+lastY];if(absCommand==="H")return[absCommand,segment2[1]+lastX];if(absCommand==="L")return[absCommand,segment2[1]+lastX,segment2[2]+lastY];{let absValues=[],seglen=segment2.length;for(let j4=1;j4<seglen;j4+=1)absValues.push(segment2[j4]+(j4%2?lastX:lastY));return[absCommand].concat(absValues)}},iterate=(path,iterator)=>{let x4=0,y4=0,mx3=0,my3=0,i3=0;for(;i3<path.length;){let segment2=path[i3],[pathCommand]=segment2,absCommand=pathCommand.toUpperCase(),isRelative=absCommand!==pathCommand,iteratorResult=iterator(segment2,i3,x4,y4);if(iteratorResult===!1)break;if(absCommand==="Z")x4=mx3,y4=my3;else if(absCommand==="H")x4=segment2[1]+(isRelative?x4:0);else if(absCommand==="V")y4=segment2[1]+(isRelative?y4:0);else{let segLen=segment2.length;x4=segment2[segLen-2]+(isRelative?x4:0),y4=segment2[segLen-1]+(isRelative?y4:0),absCommand==="M"&&(mx3=x4,my3=y4)}iteratorResult&&(path[i3]=iteratorResult),i3+=1}return path},pathToAbsolute=pathInput=>iterate(parsePathString(pathInput),absolutizeSegment),relativizeSegment=(segment2,index,lastX,lastY)=>{let[pathCommand]=segment2,relCommand=pathCommand.toLowerCase();if(index===0||pathCommand===relCommand)return segment2;if(relCommand==="a")return[relCommand,segment2[1],segment2[2],segment2[3],segment2[4],segment2[5],segment2[6]-lastX,segment2[7]-lastY];if(relCommand==="v")return[relCommand,segment2[1]-lastY];if(relCommand==="h")return[relCommand,segment2[1]-lastX];if(relCommand==="l")return[relCommand,segment2[1]-lastX,segment2[2]-lastY];{let relValues=[],seglen=segment2.length;for(let j4=1;j4<seglen;j4+=1)relValues.push(segment2[j4]-(j4%2?lastX:lastY));return[relCommand].concat(relValues)}},pathToRelative=pathInput=>iterate(parsePathString(pathInput),relativizeSegment),arcToCubic=(X12,Y12,RX,RY2,angle,LAF,SF,X22,Y22,recursive)=>{let x12=X12,y12=Y12,rx3=RX,ry3=RY2,x22=X22,y22=Y22,d120=Math.PI*120/180,rad=Math.PI/180*(+angle||0),res2=[],xy3,f12,f22,cx3,cy3;if(recursive)[f12,f22,cx3,cy3]=recursive;else{xy3=rotateVector(x12,y12,-rad),x12=xy3.x,y12=xy3.y,xy3=rotateVector(x22,y22,-rad),x22=xy3.x,y22=xy3.y;let x4=(x12-x22)/2,y4=(y12-y22)/2,h6=x4*x4/(rx3*rx3)+y4*y4/(ry3*ry3);h6>1&&(h6=Math.sqrt(h6),rx3*=h6,ry3*=h6);let rx22=rx3*rx3,ry22=ry3*ry3,k4=(LAF===SF?-1:1)*Math.sqrt(Math.abs((rx22*ry22-rx22*y4*y4-ry22*x4*x4)/(rx22*y4*y4+ry22*x4*x4)));cx3=k4*rx3*y4/ry3+(x12+x22)/2,cy3=k4*-ry3*x4/rx3+(y12+y22)/2,f12=Math.asin(((y12-cy3)/ry3*10**9>>0)/10**9),f22=Math.asin(((y22-cy3)/ry3*10**9>>0)/10**9),f12=x12<cx3?Math.PI-f12:f12,f22=x22<cx3?Math.PI-f22:f22,f12<0&&(f12=Math.PI*2+f12),f22<0&&(f22=Math.PI*2+f22),SF&&f12>f22&&(f12-=Math.PI*2),!SF&&f22>f12&&(f22-=Math.PI*2)}let df3=f22-f12;if(Math.abs(df3)>d120){let f2old=f22,x2old=x22,y2old=y22;f22=f12+d120*(SF&&f22>f12?1:-1),x22=cx3+rx3*Math.cos(f22),y22=cy3+ry3*Math.sin(f22),res2=arcToCubic(x22,y22,rx3,ry3,angle,0,SF,x2old,y2old,[f22,f2old,cx3,cy3])}df3=f22-f12;let c12=Math.cos(f12),s12=Math.sin(f12),c22=Math.cos(f22),s22=Math.sin(f22),t52=Math.tan(df3/4),hx3=4/3*rx3*t52,hy3=4/3*ry3*t52,m12=[x12,y12],m22=[x12+hx3*s12,y12-hy3*c12],m32=[x22+hx3*s22,y22-hy3*c22],m4=[x22,y22];if(m22[0]=2*m12[0]-m22[0],m22[1]=2*m12[1]-m22[1],recursive)return[m22[0],m22[1],m32[0],m32[1],m4[0],m4[1]].concat(res2);res2=[m22[0],m22[1],m32[0],m32[1],m4[0],m4[1]].concat(res2);let newres=[];for(let i3=0,ii3=res2.length;i3<ii3;i3+=1)newres[i3]=i3%2?rotateVector(res2[i3-1],res2[i3],rad).y:rotateVector(res2[i3],res2[i3+1],rad).x;return newres},quadToCubic=(x12,y12,qx3,qy3,x22,y22)=>{let r13=.3333333333333333,r23=2/3;return[r13*x12+r23*qx3,r13*y12+r23*qy3,r13*x22+r23*qx3,r13*y22+r23*qy3,x22,y22]},lineToCubic=(x12,y12,x22,y22)=>{let c12=midPoint([x12,y12],[x22,y22],.3333333333333333),c22=midPoint([x12,y12],[x22,y22],2/3);return[c12[0],c12[1],c22[0],c22[1],x22,y22]},segmentToCubic=(segment2,params)=>{let pathCommand=segment2[0],values=segment2.slice(1).map(Number),[x4,y4]=values,{x1:px1,y1:py1}=params;return"TQ".includes(pathCommand)||(params.qx=null,params.qy=null),pathCommand==="M"?(params.mx=x4,params.my=y4,params.x=x4,params.y=y4,segment2):pathCommand==="A"?["C"].concat(arcToCubic(px1,py1,values[0],values[1],values[2],values[3],values[4],values[5],values[6])):pathCommand==="Q"?(params.qx=x4,params.qy=y4,["C"].concat(quadToCubic(px1,py1,values[0],values[1],values[2],values[3]))):pathCommand==="L"?["C"].concat(lineToCubic(px1,py1,x4,y4)):pathCommand==="Z"?["C"].concat(lineToCubic(px1,py1,params.mx,params.my)):segment2},normalizeSegment=(segment2,params)=>{let[pathCommand]=segment2,absCommand=pathCommand.toUpperCase(),isRelative=pathCommand!==absCommand,{x1:px1,y1:py1,x2:px22,y2:py22,x:x4,y:y4}=params,values=segment2.slice(1),absValues=values.map((n4,j4)=>n4+(isRelative?j4%2?y4:x4:0));if("TQ".includes(absCommand)||(params.qx=null,params.qy=null),absCommand==="A")return absValues=values.slice(0,-2).concat(values[5]+(isRelative?x4:0),values[6]+(isRelative?y4:0)),["A"].concat(absValues);if(absCommand==="H")return["L",segment2[1]+(isRelative?x4:0),py1];if(absCommand==="V")return["L",px1,segment2[1]+(isRelative?y4:0)];if(absCommand==="L")return["L",segment2[1]+(isRelative?x4:0),segment2[2]+(isRelative?y4:0)];if(absCommand==="M")return["M",segment2[1]+(isRelative?x4:0),segment2[2]+(isRelative?y4:0)];if(absCommand==="C")return["C"].concat(absValues);if(absCommand==="S"){let x12=px1*2-px22,y12=py1*2-py22;return params.x1=x12,params.y1=y12,["C",x12,y12].concat(absValues)}else if(absCommand==="T"){let qx3=px1*2-(params.qx?params.qx:0),qy3=py1*2-(params.qy?params.qy:0);return params.qx=qx3,params.qy=qy3,["Q",qx3,qy3].concat(absValues)}else if(absCommand==="Q"){let[nqx,nqy]=absValues;return params.qx=nqx,params.qy=nqy,["Q"].concat(absValues)}else if(absCommand==="Z")return["Z"];return segment2},paramsParser={mx:0,my:0,x1:0,y1:0,x2:0,y2:0,x:0,y:0,qx:null,qy:null},pathToCurve=pathInput=>{let params={...paramsParser},path=parsePathString(pathInput);return iterate(path,(seg,index,lastX,lastY)=>{params.x=lastX,params.y=lastY;let normalSegment=normalizeSegment(seg,params);normalSegment[0]==="M"&&(params.mx=normalSegment[1],params.my=normalSegment[2]);let result=segmentToCubic(normalSegment,params);result[0]==="C"&&result.length>7&&(path.splice(index+1,0,["C"].concat(result.slice(7))),result=result.slice(0,7));let seglen=result.length;return params.x1=+result[seglen-2],params.y1=+result[seglen-1],params.x2=+result[seglen-4]||params.x1,params.y2=+result[seglen-3]||params.y1,result})},pathToString=(path,roundOption)=>{let pathLen=path.length,{round}=defaultOptions2,segment2=path[0],result="";round=roundOption==="off"||typeof roundOption=="number"&&roundOption>=0?roundOption:typeof round=="number"&&round>=0?round:"off";for(let i3=0;i3<pathLen;i3+=1){segment2=path[i3];let[pathCommand]=segment2,values=segment2.slice(1);if(result+=pathCommand,round==="off")result+=values.join(" ");else{let j4=0,valLen=values.length;for(;j4<valLen;)result+=roundTo(values[j4],round),j4!==valLen-1&&(result+=" "),j4+=1}}return result},getPathBBox=pathInput=>{if(!pathInput)return{x:0,y:0,width:0,height:0,x2:0,y2:0,cx:0,cy:0,cz:0};let path=parsePathString(pathInput),pathCommand="M",mx3=0,my3=0,{max,min}=Math,xMin=1/0,yMin=1/0,xMax=-1/0,yMax=-1/0,minX=0,minY=0,maxX=0,maxY=0,paramX1=0,paramY1=0,paramX2=0,paramY2=0,paramQX=0,paramQY=0;iterate(path,(seg,index,lastX,lastY)=>{[pathCommand]=seg;let absCommand=pathCommand.toUpperCase(),absoluteSegment=absCommand!==pathCommand?absolutizeSegment(seg,index,lastX,lastY):seg.slice(0),normalSegment=absCommand==="V"?["L",lastX,absoluteSegment[1]]:absCommand==="H"?["L",absoluteSegment[1],lastY]:absoluteSegment;if([pathCommand]=normalSegment,"TQ".includes(absCommand)||(paramQX=0,paramQY=0),pathCommand==="M")[,mx3,my3]=normalSegment,minX=mx3,minY=my3,maxX=mx3,maxY=my3;else if(pathCommand==="L")[minX,minY,maxX,maxY]=getLineBBox(lastX,lastY,normalSegment[1],normalSegment[2]);else if(pathCommand==="A")[minX,minY,maxX,maxY]=getArcBBox(lastX,lastY,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4],normalSegment[5],normalSegment[6],normalSegment[7]);else if(pathCommand==="S"){let cp1x=paramX1*2-paramX2,cp1y=paramY1*2-paramY2;[minX,minY,maxX,maxY]=getCubicBBox(lastX,lastY,cp1x,cp1y,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4])}else pathCommand==="C"?[minX,minY,maxX,maxY]=getCubicBBox(lastX,lastY,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4],normalSegment[5],normalSegment[6]):pathCommand==="T"?(paramQX=paramX1*2-paramQX,paramQY=paramY1*2-paramQY,[minX,minY,maxX,maxY]=getQuadBBox(lastX,lastY,paramQX,paramQY,normalSegment[1],normalSegment[2])):pathCommand==="Q"?(paramQX=normalSegment[1],paramQY=normalSegment[2],[minX,minY,maxX,maxY]=getQuadBBox(lastX,lastY,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4])):pathCommand==="Z"&&([minX,minY,maxX,maxY]=getLineBBox(lastX,lastY,mx3,my3));xMin=min(minX,xMin),yMin=min(minY,yMin),xMax=max(maxX,xMax),yMax=max(maxY,yMax),[paramX1,paramY1]=pathCommand==="Z"?[mx3,my3]:normalSegment.slice(-2),[paramX2,paramY2]=pathCommand==="C"?[normalSegment[3],normalSegment[4]]:pathCommand==="S"?[normalSegment[1],normalSegment[2]]:[paramX1,paramY1]});let width=xMax-xMin,height=yMax-yMin;return{width,height,x:xMin,y:yMin,x2:xMax,y2:yMax,cx:xMin+width/2,cy:yMin+height/2,cz:Math.max(width,height)+Math.min(width,height)/2}},getTotalLength=pathInput=>{let path=parsePathString(pathInput),paramX1=0,paramY1=0,paramX2=0,paramY2=0,paramQX=0,paramQY=0,pathCommand="M",mx3=0,my3=0,totalLength=0;return iterate(path,(seg,index,lastX,lastY)=>{[pathCommand]=seg;let absCommand=pathCommand.toUpperCase(),absoluteSegment=absCommand!==pathCommand?absolutizeSegment(seg,index,lastX,lastY):seg.slice(0),normalSegment=absCommand==="V"?["L",lastX,absoluteSegment[1]]:absCommand==="H"?["L",absoluteSegment[1],lastY]:absoluteSegment;if([pathCommand]=normalSegment,"TQ".includes(absCommand)||(paramQX=0,paramQY=0),pathCommand==="M")[,mx3,my3]=normalSegment;else if(pathCommand==="L")totalLength+=getLineLength(lastX,lastY,normalSegment[1],normalSegment[2]);else if(pathCommand==="A")totalLength+=getArcLength(lastX,lastY,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4],normalSegment[5],normalSegment[6],normalSegment[7]);else if(pathCommand==="S"){let cp1x=paramX1*2-paramX2,cp1y=paramY1*2-paramY2;totalLength+=getCubicLength(lastX,lastY,cp1x,cp1y,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4])}else pathCommand==="C"?totalLength+=getCubicLength(lastX,lastY,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4],normalSegment[5],normalSegment[6]):pathCommand==="T"?(paramQX=paramX1*2-paramQX,paramQY=paramY1*2-paramQY,totalLength+=getQuadLength(lastX,lastY,paramQX,paramQY,normalSegment[1],normalSegment[2])):pathCommand==="Q"?(paramQX=normalSegment[1],paramQY=normalSegment[2],totalLength+=getQuadLength(lastX,lastY,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4])):pathCommand==="Z"&&(totalLength+=getLineLength(lastX,lastY,mx3,my3));[paramX1,paramY1]=pathCommand==="Z"?[mx3,my3]:normalSegment.slice(-2),[paramX2,paramY2]=pathCommand==="C"?[normalSegment[3],normalSegment[4]]:pathCommand==="S"?[normalSegment[1],normalSegment[2]]:[paramX1,paramY1]}),totalLength},DISTANCE_EPSILON=1e-5,normalizePath=pathInput=>{let path=parsePathString(pathInput),params={...paramsParser};return iterate(path,(seg,_4,lastX,lastY)=>{params.x=lastX,params.y=lastY;let result=normalizeSegment(seg,params),seglen=result.length;return params.x1=+result[seglen-2],params.y1=+result[seglen-1],params.x2=+result[seglen-4]||params.x1,params.y2=+result[seglen-3]||params.y1,result})},getPointAtLength=(pathInput,distance8)=>{let path=normalizePath(pathInput),isM=!1,data=[],x4=0,y4=0,[mx3,my3]=path[0].slice(1),distanceIsNumber=typeof distance8=="number",point7={x:mx3,y:my3},length4=0,POINT=point7,totalLength=0;return!distanceIsNumber||distance8<1e-5?point7:(iterate(path,(seg,_4,lastX,lastY)=>{let pathCommand=seg[0];if(isM=pathCommand==="M",data=isM?data:[lastX,lastY].concat(seg.slice(1)),isM?([,mx3,my3]=seg,point7={x:mx3,y:my3},length4=0):pathCommand==="L"?(point7=getPointAtLineLength(data[0],data[1],data[2],data[3],distance8-totalLength),length4=getLineLength(data[0],data[1],data[2],data[3])):pathCommand==="A"?(point7=getPointAtArcLength(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7],data[8],distance8-totalLength),length4=getArcLength(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7],data[8])):pathCommand==="C"?(point7=getPointAtCubicLength(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7],distance8-totalLength),length4=getCubicLength(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7])):pathCommand==="Q"?(point7=getPointAtQuadLength(data[0],data[1],data[2],data[3],data[4],data[5],distance8-totalLength),length4=getQuadLength(data[0],data[1],data[2],data[3],data[4],data[5])):pathCommand==="Z"&&(data=[lastX,lastY,mx3,my3],point7={x:mx3,y:my3},length4=getLineLength(data[0],data[1],data[2],data[3])),[x4,y4]=data.slice(-2),totalLength<distance8)POINT=point7;else return!1;totalLength+=length4}),distance8>totalLength-1e-5?{x:x4,y:y4}:POINT)},getPropertiesAtLength=(pathInput,distance8)=>{let pathArray=parsePathString(pathInput),pathTemp=pathArray.slice(0),pathLength4=getTotalLength(pathTemp),index=pathTemp.length-1,lengthAtSegment=0,length4=0,segment2=pathArray[0];if(index<=0||!distance8||!Number.isFinite(distance8))return{segment:segment2,index:0,length:length4,lengthAtSegment};if(distance8>=pathLength4)return pathTemp=pathArray.slice(0,-1),lengthAtSegment=getTotalLength(pathTemp),length4=pathLength4-lengthAtSegment,segment2=pathArray[index],{segment:segment2,index,length:length4,lengthAtSegment};let segments=[];for(;index>0;)segment2=pathTemp[index],pathTemp=pathTemp.slice(0,-1),lengthAtSegment=getTotalLength(pathTemp),length4=pathLength4-lengthAtSegment,pathLength4=lengthAtSegment,segments.push({segment:segment2,index,length:length4,lengthAtSegment}),index-=1;return segments.find(({lengthAtSegment:l4})=>l4<=distance8)},getPropertiesAtPoint=(pathInput,point7)=>{let path=parsePathString(pathInput),normalPath=normalizePath(path),pathLength4=getTotalLength(normalPath),distanceTo=p4=>{let dx3=p4.x-point7.x,dy3=p4.y-point7.y;return dx3*dx3+dy3*dy3},precision=8,scan,closest={x:0,y:0},scanDistance=0,bestLength=0,bestDistance=1/0;for(let scanLength=0;scanLength<=pathLength4;scanLength+=precision)scan=getPointAtLength(normalPath,scanLength),scanDistance=distanceTo(scan),scanDistance<bestDistance&&(closest=scan,bestLength=scanLength,bestDistance=scanDistance);precision/=2;let before,after,beforeLength=0,afterLength=0,beforeDistance=0,afterDistance=0;for(;precision>1e-6&&(beforeLength=bestLength-precision,before=getPointAtLength(normalPath,beforeLength),beforeDistance=distanceTo(before),afterLength=bestLength+precision,after=getPointAtLength(normalPath,afterLength),afterDistance=distanceTo(after),beforeLength>=0&&beforeDistance<bestDistance?(closest=before,bestLength=beforeLength,bestDistance=beforeDistance):afterLength<=pathLength4&&afterDistance<bestDistance?(closest=after,bestLength=afterLength,bestDistance=afterDistance):precision/=2,!(precision<1e-5)););let segment2=getPropertiesAtLength(path,bestLength);return{closest,distance:Math.sqrt(bestDistance),segment:segment2}},getClosestPoint=(pathInput,point7)=>getPropertiesAtPoint(pathInput,point7).closest,getCubicSegArea=(x12,y12,c1x,c1y,c2x,c2y,x22,y22)=>3*((y22-y12)*(c1x+c2x)-(x22-x12)*(c1y+c2y)+c1y*(x12-c2x)-c1x*(y12-c2y)+y22*(c2x+x12/3)-x22*(c2y+y12/3))/20,getPathArea=path=>{let x4=0,y4=0,len=0;return pathToCurve(path).map(seg=>seg[0]==="M"?([,x4,y4]=seg,0):(len=getCubicSegArea(x4,y4,seg[1],seg[2],seg[3],seg[4],seg[5],seg[6]),[x4,y4]=seg.slice(-2),len)).reduce((a3,b3)=>a3+b3,0)},getDrawDirection=path=>getPathArea(pathToCurve(path))>=0,getSegmentAtLength=(pathInput,distance8)=>getPropertiesAtLength(pathInput,distance8).segment,getSegmentOfPoint=(path,point7)=>getPropertiesAtPoint(path,point7).segment,isPathArray=path=>Array.isArray(path)&&path.every(seg=>{let lk2=seg[0].toLowerCase();return paramsCounts[lk2]===seg.length-1&&"achlmqstvz".includes(lk2)&&seg.slice(1).every(Number.isFinite)})&&path.length>0,isAbsoluteArray=path=>isPathArray(path)&&path.every(([x4])=>x4===x4.toUpperCase()),isNormalizedArray=path=>isAbsoluteArray(path)&&path.every(([pc3])=>"ACLMQZ".includes(pc3)),isPolygonArray=path=>isNormalizedArray(path)&&path.every(([pc3])=>"MLVHZ".includes(pc3)),isCurveArray=path=>isNormalizedArray(path)&&path.every(([pc3])=>"MC".includes(pc3)),isPointInStroke=(pathInput,point7)=>{let{distance:distance8}=getPropertiesAtPoint(pathInput,point7);return Math.abs(distance8)<DISTANCE_EPSILON},isRelativeArray=path=>isPathArray(path)&&path.slice(1).every(([pc3])=>pc3===pc3.toLowerCase()),isValidPath=pathString=>{if(typeof pathString!="string"||!pathString.length)return!1;let path=new PathParser(pathString);for(skipSpaces(path);path.index<path.max&&!path.err.length;)scanSegment(path);return!path.err.length&&"mM".includes(path.segments[0][0])};function samplePolygon(path){let points=[],[mx3,my3]=[0,0];return iterate(path,seg=>{let cmd=seg[0];if(cmd==="M")[mx3,my3]=[seg[1],seg[2]],points.push([mx3,my3]);else if(cmd==="L")points.push([seg[1],seg[2]]);else if(cmd==="C")points.push([seg[5],seg[6]]);else if(cmd==="A")points.push([seg[6],seg[7]]);else if(cmd==="Z")points.push([mx3,my3]);else throw new TypeError(`${error}: path command "${cmd}" is not supported`)}),points}var shapeParams={line:["x1","y1","x2","y2"],circle:["cx","cy","r"],ellipse:["cx","cy","rx","ry"],rect:["width","height","x","y","rx","ry"],polygon:["points"],polyline:["points"],glyph:["d"]},isElement=node=>node!=null&&typeof node=="object"&&node.nodeType===1,getLinePath=attr=>{let{x1:x12,y1:y12,x2:x22,y2:y22}=attr;return[x12,y12,x22,y22]=[x12,y12,x22,y22].map(a3=>+a3),[["M",x12,y12],["L",x22,y22]]},getPolyPath=attr=>{let pathArray=[],points=(attr.points||"").trim().split(/[\s|,]/).map(a3=>+a3),index=0;for(;index<points.length;)pathArray.push([index?"L":"M",points[index],points[index+1]]),index+=2;return attr.type==="polygon"?[...pathArray,["z"]]:pathArray},getCirclePath=attr=>{let{cx:cx3,cy:cy3,r:r5}=attr;return[cx3,cy3,r5]=[cx3,cy3,r5].map(a3=>+a3),[["M",cx3-r5,cy3],["a",r5,r5,0,1,0,2*r5,0],["a",r5,r5,0,1,0,-2*r5,0]]},getEllipsePath=attr=>{let{cx:cx3,cy:cy3}=attr,rx3=attr.rx||0,ry3=attr.ry||rx3;return[cx3,cy3,rx3,ry3]=[cx3,cy3,rx3,ry3].map(a3=>+a3),[["M",cx3-rx3,cy3],["a",rx3,ry3,0,1,0,2*rx3,0],["a",rx3,ry3,0,1,0,-2*rx3,0]]},getRectanglePath=attr=>{let x4=+attr.x||0,y4=+attr.y||0,w4=+attr.width,h6=+attr.height,rx3=+(attr.rx||0),ry3=+(attr.ry||rx3);return rx3||ry3?(rx3*2>w4&&(rx3-=(rx3*2-w4)/2),ry3*2>h6&&(ry3-=(ry3*2-h6)/2),[["M",x4+rx3,y4],["h",w4-rx3*2],["s",rx3,0,rx3,ry3],["v",h6-ry3*2],["s",0,ry3,-rx3,ry3],["h",-w4+rx3*2],["s",-rx3,0,-rx3,-ry3],["v",-h6+ry3*2],["s",0,-ry3,rx3,-ry3]]):[["M",x4,y4],["h",w4],["v",h6],["H",x4],["Z"]]},shapeToPathArray=element=>{let supportedShapes=Object.keys(shapeParams),targetIsElement=isElement(element),tagName=targetIsElement?element.tagName:null;if(tagName&&[...supportedShapes,"path"].every(s3=>tagName!==s3))throw TypeError(`${error}: "${tagName}" is not SVGElement`);let type=targetIsElement?tagName:element.type,shapeAttrs=shapeParams[type],config={type};targetIsElement?shapeAttrs.forEach(p4=>{config[p4]=element.getAttribute(p4)}):Object.assign(config,element);let pathArray=[];return type==="circle"?pathArray=getCirclePath(config):type==="ellipse"?pathArray=getEllipsePath(config):["polyline","polygon"].includes(type)?pathArray=getPolyPath(config):type==="rect"?pathArray=getRectanglePath(config):type==="line"?pathArray=getLinePath(config):["glyph","path"].includes(type)&&(pathArray=parsePathString(targetIsElement?element.getAttribute("d")||"":element.d||"")),isPathArray(pathArray)&&pathArray.length?pathArray:!1},shapeToPath=(element,replace,ownerDocument)=>{let doc=ownerDocument||document,supportedShapes=Object.keys(shapeParams),targetIsElement=isElement(element),tagName=targetIsElement?element.tagName:null;if(tagName==="path")throw TypeError(`${error}: "${tagName}" is already SVGPathElement`);if(tagName&&supportedShapes.every(s3=>tagName!==s3))throw TypeError(`${error}: "${tagName}" is not SVGElement`);let path=doc.createElementNS("http://www.w3.org/2000/svg","path"),type=targetIsElement?tagName:element.type,shapeAttrs=shapeParams[type],config={type},round=defaultOptions2.round,pathArray=shapeToPathArray(element),description=pathArray&&pathArray.length?pathToString(pathArray,round):"";if(targetIsElement){shapeAttrs.forEach(p4=>{config[p4]=element.getAttribute(p4)});for(let i3=0;i3<element.attributes.length;i3++){let attr=element.attributes[i3];attr&&!shapeAttrs.includes(attr.name)&&path.setAttribute(attr.name,attr.value)}}else Object.assign(config,element),Object.keys(config).forEach(k4=>{!shapeAttrs.includes(k4)&&k4!=="type"&&path.setAttribute(k4.replace(/[A-Z]/g,m4=>`-${m4.toLowerCase()}`),config[k4])});return isValidPath(description)?(path.setAttribute("d",description),replace&&targetIsElement&&(element.before(path,element),element.remove()),path):!1},isMultiPath=path=>{if(typeof path=="string"){let matches=path.match(/[Mm]/g);return matches?matches.length>1:!1}if(isPathArray(path)){let moveCount=0;for(let segment2 of path)if(segment2[0].toUpperCase()==="M"&&(moveCount++,moveCount>1))return!0;return!1}throw new TypeError(error+": expected string or PathArray")};function isPolylineArray(path){return isNormalizedArray(path)&&path.every(([pc3])=>"MLVH".includes(pc3))}var isClosedPath=path=>path[path.length-1][0].toUpperCase()==="Z",shortenSegment=(segment2,normalSegment,params,prevCommand)=>{let[pathCommand]=segment2,{round:defaultRound}=defaultOptions2,round=typeof defaultRound=="number"?defaultRound:4,normalValues=normalSegment.slice(1),{x1:x12,y1:y12,x2:x22,y2:y22,x:x4,y:y4}=params,[nx3,ny3]=normalValues.slice(-2),result=segment2;if("TQ".includes(pathCommand)||(params.qx=null,params.qy=null),pathCommand==="L"){if(roundTo(x4,round)===roundTo(nx3,round))return["V",ny3];if(roundTo(y4,round)===roundTo(ny3,round))return["H",nx3]}else if(pathCommand==="C"){let[nx1,ny1]=normalValues;if(params.x1=nx1,params.y1=ny1,"CS".includes(prevCommand)&&(roundTo(nx1,round)===roundTo(x12*2-x22,round)&&roundTo(ny1,round)===roundTo(y12*2-y22,round)||roundTo(x12,round)===roundTo(x22*2-x4,round)&&roundTo(y12,round)===roundTo(y22*2-y4,round)))return["S",normalValues[2],normalValues[3],normalValues[4],normalValues[5]]}else if(pathCommand==="Q"){let[qx3,qy3]=normalValues;if(params.qx=qx3,params.qy=qy3,"QT".includes(prevCommand)&&roundTo(qx3,round)===roundTo(x12*2-x22,round)&&roundTo(qy3,round)===roundTo(y12*2-y22,round))return["T",normalValues[2],normalValues[3]]}return result},roundSegment=(segment2,roundOption)=>{let values=segment2.slice(1).map(n4=>roundTo(n4,roundOption));return[segment2[0]].concat(values)},optimizePath=(pathInput,roundOption)=>{let path=pathToAbsolute(pathInput),round=typeof roundOption=="number"&&roundOption>=0?roundOption:2,optimParams={...paramsParser},allPathCommands=[],pathCommand="M",prevCommand="Z";return iterate(path,(seg,i3,lastX,lastY)=>{optimParams.x=lastX,optimParams.y=lastY;let normalizedSegment=normalizeSegment(seg,optimParams),result=seg;if(pathCommand=seg[0],allPathCommands[i3]=pathCommand,i3){prevCommand=allPathCommands[i3-1];let shortSegment=shortenSegment(seg,normalizedSegment,optimParams,prevCommand),absSegment=roundSegment(shortSegment,round),absString=absSegment.join(""),relSegment=roundSegment(relativizeSegment(shortSegment,i3,lastX,lastY),round),relString=relSegment.join("");result=absString.length<relString.length?absSegment:relSegment}let seglen=normalizedSegment.length;return optimParams.x1=+normalizedSegment[seglen-2],optimParams.y1=+normalizedSegment[seglen-1],optimParams.x2=+normalizedSegment[seglen-4]||optimParams.x1,optimParams.y2=+normalizedSegment[seglen-3]||optimParams.y1,result})},reversePath=pathInput=>{let absolutePath=pathToAbsolute(pathInput),normalizedPath=normalizePath(absolutePath),pLen=absolutePath.length,isClosed=absolutePath[pLen-1][0]==="Z",reversedPath=iterate(absolutePath,(segment2,i3)=>{let normalizedSegment=normalizedPath[i3],prevSeg=i3&&absolutePath[i3-1],prevCommand=prevSeg&&prevSeg[0],nextSeg=absolutePath[i3+1],nextCommand=nextSeg&&nextSeg[0],pathCommand=segment2[0],[x4,y4]=normalizedPath[i3?i3-1:pLen-1].slice(-2),result=segment2;switch(pathCommand){case"M":result=isClosed?["Z"]:[pathCommand,x4,y4];break;case"A":result=[pathCommand,segment2[1],segment2[2],segment2[3],segment2[4],segment2[5]===1?0:1,x4,y4];break;case"C":nextSeg&&nextCommand==="S"?result=["S",segment2[1],segment2[2],x4,y4]:result=[pathCommand,segment2[3],segment2[4],segment2[1],segment2[2],x4,y4];break;case"S":prevCommand&&"CS".includes(prevCommand)&&(!nextSeg||nextCommand!=="S")?result=["C",normalizedSegment[3],normalizedSegment[4],normalizedSegment[1],normalizedSegment[2],x4,y4]:result=[pathCommand,normalizedSegment[1],normalizedSegment[2],x4,y4];break;case"Q":nextSeg&&nextCommand==="T"?result=["T",x4,y4]:result=[pathCommand,segment2[1],segment2[2],x4,y4];break;case"T":prevCommand&&"QT".includes(prevCommand)&&(!nextSeg||nextCommand!=="T")?result=["Q",normalizedSegment[1],normalizedSegment[2],x4,y4]:result=[pathCommand,x4,y4];break;case"Z":result=["M",x4,y4];break;case"H":result=[pathCommand,x4];break;case"V":result=[pathCommand,y4];break;default:result=[pathCommand].concat(segment2.slice(1,-2),x4,y4)}return result});return isClosed?reversedPath.reverse():[reversedPath[0]].concat(reversedPath.slice(1).reverse())},splitPath=pathInput=>{let composite=[],parsedPath=parsePathString(pathInput),path=[],pi3=-1,x4=0,y4=0,mx3=0,my3=0;return iterate(parsedPath,(seg,_4,prevX,prevY)=>{let cmd=seg[0],absCommand=cmd.toUpperCase(),isRelative=cmd===cmd.toLowerCase(),values=seg.slice(1);absCommand==="M"?(pi3+=1,[x4,y4]=values,x4+=isRelative?prevX:0,y4+=isRelative?prevY:0,mx3=x4,my3=y4,path=[isRelative?[absCommand,mx3,my3]:seg]):(absCommand==="Z"?(x4=mx3,y4=my3):absCommand==="H"?([,x4]=seg,x4+=isRelative?prevX:0):absCommand==="V"?([,y4]=seg,y4+=isRelative?prevY:0):([x4,y4]=seg.slice(-2),x4+=isRelative?prevX:0,y4+=isRelative?prevY:0),path.push(seg)),composite[pi3]=path}),composite},getSVGMatrix=transform6=>{let matrix2=new h,{origin}=transform6,[originX,originY]=origin,{translate:translate5}=transform6,{rotate:rotate4}=transform6,{skew}=transform6,{scale:scale5}=transform6;return Array.isArray(translate5)&&translate5.length>=2&&translate5.every(x4=>!Number.isNaN(+x4))&&translate5.some(x4=>x4!==0)?matrix2=matrix2.translate(...translate5):typeof translate5=="number"&&!Number.isNaN(translate5)&&(matrix2=matrix2.translate(translate5)),(rotate4||skew||scale5)&&(matrix2=matrix2.translate(originX,originY),Array.isArray(rotate4)&&rotate4.length>=2&&rotate4.every(x4=>!Number.isNaN(+x4))&&rotate4.some(x4=>x4!==0)?matrix2=matrix2.rotate(...rotate4):typeof rotate4=="number"&&!Number.isNaN(rotate4)&&(matrix2=matrix2.rotate(rotate4)),Array.isArray(skew)&&skew.length===2&&skew.every(x4=>!Number.isNaN(+x4))&&skew.some(x4=>x4!==0)?(matrix2=skew[0]?matrix2.skewX(skew[0]):matrix2,matrix2=skew[1]?matrix2.skewY(skew[1]):matrix2):typeof skew=="number"&&!Number.isNaN(skew)&&(matrix2=matrix2.skewX(skew)),Array.isArray(scale5)&&scale5.length>=2&&scale5.every(x4=>!Number.isNaN(+x4))&&scale5.some(x4=>x4!==1)?matrix2=matrix2.scale(...scale5):typeof scale5=="number"&&!Number.isNaN(scale5)&&(matrix2=matrix2.scale(scale5)),matrix2=matrix2.translate(-originX,-originY)),matrix2},translatePoint=(cssm,v4)=>{let m4=h.Translate(v4[0],v4[1],v4[2]);return[,,,m4.m44]=v4,m4=cssm.multiply(m4),[m4.m41,m4.m42,m4.m43,m4.m44]},projection2d=(m4,point2D,origin)=>{let[originX,originY,originZ]=origin,[x4,y4,z4]=translatePoint(m4,[point2D[0],point2D[1],0,1]),relativePositionX=x4-originX,relativePositionY=y4-originY,relativePositionZ=z4-originZ;return[relativePositionX*(Math.abs(originZ)/Math.abs(relativePositionZ)||1)+originX,relativePositionY*(Math.abs(originZ)/Math.abs(relativePositionZ)||1)+originY]},transformPath=(pathInput,transform6)=>{let x4=0,y4=0,lx3=0,ly3=0,j4=0,jj2=0,path=parsePathString(pathInput),transformProps=transform6&&Object.keys(transform6);if(!transform6||transformProps&&!transformProps.length)return path.slice(0);transform6.origin||Object.assign(transform6,{origin:defaultOptions2.origin});let origin=transform6.origin,matrixInstance=getSVGMatrix(transform6);return matrixInstance.isIdentity?path.slice(0):iterate(path,(seg,index,lastX,lastY)=>{let[pathCommand]=seg,absCommand=pathCommand.toUpperCase(),absoluteSegment=absCommand!==pathCommand?absolutizeSegment(seg,index,lastX,lastY):seg.slice(0),result=absCommand==="A"?["C"].concat(arcToCubic(lastX,lastY,absoluteSegment[1],absoluteSegment[2],absoluteSegment[3],absoluteSegment[4],absoluteSegment[5],absoluteSegment[6],absoluteSegment[7])):absCommand==="V"?["L",lastX,absoluteSegment[1]]:absCommand==="H"?["L",absoluteSegment[1],lastY]:absoluteSegment;pathCommand=result[0];let isLongArc=pathCommand==="C"&&result.length>7,tempSegment=isLongArc?result.slice(0,7):result.slice(0);if(isLongArc&&(path.splice(index+1,0,["C"].concat(result.slice(7))),result=tempSegment),pathCommand==="L")[lx3,ly3]=projection2d(matrixInstance,[result[1],result[2]],origin),x4!==lx3&&y4!==ly3?result=["L",lx3,ly3]:y4===ly3?result=["H",lx3]:x4===lx3&&(result=["V",ly3]);else for(j4=1,jj2=result.length;j4<jj2;j4+=2)[lx3,ly3]=projection2d(matrixInstance,[+result[j4],+result[j4+1]],origin),result[j4]=lx3,result[j4+1]=ly3;return x4=lx3,y4=ly3,result})},reverseCurve=path=>{let rotatedCurve=path.slice(1).map((x4,i3,curveOnly)=>i3?curveOnly[i3-1].slice(-2).concat(x4.slice(1)):path[0].slice(1).concat(x4.slice(1))).map(x4=>x4.map((_4,i3)=>x4[x4.length-i3-2*(1-i3%2)])).reverse();return[["M"].concat(rotatedCurve[0].slice(0,2))].concat(rotatedCurve.map(x4=>["C"].concat(x4.slice(2))))},roundPath=(path,roundOption)=>{let{round}=defaultOptions2;return round=roundOption==="off"||typeof roundOption=="number"&&roundOption>=0?roundOption:typeof round=="number"&&round>=0?round:"off",round==="off"?path.slice(0):iterate(path,segment2=>roundSegment(segment2,round))},fixPath=pathInput=>{let pathArray=parsePathString(pathInput);if(isClosedPath(pathArray)){let normalArray=normalizePath(pathArray),length4=pathArray.length,segBeforeZ=length4-2,[mx3,my3]=normalArray[0].slice(1),[x4,y4]=normalArray[segBeforeZ].slice(-2);mx3===x4&&my3===y4&&pathArray.splice(length4-1,1)}};function splitCubicSegment(x12,y12,x22,y22,x32,y32,x4,y4,t52){let[px01,py01]=midPoint([x12,y12],[x22,y22],t52),[px12,py12]=midPoint([x22,y22],[x32,y32],t52),[px23,py23]=midPoint([x32,y32],[x4,y4],t52),[cx0,cy0]=midPoint([px01,py01],[px12,py12],t52),[cx1,cy1]=midPoint([px12,py12],[px23,py23],t52),[px3,py3]=midPoint([cx0,cy0],[cx1,cy1],t52);return[[x12,y12,px01,py01,cx0,cy0,px3,py3],[px3,py3,cx1,cy1,px23,py23,x4,y4]]}var pathToPolyline=path=>{let normal=normalizePath(path);if(!isPolygonArray(normal)&&!isPolylineArray(normal))throw TypeError(`${error}: pathValue is not a polyline/polygon`);if(!isClosedPath(normal))return normal;let result=[normal[0]],[mx3,my3]=normal[0].slice(1);for(let i3=1;i3<normal.length;i3++){let seg=normal[i3];seg[0].toUpperCase()==="Z"?result.push(["L",mx3,my3]):result.push(seg)}return result};function splitLineToCount(x12,y12,x22,y22,count){if(count<=1)return[[x12,y12,x22,y22]];let result=[],dx3=x22-x12,dy3=y22-y12,currentX=x12,currentY=y12,i3=0;for(;i3<count;){let t52=1/(count-i3),nextX=x12+t52*dx3,nextY=y12+t52*dy3;result.push([currentX,currentY,nextX,nextY]),currentX=nextX,currentY=nextY,i3++}return result}function getPathSplits(path,target){if(target<=1)throw new TypeError(`${error}: target must be >= 2`);let totalLength=getTotalLength(path);if(totalLength===0)return Array(path.length).fill(1);let idealSegLen=totalLength/target,isPoly=isPolylineArray(path),splits=[1],lengths=[0];iterate(path,(seg,i3,prevX,prevY)=>{if(i3>0){let[endX,endY]=seg.slice(-2),segLen=isPoly?getLineLength(prevX,prevY,endX,endY):getCubicLength(prevX,prevY,seg[1],seg[2],seg[3],seg[4],seg[5],seg[6]);lengths.push(segLen),splits.push(1)}});let totalAllocated=1;for(let i3=1;i3<lengths.length;i3++){let segLen=lengths[i3],desired=segLen>idealSegLen?Math.round(segLen/idealSegLen):1;splits[i3]=desired,totalAllocated+=desired}let diff=target-totalAllocated;if(diff!==0){let candidates=[];for(let i3=1;i3<lengths.length;i3++)lengths[i3]>0&&candidates.push([i3,lengths[i3]]);let cLen=candidates.length;if(diff<0){candidates.sort((a3,b3)=>a3[1]-b3[1]);for(let i3=0;i3<cLen;i3++){let idx=candidates[i3][0];if(splits[idx]>1&&candidates[i3][1]>0&&(splits[idx]--,diff++),diff===0)break;i3===cLen-1&&(i3=0)}}else if(diff>0){candidates.sort((a3,b3)=>b3[1]-a3[1]);for(let i3=0;i3<cLen;i3++){let idx=candidates[i3][0];if(candidates[i3][1]>0&&(splits[idx]++,diff--),diff===0)break;i3===cLen-1&&(i3=0)}}}return splits}function splitLinePathToCount(path,target){if(path.length<2||target<=1)return path;let splits=getPathSplits(path,target),totalAdded=0,newPath=[path[0]],pathLen=path.length,currentX=path[0][1],currentY=path[0][2];for(let i3=1;i3<pathLen;i3++){let[endX,endY]=path[i3].slice(1),count=splits[i3];if(count>=1){let subLines=splitLineToCount(currentX,currentY,endX,endY,count);for(let sub of subLines)newPath.push(["L",sub[2],sub[3]]),totalAdded++}currentX=endX,currentY=endY}return newPath.length!==target&&console.warn(`${error}: requested ${target} segments, got ${newPath.length}. Adjusted on last segment.`),newPath}function splitCubicToCount(x12,y12,x22,y22,x32,y32,x4,y4,count){if(count<=1)return[[x12,y12,x22,y22,x32,y32,x4,y4]];let result=[],cx1=x12,cy1=y12,cx22=x22,cy22=y22,cx3=x32,cy3=y32,cx4=x4,cy4=y4,i3=0;for(;i3<count;){let t52=1/(count-i3),[first,second]=splitCubicSegment(cx1,cy1,cx22,cy22,cx3,cy3,cx4,cy4,t52);result.push(first),[cx1,cy1,cx22,cy22,cx3,cy3,cx4,cy4]=second,i3++}return result}function splitCurvePathToCount(path,target){if(path.length<2||target<=1)return path;let splits=getPathSplits(path,target),totalAdded=0,newPath=[path[0]],pathLen=path.length,currentX=path[0][1],currentY=path[0][2];for(let i3=1;i3<pathLen;i3++){let seg=path[i3],[endX,endY]=seg.slice(-2),count=splits[i3];if(count>=1){let subs=splitCubicToCount(currentX,currentY,seg[1],seg[2],seg[3],seg[4],seg[5],seg[6],count);for(let sub of subs)newPath.push(["C",sub[2],sub[3],sub[4],sub[5],sub[6],sub[7]]),totalAdded++}currentX=endX,currentY=endY}return newPath.length!==target&&console.warn(`${error}: requested ${target} segments, got ${newPath.length}.`),newPath}function getRotations(a3){let pathLen=a3.length,pointCount=pathLen-1,path,result=[];for(let idx=0;idx<pathLen;idx++){path=[];for(let i3=0;i3<pathLen;i3++){let oldSegIdx=idx+i3,seg;if(i3===0||a3[oldSegIdx]&&a3[oldSegIdx][0]==="M"){seg=a3[oldSegIdx],path.push(["M",...seg.slice(-2)]);continue}oldSegIdx>=pathLen&&(oldSegIdx-=pointCount),path.push(a3[oldSegIdx])}result.push(path)}return result}function getRotatedPath(pathA,pathB,computedRotations){let rotations=computedRotations||getRotations(pathA);if(pathA.length!==pathB.length)throw new TypeError(error+": paths must have the same number of segments after equalization");let bestIndex=0,minDistanceSq=1/0;for(let ri3=0;ri3<rotations.length;ri3++){let rotation5=rotations[ri3],rLen=rotation5.length,sumDistSq=0;for(let i3=0;i3<rLen;i3++){let segA=rotation5[i3],segB=pathB[i3],endA=segA.slice(-2),endB=segB.slice(-2),dx3=endA[0]-endB[0],dy3=endA[1]-endB[1];sumDistSq+=dx3*dx3+dy3*dy3}sumDistSq<minDistanceSq&&(minDistanceSq=sumDistSq,bestIndex=ri3)}return rotations[bestIndex]}var equalizeSegmentsDefaults={mode:"auto",sampleSize:10,roundValues:4,reverse:!0,close:!1,target:void 0},equalizeSegments=(path1,path2,initialCfg={})=>{let{close,mode,reverse,roundValues,target:initialTarget}=Object.assign(equalizeSegmentsDefaults,initialCfg),p12=normalizePath(path1),p22=normalizePath(path2);fixPath(p12),fixPath(p22);let bothPoly=(isPolygonArray(p12)||isPolylineArray(p12))&&(isPolygonArray(p22)||isPolylineArray(p22));bothPoly&&mode==="auto"?(p12=pathToPolyline(p12),p22=pathToPolyline(p22)):(bothPoly=!1,p12=pathToCurve(p12),p22=pathToCurve(p22));let area1=polygonArea(samplePolygon(p12)),area2=polygonArea(samplePolygon(p22));reverse!==!1&&Math.sign(area1)!==Math.sign(area2)&&(p22=reversePath(p22));let segCount1=p12.length,segCount2=p22.length,minTarget=Math.max(segCount1,segCount2),target=minTarget;if(typeof initialTarget!="number"){let avgLen=(getTotalLength(p12)+getTotalLength(p22))/2,avgSegLen=avgLen/Math.max(segCount1,segCount2),idealSegCount=Math.max(minTarget,Math.round(avgLen/Math.max(avgSegLen,1)));target=Math.min(idealSegCount,Math.max(segCount1,segCount2)*3)}else initialTarget>=minTarget?target=initialTarget:console.warn('equalizeSegments "target" option: '+initialTarget+", expected >= "+minTarget);let equalP1=p12,equalP2=p22;return bothPoly?(equalP1=splitLinePathToCount(p12,target),equalP2=splitLinePathToCount(p22,target)):(equalP1=splitCurvePathToCount(p12,target),equalP2=splitCurvePathToCount(p22,target)),equalP2=getRotatedPath(equalP2,equalP1),typeof roundValues=="number"&&roundValues!==4&&(equalP1=roundPath(equalP1,roundValues),equalP2=roundPath(equalP2,roundValues)),close&&(equalP1.push(["Z"]),equalP2.push(["Z"])),[equalP1,equalP2]},isPointInsideBBox=(bbox,[x4,y4])=>{let[minX,minY,maxX,maxY]=bbox;return x4>=minX&&x4<=maxX&&y4>=minY&&y4<=maxY},boundingBoxIntersect=(a3,b3)=>{let[ax1,ay1,ax22,ay22]=a3,[bx1,by1,bx22,by22]=b3;return isPointInsideBBox(b3,[ax1,ay1])||isPointInsideBBox(b3,[ax22,ay1])||isPointInsideBBox(b3,[ax1,ay22])||isPointInsideBBox(b3,[ax22,ay22])||isPointInsideBBox(a3,[bx1,by1])||isPointInsideBBox(a3,[bx22,by1])||isPointInsideBBox(a3,[bx1,by22])||isPointInsideBBox(a3,[bx22,by22])||(ax1<bx22&&ax1>bx1||bx1<ax22&&bx1>ax1)&&(ay1<by22&&ay1>by1||by1<ay22&&by1>ay1)},createPlaceholder=([atx,aty])=>[["M",atx,aty],["L",atx+.001,aty],["L",atx+.001,aty+.001],["L",atx,aty+.001],["L",atx,aty],["Z"]];function getBestMatch(target,candidates){let targetBBox=target.bbox,potentialCandidates=[];for(let i3=0;i3<candidates.length;i3++){let{bbox,size:size3}=candidates[i3],dx3=targetBBox.cx-bbox.cx,dy3=targetBBox.cy-bbox.cy,centeredDistance=Math.sqrt(dx3*dx3+dy3*dy3),sizeDifference=Math.abs(target.size-size3)/Math.max(target.size,size3,1e-6),hasOverlap=isPointInsideBBox([targetBBox.x,targetBBox.y,targetBBox.x2,targetBBox.y2],[bbox.cx,bbox.cy])||isPointInsideBBox([bbox.x,bbox.y,bbox.x2,bbox.y2],[targetBBox.cx,targetBBox.cy]),boxIntersect=boundingBoxIntersect([targetBBox.x,targetBBox.y,targetBBox.x2,targetBBox.y2],[bbox.x,bbox.y,bbox.x2,bbox.y2]);potentialCandidates.push({index:i3,hasOverlap,boxIntersect,sizeDifference,centeredDistance})}let overlaping=potentialCandidates.filter(c4=>c4.hasOverlap&&c4.boxIntersect);if(overlaping.length>0){let best=overlaping[0];for(let i3=1;i3<overlaping.length;i3++)overlaping[i3].centeredDistance<best.centeredDistance&&(best=overlaping[i3]);return candidates.splice(best.index,1)[0]}return null}function matchPaths(fromPaths,toPaths){let pairs5=[];for(fromPaths.sort((a3,b3)=>b3.size-a3.size),toPaths.sort((a3,b3)=>b3.size-a3.size);fromPaths.length>0;){let from=fromPaths.shift(),bestTo=getBestMatch(from,toPaths);if(bestTo)pairs5.push([from.path,bestTo.path]);else{let fromCentroid=[from.bbox.cx,from.bbox.cy];pairs5.push([from.path,createPlaceholder(fromCentroid)])}}for(;toPaths.length>0;){let to3=toPaths.shift(),toCentroid=[to3.bbox.cx,to3.bbox.cy];pairs5.push([createPlaceholder(toCentroid),to3.path])}return pairs5}var classifyPaths=paths=>{let outers=[],inners=[];for(let path of paths){let signedArea3=polygonArea(samplePolygon(path)),bbox=getPathBBox(path),feature={isPoly:isPolygonArray(path)||isPolylineArray(path),size:bbox.width*bbox.height,path,signedArea:signedArea3,area:Math.abs(signedArea3),bbox};signedArea3>0?outers.push(feature):inners.push(feature)}return{outers,inners}},equalizePathsDefaults={mode:"auto",roundValues:4,close:!1,sampleSize:10},equalizePaths=(pathInput1,pathInput2,initialCfg={})=>{let cfg=Object.assign(equalizePathsDefaults,initialCfg),p12=normalizePath(pathInput1),p22=normalizePath(pathInput2),multi1=isMultiPath(p12),multi2=isMultiPath(p22);if(!multi1&&!multi2)return equalizeSegments(p12,p22,cfg);let globalArea1=polygonArea(samplePolygon(p12)),globalArea2=polygonArea(samplePolygon(p22)),path1=p12,path2=p22;Math.sign(globalArea1)<0&&(path1=reversePath(path1)),Math.sign(globalArea2)<0&&(path2=reversePath(path2));let multiPath1=splitPath(path1),multiPath2=splitPath(path2),{outers:outers1,inners:inners1}=classifyPaths(multiPath1),{outers:outers2,inners:inners2}=classifyPaths(multiPath2),outerPairs=matchPaths(outers1,outers2),innerPairs=matchPaths(inners1,inners2),equalizedPairs=[];for(let[from,to3]of[...outerPairs,...innerPairs]){let[eqFrom,eqTo]=equalizeSegments(from,to3,{...cfg,reverse:!1});equalizedPairs.push([eqFrom,eqTo])}return[equalizedPairs.map(p4=>p4[0]).flat(),equalizedPairs.map(p4=>p4[1]).flat()]},intersect2=(x12,y12,x22,y22,x32,y32,x4,y4)=>{if(Math.max(x12,x22)<Math.min(x32,x4)||Math.min(x12,x22)>Math.max(x32,x4)||Math.max(y12,y22)<Math.min(y32,y4)||Math.min(y12,y22)>Math.max(y32,y4))return;let nx3=(x12*y22-y12*x22)*(x32-x4)-(x12-x22)*(x32*y4-y32*x4),ny3=(x12*y22-y12*x22)*(y32-y4)-(y12-y22)*(x32*y4-y32*x4),denominator=(x12-x22)*(y32-y4)-(y12-y22)*(x32-x4);if(!denominator)return;let px3=nx3/denominator,py3=ny3/denominator,px22=roundTo(px3,2),py22=roundTo(py3,2);if(!(px22<roundTo(Math.min(x12,x22),2)||px22>roundTo(Math.max(x12,x22),2)||px22<roundTo(Math.min(x32,x4),2)||px22>roundTo(Math.max(x32,x4),2)||py22<roundTo(Math.min(y12,y22),2)||py22>roundTo(Math.max(y12,y22),2)||py22<roundTo(Math.min(y32,y4),2)||py22>roundTo(Math.max(y32,y4),2)))return{x:px3,y:py3}},interHelper=(bez1,bez2,config)=>{let bbox1=getCubicBBox(...bez1),bbox2=getCubicBBox(...bez2),{justCount,epsilon}=Object.assign({justCount:!0,epsilon:DISTANCE_EPSILON},config);if(!boundingBoxIntersect(bbox1,bbox2))return justCount?0:[];let l12=getCubicLength(...bez1),l22=getCubicLength(...bez2),n12=Math.max(l12/5>>0,1),n22=Math.max(l22/5>>0,1),points1=[],points2=[],xy3={},res2=justCount?0:[];for(let i3=0;i3<n12+1;i3++){let p4=getPointAtCubicLength(...bez1,i3/n12*l12);points1.push({x:p4.x,y:p4.y,t:i3/n12})}for(let i3=0;i3<n22+1;i3++){let p4=getPointAtCubicLength(...bez2,i3/n22*l22);points2.push({x:p4.x,y:p4.y,t:i3/n22})}for(let i3=0;i3<n12;i3++)for(let j4=0;j4<n22;j4++){let maxLimit=1+epsilon,di3=points1[i3],di1=points1[i3+1],dj2=points2[j4],dj1=points2[j4+1],ci3=Math.abs(di1.x-di3.x)<.001?"y":"x",cj2=Math.abs(dj1.x-dj2.x)<.001?"y":"x",is4=intersect2(di3.x,di3.y,di1.x,di1.y,dj2.x,dj2.y,dj1.x,dj1.y);if(is4){if(xy3[is4.x.toFixed(4)]==is4.y.toFixed(4))continue;xy3[is4.x.toFixed(4)]=is4.y.toFixed(4);let t110=di3.t+Math.abs((is4[ci3]-di3[ci3])/(di1[ci3]-di3[ci3]))*(di1.t-di3.t),t210=dj2.t+Math.abs((is4[cj2]-dj2[cj2])/(dj1[cj2]-dj2[cj2]))*(dj1.t-dj2.t);t110>=0&&t110<=maxLimit&&t210>=0&&t210<=maxLimit&&(justCount?res2++:res2.push({x:is4.x,y:is4.y,t1:Math.min(t110,1),t2:Math.min(t210,1)}))}}return res2},pathsIntersection=(pathInput1,pathInput2,justCount=!0)=>{let path1=pathToCurve(pathInput1),path2=pathToCurve(pathInput2),x12=0,y12=0,x22=0,y22=0,x1m=0,y1m=0,x2m=0,y2m=0,bez1=[x12,y12,x12,y12,x1m,y1m,x1m,y1m],bez2=[x22,y22,x22,y22,x2m,y2m,x2m,y2m],countResult=0,pointsResult=[],pathLen1=path1.length,pathLen2=path2.length;for(let i3=0;i3<pathLen1;i3++){let seg1=path1[i3];if(seg1[0]=="M")x12=seg1[1],y12=seg1[2],x1m=x12,y1m=y12;else{seg1[0]=="C"?(bez1=[x12,y12,seg1[1],seg1[2],seg1[3],seg1[4],seg1[5],seg1[6]],x12=bez1[6],y12=bez1[7]):(bez1=[x12,y12,x12,y12,x1m,y1m,x1m,y1m],x12=x1m,y12=y1m);for(let j4=0;j4<pathLen2;j4++){let seg2=path2[j4];seg2[0]=="M"?(x22=seg2[1],y22=seg2[2],x2m=x22,y2m=y22):seg2[0]=="C"&&(bez2=[x22,y22,seg2[1],seg2[2],seg2[3],seg2[4],seg2[5],seg2[6]],x22=bez2[6],y22=bez2[7]);let intr=interHelper(bez1,bez2,{justCount});justCount?countResult+=intr:pointsResult.push(...intr)}}}return justCount?countResult:pointsResult},_a4,SVGPathCommander=(_a4=class{constructor(pathValue,config){let instanceOptions=config||{},undefPath=typeof pathValue>"u";if(undefPath||!pathValue.length)throw TypeError(`${error}: "pathValue" is ${undefPath?"undefined":"empty"}`);this.segments=parsePathString(pathValue);let{round:roundOption,origin:originOption}=instanceOptions,round;Number.isInteger(roundOption)||roundOption==="off"?round=roundOption:round=defaultOptions2.round;let origin=defaultOptions2.origin;if(Array.isArray(originOption)&&originOption.length>=2){let[originX,originY,originZ]=originOption.map(Number);origin=[Number.isNaN(originX)?0:originX,Number.isNaN(originY)?0:originY,Number.isNaN(originZ)?0:originZ]}return this.round=round,this.origin=origin,this}get bbox(){return getPathBBox(this.segments)}get length(){return getTotalLength(this.segments)}getBBox(){return this.bbox}getTotalLength(){return this.length}getPointAtLength(length4){return getPointAtLength(this.segments,length4)}toAbsolute(){let{segments}=this;return this.segments=pathToAbsolute(segments),this}toRelative(){let{segments}=this;return this.segments=pathToRelative(segments),this}toCurve(){let{segments}=this;return this.segments=pathToCurve(segments),this}reverse(onlySubpath){let{segments}=this,split=splitPath(segments),subPath=split.length>1?split:!1,absoluteMultiPath=subPath?subPath.map((x4,i3)=>onlySubpath?i3?reversePath(x4):x4.slice(0):reversePath(x4)):segments.slice(0),path=[];return subPath?path=absoluteMultiPath.flat(1):path=onlySubpath?segments:reversePath(segments),this.segments=path.slice(0),this}normalize(){let{segments}=this;return this.segments=normalizePath(segments),this}optimize(){let{segments}=this;return this.segments=optimizePath(segments,this.round==="off"?2:this.round),this}transform(source){if(!source||typeof source!="object"||typeof source=="object"&&!["translate","rotate","skew","scale"].some(x4=>x4 in source))return this;let{segments,origin:[cx3,cy3,cz2]}=this,transform6={};for(let[k4,v4]of Object.entries(source))k4==="skew"&&Array.isArray(v4)||(k4==="rotate"||k4==="translate"||k4==="origin"||k4==="scale")&&Array.isArray(v4)?transform6[k4]=v4.map(Number):k4!=="origin"&&typeof Number(v4)=="number"&&(transform6[k4]=Number(v4));let{origin}=transform6;if(Array.isArray(origin)&&origin.length>=2){let[originX,originY,originZ]=origin.map(Number);transform6.origin=[Number.isNaN(originX)?cx3:originX,Number.isNaN(originY)?cy3:originY,originZ||cz2]}else transform6.origin=[cx3,cy3,cz2];return this.segments=transformPath(segments,transform6),this}flipX(){let{cx:cx3,cy:cy3}=this.bbox;return this.transform({rotate:[0,180,0],origin:[cx3,cy3,0]}),this}flipY(){let{cx:cx3,cy:cy3}=this.bbox;return this.transform({rotate:[180,0,0],origin:[cx3,cy3,0]}),this}toString(){return pathToString(this.segments,this.round)}dispose(){Object.keys(this).forEach(key=>delete this[key])}},__publicField(_a4,"options",defaultOptions2),__publicField(_a4,"CSSMatrix",h),__publicField(_a4,"arcTools",arcTools),__publicField(_a4,"bezierTools",bezierTools),__publicField(_a4,"cubicTools",cubicTools),__publicField(_a4,"lineTools",lineTools),__publicField(_a4,"polygonTools",polygonTools),__publicField(_a4,"quadTools",quadTools),__publicField(_a4,"pathToAbsolute",pathToAbsolute),__publicField(_a4,"pathToRelative",pathToRelative),__publicField(_a4,"pathToCurve",pathToCurve),__publicField(_a4,"pathToString",pathToString),__publicField(_a4,"distanceSquareRoot",distanceSquareRoot),__publicField(_a4,"midPoint",midPoint),__publicField(_a4,"rotateVector",rotateVector),__publicField(_a4,"roundTo",roundTo),__publicField(_a4,"parsePathString",parsePathString),__publicField(_a4,"finalizeSegment",finalizeSegment),__publicField(_a4,"invalidPathValue",invalidPathValue),__publicField(_a4,"isArcCommand",isArcCommand),__publicField(_a4,"isDigit",isDigit),__publicField(_a4,"isDigitStart",isDigitStart),__publicField(_a4,"isMoveCommand",isMoveCommand),__publicField(_a4,"isPathCommand",isPathCommand),__publicField(_a4,"isSpace",isSpace),__publicField(_a4,"paramsCount",paramsCounts),__publicField(_a4,"paramsParser",paramsParser),__publicField(_a4,"PathParser",PathParser),__publicField(_a4,"scanFlag",scanFlag),__publicField(_a4,"scanParam",scanParam),__publicField(_a4,"scanSegment",scanSegment),__publicField(_a4,"skipSpaces",skipSpaces),__publicField(_a4,"distanceEpsilon",DISTANCE_EPSILON),__publicField(_a4,"fixPath",fixPath),__publicField(_a4,"getClosestPoint",getClosestPoint),__publicField(_a4,"getDrawDirection",getDrawDirection),__publicField(_a4,"getPathArea",getPathArea),__publicField(_a4,"getPathBBox",getPathBBox),__publicField(_a4,"getPointAtLength",getPointAtLength),__publicField(_a4,"getPropertiesAtLength",getPropertiesAtLength),__publicField(_a4,"getPropertiesAtPoint",getPropertiesAtPoint),__publicField(_a4,"getSegmentAtLength",getSegmentAtLength),__publicField(_a4,"getSegmentOfPoint",getSegmentOfPoint),__publicField(_a4,"getTotalLength",getTotalLength),__publicField(_a4,"isAbsoluteArray",isAbsoluteArray),__publicField(_a4,"isCurveArray",isCurveArray),__publicField(_a4,"isPolygonArray",isPolygonArray),__publicField(_a4,"isNormalizedArray",isNormalizedArray),__publicField(_a4,"isPathArray",isPathArray),__publicField(_a4,"isPointInStroke",isPointInStroke),__publicField(_a4,"isRelativeArray",isRelativeArray),__publicField(_a4,"isValidPath",isValidPath),__publicField(_a4,"samplePolygon",samplePolygon),__publicField(_a4,"shapeParams",shapeParams),__publicField(_a4,"shapeToPath",shapeToPath),__publicField(_a4,"shapeToPathArray",shapeToPathArray),__publicField(_a4,"absolutizeSegment",absolutizeSegment),__publicField(_a4,"arcToCubic",arcToCubic),__publicField(_a4,"getSVGMatrix",getSVGMatrix),__publicField(_a4,"iterate",iterate),__publicField(_a4,"lineToCubic",lineToCubic),__publicField(_a4,"normalizePath",normalizePath),__publicField(_a4,"normalizeSegment",normalizeSegment),__publicField(_a4,"optimizePath",optimizePath),__publicField(_a4,"projection2d",projection2d),__publicField(_a4,"quadToCubic",quadToCubic),__publicField(_a4,"relativizeSegment",relativizeSegment),__publicField(_a4,"reverseCurve",reverseCurve),__publicField(_a4,"reversePath",reversePath),__publicField(_a4,"roundPath",roundPath),__publicField(_a4,"roundSegment",roundSegment),__publicField(_a4,"segmentToCubic",segmentToCubic),__publicField(_a4,"shortenSegment",shortenSegment),__publicField(_a4,"splitPath",splitPath),__publicField(_a4,"equalizePaths",equalizePaths),__publicField(_a4,"equalizeSegments",equalizeSegments),__publicField(_a4,"splitCubicSegment",splitCubicSegment),__publicField(_a4,"transformPath",transformPath),__publicField(_a4,"isPointInsideBBox",isPointInsideBBox),__publicField(_a4,"pathsIntersection",pathsIntersection),__publicField(_a4,"boundingBoxIntersect",boundingBoxIntersect),__publicField(_a4,"isMultiPath",isMultiPath),__publicField(_a4,"isClosedPath",isClosedPath),__publicField(_a4,"isPolylineArray",isPolylineArray),__publicField(_a4,"version",version),_a4),src_default=SVGPathCommander;init_dist();init_dist4();init_dist();var import_react2=__toESM(require_react(),1);init_dist4();init_zod();init_zod();init_dist();function createMap(){return new IndexedMap}var IndexedMap=class _IndexedMap{constructor(){__publicField(this,"index",{});__publicField(this,"array",[])}size(){return this.array.length}empty(){return this.array.length===0}itemAt(index){return this.array[index]}contains(key){return this.index[key.id()]!==void 0}find(key){let i3=this.index[key.id()];return i3===void 0?void 0:this.array[i3]}setDefault(key,factory){let i3=this.index[key.id()];if(i3===void 0){let pair=new Pair(key,factory());return this.index[key.id()]=this.array.length,this.array.push(pair),pair}else return this.array[i3]}insert(key,value){let pair=new Pair(key,value),i3=this.index[key.id()];return i3===void 0?(this.index[key.id()]=this.array.length,this.array.push(pair)):this.array[i3]=pair,pair}erase(key){let i3=this.index[key.id()];if(i3===void 0)return;this.index[key.id()]=void 0;let pair=this.array[i3],last=this.array.pop();return pair!==last&&(this.array[i3]=last,this.index[last.first.id()]=i3),pair}copy(){let copy=new _IndexedMap;for(let i3=0;i3<this.array.length;i3++){let pair=this.array[i3].copy();copy.array[i3]=pair,copy.index[pair.first.id()]=i3}return copy}},Pair=class _Pair{constructor(first,second){__publicField(this,"first");__publicField(this,"second");this.first=first,this.second=second}copy(){return new _Pair(this.first,this.second)}};var Variable=class{constructor(name=""){__publicField(this,"_name");__publicField(this,"_value",0);__publicField(this,"_context",null);__publicField(this,"_id",VarId++);this._name=name}id(){return this._id}name(){return this._name}setName(name){this._name=name}context(){return this._context}setContext(context){this._context=context}value(){return this._value}setValue(value){this._value=value}plus(value){return new Expression(this,value)}minus(value){return new Expression(this,typeof value=="number"?-value:[-1,value])}multiply(coefficient){return new Expression([coefficient,this])}divide(coefficient){return new Expression([1/coefficient,this])}toJSON(){return{name:this._name,value:this._value}}toString(){return this._context+"["+this._name+":"+this._value+"]"}},VarId=0;var Expression=class _Expression{constructor(){__publicField(this,"_terms");__publicField(this,"_constant");let parsed=parseArgs(arguments);this._terms=parsed.terms,this._constant=parsed.constant}terms(){return this._terms}constant(){return this._constant}value(){let result=this._constant;for(let i3=0,n4=this._terms.size();i3<n4;i3++){let pair=this._terms.itemAt(i3);result+=pair.first.value()*pair.second}return result}plus(value){return new _Expression(this,value)}minus(value){return new _Expression(this,typeof value=="number"?-value:[-1,value])}multiply(coefficient){return new _Expression([coefficient,this])}divide(coefficient){return new _Expression([1/coefficient,this])}isConstant(){return this._terms.size()==0}toString(){let result=this._terms.array.map(function(pair){return pair.second+"*"+pair.first.toString()}).join(" + ");return!this.isConstant()&&this._constant!==0&&(result+=" + "),result+=this._constant,result}};function parseArgs(args){let constant=0,factory=()=>0,terms=createMap();for(let i3=0,n4=args.length;i3<n4;++i3){let item=args[i3];if(typeof item=="number")constant+=item;else if(item instanceof Variable)terms.setDefault(item,factory).second+=1;else if(item instanceof Expression){constant+=item.constant();let terms2=item.terms();for(let j4=0,k4=terms2.size();j4<k4;j4++){let termPair=terms2.itemAt(j4);terms.setDefault(termPair.first,factory).second+=termPair.second}}else if(item instanceof Array){if(item.length!==2)throw new Error("array must have length 2");let value=item[0],value2=item[1];if(typeof value!="number")throw new Error("array item 0 must be a number");if(value2 instanceof Variable)terms.setDefault(value2,factory).second+=value;else if(value2 instanceof Expression){constant+=value2.constant()*value;let terms2=value2.terms();for(let j4=0,k4=terms2.size();j4<k4;j4++){let termPair=terms2.itemAt(j4);terms.setDefault(termPair.first,factory).second+=termPair.second*value}}else throw new Error("array item 1 must be a variable or expression")}else throw new Error("invalid Expression argument: "+item)}return{terms,constant}}var _Strength=class _Strength{static create(a3,b3,c4,w4=1){let result=0;return result+=Math.max(0,Math.min(1e3,a3*w4))*1e6,result+=Math.max(0,Math.min(1e3,b3*w4))*1e3,result+=Math.max(0,Math.min(1e3,c4*w4)),result}static clip(value){return Math.max(0,Math.min(_Strength.required,value))}};__publicField(_Strength,"required",_Strength.create(1e3,1e3,1e3)),__publicField(_Strength,"strong",_Strength.create(1,0,0)),__publicField(_Strength,"medium",_Strength.create(0,1,0)),__publicField(_Strength,"weak",_Strength.create(0,0,1));var Strength=_Strength;var Operator;(function(Operator2){Operator2[Operator2.Le=0]="Le",Operator2[Operator2.Ge=1]="Ge",Operator2[Operator2.Eq=2]="Eq"})(Operator||(Operator={}));var Constraint=class{constructor(expression,operator,rhs,strength=Strength.required){__publicField(this,"_expression");__publicField(this,"_operator");__publicField(this,"_strength");__publicField(this,"_id",CnId++);this._operator=operator,this._strength=Strength.clip(strength),rhs===void 0&&expression instanceof Expression?this._expression=expression:this._expression=expression.minus(rhs)}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()+")"}},CnId=0;var Solver=class{constructor(){__publicField(this,"maxIterations",1e3);__publicField(this,"_cnMap",createCnMap());__publicField(this,"_rowMap",createRowMap());__publicField(this,"_varMap",createVarMap());__publicField(this,"_editMap",createEditMap());__publicField(this,"_infeasibleRows",[]);__publicField(this,"_objective",new Row);__publicField(this,"_artificial",null);__publicField(this,"_idTick",0)}createConstraint(lhs,operator,rhs,strength=Strength.required){let cn3=new Constraint(lhs,operator,rhs,strength);return this.addConstraint(cn3),cn3}addConstraint(constraint){if(this._cnMap.find(constraint)!==void 0)throw new Error("duplicate constraint");let data=this._createRow(constraint),row=data.row,tag=data.tag,subject=this._chooseSubject(row,tag);if(subject.type()===SymbolType.Invalid&&row.allDummies())if(nearZero(row.constant()))subject=tag.marker;else throw new Error("unsatisfiable constraint");if(subject.type()===SymbolType.Invalid){if(!this._addWithArtificialVariable(row))throw new Error("unsatisfiable constraint")}else row.solveFor(subject),this._substitute(subject,row),this._rowMap.insert(subject,row);this._cnMap.insert(constraint,tag),this._optimize(this._objective)}removeConstraint(constraint){let cnPair=this._cnMap.erase(constraint);if(cnPair===void 0)throw new Error("unknown constraint");this._removeConstraintEffects(constraint,cnPair.second);let marker=cnPair.second.marker,rowPair=this._rowMap.erase(marker);if(rowPair===void 0){let leaving=this._getMarkerLeavingSymbol(marker);if(leaving.type()===SymbolType.Invalid)throw new Error("failed to find leaving row");rowPair=this._rowMap.erase(leaving),rowPair.second.solveForEx(leaving,marker),this._substitute(marker,rowPair.second)}this._optimize(this._objective)}hasConstraint(constraint){return this._cnMap.contains(constraint)}getConstraints(){return this._cnMap.array.map(({first})=>first)}addEditVariable(variable,strength){if(this._editMap.find(variable)!==void 0)throw new Error("duplicate edit variable");if(strength=Strength.clip(strength),strength===Strength.required)throw new Error("bad required strength");let expr=new Expression(variable),cn3=new Constraint(expr,Operator.Eq,void 0,strength);this.addConstraint(cn3);let info={tag:this._cnMap.find(cn3).second,constraint:cn3,constant:0};this._editMap.insert(variable,info)}removeEditVariable(variable){let editPair=this._editMap.erase(variable);if(editPair===void 0)throw new Error("unknown edit variable");this.removeConstraint(editPair.second.constraint)}hasEditVariable(variable){return this._editMap.contains(variable)}suggestValue(variable,value){let editPair=this._editMap.find(variable);if(editPair===void 0)throw new Error("unknown edit variable");let rows=this._rowMap,info=editPair.second,delta=value-info.constant;info.constant=value;let marker=info.tag.marker,rowPair=rows.find(marker);if(rowPair!==void 0){rowPair.second.add(-delta)<0&&this._infeasibleRows.push(marker),this._dualOptimize();return}let other=info.tag.other;if(rowPair=rows.find(other),rowPair!==void 0){rowPair.second.add(delta)<0&&this._infeasibleRows.push(other),this._dualOptimize();return}for(let i3=0,n4=rows.size();i3<n4;++i3){let rowPair2=rows.itemAt(i3),row=rowPair2.second,coeff=row.coefficientFor(marker);coeff!==0&&row.add(delta*coeff)<0&&rowPair2.first.type()!==SymbolType.External&&this._infeasibleRows.push(rowPair2.first)}this._dualOptimize()}updateVariables(){let vars=this._varMap,rows=this._rowMap;for(let i3=0,n4=vars.size();i3<n4;++i3){let pair=vars.itemAt(i3),rowPair=rows.find(pair.second);rowPair!==void 0?pair.first.setValue(rowPair.second.constant()):pair.first.setValue(0)}}_getVarSymbol(variable){let factory=()=>this._makeSymbol(SymbolType.External);return this._varMap.setDefault(variable,factory).second}_createRow(constraint){let expr=constraint.expression(),row=new Row(expr.constant()),terms=expr.terms();for(let i3=0,n4=terms.size();i3<n4;++i3){let termPair=terms.itemAt(i3);if(!nearZero(termPair.second)){let symbol=this._getVarSymbol(termPair.first),basicPair=this._rowMap.find(symbol);basicPair!==void 0?row.insertRow(basicPair.second,termPair.second):row.insertSymbol(symbol,termPair.second)}}let objective=this._objective,strength=constraint.strength(),tag={marker:INVALID_SYMBOL,other:INVALID_SYMBOL};switch(constraint.op()){case Operator.Le:case Operator.Ge:{let coeff=constraint.op()===Operator.Le?1:-1,slack=this._makeSymbol(SymbolType.Slack);if(tag.marker=slack,row.insertSymbol(slack,coeff),strength<Strength.required){let error2=this._makeSymbol(SymbolType.Error);tag.other=error2,row.insertSymbol(error2,-coeff),objective.insertSymbol(error2,strength)}break}case Operator.Eq:{if(strength<Strength.required){let errplus=this._makeSymbol(SymbolType.Error),errminus=this._makeSymbol(SymbolType.Error);tag.marker=errplus,tag.other=errminus,row.insertSymbol(errplus,-1),row.insertSymbol(errminus,1),objective.insertSymbol(errplus,strength),objective.insertSymbol(errminus,strength)}else{let dummy=this._makeSymbol(SymbolType.Dummy);tag.marker=dummy,row.insertSymbol(dummy)}break}}return row.constant()<0&&row.reverseSign(),{row,tag}}_chooseSubject(row,tag){let cells=row.cells();for(let i3=0,n4=cells.size();i3<n4;++i3){let pair=cells.itemAt(i3);if(pair.first.type()===SymbolType.External)return pair.first}let type=tag.marker.type();return(type===SymbolType.Slack||type===SymbolType.Error)&&row.coefficientFor(tag.marker)<0?tag.marker:(type=tag.other.type(),(type===SymbolType.Slack||type===SymbolType.Error)&&row.coefficientFor(tag.other)<0?tag.other:INVALID_SYMBOL)}_addWithArtificialVariable(row){let art=this._makeSymbol(SymbolType.Slack);this._rowMap.insert(art,row.copy()),this._artificial=row.copy(),this._optimize(this._artificial);let success=nearZero(this._artificial.constant());this._artificial=null;let pair=this._rowMap.erase(art);if(pair!==void 0){let basicRow=pair.second;if(basicRow.isConstant())return success;let entering=this._anyPivotableSymbol(basicRow);if(entering.type()===SymbolType.Invalid)return!1;basicRow.solveForEx(art,entering),this._substitute(entering,basicRow),this._rowMap.insert(entering,basicRow)}let rows=this._rowMap;for(let i3=0,n4=rows.size();i3<n4;++i3)rows.itemAt(i3).second.removeSymbol(art);return this._objective.removeSymbol(art),success}_substitute(symbol,row){let rows=this._rowMap;for(let i3=0,n4=rows.size();i3<n4;++i3){let pair=rows.itemAt(i3);pair.second.substitute(symbol,row),pair.second.constant()<0&&pair.first.type()!==SymbolType.External&&this._infeasibleRows.push(pair.first)}this._objective.substitute(symbol,row),this._artificial&&this._artificial.substitute(symbol,row)}_optimize(objective){let iterations=0;for(;iterations<this.maxIterations;){let entering=this._getEnteringSymbol(objective);if(entering.type()===SymbolType.Invalid)return;let leaving=this._getLeavingSymbol(entering);if(leaving.type()===SymbolType.Invalid)throw new Error("the objective is unbounded");let row=this._rowMap.erase(leaving).second;row.solveForEx(leaving,entering),this._substitute(entering,row),this._rowMap.insert(entering,row),iterations++}throw new Error("solver iterations exceeded")}_dualOptimize(){let rows=this._rowMap,infeasible=this._infeasibleRows;for(;infeasible.length!==0;){let leaving=infeasible.pop(),pair=rows.find(leaving);if(pair!==void 0&&pair.second.constant()<0){let entering=this._getDualEnteringSymbol(pair.second);if(entering.type()===SymbolType.Invalid)throw new Error("dual optimize failed");let row=pair.second;rows.erase(leaving),row.solveForEx(leaving,entering),this._substitute(entering,row),rows.insert(entering,row)}}}_getEnteringSymbol(objective){let cells=objective.cells();for(let i3=0,n4=cells.size();i3<n4;++i3){let pair=cells.itemAt(i3),symbol=pair.first;if(pair.second<0&&symbol.type()!==SymbolType.Dummy)return symbol}return INVALID_SYMBOL}_getDualEnteringSymbol(row){let ratio=Number.MAX_VALUE,entering=INVALID_SYMBOL,cells=row.cells();for(let i3=0,n4=cells.size();i3<n4;++i3){let pair=cells.itemAt(i3),symbol=pair.first,c4=pair.second;if(c4>0&&symbol.type()!==SymbolType.Dummy){let r5=this._objective.coefficientFor(symbol)/c4;r5<ratio&&(ratio=r5,entering=symbol)}}return entering}_getLeavingSymbol(entering){let ratio=Number.MAX_VALUE,found=INVALID_SYMBOL,rows=this._rowMap;for(let i3=0,n4=rows.size();i3<n4;++i3){let pair=rows.itemAt(i3),symbol=pair.first;if(symbol.type()!==SymbolType.External){let row=pair.second,temp=row.coefficientFor(entering);if(temp<0){let temp_ratio=-row.constant()/temp;temp_ratio<ratio&&(ratio=temp_ratio,found=symbol)}}}return found}_getMarkerLeavingSymbol(marker){let dmax=Number.MAX_VALUE,r12=dmax,r22=dmax,invalid=INVALID_SYMBOL,first=invalid,second=invalid,third=invalid,rows=this._rowMap;for(let i3=0,n4=rows.size();i3<n4;++i3){let pair=rows.itemAt(i3),row=pair.second,c4=row.coefficientFor(marker);if(c4===0)continue;let symbol=pair.first;if(symbol.type()===SymbolType.External)third=symbol;else if(c4<0){let r5=-row.constant()/c4;r5<r12&&(r12=r5,first=symbol)}else{let r5=row.constant()/c4;r5<r22&&(r22=r5,second=symbol)}}return first!==invalid?first:second!==invalid?second:third}_removeConstraintEffects(cn3,tag){tag.marker.type()===SymbolType.Error&&this._removeMarkerEffects(tag.marker,cn3.strength()),tag.other.type()===SymbolType.Error&&this._removeMarkerEffects(tag.other,cn3.strength())}_removeMarkerEffects(marker,strength){let pair=this._rowMap.find(marker);pair!==void 0?this._objective.insertRow(pair.second,-strength):this._objective.insertSymbol(marker,-strength)}_anyPivotableSymbol(row){let cells=row.cells();for(let i3=0,n4=cells.size();i3<n4;++i3){let pair=cells.itemAt(i3),type=pair.first.type();if(type===SymbolType.Slack||type===SymbolType.Error)return pair.first}return INVALID_SYMBOL}_makeSymbol(type){return new Symbol2(type,this._idTick++)}};function nearZero(value){let eps=1e-8;return value<0?-value<eps:value<eps}function createCnMap(){return createMap()}function createRowMap(){return createMap()}function createVarMap(){return createMap()}function createEditMap(){return createMap()}var SymbolType;(function(SymbolType2){SymbolType2[SymbolType2.Invalid=0]="Invalid",SymbolType2[SymbolType2.External=1]="External",SymbolType2[SymbolType2.Slack=2]="Slack",SymbolType2[SymbolType2.Error=3]="Error",SymbolType2[SymbolType2.Dummy=4]="Dummy"})(SymbolType||(SymbolType={}));var Symbol2=class{constructor(type,id2){__publicField(this,"_id");__publicField(this,"_type");this._id=id2,this._type=type}id(){return this._id}type(){return this._type}},INVALID_SYMBOL=new Symbol2(SymbolType.Invalid,-1),Row=class _Row{constructor(constant=0){__publicField(this,"_cellMap",createMap());__publicField(this,"_constant");this._constant=constant}cells(){return this._cellMap}constant(){return this._constant}isConstant(){return this._cellMap.empty()}allDummies(){let cells=this._cellMap;for(let i3=0,n4=cells.size();i3<n4;++i3)if(cells.itemAt(i3).first.type()!==SymbolType.Dummy)return!1;return!0}copy(){let theCopy=new _Row(this._constant);return theCopy._cellMap=this._cellMap.copy(),theCopy}add(value){return this._constant+=value}insertSymbol(symbol,coefficient=1){let pair=this._cellMap.setDefault(symbol,()=>0);nearZero(pair.second+=coefficient)&&this._cellMap.erase(symbol)}insertRow(other,coefficient=1){this._constant+=other._constant*coefficient;let cells=other._cellMap;for(let i3=0,n4=cells.size();i3<n4;++i3){let pair=cells.itemAt(i3);this.insertSymbol(pair.first,pair.second*coefficient)}}removeSymbol(symbol){this._cellMap.erase(symbol)}reverseSign(){this._constant=-this._constant;let cells=this._cellMap;for(let i3=0,n4=cells.size();i3<n4;++i3){let pair=cells.itemAt(i3);pair.second=-pair.second}}solveFor(symbol){let cells=this._cellMap,coeff=-1/cells.erase(symbol).second;this._constant*=coeff;for(let i3=0,n4=cells.size();i3<n4;++i3)cells.itemAt(i3).second*=coeff}solveForEx(lhs,rhs){this.insertSymbol(lhs,-1),this.solveFor(rhs)}coefficientFor(symbol){let pair=this._cellMap.find(symbol);return pair!==void 0?pair.second:0}substitute(symbol,row){let pair=this._cellMap.erase(symbol);pair!==void 0&&this.insertRow(row,pair.second)}};var import_debug9=__toESM(require_browser(),1);init_dist6();var import_react3=__toESM(require_react(),1);init_dist();var import_debug10=__toESM(require_browser(),1);init_dist6();init_dist();init_dist3();init_dist6();init_dist6();init_dist6();init_dist3();init_dist();init_dist6();init_dist6();init_src();init_dist6();init_dist3();init_dist6();init_dist3();init_dist6();init_dist3();init_dist3();init_dist6();init_dist6();init_dist3();init_dist6();init_dist6();init_dist3();init_dist6();init_dist6();init_dist3();init_dist6();init_dist3();init_dist6();init_dist6();init_dist6();init_dist6();init_dist6();init_dist3();function distance5(x12,y12,x22,y22){return Math.sqrt((x22-x12)**2+(y22-y12)**2)}var addStartAndEndPortIdsIfMissing=soup=>{let pcbPorts=soup.filter(item=>item.type==="pcb_port"),pcbSmtPads=soup.filter(item=>item.type==="pcb_smtpad"),pcbTraces=soup.filter(item=>item.type==="pcb_trace");function findPortIdOverlappingPoint(point7,options={}){let traceWidth=options.traceWidth||0,directPort=pcbPorts.find(port=>distance5(port.x,port.y,point7.x,point7.y)<.01);if(directPort)return directPort.pcb_port_id;if(options.isFirstOrLastPoint){let smtPad=pcbSmtPads.find(pad2=>{if(pad2.shape==="rect")return Math.abs(point7.x-pad2.x)<pad2.width/2+traceWidth/2&&Math.abs(point7.y-pad2.y)<pad2.height/2+traceWidth/2;if(pad2.shape==="circle")return distance5(point7.x,point7.y,pad2.x,pad2.y)<pad2.radius});if(smtPad)return smtPad.pcb_port_id??null}return null}for(let trace of pcbTraces)for(let index=0;index<trace.route.length;index++){let segment2=trace.route[index],isFirstOrLastPoint=index===0||index===trace.route.length-1;if(segment2.route_type==="wire"){if(!segment2.start_pcb_port_id&&index===0){let startPortId=findPortIdOverlappingPoint(segment2,{isFirstOrLastPoint,traceWidth:segment2.width});startPortId&&(segment2.start_pcb_port_id=startPortId)}if(!segment2.end_pcb_port_id&&index===trace.route.length-1){let endPortId=findPortIdOverlappingPoint(segment2,{isFirstOrLastPoint,traceWidth:segment2.width});endPortId&&(segment2.end_pcb_port_id=endPortId)}}}},CIRCUIT_JSON_ID_PATTERN=/\b(?:pcb|source|schematic|subcircuit)_[a-z0-9_]+\b/i,sanitizeReadableName=(candidate,id2,fallbackLabel)=>!candidate||candidate===id2||CIRCUIT_JSON_ID_PATTERN.test(candidate)?fallbackLabel:candidate,firstReadableName=(candidates,id2)=>{for(let candidate of candidates){let readableName=sanitizeReadableName(candidate,id2,"");if(readableName)return readableName}return""},getReadableNameForComponent=(circuitJson,pcbComponentId)=>sanitizeReadableName(getReadableNameForElement(circuitJson,pcbComponentId),pcbComponentId,"component"),getReadableNameForPort=(circuitJson,pcbPortId)=>{let pcbPort=circuitJson.find(element=>element.type==="pcb_port"&&element.pcb_port_id===pcbPortId);if(pcbPort?.type==="pcb_port"){let sourcePort=circuitJson.find(element=>element.type==="source_port"&&element.source_port_id===pcbPort.source_port_id),sourceComponent=sourcePort?.type==="source_port"?circuitJson.find(element=>element.type==="source_component"&&element.source_component_id===sourcePort.source_component_id):null,readableSourceComponentName=firstReadableName([sourceComponent?.type==="source_component"?sourceComponent.name:null],sourceComponent?.type==="source_component"?sourceComponent.source_component_id:""),readableSourcePortName=firstReadableName([sourcePort?.type==="source_port"?sourcePort.name:null,sourcePort?.type==="source_port"?sourcePort.pin_number?.toString():null,sourcePort?.type==="source_port"?sourcePort.port_hints?.[0]:null],sourcePort?.type==="source_port"?sourcePort.source_port_id:"");if(readableSourceComponentName&&readableSourcePortName)return`${readableSourceComponentName}.${readableSourcePortName}`;if(readableSourcePortName)return readableSourcePortName}return sanitizeReadableName(getReadableNameForPcbPort(circuitJson,pcbPortId)??getReadableNameForElement(circuitJson,pcbPortId),pcbPortId,"port")};var getReadableNameForElementId=(circuitJson,elementId)=>sanitizeReadableName(getReadableNameForElement(circuitJson,elementId),elementId,"element"),containsCircuitJsonId=message=>CIRCUIT_JSON_ID_PATTERN.test(message);function checkEachPcbPortConnectedToPcbTraces(circuitJson){addStartAndEndPortIdsIfMissing(circuitJson);let sourceTraces=circuitJson.filter(item=>item.type==="source_trace"),pcbPorts=circuitJson.filter(item=>item.type==="pcb_port"),errors=[],connectivityMap=getFullConnectivityMapFromCircuitJson(circuitJson),sourcePortToPcbPort=new Map;for(let pcbPort of pcbPorts)sourcePortToPcbPort.set(pcbPort.source_port_id,pcbPort);for(let sourceTrace of sourceTraces){let connectedSourcePortIds=sourceTrace.connected_source_port_ids;if(connectedSourcePortIds.length<2)continue;let pcbPortsInTrace=[],missingPcbPorts=[];for(let sourcePortId of connectedSourcePortIds){let pcbPort=sourcePortToPcbPort.get(sourcePortId);pcbPort?pcbPortsInTrace.push(pcbPort):missingPcbPorts.push(sourcePortId)}if(pcbPortsInTrace.length<2)continue;let firstPcbPort=pcbPortsInTrace[0],referenceNetId=connectivityMap.getNetConnectedToId(firstPcbPort.pcb_port_id);connectivityMap.getIdsConnectedToNet(referenceNetId).filter(id2=>circuitJson.some(element=>element.type==="pcb_trace"&&("pcb_trace_id"in element&&element.pcb_trace_id===id2||"route_id"in element&&element.route_id===id2))).length===0&&new Set(pcbPortsInTrace.map(p4=>p4.pcb_component_id)).size>1&&errors.push({type:"pcb_port_not_connected_error",message:`Ports [${pcbPortsInTrace.map(p4=>getReadableNameForPort(circuitJson,p4.pcb_port_id)).join(", ")}] are not connected together through the same net.`,error_type:"pcb_port_not_connected_error",pcb_port_ids:pcbPortsInTrace.map(p4=>p4.pcb_port_id),pcb_component_ids:pcbPortsInTrace.map(p4=>p4.pcb_component_id).filter(id2=>id2!==void 0),pcb_port_not_connected_error_id:`pcb_port_not_connected_error_trace_${sourceTrace.source_trace_id}`})}return errors}var SpatialObjectIndex=class{constructor({objects,getBounds:getBounds3,getId,CELL_SIZE}){__publicField(this,"buckets");__publicField(this,"objectsById");__publicField(this,"getBounds");__publicField(this,"getId");__publicField(this,"CELL_SIZE",.4);__publicField(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=getBounds3,this.getId=getId??(()=>this._getNextId()),this.CELL_SIZE=CELL_SIZE??this.CELL_SIZE;for(let obj of objects)this.addObject(obj)}_getNextId(){return`${this._idCounter++}`}addObject(obj){let bounds=this.getBounds(obj),spatialIndexId=this.getId(obj),objWithId={...obj,spatialIndexId};this.objectsById.set(spatialIndexId,objWithId);let minBucketX=Math.floor(bounds.minX/this.CELL_SIZE),minBucketY=Math.floor(bounds.minY/this.CELL_SIZE),maxBucketX=Math.floor(bounds.maxX/this.CELL_SIZE),maxBucketY=Math.floor(bounds.maxY/this.CELL_SIZE);for(let bx3=minBucketX;bx3<=maxBucketX;bx3++)for(let by3=minBucketY;by3<=maxBucketY;by3++){let bucketKey=`${bx3}x${by3}`,bucket=this.buckets.get(bucketKey);bucket?bucket.push(objWithId):this.buckets.set(bucketKey,[objWithId])}}removeObject(id2){let obj=this.objectsById.get(id2);if(!obj)return!1;this.objectsById.delete(id2);let bounds=this.getBounds(obj),minBucketX=Math.floor(bounds.minX/this.CELL_SIZE),minBucketY=Math.floor(bounds.minY/this.CELL_SIZE),maxBucketX=Math.floor(bounds.maxX/this.CELL_SIZE),maxBucketY=Math.floor(bounds.maxY/this.CELL_SIZE);for(let bx3=minBucketX;bx3<=maxBucketX;bx3++)for(let by3=minBucketY;by3<=maxBucketY;by3++){let bucketKey=`${bx3}x${by3}`,bucket=this.buckets.get(bucketKey);if(bucket){let index=bucket.findIndex(item=>item.spatialIndexId===id2);index!==-1&&(bucket.splice(index,1),bucket.length===0&&this.buckets.delete(bucketKey))}}return!0}getBucketKey(x4,y4){return`${Math.floor(x4/this.CELL_SIZE)}x${Math.floor(y4/this.CELL_SIZE)}`}getObjectsInBounds(bounds,margin=0){let objects=[],addedIds=new Set,minBucketX=Math.floor((bounds.minX-margin)/this.CELL_SIZE),minBucketY=Math.floor((bounds.minY-margin)/this.CELL_SIZE),maxBucketX=Math.floor((bounds.maxX+margin)/this.CELL_SIZE),maxBucketY=Math.floor((bounds.maxY+margin)/this.CELL_SIZE);for(let bx3=minBucketX;bx3<=maxBucketX;bx3++)for(let by3=minBucketY;by3<=maxBucketY;by3++){let bucketKey=`${bx3}x${by3}`,bucket=this.buckets.get(bucketKey)||[];for(let obj of bucket){let id2=obj.spatialIndexId;addedIds.has(id2)||(addedIds.add(id2),objects.push(obj))}}return objects}},jlcMinTolerances={min_trace_width:.1,min_via_hole_edge_to_via_hole_edge_clearance:.1,min_plated_hole_drill_edge_to_drill_edge_clearance:.15,min_trace_to_pad_edge_clearance:.1,min_pad_edge_to_pad_edge_clearance:.1,min_board_edge_clearance:.2,min_via_hole_diameter:.2,min_via_pad_diameter:.3},DEFAULT_TRACE_MARGIN=.1,DEFAULT_TRACE_THICKNESS=jlcMinTolerances.min_trace_width,DEFAULT_VIA_DIAMETER=jlcMinTolerances.min_via_pad_diameter,DEFAULT_VIA_BOARD_MARGIN=jlcMinTolerances.min_board_edge_clearance,DEFAULT_SAME_NET_VIA_MARGIN=jlcMinTolerances.min_via_hole_edge_to_via_hole_edge_clearance,DEFAULT_DIFFERENT_NET_VIA_MARGIN=jlcMinTolerances.min_via_hole_edge_to_via_hole_edge_clearance,DEFAULT_PAD_PAD_CLEARANCE=jlcMinTolerances.min_pad_edge_to_pad_edge_clearance,DEFAULT_PAD_TRACE_CLEARANCE=jlcMinTolerances.min_trace_to_pad_edge_clearance,EPSILON2=.005,getPcbBoard=circuitJson=>circuitJson.find(el3=>el3.type==="pcb_board"),getBoardDrcValue=(board,key)=>board?.[key];function getLayersOfPcbElement(obj){return obj.type==="pcb_trace_segment"?[obj.layer]:obj.type==="pcb_smtpad"?[obj.layer]:obj.type==="pcb_plated_hole"?Array.isArray(obj.layers)?obj.layers:[...all_layers]:obj.type==="pcb_hole"?[...all_layers]:obj.type==="pcb_via"?Array.isArray(obj.layers)?obj.layers:[...all_layers]:obj.type==="pcb_keepout"?Array.isArray(obj.layers)?obj.layers:[]:[]}var getClosestPointBetweenSegmentAndBounds=(segment2,bounds)=>{let p12={x:segment2.x1,y:segment2.y1},p22={x:segment2.x2,y:segment2.y2},minX=bounds.minX,minY=bounds.minY,maxX=bounds.maxX,maxY=bounds.maxY;if(p12.x===p22.x&&p12.y===p22.y){let closestX=Math.max(minX,Math.min(maxX,p12.x)),closestY=Math.max(minY,Math.min(maxY,p12.y));return closestX===p12.x&&closestY===p12.y?{x:p12.x,y:p12.y}:{x:closestX,y:closestY}}let dx3=p22.x-p12.x,dy3=p22.y-p12.y,tMinX=dx3!==0?(minX-p12.x)/dx3:Number.NEGATIVE_INFINITY,tMaxX=dx3!==0?(maxX-p12.x)/dx3:Number.POSITIVE_INFINITY,tMinY=dy3!==0?(minY-p12.y)/dy3:Number.NEGATIVE_INFINITY,tMaxY=dy3!==0?(maxY-p12.y)/dy3:Number.POSITIVE_INFINITY,tEnter=Math.max(Math.min(tMinX,tMaxX),Math.min(tMinY,tMaxY)),tExit=Math.min(Math.max(tMinX,tMaxX),Math.max(tMinY,tMaxY));if(tEnter<=tExit&&tExit>=0&&tEnter<=1){let t52=Math.max(0,Math.min(1,tEnter));return{x:p12.x+t52*dx3,y:p12.y+t52*dy3}}let closestToP1={x:Math.max(minX,Math.min(maxX,p12.x)),y:Math.max(minY,Math.min(maxY,p12.y))},closestToP2={x:Math.max(minX,Math.min(maxX,p22.x)),y:Math.max(minY,Math.min(maxY,p22.y))},distToP1Squared=(closestToP1.x-p12.x)**2+(closestToP1.y-p12.y)**2,distToP2Squared=(closestToP2.x-p22.x)**2+(closestToP2.y-p22.y)**2,edges=[{start:{x:minX,y:minY},end:{x:maxX,y:minY}},{start:{x:maxX,y:minY},end:{x:maxX,y:maxY}},{start:{x:maxX,y:maxY},end:{x:minX,y:maxY}},{start:{x:minX,y:maxY},end:{x:minX,y:minY}}],minDistance=Math.min(distToP1Squared,distToP2Squared),closestPoint=distToP1Squared<=distToP2Squared?closestToP1:closestToP2,clamp22=(value,min,max)=>Math.max(min,Math.min(max,value));for(let edge of edges){let va3={x:p22.x-p12.x,y:p22.y-p12.y},vb3={x:edge.end.x-edge.start.x,y:edge.end.y-edge.start.y},w4={x:p12.x-edge.start.x,y:p12.y-edge.start.y},dotAA=va3.x*va3.x+va3.y*va3.y,dotAB=va3.x*vb3.x+va3.y*vb3.y,dotAW=va3.x*w4.x+va3.y*w4.y,dotBB=vb3.x*vb3.x+vb3.y*vb3.y,dotBW=vb3.x*w4.x+vb3.y*w4.y,denominator=dotAA*dotBB-dotAB*dotAB;if(Math.abs(denominator)<1e-10)continue;let tA2=(dotAB*dotBW-dotBB*dotAW)/denominator,tB=(dotAA*dotBW-dotAB*dotAW)/denominator;tA2=clamp22(tA2,0,1),tB=clamp22(tB,0,1);let closestOnSegment={x:p12.x+tA2*va3.x,y:p12.y+tA2*va3.y},closestOnEdge={x:edge.start.x+tB*vb3.x,y:edge.start.y+tB*vb3.y},dx22=closestOnSegment.x-closestOnEdge.x,dy22=closestOnSegment.y-closestOnEdge.y,distSquared=dx22*dx22+dy22*dy22;distSquared<minDistance&&(minDistance=distSquared,closestPoint={x:(closestOnSegment.x+closestOnEdge.x)/2,y:(closestOnSegment.y+closestOnEdge.y)/2})}return closestPoint},getClosestPointBetweenSegments=(segmentA,segmentB)=>{let a12={x:segmentA.x1,y:segmentA.y1},a22={x:segmentA.x2,y:segmentA.y2},b12={x:segmentB.x1,y:segmentB.y1},b22={x:segmentB.x2,y:segmentB.y2},va3={x:a22.x-a12.x,y:a22.y-a12.y},vb3={x:b22.x-b12.x,y:b22.y-b12.y},lenSqrA=va3.x*va3.x+va3.y*va3.y,lenSqrB=vb3.x*vb3.x+vb3.y*vb3.y;if(lenSqrA===0||lenSqrB===0){if(lenSqrA===0&&lenSqrB===0)return{x:(a12.x+b12.x)/2,y:(a12.y+b12.y)/2};if(lenSqrA===0){let t210=clamp4(((a12.x-b12.x)*vb3.x+(a12.y-b12.y)*vb3.y)/lenSqrB,0,1),closestOnB2={x:b12.x+t210*vb3.x,y:b12.y+t210*vb3.y};return{x:(a12.x+closestOnB2.x)/2,y:(a12.y+closestOnB2.y)/2}}let t52=clamp4(((b12.x-a12.x)*va3.x+(b12.y-a12.y)*va3.y)/lenSqrA,0,1),closestOnA2={x:a12.x+t52*va3.x,y:a12.y+t52*va3.y};return{x:(closestOnA2.x+b12.x)/2,y:(closestOnA2.y+b12.y)/2}}let w4={x:a12.x-b12.x,y:a12.y-b12.y},dotAA=va3.x*va3.x+va3.y*va3.y,dotAB=va3.x*vb3.x+va3.y*vb3.y,dotAW=va3.x*w4.x+va3.y*w4.y,dotBB=vb3.x*vb3.x+vb3.y*vb3.y,dotBW=vb3.x*w4.x+vb3.y*w4.y,denominator=dotAA*dotBB-dotAB*dotAB;if(denominator<1e-10)return closestPointsParallelSegments(a12,a22,b12,b22,va3,vb3,lenSqrA,lenSqrB);let tA2=(dotAB*dotBW-dotBB*dotAW)/denominator,tB=(dotAA*dotBW-dotAB*dotAW)/denominator;tA2=clamp4(tA2,0,1),tB=clamp4(tB,0,1),tB=(tA2*dotAB+dotBW)/dotBB,tB=clamp4(tB,0,1),tA2=(tB*dotAB-dotAW)/dotAA,tA2=clamp4(tA2,0,1);let closestOnA={x:a12.x+tA2*va3.x,y:a12.y+tA2*va3.y},closestOnB={x:b12.x+tB*vb3.x,y:b12.y+tB*vb3.y},dx3=closestOnA.x-closestOnB.x,dy3=closestOnA.y-closestOnB.y,distance32=Math.sqrt(dx3*dx3+dy3*dy3);return{x:(closestOnA.x+closestOnB.x)/2,y:(closestOnA.y+closestOnB.y)/2}},closestPointsParallelSegments=(a12,a22,b12,b22,va3,vb3,lenSqrA,lenSqrB)=>{let tA2=((b12.x-a12.x)*va3.x+(b12.y-a12.y)*va3.y)/lenSqrA;tA2=clamp4(tA2,0,1);let pointOnA1={x:a12.x+tA2*va3.x,y:a12.y+tA2*va3.y},tA22=((b22.x-a12.x)*va3.x+(b22.y-a12.y)*va3.y)/lenSqrA;tA22=clamp4(tA22,0,1);let pointOnA2={x:a12.x+tA22*va3.x,y:a12.y+tA22*va3.y},tB=((a12.x-b12.x)*vb3.x+(a12.y-b12.y)*vb3.y)/lenSqrB;tB=clamp4(tB,0,1);let pointOnB1={x:b12.x+tB*vb3.x,y:b12.y+tB*vb3.y},tB2=((a22.x-b12.x)*vb3.x+(a22.y-b12.y)*vb3.y)/lenSqrB;tB2=clamp4(tB2,0,1);let pointOnB2={x:b12.x+tB2*vb3.x,y:b12.y+tB2*vb3.y},closestPair=[{pointA:pointOnA1,pointB:b12,distance:Math.sqrt((pointOnA1.x-b12.x)**2+(pointOnA1.y-b12.y)**2)},{pointA:pointOnA2,pointB:b22,distance:Math.sqrt((pointOnA2.x-b22.x)**2+(pointOnA2.y-b22.y)**2)},{pointA:a12,pointB:pointOnB1,distance:Math.sqrt((a12.x-pointOnB1.x)**2+(a12.y-pointOnB1.y)**2)},{pointA:a22,pointB:pointOnB2,distance:Math.sqrt((a22.x-pointOnB2.x)**2+(a22.y-pointOnB2.y)**2)}].reduce((closest,current3)=>current3.distance<closest.distance?current3:closest);return{x:(closestPair.pointA.x+closestPair.pointB.x)/2,y:(closestPair.pointA.y+closestPair.pointB.y)/2}},clamp4=(value,min,max)=>Math.max(min,Math.min(max,value)),rotatePoint=(point7,angleDegrees)=>{let angle=angleDegrees*Math.PI/180;return{x:point7.x*Math.cos(angle)-point7.y*Math.sin(angle),y:point7.x*Math.sin(angle)+point7.y*Math.cos(angle)}},getRotatedRectPoints=({x:x4,y:y4,width,height,ccwRotation})=>{let halfWidth=width/2,halfHeight=height/2;return[{x:-halfWidth,y:-halfHeight},{x:halfWidth,y:-halfHeight},{x:halfWidth,y:halfHeight},{x:-halfWidth,y:halfHeight}].map(point7=>{let rotated=rotatePoint(point7,ccwRotation);return{x:x4+rotated.x,y:y4+rotated.y}})},getPolygonPointsForPad=pad2=>{if(pad2.type==="pcb_smtpad"){if(pad2.shape==="polygon")return pad2.points;if(pad2.shape==="rotated_rect")return getRotatedRectPoints({x:pad2.x,y:pad2.y,width:pad2.width,height:pad2.height,ccwRotation:pad2.ccw_rotation})}if(pad2.type==="pcb_plated_hole"&&"rect_pad_width"in pad2&&"rect_pad_height"in pad2)return getRotatedRectPoints({x:pad2.x,y:pad2.y,width:pad2.rect_pad_width,height:pad2.rect_pad_height,ccwRotation:"rect_ccw_rotation"in pad2&&typeof pad2.rect_ccw_rotation=="number"?pad2.rect_ccw_rotation:0});throw new Error(`Expected polygonal pad geometry, got ${pad2.type} with shape "${pad2.shape}"`)},getPolygonEdges3=points=>points.map((point7,index)=>[point7,points[(index+1)%points.length]]),getClosestPointsBetweenSegments=(a12,a22,b12,b22)=>{let intersection=getSegmentIntersection(a12,a22,b12,b22);if(intersection)return{distance:0,pointOnA:intersection,pointOnB:intersection,center:intersection};let candidates=[{pointOnA:a12,pointOnB:pointToSegmentClosestPoint(a12,b12,b22)},{pointOnA:a22,pointOnB:pointToSegmentClosestPoint(a22,b12,b22)},{pointOnA:pointToSegmentClosestPoint(b12,a12,a22),pointOnB:b12},{pointOnA:pointToSegmentClosestPoint(b22,a12,a22),pointOnB:b22}],best=candidates[0],bestDistanceSquared=distSq(best.pointOnA,best.pointOnB);for(let candidate of candidates.slice(1)){let candidateDistanceSquared=distSq(candidate.pointOnA,candidate.pointOnB);candidateDistanceSquared<bestDistanceSquared&&(best=candidate,bestDistanceSquared=candidateDistanceSquared)}return{distance:segmentToSegmentMinDistance(a12,a22,b12,b22),pointOnA:best.pointOnA,pointOnB:best.pointOnB,center:{x:(best.pointOnA.x+best.pointOnB.x)/2,y:(best.pointOnA.y+best.pointOnB.y)/2}}},getSegmentToPolygonClearance=(segment2,polygon2)=>{let start={x:segment2.x1,y:segment2.y1},end={x:segment2.x2,y:segment2.y2};if(polygon2.length<3)return{distance:Number.POSITIVE_INFINITY,center:start};let intersections=getPolygonEdges3(polygon2).map(([edgeStart,edgeEnd])=>getSegmentIntersection(start,end,edgeStart,edgeEnd)).filter(point7=>point7!==null);if(intersections.length>0){let dx3=end.x-start.x,dy3=end.y-start.y,lengthSquared=dx3*dx3+dy3*dy3;return intersections.sort((a3,b3)=>{let ta3=((a3.x-start.x)*dx3+(a3.y-start.y)*dy3)/lengthSquared,tb2=((b3.x-start.x)*dx3+(b3.y-start.y)*dy3)/lengthSquared;return ta3-tb2}),{distance:0,center:intersections[0]}}if(isPointInsidePolygon(start,polygon2)||isPointInsidePolygon(end,polygon2))return{distance:0,center:{x:(start.x+end.x)/2,y:(start.y+end.y)/2}};let best=getClosestPointsBetweenSegments(start,end,polygon2[0],polygon2[1]);for(let[edgeStart,edgeEnd]of getPolygonEdges3(polygon2).slice(1)){let candidate=getClosestPointsBetweenSegments(start,end,edgeStart,edgeEnd);candidate.distance<best.distance&&(best=candidate)}return{distance:best.distance,center:best.center}},getCollidableBounds=collidable=>{if(collidable.type==="pcb_trace_segment")return{minX:Math.min(collidable.x1,collidable.x2),minY:Math.min(collidable.y1,collidable.y2),maxX:Math.max(collidable.x1,collidable.x2),maxY:Math.max(collidable.y1,collidable.y2)};if((collidable.type==="pcb_smtpad"||collidable.type==="pcb_plated_hole")&&(collidable.type==="pcb_smtpad"&&(collidable.shape==="rotated_rect"||collidable.shape==="polygon")||collidable.type==="pcb_plated_hole"&&"rect_pad_width"in collidable&&"rect_pad_height"in collidable)){let polygonPoints=getPolygonPointsForPad(collidable);return{minX:Math.min(...polygonPoints.map(point7=>point7.x)),minY:Math.min(...polygonPoints.map(point7=>point7.y)),maxX:Math.max(...polygonPoints.map(point7=>point7.x)),maxY:Math.max(...polygonPoints.map(point7=>point7.y))}}return getBoundsOfPcbElements([collidable])};function getPcbPortIdsConnectedToRoutePoint(routePoint){return routePoint.route_type!=="wire"?[]:[routePoint.start_pcb_port_id,routePoint.end_pcb_port_id].filter(portId=>!!portId)}function getPcbPortIdsConnectedToTrace(trace){let connectedPcbPorts=new Set;for(let segment2 of trace.route)for(let portId of getPcbPortIdsConnectedToRoutePoint(segment2))connectedPcbPorts.add(portId);return Array.from(connectedPcbPorts)}function getPcbPortIdsConnectedToTraces(traces){let connectedPorts=new Set;for(let trace of traces)for(let portId of getPcbPortIdsConnectedToTrace(trace))connectedPorts.add(portId);return Array.from(connectedPorts)}var getRadiusOfCircuitJsonElement=obj=>{if(obj.type==="pcb_via"||obj.type==="pcb_plated_hole"&&obj.shape==="circle")return obj.outer_diameter/2;if(obj.type==="pcb_hole"&&obj.hole_shape==="circle")return obj.hole_diameter/2;if(obj.type==="pcb_smtpad"&&obj.shape==="circle")return obj.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(obj)}`)};function checkEachPcbTraceNonOverlapping(circuitJson,{connMap,minClearance}={}){let errors=[];addStartAndEndPortIdsIfMissing(circuitJson),connMap??(connMap=getFullConnectivityMapFromCircuitJson(circuitJson));let board=getPcbBoard(circuitJson);minClearance??(minClearance=getBoardDrcValue(board,"min_trace_to_pad_edge_clearance")??DEFAULT_TRACE_MARGIN);let pcbTraceSegments=cju_default(circuitJson).pcb_trace.list().flatMap(pcbTrace=>{let segments=[];for(let i3=0;i3<pcbTrace.route.length-1;i3++){let p12=pcbTrace.route[i3],p22=pcbTrace.route[i3+1];p12.route_type==="wire"&&p22.route_type==="wire"&&p12.layer===p22.layer&&segments.push({type:"pcb_trace_segment",pcb_trace_id:pcbTrace.pcb_trace_id,_pcbTrace:pcbTrace,thickness:"width"in p12?p12.width:"width"in p22?p22.width:DEFAULT_TRACE_THICKNESS,layer:p12.layer,x1:p12.x,y1:p12.y,x2:p22.x,y2:p22.y})}return segments}),pcbSmtPads=cju_default(circuitJson).pcb_smtpad.list(),pcbPlatedHoles=cju_default(circuitJson).pcb_plated_hole.list(),pcbHoles=cju_default(circuitJson).pcb_hole.list(),pcbVias=cju_default(circuitJson).pcb_via.list(),pcbKeepouts=cju_default(circuitJson).pcb_keepout.list(),allObjects=[...pcbTraceSegments,...pcbSmtPads,...pcbPlatedHoles,...pcbHoles,...pcbVias,...pcbKeepouts],spatialIndex=new SpatialObjectIndex({objects:allObjects,getBounds:getCollidableBounds}),getReadableName=id2=>getReadableNameForElement(circuitJson,id2),constructErrorMessage=(traceName,otherName,gap)=>gap<0?`PCB trace ${traceName} overlaps with ${otherName} (accidental contact)`:`PCB trace ${traceName} is too close to ${otherName} (gap: ${gap.toFixed(3)}mm)`,errorIds=new Set;for(let segmentA of pcbTraceSegments){let requiredMargin=minClearance,bounds=getCollidableBounds(segmentA),nearbyObjects=spatialIndex.getObjectsInBounds(bounds,requiredMargin+segmentA.thickness/2);if(!(segmentA.x1===segmentA.x2&&segmentA.y1===segmentA.y2))for(let obj of nearbyObjects){if(!getLayersOfPcbElement(obj).includes(segmentA.layer))continue;if(obj.type==="pcb_trace_segment"){let segmentB=obj;if(segmentA.layer!==segmentB.layer||connMap.areIdsConnected(segmentA.pcb_trace_id,segmentB.pcb_trace_id))continue;let gap2=segmentToSegmentMinDistance({x:segmentA.x1,y:segmentA.y1},{x:segmentA.x2,y:segmentA.y2},{x:segmentB.x1,y:segmentB.y1},{x:segmentB.x2,y:segmentB.y2})-segmentA.thickness/2-segmentB.thickness/2;if(gap2>minClearance-EPSILON2)continue;let pcb_trace_error_id=`overlap_${segmentA.pcb_trace_id}_${segmentB.pcb_trace_id}`,pcb_trace_error_id_reverse=`overlap_${segmentB.pcb_trace_id}_${segmentA.pcb_trace_id}`;if(errorIds.has(pcb_trace_error_id)||errorIds.has(pcb_trace_error_id_reverse))continue;errorIds.add(pcb_trace_error_id),errors.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:constructErrorMessage(getReadableName(segmentA.pcb_trace_id),getReadableName(segmentB.pcb_trace_id),gap2),pcb_trace_id:segmentA.pcb_trace_id,source_trace_id:"",pcb_trace_error_id,pcb_component_ids:[],center:getClosestPointBetweenSegments(segmentA,segmentB),pcb_port_ids:getPcbPortIdsConnectedToTraces([segmentA._pcbTrace,segmentB._pcbTrace])});continue}let primaryObjId=getPrimaryId(obj);if(connMap.areIdsConnected(segmentA.pcb_trace_id,"pcb_trace_id"in obj?obj.pcb_trace_id:primaryObjId))continue;if(obj.type==="pcb_via"||obj.type==="pcb_plated_hole"&&obj.shape==="circle"||obj.type==="pcb_hole"||obj.type==="pcb_smtpad"&&obj.shape==="circle"){let radius=getRadiusOfCircuitJsonElement(obj),gap2=segmentToCircleMinDistance({x:segmentA.x1,y:segmentA.y1},{x:segmentA.x2,y:segmentA.y2},{x:obj.x,y:obj.y,radius})-segmentA.thickness/2;if(gap2>minClearance-EPSILON2)continue;let pcb_trace_error_id=`overlap_${segmentA.pcb_trace_id}_${primaryObjId}`;if(errorIds.has(pcb_trace_error_id))continue;errorIds.add(pcb_trace_error_id),errors.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:constructErrorMessage(getReadableName(segmentA.pcb_trace_id),`${obj.type} "${getReadableName(getPrimaryId(obj))}"`,gap2),pcb_trace_id:segmentA.pcb_trace_id,center:getClosestPointBetweenSegmentAndBounds(segmentA,getCollidableBounds(obj)),source_trace_id:"",pcb_trace_error_id,pcb_component_ids:["pcb_component_id"in obj?obj.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...getPcbPortIdsConnectedToTraces([segmentA._pcbTrace]),"pcb_port_id"in obj?obj.pcb_port_id:void 0].filter(Boolean)})}if(obj.type==="pcb_smtpad"&&(obj.shape==="rotated_rect"||obj.shape==="polygon")||obj.type==="pcb_plated_hole"&&"rect_pad_width"in obj&&"rect_pad_height"in obj){let padOutline=getPolygonPointsForPad(obj),{distance:distance32,center:center2}=getSegmentToPolygonClearance(segmentA,padOutline),gap2=distance32-segmentA.thickness/2;if(gap2>minClearance-EPSILON2)continue;let pcb_trace_error_id=`overlap_${segmentA.pcb_trace_id}_${primaryObjId}`;if(errorIds.has(pcb_trace_error_id))continue;errorIds.add(pcb_trace_error_id),errors.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:constructErrorMessage(getReadableName(segmentA.pcb_trace_id),`${obj.type} "${getReadableName(getPrimaryId(obj))}"`,gap2),pcb_trace_id:segmentA.pcb_trace_id,center:center2,source_trace_id:"",pcb_trace_error_id,pcb_component_ids:["pcb_component_id"in obj?obj.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...getPcbPortIdsConnectedToTraces([segmentA._pcbTrace]),"pcb_port_id"in obj?obj.pcb_port_id:void 0].filter(Boolean)});continue}let gap=segmentToBoundsMinDistance({x:segmentA.x1,y:segmentA.y1},{x:segmentA.x2,y:segmentA.y2},getCollidableBounds(obj))-segmentA.thickness/2;if(gap+EPSILON2<requiredMargin){let pcb_trace_error_id=`overlap_${segmentA.pcb_trace_id}_${primaryObjId}`;if(errorIds.has(pcb_trace_error_id))continue;errorIds.add(pcb_trace_error_id),errors.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:constructErrorMessage(getReadableName(segmentA.pcb_trace_id),`${obj.type} "${getReadableName(getPrimaryId(obj))}"`,gap),pcb_trace_id:segmentA.pcb_trace_id,source_trace_id:"",pcb_trace_error_id,pcb_component_ids:["pcb_component_id"in obj?obj.pcb_component_id:void 0].filter(Boolean),center:getClosestPointBetweenSegmentAndBounds(segmentA,getCollidableBounds(obj)),pcb_port_ids:[...getPcbPortIdsConnectedToTraces([segmentA._pcbTrace]),"pcb_port_id"in obj?obj.pcb_port_id:void 0].filter(Boolean)})}}}return errors}function checkViasOffBoard(circuitJson){let board=getPcbBoard(circuitJson);if(!board)return[];let vias=circuitJson.filter(el3=>el3.type==="pcb_via");if(vias.length===0)return[];if(board.width===void 0||board.height===void 0)return[];let boardEdgeClearance=getBoardDrcValue(board,"min_board_edge_clearance")??jlcMinTolerances.min_board_edge_clearance,boardMinX=board.center.x-board.width/2,boardMaxX=board.center.x+board.width/2,boardMinY=board.center.y-board.height/2,boardMaxY=board.center.y+board.height/2,errors=[];for(let via of vias){let viaRadius=via.outer_diameter/2,viaMinX=via.x-viaRadius,viaMaxX=via.x+viaRadius,viaMinY=via.y-viaRadius,viaMaxY=via.y+viaRadius;if(viaMinX<boardMinX+boardEdgeClearance||viaMaxX>boardMaxX-boardEdgeClearance||viaMinY<boardMinY+boardEdgeClearance||viaMaxY>boardMaxY-boardEdgeClearance){let viaName=getReadableNameForElement(circuitJson,via.pcb_via_id);errors.push({type:"pcb_placement_error",pcb_placement_error_id:`out_of_board_${via.pcb_via_id}`,message:`Via ${viaName} is outside or crossing the board boundary`,error_type:"pcb_placement_error"})}}return errors}function isPolygonCCW(poly){return poly.area()>=0}function rectanglePolygon({center:center2,size:size3,rotationDeg=0}){let cx3=center2.x,cy3=center2.y,hw3=size3.width/2,hh3=size3.height/2,corners=[new Point$3(cx3-hw3,cy3-hh3),new Point$3(cx3+hw3,cy3-hh3),new Point$3(cx3+hw3,cy3+hh3),new Point$3(cx3-hw3,cy3+hh3)],poly=new Polygon$1(corners);if(rotationDeg){let matrix2=rotateDEG(rotationDeg,cx3,cy3),rotatedCorners=corners.map(pt3=>{let p4=applyToPoint(matrix2,{x:pt3.x,y:pt3.y});return new Point$3(p4.x,p4.y)});poly=new Polygon$1(rotatedCorners)}return isPolygonCCW(poly)||poly.reverse(),poly}function boardToPolygon({board}){if(board.outline&&board.outline.length>0){let points=board.outline.map(p4=>new Point$3(p4.x,p4.y)),poly=new Polygon$1(points);return isPolygonCCW(poly)||poly.reverse(),poly}return board.center&&typeof board.width=="number"&&typeof board.height=="number"?rectanglePolygon({center:board.center,size:{width:board.width,height:board.height},rotationDeg:0}):null}function getComponentName({circuitJson,component}){if(component.source_component_id){let sourceComponent=circuitJson.find(el3=>el3.type==="source_component"&&el3.source_component_id===component.source_component_id);if(sourceComponent&&"name"in sourceComponent&&sourceComponent.name)return sourceComponent.name}return getReadableNameForComponent(circuitJson,component.pcb_component_id)}function computeOverlapDistance(compPoly,boardPoly,componentCenter,componentWidth,componentHeight,rotationDeg){let centerPoint=new Point$3(componentCenter.x,componentCenter.y);if(!boardPoly.contains(centerPoint)){let dist=boardPoly.distanceTo(centerPoint);return Array.isArray(dist)?dist[0]:Number(dist)||0}let hw3=componentWidth/2,hh3=componentHeight/2,corners=[{x:componentCenter.x-hw3,y:componentCenter.y-hh3},{x:componentCenter.x+hw3,y:componentCenter.y-hh3},{x:componentCenter.x+hw3,y:componentCenter.y+hh3},{x:componentCenter.x-hw3,y:componentCenter.y+hh3}],midpoints=[];for(let i3=0;i3<4;i3++){let next2=(i3+1)%4;midpoints.push({x:(corners[i3].x+corners[next2].x)/2,y:(corners[i3].y+corners[next2].y)/2})}let matrix2=rotateDEG(rotationDeg,componentCenter.x,componentCenter.y),rotatePoint22=pt3=>{let p4=applyToPoint(matrix2,pt3);return new Point$3(p4.x,p4.y)},rotatedPoints=corners.concat(midpoints).map(rotatePoint22),maxDistance=0;for(let pt3 of rotatedPoints)if(!boardPoly.contains(pt3)){let dist=boardPoly.distanceTo(pt3),d4=Array.isArray(dist)?dist[0]:Number(dist)||0;d4>maxDistance&&(maxDistance=d4)}if(maxDistance>0)return maxDistance;try{let intersection=BooleanOperations.intersect(compPoly,boardPoly),intersectionArea=0;intersection?Array.isArray(intersection)?intersectionArea=intersection.reduce((sum,p4)=>sum+(typeof p4.area=="function"?p4.area():0),0):typeof intersection.area=="function"?intersectionArea=intersection.area():intersectionArea=0:intersectionArea=0;let compArea=compPoly.area();if(intersectionArea>0&&intersectionArea<compArea){let overlapRatio=1-intersectionArea/compArea,compWidth=Math.abs(componentWidth),compHeight=Math.abs(componentHeight);return Math.min(compWidth,compHeight)*overlapRatio}else return .1}catch{return .1}}function getRepositionSuggestion({componentPoly,boardPoly}){let boardBox=boardPoly.box,componentBox=componentPoly.box,deltaX=0,deltaY=0;if(componentBox.xmin<boardBox.xmin?deltaX=boardBox.xmin-componentBox.xmin:componentBox.xmax>boardBox.xmax&&(deltaX=boardBox.xmax-componentBox.xmax),componentBox.ymin<boardBox.ymin?deltaY=boardBox.ymin-componentBox.ymin:componentBox.ymax>boardBox.ymax&&(deltaY=boardBox.ymax-componentBox.ymax),deltaX===0&&deltaY===0)return null;let xDir=deltaX>=0?"right":"left",yDir=deltaY>=0?"up":"down",absDx=Math.abs(Math.round(deltaX*100)/100),absDy=Math.abs(Math.round(deltaY*100)/100);return absDx>0&&absDy>0?`Try moving it ${absDx}mm ${xDir} and ${absDy}mm ${yDir} to fit within the board edge.`:absDx>0?`Try moving it ${absDx}mm ${xDir} to fit within the board edge.`:`Try moving it ${absDy}mm ${yDir} to fit within the board edge.`}function checkPcbComponentsOutOfBoard(circuitJson){let board=circuitJson.find(el3=>el3.type==="pcb_board");if(!board)return[];let boardPoly=boardToPolygon({board});if(!boardPoly)return[];let components=circuitJson.filter(el3=>el3.type==="pcb_component");if(components.length===0)return[];let errors=[];for(let c4 of components){if(c4.is_allowed_to_be_off_board||!c4.center||typeof c4.width!="number"||typeof c4.height!="number"||c4.width<=0||c4.height<=0)continue;let compPoly=rectanglePolygon({center:c4.center,size:{width:c4.width,height:c4.height},rotationDeg:0});if(compPoly.area()===0||boardPoly.contains(compPoly))continue;let overlapDistance=computeOverlapDistance(compPoly,boardPoly,c4.center,c4.width,c4.height,0),compName=getComponentName({circuitJson,component:c4}),overlapDistanceMm=Math.round(overlapDistance*100)/100,repositionSuggestion=getRepositionSuggestion({componentPoly:compPoly,boardPoly});errors.push({type:"pcb_component_outside_board_error",error_type:"pcb_component_outside_board_error",pcb_component_outside_board_error_id:`pcb_component_outside_board_${c4.pcb_component_id}`,message:`Component ${compName} extends outside board boundaries by ${overlapDistanceMm}mm.${repositionSuggestion?` ${repositionSuggestion}`:""}`,pcb_component_id:c4.pcb_component_id,pcb_board_id:board.pcb_board_id,component_center:c4.center,component_bounds:{min_x:compPoly.box.xmin,max_x:compPoly.box.xmax,min_y:compPoly.box.ymin,max_y:compPoly.box.ymax},subcircuit_id:c4.subcircuit_id,source_component_id:c4.source_component_id})}return errors}function distance22(a3,b3){return Math.hypot(a3.x-b3.x,a3.y-b3.y)}function viasAreAtSameLocation(a3,b3){return distance22(a3,b3)<=EPSILON2}function checkSameNetViaSpacing(circuitJson,{connMap,minClearance}={}){let vias=circuitJson.filter(el3=>el3.type==="pcb_via");if(vias.length<2)return[];let board=getPcbBoard(circuitJson);minClearance??(minClearance=getBoardDrcValue(board,"min_via_hole_edge_to_via_hole_edge_clearance")??jlcMinTolerances.min_via_hole_edge_to_via_hole_edge_clearance),connMap??(connMap=getFullConnectivityMapFromCircuitJson(circuitJson));let errors=[],reported=new Set;for(let i3=0;i3<vias.length;i3++)for(let j4=i3+1;j4<vias.length;j4++){let viaA=vias[i3],viaB=vias[j4];if(viasAreAtSameLocation(viaA,viaB)||!connMap.areIdsConnected(viaA.pcb_via_id,viaB.pcb_via_id))continue;let gap=distance22(viaA,viaB)-viaA.hole_diameter/2-viaB.hole_diameter/2;if(gap+EPSILON2>=minClearance)continue;let pairId=[viaA.pcb_via_id,viaB.pcb_via_id].sort().join("_");reported.has(pairId)||(reported.add(pairId),errors.push({type:"pcb_via_clearance_error",pcb_error_id:`same_net_vias_close_${pairId}`,message:`Vias ${getReadableNameForElement(circuitJson,viaA.pcb_via_id)} and ${getReadableNameForElement(circuitJson,viaB.pcb_via_id)} are too close together (gap: ${gap.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[viaA.pcb_via_id,viaB.pcb_via_id],minimum_clearance:minClearance,actual_clearance:gap,pcb_center:{x:(viaA.x+viaB.x)/2,y:(viaA.y+viaB.y)/2}}))}return errors}function checkDifferentNetViaSpacing(circuitJson,{connMap,minClearance}={}){let vias=circuitJson.filter(el3=>el3.type==="pcb_via");if(vias.length<2)return[];let board=getPcbBoard(circuitJson);minClearance??(minClearance=getBoardDrcValue(board,"min_via_hole_edge_to_via_hole_edge_clearance")??jlcMinTolerances.min_via_hole_edge_to_via_hole_edge_clearance),connMap??(connMap=getFullConnectivityMapFromCircuitJson(circuitJson));let errors=[],reported=new Set;for(let i3=0;i3<vias.length;i3++)for(let j4=i3+1;j4<vias.length;j4++){let viaA=vias[i3],viaB=vias[j4];if(viasAreAtSameLocation(viaA,viaB)||connMap.areIdsConnected(viaA.pcb_via_id,viaB.pcb_via_id))continue;let gap=distance22(viaA,viaB)-viaA.hole_diameter/2-viaB.hole_diameter/2;if(gap+EPSILON2>=minClearance)continue;let pairId=[viaA.pcb_via_id,viaB.pcb_via_id].sort().join("_");reported.has(pairId)||(reported.add(pairId),errors.push({type:"pcb_via_clearance_error",pcb_error_id:`different_net_vias_close_${pairId}`,message:`Vias ${getReadableNameForElement(circuitJson,viaA.pcb_via_id)} and ${getReadableNameForElement(circuitJson,viaB.pcb_via_id)} from different nets are too close together (gap: ${gap.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[viaA.pcb_via_id,viaB.pcb_via_id],minimum_clearance:minClearance,actual_clearance:gap,pcb_center:{x:(viaA.x+viaB.x)/2,y:(viaA.y+viaB.y)/2}}))}return errors}function checkSourceTracesHavePcbTraces(circuitJson){let errors=[],sourceTraces=circuitJson.filter(el3=>el3.type==="source_trace"),pcbTraces=circuitJson.filter(el3=>el3.type==="pcb_trace"),pcbPorts=circuitJson.filter(el3=>el3.type==="pcb_port"),sourcePortToPcbPort=new Map(pcbPorts.map(pcbPort=>[pcbPort.source_port_id,pcbPort])),connectivityMap=getFullConnectivityMapFromCircuitJson(circuitJson);for(let sourceTrace of sourceTraces){if(!sourceTrace.connected_source_port_ids?.length||(sourceTrace.connected_source_net_ids?.length??0)>0||sourceTrace.connected_source_port_ids.length<2)continue;if(!pcbTraces.some(pcbTrace=>connectivityMap.areIdsConnected(sourceTrace.source_trace_id,pcbTrace.pcb_trace_id))){let connectedPcbPorts=sourceTrace.connected_source_port_ids.map(sourcePortId=>sourcePortToPcbPort.get(sourcePortId)).filter(pcbPort=>pcbPort!==void 0),connectedPcbComponentIds=Array.from(new Set(connectedPcbPorts.map(port=>port.pcb_component_id).filter(id2=>id2!==void 0)));errors.push({type:"pcb_trace_missing_error",pcb_trace_missing_error_id:`pcb_trace_missing_${sourceTrace.source_trace_id}`,error_type:"pcb_trace_missing_error",message:`Trace [${sourceTrace.display_name&&!containsCircuitJsonId(sourceTrace.display_name)?sourceTrace.display_name:"trace"}] is not connected (it has no PCB trace)`,source_trace_id:sourceTrace.source_trace_id,pcb_component_ids:connectedPcbComponentIds,pcb_port_ids:connectedPcbPorts.map(port=>port.pcb_port_id)})}}return errors}function getBoardPolygonPoints(board){if(board.outline&&board.outline.length>0)return board.outline.map(p4=>({x:p4.x,y:p4.y}));if(board.center&&typeof board.width=="number"&&typeof board.height=="number"){let cx3=board.center.x,cy3=board.center.y,hw3=board.width/2,hh3=board.height/2;return[{x:cx3-hw3,y:cy3-hh3},{x:cx3+hw3,y:cy3-hh3},{x:cx3+hw3,y:cy3+hh3},{x:cx3-hw3,y:cy3+hh3}]}return null}function checkPcbTracesOutOfBoard(circuitJson,config={}){let errors=[],board=getPcbBoard(circuitJson);if(!board)return errors;let margin=config.margin??getBoardDrcValue(board,"min_board_edge_clearance")??jlcMinTolerances.min_board_edge_clearance,boardPoints=getBoardPolygonPoints(board);if(!boardPoints)return errors;let pcbTraces=cju_default(circuitJson).pcb_trace.list();for(let trace of pcbTraces)if(!(trace.route.length<2))for(let i3=0;i3<trace.route.length-1;i3++){let p12=trace.route[i3],p22=trace.route[i3+1];if(p12.route_type!=="wire"||p22.route_type!=="wire")continue;let traceWidth="width"in p12?p12.width:"width"in p22?p22.width:.1,segmentStart={x:p12.x,y:p12.y},segmentEnd={x:p22.x,y:p22.y},minDistance=Number.POSITIVE_INFINITY;for(let j4=0;j4<boardPoints.length;j4++){let edgeStart=boardPoints[j4],edgeEnd=boardPoints[(j4+1)%boardPoints.length],distance32=segmentToSegmentMinDistance(segmentStart,segmentEnd,edgeStart,edgeEnd);distance32<minDistance&&(minDistance=distance32)}let minimumDistance=traceWidth/2+margin;if(minDistance<minimumDistance){let error2={type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:`trace_too_close_to_board_${trace.pcb_trace_id}_segment_${i3}`,message:`Trace too close to board edge (${minDistance.toFixed(3)}mm < ${minimumDistance.toFixed(3)}mm required, margin: ${margin}mm)`,pcb_trace_id:trace.pcb_trace_id,source_trace_id:trace.source_trace_id||"",center:{x:(segmentStart.x+segmentEnd.x)/2,y:(segmentStart.y+segmentEnd.y)/2},pcb_component_ids:[],pcb_port_ids:[]};errors.push(error2)}}return errors}function getElementLayers(elem){return elem.type==="pcb_courtyard_circle"||elem.type==="pcb_courtyard_outline"||elem.type==="pcb_courtyard_polygon"||elem.type==="pcb_courtyard_rect"?[elem.layer]:getLayersOfPcbElement(elem)}function doLayersOverlap(layers1,layers2){return layers1.length===0||layers2.length===0?!0:layers1.some(l4=>layers2.includes(l4))}function doPcbElementsOverlap(elem1,elem2){let layers1=getElementLayers(elem1),layers2=getElementLayers(elem2);if(!doLayersOverlap(layers1,layers2))return!1;let bounds1=getBoundsOfPcbElements([elem1]),bounds2=getBoundsOfPcbElements([elem2]);return doBoundsOverlap(bounds1,bounds2)}var isCourtyardElement=element=>element.type==="pcb_courtyard_circle"||element.type==="pcb_courtyard_outline"||element.type==="pcb_courtyard_polygon"||element.type==="pcb_courtyard_rect",formatOverlapElementDescription=(circuitJson,element)=>{if("pcb_port_id"in element&&element.pcb_port_id)return getReadableNameForPort(circuitJson,element.pcb_port_id);let id2=getPrimaryId(element),readableName=getReadableNameForElementId(circuitJson,id2);return readableName==="element"?`[${id2}]`:readableName};function checkPcbComponentOverlap(circuitJson){let errors=[],connMap=getFullConnectivityMapFromCircuitJson(circuitJson),smtPads=cju_default(circuitJson).pcb_smtpad.list(),platedHoles=cju_default(circuitJson).pcb_plated_hole.list(),holes=cju_default(circuitJson).pcb_hole.list(),courtyards=circuitJson.filter(isCourtyardElement),componentMap=new Map;for(let pad2 of smtPads){let componentId=pad2.pcb_component_id||`standalone_pad_${getPrimaryId(pad2)}`;componentMap.has(componentId)||componentMap.set(componentId,{component_id:componentId,elements:[]}),componentMap.get(componentId).elements.push(pad2)}for(let hole of platedHoles){let componentId=hole.pcb_component_id||`standalone_plated_hole_${getPrimaryId(hole)}`;componentMap.has(componentId)||componentMap.set(componentId,{component_id:componentId,elements:[]}),componentMap.get(componentId).elements.push(hole)}for(let hole of holes){let componentId=hole.pcb_component_id||`standalone_hole_${getPrimaryId(hole)}`;componentMap.has(componentId)||componentMap.set(componentId,{component_id:componentId,elements:[hole]})}for(let courtyard of courtyards){let componentId=courtyard.pcb_component_id;componentMap.has(componentId)||componentMap.set(componentId,{component_id:componentId,elements:[]}),componentMap.get(componentId).elements.push(courtyard)}for(let[componentId,componentData]of componentMap)componentData.elements.length>0&&(componentData.bounds=getBoundsOfPcbElements(componentData.elements));let componentsWithElements=Array.from(componentMap.values());for(let i3=0;i3<componentsWithElements.length;i3++)for(let j4=i3+1;j4<componentsWithElements.length;j4++){let comp1=componentsWithElements[i3],comp2=componentsWithElements[j4];if(!(!comp1.bounds||!comp2.bounds)&&doBoundsOverlap(comp1.bounds,comp2.bounds))for(let elem1 of comp1.elements)for(let elem2 of comp2.elements){let id1=getPrimaryId(elem1),id2=getPrimaryId(elem2);if(!((isCourtyardElement(elem1)||isCourtyardElement(elem2))&&elem1.type!=="pcb_hole"&&elem2.type!=="pcb_hole")&&!(elem1.type==="pcb_smtpad"&&elem2.type==="pcb_smtpad"&&connMap.areIdsConnected(id1,id2))&&doPcbElementsOverlap(elem1,elem2)){let elem1Description=formatOverlapElementDescription(circuitJson,elem1),elem2Description=formatOverlapElementDescription(circuitJson,elem2),error2={type:"pcb_footprint_overlap_error",pcb_error_id:`pcb_footprint_overlap_${id1}_${id2}`,error_type:"pcb_footprint_overlap_error",message:`${elem1.type} ${elem1Description} overlaps with ${elem2.type} ${elem2Description}`};(elem1.type==="pcb_smtpad"||elem2.type==="pcb_smtpad")&&(error2.pcb_smtpad_ids=[],elem1.type==="pcb_smtpad"&&error2.pcb_smtpad_ids.push(id1),elem2.type==="pcb_smtpad"&&error2.pcb_smtpad_ids.push(id2)),(elem1.type==="pcb_plated_hole"||elem2.type==="pcb_plated_hole")&&(error2.pcb_plated_hole_ids=[],elem1.type==="pcb_plated_hole"&&error2.pcb_plated_hole_ids.push(id1),elem2.type==="pcb_plated_hole"&&error2.pcb_plated_hole_ids.push(id2)),(elem1.type==="pcb_hole"||elem2.type==="pcb_hole")&&(error2.pcb_hole_ids=[],elem1.type==="pcb_hole"&&error2.pcb_hole_ids.push(id1),elem2.type==="pcb_hole"&&error2.pcb_hole_ids.push(id2)),errors.push(error2)}}}return errors}var formatMm=value=>{let rounded=Math.round(value*1e3)/1e3;return`${Number(rounded.toFixed(3))}mm`},getPadBounds=pad2=>getBoundsOfPcbElements([pad2]),getPadCenter=pad2=>{let bounds=getPadBounds(pad2);return midpoint({x:bounds.minX,y:bounds.minY},{x:bounds.maxX,y:bounds.maxY})},getPadRadius=pad2=>{let bounds=getPadBounds(pad2);return Math.min(bounds.maxX-bounds.minX,bounds.maxY-bounds.minY)/2},isCircularPad=pad2=>pad2.shape==="circle",getCircleShape=pad2=>{let center2=getPadCenter(pad2);return{kind:"circle",x:center2.x,y:center2.y,radius:getPadRadius(pad2)}},getPolygonShape=pad2=>{let bounds=getPadBounds(pad2);return{kind:"polygon",points:[{x:bounds.minX,y:bounds.minY},{x:bounds.maxX,y:bounds.minY},{x:bounds.maxX,y:bounds.maxY},{x:bounds.minX,y:bounds.maxY}]}},getPadToPadGap=(padA,padB)=>isCircularPad(padA)&&isCircularPad(padB)?distanceBetweenCircleAndCircle(getCircleShape(padA),getCircleShape(padB)):isCircularPad(padA)?distanceBetweenCircleAndPolygon(getCircleShape(padA),getPolygonShape(padB)):isCircularPad(padB)?distanceBetweenCircleAndPolygon(getCircleShape(padB),getPolygonShape(padA)):distanceBetweenPolygonAndPolygon(getPolygonShape(padA),getPolygonShape(padB)),getPads=circuitJson=>[...cju_default(circuitJson).pcb_smtpad.list(),...cju_default(circuitJson).pcb_plated_hole.list()],getTraceSegments=circuitJson=>cju_default(circuitJson).pcb_trace.list().flatMap(pcbTrace=>{let segments=[];for(let i3=0;i3<pcbTrace.route.length-1;i3++){let p12=pcbTrace.route[i3],p22=pcbTrace.route[i3+1];p12.route_type==="wire"&&p22.route_type==="wire"&&p12.layer===p22.layer&&segments.push({type:"pcb_trace_segment",pcb_trace_id:pcbTrace.pcb_trace_id,_pcbTrace:pcbTrace,thickness:"width"in p12?p12.width:"width"in p22?p22.width:DEFAULT_TRACE_THICKNESS,layer:p12.layer,x1:p12.x,y1:p12.y,x2:p22.x,y2:p22.y})}return segments});function checkPadPadClearance(circuitJson,{connMap,minClearance}={}){let pads=getPads(circuitJson);if(pads.length<2)return[];let board=getPcbBoard(circuitJson);minClearance??(minClearance=getBoardDrcValue(board,"min_pad_edge_to_pad_edge_clearance")??jlcMinTolerances.min_pad_edge_to_pad_edge_clearance),connMap??(connMap=getFullConnectivityMapFromCircuitJson(circuitJson));let spatialIndex=new SpatialObjectIndex({objects:pads,getBounds:getPadBounds,getId:pad2=>getPrimaryId(pad2)}),errors=new Map;for(let padA of pads){let padAId=getPrimaryId(padA),nearbyPads=spatialIndex.getObjectsInBounds(getPadBounds(padA),minClearance);for(let padB of nearbyPads){let padBId=getPrimaryId(padB);if(padAId===padBId||!getLayersOfPcbElement(padA).some(layer=>getLayersOfPcbElement(padB).includes(layer))||connMap.areIdsConnected(padAId,padBId))continue;let pairId=[padAId,padBId].sort().join("_"),gap=getPadToPadGap(padA,padB);if(gap+EPSILON2>=minClearance)continue;let centerA=getPadCenter(padA),centerB=getPadCenter(padB),nextError={type:"pcb_pad_pad_clearance_error",pcb_pad_pad_clearance_error_id:`pad_pad_clearance_${pairId}`,error_type:"pcb_pad_pad_clearance_error",message:`Pads ${getReadableNameForElement(circuitJson,padAId)} and ${getReadableNameForElement(circuitJson,padBId)} are too close (clearance: ${formatMm(gap)}, minimum: ${formatMm(minClearance)})`,pcb_pad_ids:[padAId,padBId],minimum_clearance:minClearance,actual_clearance:gap,center:{x:(centerA.x+centerB.x)/2,y:(centerA.y+centerB.y)/2}};errors.has(pairId)||errors.set(pairId,nextError)}}return Array.from(errors.values())}function checkPadTraceClearance(circuitJson,{connMap,minClearance}={}){let pads=getPads(circuitJson),segments=getTraceSegments(circuitJson);if(pads.length===0||segments.length===0)return[];let board=getPcbBoard(circuitJson);minClearance??(minClearance=getBoardDrcValue(board,"min_trace_to_pad_edge_clearance")??jlcMinTolerances.min_trace_to_pad_edge_clearance),connMap??(connMap=getFullConnectivityMapFromCircuitJson(circuitJson));let spatialIndex=new SpatialObjectIndex({objects:pads,getBounds:getPadBounds,getId:pad2=>getPrimaryId(pad2)}),errors=new Map;for(let segment2 of segments){let nearbyPads=spatialIndex.getObjectsInBounds(getCollidableBounds(segment2),minClearance+segment2.thickness/2);for(let pad2 of nearbyPads){let padId=getPrimaryId(pad2);if(!getLayersOfPcbElement(pad2).includes(segment2.layer)||connMap.areIdsConnected(segment2.pcb_trace_id,padId))continue;let center2=getPadCenter(pad2),gap=isCircularPad(pad2)?segmentToCircleMinDistance({x:segment2.x1,y:segment2.y1},{x:segment2.x2,y:segment2.y2},{x:center2.x,y:center2.y,radius:getPadRadius(pad2)})-segment2.thickness/2:segmentToBoundsMinDistance({x:segment2.x1,y:segment2.y1},{x:segment2.x2,y:segment2.y2},getPadBounds(pad2))-segment2.thickness/2;if(gap+EPSILON2>=minClearance)continue;let pairId=`${padId}_${segment2.pcb_trace_id}`,nextError={type:"pcb_pad_trace_clearance_error",pcb_pad_trace_clearance_error_id:`pad_trace_clearance_${pairId}`,error_type:"pcb_pad_trace_clearance_error",message:`Pad ${getReadableNameForElement(circuitJson,padId)} and trace ${getReadableNameForElement(circuitJson,segment2.pcb_trace_id)} are too close (clearance: ${formatMm(gap)}, minimum: ${formatMm(minClearance)})`,pcb_pad_id:padId,pcb_trace_id:segment2.pcb_trace_id,minimum_clearance:minClearance,actual_clearance:gap,center:{x:(center2.x+(segment2.x1+segment2.x2)/2)/2,y:(center2.y+(segment2.y1+segment2.y2)/2)/2}},current3=errors.get(pairId);(!current3||gap<current3.gap)&&errors.set(pairId,{error:nextError,gap})}}return Array.from(errors.values()).map(({error:error2})=>error2)}var getClosestPointOnSegment=(point7,segmentStart,segmentEnd)=>{let dx3=segmentEnd.x-segmentStart.x,dy3=segmentEnd.y-segmentStart.y,lengthSquared=dx3*dx3+dy3*dy3;if(lengthSquared===0)return segmentStart;let t52=Math.max(0,Math.min(1,((point7.x-segmentStart.x)*dx3+(point7.y-segmentStart.y)*dy3)/lengthSquared));return{x:segmentStart.x+t52*dx3,y:segmentStart.y+t52*dy3}};function checkViaTraceClearance(circuitJson,{connMap,minClearance}={}){let vias=circuitJson.filter(el3=>el3.type==="pcb_via"),segments=getTraceSegments(circuitJson);if(vias.length===0||segments.length===0)return[];let board=getPcbBoard(circuitJson);minClearance??(minClearance=getBoardDrcValue(board,"min_trace_to_pad_edge_clearance")??jlcMinTolerances.min_trace_to_pad_edge_clearance),connMap??(connMap=getFullConnectivityMapFromCircuitJson(circuitJson));let errors=new Map;for(let via of vias){let viaRadius=via.outer_diameter/2;for(let segment2 of segments){if(!getLayersOfPcbElement(via).includes(segment2.layer)||connMap.areIdsConnected(segment2.pcb_trace_id,via.pcb_via_id))continue;let gap=segmentToCircleMinDistance({x:segment2.x1,y:segment2.y1},{x:segment2.x2,y:segment2.y2},{x:via.x,y:via.y,radius:viaRadius})-segment2.thickness/2;if(gap+EPSILON2>=minClearance)continue;let closestPoint=getClosestPointOnSegment({x:via.x,y:via.y},{x:segment2.x1,y:segment2.y1},{x:segment2.x2,y:segment2.y2}),pairId=`${via.pcb_via_id}_${segment2.pcb_trace_id}`,nextError={type:"pcb_via_trace_clearance_error",pcb_via_trace_clearance_error_id:`via_trace_clearance_${pairId}`,error_type:"pcb_via_trace_clearance_error",message:`Via ${getReadableNameForElement(circuitJson,via.pcb_via_id)} and trace ${getReadableNameForElement(circuitJson,segment2.pcb_trace_id)} are too close (clearance: ${formatMm(gap)}, minimum: ${formatMm(minClearance)})`,pcb_via_id:via.pcb_via_id,pcb_trace_id:segment2.pcb_trace_id,minimum_clearance:minClearance,actual_clearance:gap,center:{x:(via.x+closestPoint.x)/2,y:(via.y+closestPoint.y)/2}},current3=errors.get(pairId);(!current3||gap<current3.gap)&&errors.set(pairId,{error:nextError,gap})}}return Array.from(errors.values()).map(({error:error2})=>error2)}function checkPinMustBeConnected(circuitJson){let errors=[],sourceComponents=circuitJson.filter(el3=>"source_component_id"in el3&&(el3.type==="source_component"||el3.type.startsWith("source_simple_"))),sourcePorts=circuitJson.filter(el3=>el3.type==="source_port"),sourceTraces=circuitJson.filter(el3=>el3.type==="source_trace"),connectedPortIds=new Set;for(let trace of sourceTraces)for(let portId of trace.connected_source_port_ids??[])connectedPortIds.add(portId);let componentInternalConnections=new Map;for(let component of sourceComponents)"internally_connected_source_port_ids"in component&&component.internally_connected_source_port_ids&&componentInternalConnections.set(component.source_component_id,component.internally_connected_source_port_ids);for(let internalGroups of componentInternalConnections.values())for(let group of internalGroups)if(group.some(portId=>connectedPortIds.has(portId)))for(let portId of group)connectedPortIds.add(portId);for(let port of sourcePorts)if(port.must_be_connected===!0&&!connectedPortIds.has(port.source_port_id)){let componentName=sourceComponents.find(c4=>c4.source_component_id===port.source_component_id)?.name??"Unknown";errors.push({type:"source_pin_must_be_connected_error",source_pin_must_be_connected_error_id:`source_pin_must_be_connected_error_${port.source_port_id}`,error_type:"source_pin_must_be_connected_error",message:`Port ${port.name} on ${componentName} must be connected but is floating`,source_component_id:port.source_component_id??"",source_port_id:port.source_port_id,subcircuit_id:port.subcircuit_id})}return errors}var PIN_ATTRIBUTE_KEYS=["must_be_connected","provides_power","requires_power","provides_ground","requires_ground","provides_voltage","requires_voltage","do_not_connect","include_in_board_pinout","can_use_internal_pullup","is_using_internal_pullup","needs_external_pullup","can_use_internal_pulldown","is_using_internal_pulldown","needs_external_pulldown","can_use_open_drain","is_using_open_drain","can_use_push_pull","is_using_push_pull","should_have_decoupling_capacitor","recommended_decoupling_capacitor_capacitance","is_configured_for_i2c_sda","is_configured_for_i2c_scl","is_configured_for_spi_mosi","is_configured_for_spi_miso","is_configured_for_spi_sck","is_configured_for_spi_cs","is_configured_for_uart_tx","is_configured_for_uart_rx","supports_i2c_sda","supports_i2c_scl","supports_spi_mosi","supports_spi_miso","supports_spi_sck","supports_spi_cs","supports_uart_tx","supports_uart_rx"];function hasAnyPinAttribute(port){return PIN_ATTRIBUTE_KEYS.some(key=>port[key]!==void 0)}function checkAllPinsInComponentAreUnderspecified(circuitJson){let warnings=[],db2=cju_default(circuitJson),sourceComponents=db2.source_component.list(),sourcePorts=db2.source_port.list(),portsByComponent=new Map;for(let port of sourcePorts){if(!port.source_component_id)continue;let existing=portsByComponent.get(port.source_component_id)??[];existing.push(port),portsByComponent.set(port.source_component_id,existing)}for(let component of sourceComponents){if(component.ftype!=="simple_chip")continue;let componentPorts=portsByComponent.get(component.source_component_id)??[];componentPorts.length===0||componentPorts.some(port=>hasAnyPinAttribute(port))||warnings.push({type:"source_component_pins_underspecified_warning",source_component_pins_underspecified_warning_id:`source_component_pins_underspecified_warning_${component.source_component_id}`,warning_type:"source_component_pins_underspecified_warning",message:`All pins on ${component.name} are underspecified (no pinAttributes set)`,source_component_id:component.source_component_id,source_port_ids:componentPorts.map(port=>port.source_port_id),subcircuit_id:componentPorts[0]?.subcircuit_id})}return warnings}function checkNoPowerPinDefined(circuitJson){let warnings=[],db2=cju_default(circuitJson),sourceComponents=db2.source_component.list(),sourcePorts=db2.source_port.list(),portsByComponent=new Map;for(let port of sourcePorts){if(!port.source_component_id)continue;let existing=portsByComponent.get(port.source_component_id)??[];existing.push(port),portsByComponent.set(port.source_component_id,existing)}for(let component of sourceComponents){if(component.ftype!=="simple_chip")continue;let componentPorts=portsByComponent.get(component.source_component_id)??[];componentPorts.length===0||componentPorts.some(port=>port.requires_power===!0)||warnings.push({type:"source_no_power_pin_defined_warning",source_no_power_pin_defined_warning_id:`source_no_power_pin_defined_warning_${component.source_component_id}`,warning_type:"source_no_power_pin_defined_warning",message:`${component.name} has no pin with requires_power=true`,source_component_id:component.source_component_id,source_port_ids:componentPorts.map(port=>port.source_port_id),subcircuit_id:componentPorts[0]?.subcircuit_id})}return warnings}function checkNoGroundPinDefined(circuitJson){let warnings=[],db2=cju_default(circuitJson),sourceComponents=db2.source_component.list(),sourcePorts=db2.source_port.list(),portsByComponent=new Map;for(let port of sourcePorts){if(!port.source_component_id)continue;let existing=portsByComponent.get(port.source_component_id)??[];existing.push(port),portsByComponent.set(port.source_component_id,existing)}for(let component of sourceComponents){if(component.ftype!=="simple_chip")continue;let componentPorts=portsByComponent.get(component.source_component_id)??[];componentPorts.length===0||componentPorts.some(port=>port.requires_ground===!0)||warnings.push({type:"source_no_ground_pin_defined_warning",source_no_ground_pin_defined_warning_id:`source_no_ground_pin_defined_warning_${component.source_component_id}`,warning_type:"source_no_ground_pin_defined_warning",message:`${component.name} has no pin with requires_ground=true`,source_component_id:component.source_component_id,source_port_ids:componentPorts.map(port=>port.source_port_id),subcircuit_id:componentPorts[0]?.subcircuit_id})}return warnings}function getFacingDirectionFromInsertionDirection(component){switch(component.insertion_direction){case"from_left":return"x-";case"from_right":return"x+";case"from_front":return"y+";case"from_back":return"y-";case"from_above":return null;default:return null}}function getFacingDirection(component){if(component.insertion_direction)return getFacingDirectionFromInsertionDirection(component);if(!component.center||!component.cable_insertion_center)return null;let dx3=component.cable_insertion_center.x-component.center.x,dy3=component.cable_insertion_center.y-component.center.y;return Math.abs(dx3)<1e-6&&Math.abs(dy3)<1e-6?null:Math.abs(dx3)>=Math.abs(dy3)?dx3>=0?"x+":"x-":dy3>=0?"y+":"y-"}function getRecommendedFacingDirection(component,bounds){if(!component.center)return null;let distances=[{direction:"x-",distance:component.center.x-bounds.minX},{direction:"x+",distance:bounds.maxX-component.center.x},{direction:"y-",distance:component.center.y-bounds.minY},{direction:"y+",distance:bounds.maxY-component.center.y}];return distances.sort((a3,b3)=>a3.distance-b3.distance),distances[0]?.direction??null}function checkConnectorAccessibleOrientation(circuitJson){let board=circuitJson.find(el3=>el3.type==="pcb_board");if(!board)return[];let bounds=(()=>{try{return getBoardBounds(board)}catch{return null}})();if(!bounds)return[];let warnings=[],components=circuitJson.filter(el3=>el3.type==="pcb_component");for(let component of components){let facingDirection=getFacingDirection(component),recommendedFacingDirection=getRecommendedFacingDirection(component,bounds);if(!facingDirection||!recommendedFacingDirection||facingDirection===recommendedFacingDirection)continue;let componentName=getReadableNameForComponent(circuitJson,component.pcb_component_id);warnings.push({type:"pcb_connector_not_in_accessible_orientation_warning",warning_type:"pcb_connector_not_in_accessible_orientation_warning",pcb_connector_not_in_accessible_orientation_warning_id:`pcb_connector_not_in_accessible_orientation_warning_${component.pcb_component_id}`,message:`${componentName} is facing ${facingDirection} but should face ${recommendedFacingDirection} so the connector is accessible from the board edge`,pcb_component_id:component.pcb_component_id,source_component_id:component.source_component_id,pcb_board_id:board.pcb_board_id,facing_direction:facingDirection,recommended_facing_direction:recommendedFacingDirection,subcircuit_id:component.subcircuit_id})}return warnings}function getCourtyardPolygon(el3){if(el3.type==="pcb_courtyard_rect"){let hw3=el3.width/2,hh3=el3.height/2,corners=[{x:-hw3,y:-hh3},{x:+hw3,y:-hh3},{x:+hw3,y:+hh3},{x:-hw3,y:+hh3}],angle=(el3.ccw_rotation??0)*Math.PI/180,cos6=Math.cos(angle),sin6=Math.sin(angle);return corners.map(({x:x4,y:y4})=>({x:el3.center.x+x4*cos6-y4*sin6,y:el3.center.y+x4*sin6+y4*cos6}))}return el3.type==="pcb_courtyard_circle"?Array.from({length:32},(_4,i3)=>{let a3=2*Math.PI*i3/32;return{x:el3.center.x+el3.radius*Math.cos(a3),y:el3.center.y+el3.radius*Math.sin(a3)}}):el3.outline}function getComponentName2(circuitJson,pcbComponentId){let pcbComponent=circuitJson.find(el3=>el3.type==="pcb_component"&&el3.pcb_component_id===pcbComponentId);if(pcbComponent?.type!=="pcb_component")return pcbComponentId;let sourceComponent=circuitJson.find(el3=>el3.type==="source_component"&&el3.source_component_id===pcbComponent.source_component_id);return sourceComponent?.type==="source_component"&&sourceComponent.name?sourceComponent.name:pcbComponentId}function polygonsOverlap(polyA,polyB){if(polyA.some(p4=>isPointInsidePolygon(p4,polyB))||polyB.some(p4=>isPointInsidePolygon(p4,polyA)))return!0;for(let i3=0;i3<polyA.length;i3++){let a12=polyA[i3],a22=polyA[(i3+1)%polyA.length];for(let j4=0;j4<polyB.length;j4++){let b12=polyB[j4],b22=polyB[(j4+1)%polyB.length];if(doSegmentsIntersect(a12,a22,b12,b22))return!0}}return!1}function checkCourtyardOverlap(circuitJson){let courtyards=circuitJson.filter(el3=>el3.type==="pcb_courtyard_rect"||el3.type==="pcb_courtyard_circle"||el3.type==="pcb_courtyard_outline"),byComponent=new Map;for(let el3 of courtyards){let id2=el3.pcb_component_id;byComponent.has(id2)||byComponent.set(id2,[]),byComponent.get(id2).push(el3)}let componentIds=Array.from(byComponent.keys()),errors=[];for(let i3=0;i3<componentIds.length;i3++)for(let j4=i3+1;j4<componentIds.length;j4++){let idA=componentIds[i3],idB=componentIds[j4],overlapping=!1;outer:for(let a3 of byComponent.get(idA))for(let b3 of byComponent.get(idB)){if("layer"in a3&&"layer"in b3&&a3.layer!==b3.layer)continue;let polyA=getCourtyardPolygon(a3),polyB=getCourtyardPolygon(b3);if(polygonsOverlap(polyA,polyB)){overlapping=!0;break outer}}overlapping&&errors.push({type:"pcb_courtyard_overlap_error",pcb_error_id:`pcb_courtyard_overlap_${idA}_${idB}`,error_type:"pcb_courtyard_overlap_error",message:`Courtyard of ${getComponentName2(circuitJson,idA)} overlaps with courtyard of ${getComponentName2(circuitJson,idB)}`,pcb_component_ids:[idA,idB]})}return errors}function getDistanceBetweenPoints(pointA,pointB){return Math.sqrt((pointB.x-pointA.x)**2+(pointB.y-pointA.y)**2)}var POINT_ON_SEGMENT_TOLERANCE_MM=1e-9;function isPointOnSegment3(point7,segment2){let crossProduct=(point7.y-segment2.start.y)*(segment2.end.x-segment2.start.x)-(point7.x-segment2.start.x)*(segment2.end.y-segment2.start.y);if(Math.abs(crossProduct)>POINT_ON_SEGMENT_TOLERANCE_MM)return!1;let dotProduct=(point7.x-segment2.start.x)*(segment2.end.x-segment2.start.x)+(point7.y-segment2.start.y)*(segment2.end.y-segment2.start.y);if(dotProduct<-POINT_ON_SEGMENT_TOLERANCE_MM)return!1;let squaredLength=(segment2.end.x-segment2.start.x)**2+(segment2.end.y-segment2.start.y)**2;return dotProduct<=squaredLength+POINT_ON_SEGMENT_TOLERANCE_MM}function isPointInPad(point7,pad2){if(pad2.type==="pcb_smtpad"){if(pad2.shape==="circle")return getDistanceBetweenPoints(point7,pad2)<=pad2.radius;if(pad2.shape==="rect"){let halfWidth=pad2.width/2,halfHeight=pad2.height/2;return Math.abs(point7.x-pad2.x)<=halfWidth&&Math.abs(point7.y-pad2.y)<=halfHeight}if(pad2.shape==="rotated_rect"){let dx3=point7.x-pad2.x,dy3=point7.y-pad2.y,angle=-pad2.ccw_rotation,rotatedX=dx3*Math.cos(angle)-dy3*Math.sin(angle),rotatedY=dx3*Math.sin(angle)+dy3*Math.cos(angle);return Math.abs(rotatedX)<=pad2.width/2&&Math.abs(rotatedY)<=pad2.height/2}if(pad2.shape==="pill"){let halfWidth=pad2.width/2,halfHeight=pad2.height/2,radius=pad2.radius;if(Math.abs(point7.x-pad2.x)<=halfWidth-radius&&Math.abs(point7.y-pad2.y)<=halfHeight)return!0;let cornerX=Math.max(Math.abs(point7.x-pad2.x)-(halfWidth-radius),0),cornerY=Math.max(Math.abs(point7.y-pad2.y)-(halfHeight-radius),0);return cornerX*cornerX+cornerY*cornerY<=radius*radius}if(pad2.shape==="polygon"){let inside2=!1;for(let i3=0,j4=pad2.points.length-1;i3<pad2.points.length;j4=i3++){let pi3=pad2.points[i3],pj=pad2.points[j4];if(isPointOnSegment3(point7,{start:pi3,end:pj}))return!0;pi3.y>point7.y!=pj.y>point7.y&&point7.x<(pj.x-pi3.x)*(point7.y-pi3.y)/(pj.y-pi3.y)+pi3.x&&(inside2=!inside2)}return inside2}}if(pad2.type==="pcb_plated_hole"){if(pad2.shape==="circle")return getDistanceBetweenPoints(point7,pad2)<=pad2.outer_diameter/2;if(pad2.shape==="oval"||pad2.shape==="pill")return Math.abs(point7.x-pad2.x)<=pad2.outer_width/2&&Math.abs(point7.y-pad2.y)<=pad2.outer_height/2;if(pad2.shape==="circular_hole_with_rect_pad"||pad2.shape==="pill_hole_with_rect_pad")return Math.abs(point7.x-pad2.x)<=pad2.rect_pad_width/2&&Math.abs(point7.y-pad2.y)<=pad2.rect_pad_height/2}return!1}function getRoutePointCenter(point7){return point7.route_type==="through_pad"?{x:(point7.start.x+point7.end.x)/2,y:(point7.start.y+point7.end.y)/2}:{x:point7.x,y:point7.y}}function routePointConnectsToAnotherExpectedPort(point7,expectedPorts,missingPcbPortId,padMap){return point7.route_type!=="wire"?!1:expectedPorts.some(expectedPort=>!expectedPort.pcb_port_id||expectedPort.pcb_port_id===missingPcbPortId?!1:padMap.get(expectedPort.pcb_port_id)?.some(pad2=>isPointInPad({x:point7.x,y:point7.y},pad2))??!1)}function getMissingConnectionErrorCenter({firstPoint,lastPoint,port,expectedPorts,padMap}){let errorLocation,firstWirePoint=firstPoint.route_type==="wire"?firstPoint:void 0,lastWirePoint=lastPoint.route_type==="wire"?lastPoint:void 0,firstWirePointReferencesPort=getPcbPortIdsConnectedToRoutePoint(firstPoint).includes(port.pcb_port_id),lastWirePointReferencesPort=getPcbPortIdsConnectedToRoutePoint(lastPoint).includes(port.pcb_port_id);firstWirePointReferencesPort&&firstWirePoint?errorLocation=firstWirePoint:lastWirePointReferencesPort&&lastWirePoint||routePointConnectsToAnotherExpectedPort(firstPoint,expectedPorts,port.pcb_port_id,padMap)&&lastWirePoint?errorLocation=lastWirePoint:routePointConnectsToAnotherExpectedPort(lastPoint,expectedPorts,port.pcb_port_id,padMap)&&firstWirePoint?errorLocation=firstWirePoint:firstWirePoint&&lastWirePoint?errorLocation=distance22(firstWirePoint,port)<=distance22(lastWirePoint,port)?firstWirePoint:lastWirePoint:firstWirePoint?errorLocation=firstWirePoint:lastWirePoint&&(errorLocation=lastWirePoint);let firstPointCenter=getRoutePointCenter(firstPoint),lastPointCenter=getRoutePointCenter(lastPoint);return errorLocation?{x:errorLocation.x,y:errorLocation.y}:{x:(firstPointCenter.x+lastPointCenter.x)/2,y:(firstPointCenter.y+lastPointCenter.y)/2}}function checkTracesAreContiguous(circuitJson){let errors=[],pcbPorts=circuitJson.filter(el3=>el3.type==="pcb_port"),pcbTraces=circuitJson.filter(el3=>el3.type==="pcb_trace"),sourceTraces=circuitJson.filter(el3=>el3.type==="source_trace"),pcbSmtPads=circuitJson.filter(el3=>el3.type==="pcb_smtpad"),pcbPlatedHoles=circuitJson.filter(el3=>el3.type==="pcb_plated_hole"),padMap=new Map,pcbConnectivityMap=new PcbConnectivityMap(circuitJson);for(let pad2 of pcbSmtPads)pad2.pcb_port_id&&padMap.set(pad2.pcb_port_id,[...padMap.get(pad2.pcb_port_id)??[],pad2]);for(let hole of pcbPlatedHoles)hole.pcb_port_id&&padMap.set(hole.pcb_port_id,[...padMap.get(hole.pcb_port_id)??[],hole]);for(let trace of pcbTraces){if(trace.route.length===0)continue;let firstPoint=trace.route[0],lastPoint=trace.route[trace.route.length-1],sourceTrace=sourceTraces.find(st3=>st3.source_trace_id===trace.source_trace_id),expectedPorts=sourceTrace?pcbPorts.filter(port=>sourceTrace.connected_source_port_ids?.includes(port.source_port_id)):[];for(let i3=1;i3<trace.route.length-1;i3++){let prevPoint=trace.route[i3-1],currentPoint=trace.route[i3],nextPoint=trace.route[i3+1];if(currentPoint.route_type==="via"){let prevIsWire=prevPoint.route_type==="wire",nextIsWire=nextPoint.route_type==="wire";if(prevIsWire&&nextIsWire){let prevAligned=Math.abs(prevPoint.x-currentPoint.x)<.01&&Math.abs(prevPoint.y-currentPoint.y)<.01,nextAligned=Math.abs(nextPoint.x-currentPoint.x)<.01&&Math.abs(nextPoint.y-currentPoint.y)<.01;if(!prevAligned||!nextAligned){let traceName2=getReadableNameForPcbTrace(circuitJson,trace.pcb_trace_id);errors.push({type:"pcb_trace_error",message:`Via in trace [${traceName2}] is misaligned at position {x: ${currentPoint.x}, y: ${currentPoint.y}}.`,source_trace_id:sourceTrace?.source_trace_id||trace.source_trace_id||`!${trace.pcb_trace_id}`,error_type:"pcb_trace_error",pcb_trace_id:trace.pcb_trace_id,pcb_trace_error_id:`misaligned_via_${trace.pcb_trace_id}_${i3}`,pcb_component_ids:[],pcb_port_ids:[]})}}}}let traceName=getReadableNameForPcbTrace(circuitJson,trace.pcb_trace_id);for(let port of expectedPorts){if(!port.pcb_port_id)continue;let pads=padMap.get(port.pcb_port_id);if(!pads?.length)continue;let isConnectedByRoutedSourceTrace=!1;for(let candidateTrace of pcbConnectivityMap.getAllTracesConnectedToTrace(trace.pcb_trace_id)){if(candidateTrace.pcb_trace_id===trace.pcb_trace_id||!candidateTrace.source_trace_id)continue;let candidateSourceTrace=sourceTraces.find(st3=>st3.source_trace_id===candidateTrace.source_trace_id);if(!(!sourceTrace||candidateTrace.source_trace_id!==sourceTrace.source_trace_id&&!candidateSourceTrace?.connected_source_port_ids.includes(port.source_port_id))&&getPcbPortIdsConnectedToTrace(candidateTrace).includes(port.pcb_port_id)){isConnectedByRoutedSourceTrace=!0;break}}if(isConnectedByRoutedSourceTrace)continue;let isFirstPointConnected=firstPoint.route_type==="wire"&&pads.some(pad2=>isPointInPad({x:firstPoint.x,y:firstPoint.y},pad2)),isLastPointConnected=lastPoint.route_type==="wire"&&pads.some(pad2=>isPointInPad({x:lastPoint.x,y:lastPoint.y},pad2));if(!isFirstPointConnected&&!isLastPointConnected){let portName=getReadableNameForPcbPort(circuitJson,port.pcb_port_id).replace("pcb_port",""),padType=pads[0].type.replace(/pcb_/,""),errorCenter=getMissingConnectionErrorCenter({firstPoint,lastPoint,port,expectedPorts,padMap});errors.push({type:"pcb_trace_error",message:`Trace [${traceName}] is missing a connection to ${padType}${portName}`,source_trace_id:sourceTrace?.source_trace_id||trace.source_trace_id||`!${trace.pcb_trace_id}`,error_type:"pcb_trace_error",pcb_trace_id:trace.pcb_trace_id,pcb_trace_error_id:`missing_connection_${trace.pcb_trace_id}_${port.pcb_port_id}`,center:errorCenter,pcb_component_ids:[],pcb_port_ids:[port.pcb_port_id]})}}if(expectedPorts.length===0){let firstConnectsToAnyPad=!1,lastConnectsToAnyPad=!1,endpointsAreSame=firstPoint.route_type==="wire"&&lastPoint.route_type==="wire"&&Math.abs(firstPoint.x-lastPoint.x)<.01&&Math.abs(firstPoint.y-lastPoint.y)<.01;for(let pads of padMap.values())firstPoint.route_type==="wire"&&pads.some(pad2=>isPointInPad({x:firstPoint.x,y:firstPoint.y},pad2))&&(firstConnectsToAnyPad=!0),lastPoint.route_type==="wire"&&pads.some(pad2=>isPointInPad({x:lastPoint.x,y:lastPoint.y},pad2))&&(lastConnectsToAnyPad=!0);!firstConnectsToAnyPad&&firstPoint.route_type==="wire"&&errors.push({type:"pcb_trace_error",message:`Trace [${traceName}] has disconnected endpoint at (${firstPoint.x.toFixed(2)}, ${firstPoint.y.toFixed(2)})`,source_trace_id:sourceTrace?.source_trace_id||trace.source_trace_id||`!${trace.pcb_trace_id}`,error_type:"pcb_trace_error",pcb_trace_id:trace.pcb_trace_id,pcb_trace_error_id:`disconnected_endpoint_${trace.pcb_trace_id}_start`,center:{x:firstPoint.x,y:firstPoint.y},pcb_component_ids:[],pcb_port_ids:[]}),!lastConnectsToAnyPad&&lastPoint.route_type==="wire"&&!(endpointsAreSame&&!firstConnectsToAnyPad)&&errors.push({type:"pcb_trace_error",message:`Trace [${traceName}] has disconnected endpoint at (${lastPoint.x.toFixed(2)}, ${lastPoint.y.toFixed(2)})`,source_trace_id:sourceTrace?.source_trace_id||trace.source_trace_id||`!${trace.pcb_trace_id}`,error_type:"pcb_trace_error",pcb_trace_id:trace.pcb_trace_id,pcb_trace_error_id:`disconnected_endpoint_${trace.pcb_trace_id}_end`,center:{x:lastPoint.x,y:lastPoint.y},pcb_component_ids:[],pcb_port_ids:[]})}}return errors}async function runAllPlacementChecks(circuitJson){return[...checkViasOffBoard(circuitJson),...checkPcbComponentsOutOfBoard(circuitJson),...checkPcbComponentOverlap(circuitJson),...checkPadPadClearance(circuitJson),...checkPadTraceClearance(circuitJson),...checkCourtyardOverlap(circuitJson),...checkConnectorAccessibleOrientation(circuitJson)]}async function runAllNetlistChecks(circuitJson){return[...checkPinMustBeConnected(circuitJson)]}async function runAllPinSpecificationChecks(circuitJson){return[...checkAllPinsInComponentAreUnderspecified(circuitJson),...checkNoPowerPinDefined(circuitJson),...checkNoGroundPinDefined(circuitJson)]}async function runAllRoutingChecks(circuitJson){return[...checkEachPcbPortConnectedToPcbTraces(circuitJson),...checkSourceTracesHavePcbTraces(circuitJson),...checkEachPcbTraceNonOverlapping(circuitJson),...checkViaTraceClearance(circuitJson),...checkSameNetViaSpacing(circuitJson),...checkDifferentNetViaSpacing(circuitJson),...checkTracesAreContiguous(circuitJson),...checkPcbTracesOutOfBoard(circuitJson)]}init_dist6();var SI_PREFIXES=[{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 formatSiUnit(value){if(value==null)return"";if(value===0)return"0";let absValue=Math.abs(value),prefix=SI_PREFIXES.find(p4=>{let scaled2=absValue/p4.value;return scaled2>=1&&scaled2<1e3})||SI_PREFIXES[SI_PREFIXES.length-1],formatted=(value/prefix.value).toPrecision(3);return formatted.includes(".")&&!/\.0+$/.test(formatted)&&(formatted=formatted.replace(/0+$/,"")),formatted=formatted.replace(/\.0+$/,""),`${formatted}${prefix.symbol}`}init_dist6();init_dist();var FlatQueue=class{constructor(capacity2=1/0,ValuesArray=Float64Array,IdsArray=Uint32Array){let fixed=capacity2!==1/0;this.ids=fixed?new IdsArray(capacity2):[],this.values=fixed?new ValuesArray(capacity2):[],this.capacity=capacity2,this.length=0}clear(){this.length=0}push(item,priority){if(this.length===this.capacity)throw new RangeError("Queue is at capacity.");let pos=this.length++;for(;pos>0;){let parent=pos-1>>1,parentValue=this.values[parent];if(priority>=parentValue)break;this.ids[pos]=this.ids[parent],this.values[pos]=parentValue,pos=parent}this.ids[pos]=item,this.values[pos]=priority}pop(){if(this.length===0)return;let ids=this.ids,values=this.values,top=ids[0],last=--this.length;if(last>0){let id2=ids[last],value=values[last],pos=0,halfLen=last>>1;for(;pos<halfLen;){let left=(pos<<1)+1,right=left+1,child=left+(+(right<last)&+(values[right]<values[left]));if(values[child]>=value)break;ids[pos]=ids[child],values[pos]=values[child],pos=child}ids[pos]=id2,values[pos]=value}return top}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){Array.isArray(this.ids)&&(this.ids.length=this.length),Array.isArray(this.values)&&(this.values.length=this.length)}};var ARRAY_TYPES=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],VERSION=3,Flatbush=class _Flatbush{static from(data,byteOffset=0){if(byteOffset%8!==0)throw new Error("byteOffset must be 8-byte aligned.");if(!data||data.byteLength===void 0||"buffer"in data)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[magic,versionAndType]=new Uint8Array(data,byteOffset+0,2);if(magic!==251)throw new Error("Data does not appear to be in a Flatbush format.");let version2=versionAndType>>4;if(version2!==VERSION)throw new Error(`Got v${version2} data when expected v${VERSION}.`);let ArrayType=ARRAY_TYPES[versionAndType&15];if(!ArrayType)throw new Error("Unrecognized array type.");let[nodeSize]=new Uint16Array(data,byteOffset+2,1),[numItems]=new Uint32Array(data,byteOffset+4,1);return new _Flatbush(numItems,nodeSize,ArrayType,void 0,data,byteOffset)}constructor(numItems,nodeSize=16,ArrayType=Float64Array,ArrayBufferType=ArrayBuffer,data,byteOffset=0){if(numItems===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(numItems)||numItems<=0)throw new Error(`Unexpected numItems value: ${numItems}.`);this.numItems=+numItems,this.nodeSize=Math.min(Math.max(+nodeSize,2),65535),this.byteOffset=byteOffset;let n4=numItems,numNodes=n4;this._levelBounds=[n4*4];do n4=Math.ceil(n4/this.nodeSize),numNodes+=n4,this._levelBounds.push(numNodes*4);while(n4!==1);this.ArrayType=ArrayType,this.IndexArrayType=numNodes<16384?Uint16Array:Uint32Array;let arrayTypeIndex=ARRAY_TYPES.indexOf(ArrayType),nodesByteSize=numNodes*4*ArrayType.BYTES_PER_ELEMENT;if(arrayTypeIndex<0)throw new Error(`Unexpected typed array class: ${ArrayType}.`);let BoxCtor=ArrayType,IdxCtor=this.IndexArrayType;if(data)this.data=data,this._boxes=new BoxCtor(data,byteOffset+8,numNodes*4),this._indices=new IdxCtor(data,byteOffset+8+nodesByteSize,numNodes),this._pos=numNodes*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 data2=this.data=new ArrayBufferType(8+nodesByteSize+numNodes*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new BoxCtor(data2,8,numNodes*4),this._indices=new IdxCtor(data2,8+nodesByteSize,numNodes),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(data2,0,2).set([251,(VERSION<<4)+arrayTypeIndex]),new Uint16Array(data2,2,1)[0]=nodeSize,new Uint32Array(data2,4,1)[0]=numItems}this._queue=new FlatQueue}add(minX,minY,maxX=minX,maxY=minY){let index=this._pos>>2,boxes=this._boxes;return this._indices[index]=index,boxes[this._pos++]=minX,boxes[this._pos++]=minY,boxes[this._pos++]=maxX,boxes[this._pos++]=maxY,minX<this.minX&&(this.minX=minX),minY<this.minY&&(this.minY=minY),maxX>this.maxX&&(this.maxX=maxX),maxY>this.maxY&&(this.maxY=maxY),index}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let boxes=this._boxes;if(this.numItems<=this.nodeSize){boxes[this._pos++]=this.minX,boxes[this._pos++]=this.minY,boxes[this._pos++]=this.maxX,boxes[this._pos++]=this.maxY;return}let width=this.maxX-this.minX||1,height=this.maxY-this.minY||1,hilbertValues=new Int32Array(this.numItems),hilbertMax=65535;for(let i3=0,pos=0;i3<this.numItems;i3++){let minX=boxes[pos++],minY=boxes[pos++],maxX=boxes[pos++],maxY=boxes[pos++],x4=Math.floor(hilbertMax*((minX+maxX)/2-this.minX)/width),y4=Math.floor(hilbertMax*((minY+maxY)/2-this.minY)/height);hilbertValues[i3]=hilbert(x4,y4)}sort(hilbertValues,boxes,this._indices,0,this.numItems-1,this.nodeSize);for(let i3=0,pos=0;i3<this._levelBounds.length-1;i3++){let end=this._levelBounds[i3];for(;pos<end;){let nodeIndex=pos,nodeMinX=boxes[pos++],nodeMinY=boxes[pos++],nodeMaxX=boxes[pos++],nodeMaxY=boxes[pos++];for(let j4=1;j4<this.nodeSize&&pos<end;j4++)nodeMinX=Math.min(nodeMinX,boxes[pos++]),nodeMinY=Math.min(nodeMinY,boxes[pos++]),nodeMaxX=Math.max(nodeMaxX,boxes[pos++]),nodeMaxY=Math.max(nodeMaxY,boxes[pos++]);this._indices[this._pos>>2]=nodeIndex,boxes[this._pos++]=nodeMinX,boxes[this._pos++]=nodeMinY,boxes[this._pos++]=nodeMaxX,boxes[this._pos++]=nodeMaxY}}}search(minX,minY,maxX,maxY,filterFn){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let{_boxes:boxes,_levelBounds:levelBounds,_indices:indices,nodeSize}=this,numItems4=this.numItems*4,nodeIndex=boxes.length-4,level=levelBounds.length-1,q4=[],results=[],contained=!1;for(;nodeIndex!==void 0;){let end=Math.min(nodeIndex+nodeSize*4,levelBounds[level]),isNode=nodeIndex>=numItems4;if(contained)this._collectContained(nodeIndex,end,level,isNode,q4,results,filterFn);else for(let pos=nodeIndex;pos<end;pos+=4){let x02=boxes[pos];if(maxX<x02)continue;let y02=boxes[pos+1];if(maxY<y02)continue;let x12=boxes[pos+2];if(minX>x12)continue;let y12=boxes[pos+3];if(minY>y12)continue;let index=indices[pos>>2]|0;if(isNode){let c4=+(minX<=x02&&minY<=y02&&maxX>=x12&&maxY>=y12);q4.push(index|c4,level-1)}else(filterFn===void 0||filterFn(index,x02,y02,x12,y12))&&results.push(index)}level=q4.pop(),nodeIndex=q4.pop(),nodeIndex!==void 0&&(contained=(nodeIndex&1)===1,nodeIndex&=-2)}return results}_collectContained(nodeIndex,end,level,isNode,q4,results,filterFn){let boxes=this._boxes,indices=this._indices;if(isNode)for(let pos=nodeIndex;pos<end;pos+=4)q4.push(indices[pos>>2]|1,level-1);else for(let pos=nodeIndex;pos<end;pos+=4){let index=indices[pos>>2]|0;(filterFn===void 0||filterFn(index,boxes[pos],boxes[pos+1],boxes[pos+2],boxes[pos+3]))&&results.push(index)}}neighbors(x4,y4,maxResults=1/0,maxDistance=1/0,filterFn){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let{_boxes:boxes,_levelBounds:levelBounds,_indices:indices,_queue:q4,nodeSize}=this,numItems4=this.numItems*4,nodeSize4=nodeSize*4,results=[],maxDistSquared=maxDistance*maxDistance;for(q4.push(boxes.length-4<<1,0);q4.length;){let top=q4.ids[0];if(top&1){if(q4.values[0]>maxDistSquared||(q4.pop(),results.push(top>>1),results.length===maxResults))break;continue}q4.pop();let nodeIndex=top>>1,isLeafLevel=nodeIndex<numItems4,end=Math.min(nodeIndex+nodeSize4,upperBound(nodeIndex,levelBounds));for(let pos=nodeIndex;pos<end;pos+=4){let childIndex=indices[pos>>2]|0,minX=boxes[pos],minY=boxes[pos+1],maxX=boxes[pos+2],maxY=boxes[pos+3],dx3=x4<minX?minX-x4:x4>maxX?x4-maxX:0,dy3=y4<minY?minY-y4:y4>maxY?y4-maxY:0,dist=dx3*dx3+dy3*dy3;dist>maxDistSquared||(isLeafLevel?(filterFn===void 0||filterFn(childIndex))&&q4.push(childIndex<<1|1,dist):q4.push(childIndex<<1,dist))}}return q4.clear(),results}};function upperBound(value,arr){let i3=0,j4=arr.length-1;for(;i3<j4;){let m4=i3+j4>>1;arr[m4]>value?j4=m4:i3=m4+1}return arr[i3]}function sort(values,boxes,indices,left,right,nodeSize){let stack=[left,right];for(;stack.length;){let r5=stack.pop()||0,l4=stack.pop()||0;if(r5-l4<=nodeSize&&Math.floor(l4/nodeSize)>=Math.floor(r5/nodeSize))continue;let a3=values[l4],b3=values[l4+r5>>1],c4=values[r5],pivot=a3>b3!=a3>c4?a3:b3<a3!=b3<c4?b3:c4,i3=l4-1,j4=r5+1;for(;;){do i3++;while(values[i3]<pivot);do j4--;while(values[j4]>pivot);if(i3>=j4)break;swap(values,boxes,indices,i3,j4)}stack.push(l4,j4,j4+1,r5)}}function swap(values,boxes,indices,i3,j4){let temp=values[i3];values[i3]=values[j4],values[j4]=temp;let k4=4*i3,m4=4*j4,a3=boxes[k4],b3=boxes[k4+1],c4=boxes[k4+2],d4=boxes[k4+3];boxes[k4]=boxes[m4],boxes[k4+1]=boxes[m4+1],boxes[k4+2]=boxes[m4+2],boxes[k4+3]=boxes[m4+3],boxes[m4]=a3,boxes[m4+1]=b3,boxes[m4+2]=c4,boxes[m4+3]=d4;let e5=indices[i3];indices[i3]=indices[j4],indices[j4]=e5}function hilbert(x4,y4){let a3=x4^y4,b3=65535^a3,c4=65535^(x4|y4),d4=x4&(y4^65535),A4=a3|b3>>1,B4=a3>>1^a3,C4=c4^(c4>>1^b3&d4>>1),D4=d4^(a3&c4>>1^d4>>1);return a3=A4&A4>>2^B4&B4>>2,b3=A4&B4>>2^B4&(A4^B4)>>2,c4=C4^(A4&C4>>2^B4&D4>>2),d4=D4^(B4&C4>>2^(A4^B4)&D4>>2),A4=a3&a3>>4^b3&b3>>4,B4=a3&b3>>4^b3&(a3^b3)>>4,C4=c4^(a3&c4>>4^b3&d4>>4),D4=d4^(b3&c4>>4^(a3^b3)&d4>>4),c4=C4^(A4&C4>>8^B4&D4>>8),d4=D4^(B4&C4>>8^(A4^B4)&D4>>8),c4^=c4>>1,d4^=d4>>1,a3=x4^y4,b3=d4|65535^(a3|c4),a3=(a3|a3<<8)&16711935,a3=(a3|a3<<4)&252645135,a3=(a3|a3<<2)&858993459,a3=(a3|a3<<1)&1431655765,b3=(b3|b3<<8)&16711935,b3=(b3|b3<<4)&252645135,b3=(b3|b3<<2)&858993459,b3=(b3|b3<<1)&1431655765,((b3<<1|a3)>>>0)-2147483648}var __create2=Object.create,__defProp3=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__getProtoOf2=Object.getPrototypeOf,__hasOwnProp2=Object.prototype.hasOwnProperty,__commonJS2=(cb3,mod)=>function(){return mod||(0,cb3[__getOwnPropNames2(cb3)[0]])((mod={exports:{}}).exports,mod),mod.exports},__copyProps2=(to3,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to3,key)&&key!==except&&__defProp3(to3,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to3},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create2(__getProtoOf2(mod)):{},__copyProps2(isNodeMode||!mod||!mod.__esModule?__defProp3(target,"default",{value:mod,enumerable:!0}):target,mod)),require_is_buffer=__commonJS2({"node_modules/is-buffer/index.js"(exports,module){"use strict";module.exports=function(obj){return obj!=null&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)};function isBuffer(obj){return!!obj.constructor&&typeof obj.constructor.isBuffer=="function"&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return typeof obj.readFloatLE=="function"&&typeof obj.slice=="function"&&isBuffer(obj.slice(0,0))}}}),require_kind_of=__commonJS2({"node_modules/kind-of/index.js"(exports,module){"use strict";var isBuffer=require_is_buffer(),toString3=Object.prototype.toString;module.exports=function(val){if(typeof val>"u")return"undefined";if(val===null)return"null";if(val===!0||val===!1||val instanceof Boolean)return"boolean";if(typeof val=="string"||val instanceof String)return"string";if(typeof val=="number"||val instanceof Number)return"number";if(typeof val=="function"||val instanceof Function)return"function";if(typeof Array.isArray<"u"&&Array.isArray(val))return"array";if(val instanceof RegExp)return"regexp";if(val instanceof Date)return"date";var type=toString3.call(val);return type==="[object RegExp]"?"regexp":type==="[object Date]"?"date":type==="[object Arguments]"?"arguments":type==="[object Error]"?"error":isBuffer(val)?"buffer":type==="[object Set]"?"set":type==="[object WeakSet]"?"weakset":type==="[object Map]"?"map":type==="[object WeakMap]"?"weakmap":type==="[object Symbol]"?"symbol":type==="[object Int8Array]"?"int8array":type==="[object Uint8Array]"?"uint8array":type==="[object Uint8ClampedArray]"?"uint8clampedarray":type==="[object Int16Array]"?"int16array":type==="[object Uint16Array]"?"uint16array":type==="[object Int32Array]"?"int32array":type==="[object Uint32Array]"?"uint32array":type==="[object Float32Array]"?"float32array":type==="[object Float64Array]"?"float64array":"object"}}}),require_rename_keys=__commonJS2({"node_modules/rename-keys/index.js"(exports,module){"use strict";(function(){"use strict";function rename2(obj,fn3){if(typeof fn3!="function")return obj;var res2={};for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(res2[fn3(key,obj[key])||key]=obj[key]);return res2}typeof module<"u"&&module.exports?module.exports=rename2:typeof define=="function"&&define.amd?define([],function(){return rename2}):window.rename=rename2})()}}),require_deep_rename_keys=__commonJS2({"node_modules/deep-rename-keys/index.js"(exports,module){"use strict";var typeOf=require_kind_of(),rename2=require_rename_keys();module.exports=function renameDeep(obj,cb3){var type=typeOf(obj);if(type!=="object"&&type!=="array")throw new Error("expected an object");var res2=[];type==="object"&&(obj=rename2(obj,cb3),res2={});for(var key in obj)if(obj.hasOwnProperty(key)){var val=obj[key];typeOf(val)==="object"||typeOf(val)==="array"?res2[key]=renameDeep(val,cb3):res2[key]=val}return res2}}}),require_eventemitter3=__commonJS2({"node_modules/eventemitter3/index.js"(exports,module){"use strict";var has=Object.prototype.hasOwnProperty,prefix="~";function Events(){}Object.create&&(Events.prototype=Object.create(null),new Events().__proto__||(prefix=!1));function EE3(fn3,context,once){this.fn=fn3,this.context=context,this.once=once||!1}function EventEmitter(){this._events=new Events,this._eventsCount=0}EventEmitter.prototype.eventNames=function(){var names=[],events,name;if(this._eventsCount===0)return names;for(name in events=this._events)has.call(events,name)&&names.push(prefix?name.slice(1):name);return Object.getOwnPropertySymbols?names.concat(Object.getOwnPropertySymbols(events)):names},EventEmitter.prototype.listeners=function(event,exists){var evt=prefix?prefix+event:event,available=this._events[evt];if(exists)return!!available;if(!available)return[];if(available.fn)return[available.fn];for(var i3=0,l4=available.length,ee3=new Array(l4);i3<l4;i3++)ee3[i3]=available[i3].fn;return ee3},EventEmitter.prototype.emit=function(event,a12,a22,a3,a4,a52){var evt=prefix?prefix+event:event;if(!this._events[evt])return!1;var listeners=this._events[evt],len=arguments.length,args,i3;if(listeners.fn){switch(listeners.once&&this.removeListener(event,listeners.fn,void 0,!0),len){case 1:return listeners.fn.call(listeners.context),!0;case 2:return listeners.fn.call(listeners.context,a12),!0;case 3:return listeners.fn.call(listeners.context,a12,a22),!0;case 4:return listeners.fn.call(listeners.context,a12,a22,a3),!0;case 5:return listeners.fn.call(listeners.context,a12,a22,a3,a4),!0;case 6:return listeners.fn.call(listeners.context,a12,a22,a3,a4,a52),!0}for(i3=1,args=new Array(len-1);i3<len;i3++)args[i3-1]=arguments[i3];listeners.fn.apply(listeners.context,args)}else{var length22=listeners.length,j4;for(i3=0;i3<length22;i3++)switch(listeners[i3].once&&this.removeListener(event,listeners[i3].fn,void 0,!0),len){case 1:listeners[i3].fn.call(listeners[i3].context);break;case 2:listeners[i3].fn.call(listeners[i3].context,a12);break;case 3:listeners[i3].fn.call(listeners[i3].context,a12,a22);break;case 4:listeners[i3].fn.call(listeners[i3].context,a12,a22,a3);break;default:if(!args)for(j4=1,args=new Array(len-1);j4<len;j4++)args[j4-1]=arguments[j4];listeners[i3].fn.apply(listeners[i3].context,args)}}return!0},EventEmitter.prototype.on=function(event,fn3,context){var listener=new EE3(fn3,context||this),evt=prefix?prefix+event:event;return this._events[evt]?this._events[evt].fn?this._events[evt]=[this._events[evt],listener]:this._events[evt].push(listener):(this._events[evt]=listener,this._eventsCount++),this},EventEmitter.prototype.once=function(event,fn3,context){var listener=new EE3(fn3,context||this,!0),evt=prefix?prefix+event:event;return this._events[evt]?this._events[evt].fn?this._events[evt]=[this._events[evt],listener]:this._events[evt].push(listener):(this._events[evt]=listener,this._eventsCount++),this},EventEmitter.prototype.removeListener=function(event,fn3,context,once){var evt=prefix?prefix+event:event;if(!this._events[evt])return this;if(!fn3)return--this._eventsCount===0?this._events=new Events:delete this._events[evt],this;var listeners=this._events[evt];if(listeners.fn)listeners.fn===fn3&&(!once||listeners.once)&&(!context||listeners.context===context)&&(--this._eventsCount===0?this._events=new Events:delete this._events[evt]);else{for(var i3=0,events=[],length22=listeners.length;i3<length22;i3++)(listeners[i3].fn!==fn3||once&&!listeners[i3].once||context&&listeners[i3].context!==context)&&events.push(listeners[i3]);events.length?this._events[evt]=events.length===1?events[0]:events:--this._eventsCount===0?this._events=new Events:delete this._events[evt]}return this},EventEmitter.prototype.removeAllListeners=function(event){var evt;return event?(evt=prefix?prefix+event:event,this._events[evt]&&(--this._eventsCount===0?this._events=new Events:delete this._events[evt])):(this._events=new Events,this._eventsCount=0),this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.addListener=EventEmitter.prototype.on,EventEmitter.prototype.setMaxListeners=function(){return this},EventEmitter.prefixed=prefix,EventEmitter.EventEmitter=EventEmitter,typeof module<"u"&&(module.exports=EventEmitter)}}),require_lexer=__commonJS2({"node_modules/xml-lexer/dist/lexer.js"(exports,module){"use strict";function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}var EventEmitter=require_eventemitter3(),noop=function(){},State2={data:"state-data",cdata:"state-cdata",tagBegin:"state-tag-begin",tagName:"state-tag-name",tagEnd:"state-tag-end",attributeNameStart:"state-attribute-name-start",attributeName:"state-attribute-name",attributeNameEnd:"state-attribute-name-end",attributeValueBegin:"state-attribute-value-begin",attributeValue:"state-attribute-value"},Action={lt:"action-lt",gt:"action-gt",space:"action-space",equal:"action-equal",quote:"action-quote",slash:"action-slash",char:"action-char",error:"action-error"},Type={text:"text",openTag:"open-tag",closeTag:"close-tag",attributeName:"attribute-name",attributeValue:"attribute-value"},charToAction={" ":Action.space," ":Action.space,"\n":Action.space,"\r":Action.space,"<":Action.lt,">":Action.gt,'"':Action.quote,"'":Action.quote,"=":Action.equal,"/":Action.slash},getAction=function(char){return charToAction[char]||Action.char},create=function(options){var _State$data,_State$tagBegin,_State$tagName,_State$tagEnd,_State$attributeNameS,_State$attributeName,_State$attributeNameE,_State$attributeValue,_State$attributeValue2,_lexer$stateMachine;options=Object.assign({debug:!1},options);var lexer=new EventEmitter,state2=State2.data,data="",tagName="",attrName="",attrValue="",isClosing="",openingQuote="",emit=function(type,value){if(!(tagName[0]==="?"||tagName[0]==="!")){var event={type,value};options.debug&&console.log("emit:",event),lexer.emit("data",event)}};lexer.stateMachine=(_lexer$stateMachine={},_defineProperty(_lexer$stateMachine,State2.data,(_State$data={},_defineProperty(_State$data,Action.lt,function(){data.trim()&&emit(Type.text,data),tagName="",isClosing=!1,state2=State2.tagBegin}),_defineProperty(_State$data,Action.char,function(char){data+=char}),_State$data)),_defineProperty(_lexer$stateMachine,State2.cdata,_defineProperty({},Action.char,function(char){data+=char,data.substr(-3)==="]]>"&&(emit(Type.text,data.slice(0,-3)),data="",state2=State2.data)})),_defineProperty(_lexer$stateMachine,State2.tagBegin,(_State$tagBegin={},_defineProperty(_State$tagBegin,Action.space,noop),_defineProperty(_State$tagBegin,Action.char,function(char){tagName=char,state2=State2.tagName}),_defineProperty(_State$tagBegin,Action.slash,function(){tagName="",isClosing=!0}),_State$tagBegin)),_defineProperty(_lexer$stateMachine,State2.tagName,(_State$tagName={},_defineProperty(_State$tagName,Action.space,function(){isClosing?state2=State2.tagEnd:(state2=State2.attributeNameStart,emit(Type.openTag,tagName))}),_defineProperty(_State$tagName,Action.gt,function(){emit(isClosing?Type.closeTag:Type.openTag,tagName),data="",state2=State2.data}),_defineProperty(_State$tagName,Action.slash,function(){state2=State2.tagEnd,emit(Type.openTag,tagName)}),_defineProperty(_State$tagName,Action.char,function(char){tagName+=char,tagName==="![CDATA["&&(state2=State2.cdata,data="",tagName="")}),_State$tagName)),_defineProperty(_lexer$stateMachine,State2.tagEnd,(_State$tagEnd={},_defineProperty(_State$tagEnd,Action.gt,function(){emit(Type.closeTag,tagName),data="",state2=State2.data}),_defineProperty(_State$tagEnd,Action.char,noop),_State$tagEnd)),_defineProperty(_lexer$stateMachine,State2.attributeNameStart,(_State$attributeNameS={},_defineProperty(_State$attributeNameS,Action.char,function(char){attrName=char,state2=State2.attributeName}),_defineProperty(_State$attributeNameS,Action.gt,function(){data="",state2=State2.data}),_defineProperty(_State$attributeNameS,Action.space,noop),_defineProperty(_State$attributeNameS,Action.slash,function(){isClosing=!0,state2=State2.tagEnd}),_State$attributeNameS)),_defineProperty(_lexer$stateMachine,State2.attributeName,(_State$attributeName={},_defineProperty(_State$attributeName,Action.space,function(){state2=State2.attributeNameEnd}),_defineProperty(_State$attributeName,Action.equal,function(){emit(Type.attributeName,attrName),state2=State2.attributeValueBegin}),_defineProperty(_State$attributeName,Action.gt,function(){attrValue="",emit(Type.attributeName,attrName),emit(Type.attributeValue,attrValue),data="",state2=State2.data}),_defineProperty(_State$attributeName,Action.slash,function(){isClosing=!0,attrValue="",emit(Type.attributeName,attrName),emit(Type.attributeValue,attrValue),state2=State2.tagEnd}),_defineProperty(_State$attributeName,Action.char,function(char){attrName+=char}),_State$attributeName)),_defineProperty(_lexer$stateMachine,State2.attributeNameEnd,(_State$attributeNameE={},_defineProperty(_State$attributeNameE,Action.space,noop),_defineProperty(_State$attributeNameE,Action.equal,function(){emit(Type.attributeName,attrName),state2=State2.attributeValueBegin}),_defineProperty(_State$attributeNameE,Action.gt,function(){attrValue="",emit(Type.attributeName,attrName),emit(Type.attributeValue,attrValue),data="",state2=State2.data}),_defineProperty(_State$attributeNameE,Action.char,function(char){attrValue="",emit(Type.attributeName,attrName),emit(Type.attributeValue,attrValue),attrName=char,state2=State2.attributeName}),_State$attributeNameE)),_defineProperty(_lexer$stateMachine,State2.attributeValueBegin,(_State$attributeValue={},_defineProperty(_State$attributeValue,Action.space,noop),_defineProperty(_State$attributeValue,Action.quote,function(char){openingQuote=char,attrValue="",state2=State2.attributeValue}),_defineProperty(_State$attributeValue,Action.gt,function(){attrValue="",emit(Type.attributeValue,attrValue),data="",state2=State2.data}),_defineProperty(_State$attributeValue,Action.char,function(char){openingQuote="",attrValue=char,state2=State2.attributeValue}),_State$attributeValue)),_defineProperty(_lexer$stateMachine,State2.attributeValue,(_State$attributeValue2={},_defineProperty(_State$attributeValue2,Action.space,function(char){openingQuote?attrValue+=char:(emit(Type.attributeValue,attrValue),state2=State2.attributeNameStart)}),_defineProperty(_State$attributeValue2,Action.quote,function(char){openingQuote===char?(emit(Type.attributeValue,attrValue),state2=State2.attributeNameStart):attrValue+=char}),_defineProperty(_State$attributeValue2,Action.gt,function(char){openingQuote?attrValue+=char:(emit(Type.attributeValue,attrValue),data="",state2=State2.data)}),_defineProperty(_State$attributeValue2,Action.slash,function(char){openingQuote?attrValue+=char:(emit(Type.attributeValue,attrValue),isClosing=!0,state2=State2.tagEnd)}),_defineProperty(_State$attributeValue2,Action.char,function(char){attrValue+=char}),_State$attributeValue2)),_lexer$stateMachine);var step=function(char){options.debug&&console.log(state2,char);var actions=lexer.stateMachine[state2],action=actions[getAction(char)]||actions[Action.error]||actions[Action.char];action(char)};return lexer.write=function(str){for(var len=str.length,i3=0;i3<len;i3++)step(str[i3])},lexer};module.exports={State:State2,Action,Type,create}}}),require_reader=__commonJS2({"node_modules/xml-reader/dist/reader.js"(exports,module){"use strict";var EventEmitter=require_eventemitter3(),Lexer=require_lexer(),Type=Lexer.Type,NodeType={element:"element",text:"text"},createNode=function(params){return Object.assign({name:"",type:NodeType.element,value:"",parent:null,attributes:{},children:[]},params)},create=function(options){options=Object.assign({stream:!1,parentNodes:!0,doneEvent:"done",tagPrefix:"tag:",emitTopLevelOnly:!1,debug:!1},options);var lexer=void 0,rootNode=void 0,current3=void 0,attrName=void 0,reader=new EventEmitter,handleLexerData=function(data){switch(data.type){case Type.openTag:if(current3===null)current3=rootNode,current3.name=data.value;else{var node=createNode({name:data.value,parent:current3});current3.children.push(node),current3=node}break;case Type.closeTag:var parent=current3.parent;if(options.parentNodes||(current3.parent=null),current3.name!==data.value)break;options.stream&&parent===rootNode&&(rootNode.children=[],current3.parent=null),(!options.emitTopLevelOnly||parent===rootNode)&&(reader.emit(options.tagPrefix+current3.name,current3),reader.emit("tag",current3.name,current3)),current3===rootNode&&(lexer.removeAllListeners("data"),reader.emit(options.doneEvent,current3),rootNode=null),current3=parent;break;case Type.text:current3&¤t3.children.push(createNode({type:NodeType.text,value:data.value,parent:options.parentNodes?current3:null}));break;case Type.attributeName:attrName=data.value,current3.attributes[attrName]="";break;case Type.attributeValue:current3.attributes[attrName]=data.value;break}};return reader.reset=function(){lexer=Lexer.create({debug:options.debug}),lexer.on("data",handleLexerData),rootNode=createNode(),current3=null,attrName="",reader.parse=lexer.write},reader.reset(),reader},parseSync2=function(xml,options){options=Object.assign({},options,{stream:!1,tagPrefix:":"});var reader=create(options),res2=void 0;return reader.on("done",function(ast){res2=ast}),reader.parse(xml),res2};module.exports={parseSync:parseSync2,create,NodeType}}});function computeGridToAffineTransform(params){let{originX,originY,rows,cols,cellSizeMm,width,height}=params,a3,c4;cols>1?(a3=width/((cols-1)*cellSizeMm),c4=originX*(1-a3)-.5*cellSizeMm*a3):(a3=1,c4=originX+width/2-(originX+.5*cellSizeMm));let e5,f3;return rows>1?(e5=height/((rows-1)*cellSizeMm),f3=originY*(1-e5)-.5*cellSizeMm*e5):(e5=1,f3=originY+height/2-(originY+.5*cellSizeMm)),{a:a3,b:0,c:c4,d:0,e:e5,f:f3}}function applyAffineTransformToPoint(t52,p4){return{x:t52.a*p4.x+t52.b*p4.y+t52.c,y:t52.d*p4.x+t52.e*p4.y+t52.f}}var{cos:cos3,sin:sin3,PI:PI3}=Math,{tan:tan3}=Math,import_deep_rename_keys=__toESM2(require_deep_rename_keys()),import_xml_reader=__toESM2(require_reader());var BaseSolver=class{constructor(){__publicField(this,"MAX_ITERATIONS",1e5);__publicField(this,"solved",!1);__publicField(this,"failed",!1);__publicField(this,"iterations",0);__publicField(this,"progress",0);__publicField(this,"error",null);__publicField(this,"activeSubSolver");__publicField(this,"failedSubSolvers");__publicField(this,"timeToSolve");__publicField(this,"stats",{});__publicField(this,"_setupDone",!1)}getSolverName(){return this.constructor.name}setup(){this._setupDone||(this._setup(),this._setupDone=!0)}_setup(){}step(){if(this._setupDone||this.setup(),!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e5){throw this.error=`${this.getSolverName()} error: ${e5}`,this.failed=!0,e5}!this.solved&&this.iterations>=this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>=this.MAX_ITERATIONS&&(this.error=`${this.getSolverName()} ran out of iterations`,this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}getOutput(){return null}solve(){let startTime=Date.now();for(;!this.solved&&!this.failed;)this.step();let endTime=Date.now();this.timeToSolve=endTime-startTime}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function clamp5(value,min,max){return Math.max(min,Math.min(max,value))}function computeMaxIterationsByNodeSizeAndConnectionCount(input2){let states=input2.planeSize*input2.layers,connectionCount=input2.connectionCount,connectionFactor=Math.sqrt(connectionCount),requestedMaxIterations=Math.max(1,input2.maxIterations),baseComputedMaxIterations=clamp5(Math.round(states*(8+1.2*connectionFactor)),15e4,12e6),computedMaxIters=clamp5(Math.round(baseComputedMaxIterations*input2.effort),15e4,12e6),minIterationBudgetIters=clamp5(Math.round(requestedMaxIterations*.2),15e4,2e6),maxIterationsIters=Math.max(1,Math.min(requestedMaxIterations,Math.max(minIterationBudgetIters,computedMaxIters))),baseSearchBudgetIters=clamp5(Math.round(states*(10+.8*connectionFactor)*input2.effort),5e4,4e6);return{maxIterationsIters,baseSearchBudgetIters}}function rippedContains(r5,id2){for(let cur=r5;cur;cur=cur.prev)if(cur.id===id2)return!0;return!1}var MinHeap=class{constructor(){__publicField(this,"f",[]);__publicField(this,"seq",[]);__publicField(this,"id",[]);__publicField(this,"n",0)}push(f3,seq,id2){let i3=this.n++;for(this.f[i3]=f3,this.seq[i3]=seq,this.id[i3]=id2;i3>0;){let p4=i3-1>>1;if(this.less(p4,i3))break;this.swap(i3,p4),i3=p4}}pop(){let out=this.id[0];return this.n--,this.n>0&&(this.f[0]=this.f[this.n],this.seq[0]=this.seq[this.n],this.id[0]=this.id[this.n],this.siftDown(0)),out}get size(){return this.n}clear(){this.n=0}siftDown(i3){for(;;){let l4=i3*2+1,r5=l4+1;if(l4>=this.n)return;let m4=l4;if(r5<this.n&&!this.less(l4,r5)&&(m4=r5),this.less(i3,m4))return;this.swap(i3,m4),i3=m4}}less(i3,j4){let fi3=this.f[i3],fj=this.f[j4];return fi3!==fj?fi3<fj:this.seq[i3]<this.seq[j4]}swap(i3,j4){let tmpF=this.f[i3];this.f[i3]=this.f[j4],this.f[j4]=tmpF;let tmpS=this.seq[i3];this.seq[i3]=this.seq[j4],this.seq[j4]=tmpS;let tmpI=this.id[i3];this.id[i3]=this.id[j4],this.id[j4]=tmpI}};function toRootNetName(connectionName,rootConnectionName){return rootConnectionName??connectionName.replace(/_mst\d+$/,"")}var DIRS_DR=[-1,-1,-1,0,0,1,1,1],DIRS_DC=[-1,0,1,-1,1,-1,0,1],HighDensitySolverA01=class extends BaseSolver{constructor(props){super();__publicField(this,"nodeWithPortPoints");__publicField(this,"cellSizeMm");__publicField(this,"viaDiameter");__publicField(this,"MAX_RIPS");__publicField(this,"maxCellCount");__publicField(this,"traceThickness");__publicField(this,"traceMargin");__publicField(this,"viaMinDistFromBorder");__publicField(this,"showPenaltyMap");__publicField(this,"showUsedCellMap");__publicField(this,"effort");__publicField(this,"stepMultiplier");__publicField(this,"hyperParameters");__publicField(this,"initialPenaltyFn");__publicField(this,"rows");__publicField(this,"cols");__publicField(this,"layers");__publicField(this,"gridOrigin");__publicField(this,"gridToBoundsTransform");__publicField(this,"availableZ");__publicField(this,"zToLayer");__publicField(this,"layerToZ");__publicField(this,"connNameToId");__publicField(this,"connIdToName");__publicField(this,"connIdToRootNet");__publicField(this,"overlapFriendlyRootNets");__publicField(this,"planeSize");__publicField(this,"usedCellsFlat");__publicField(this,"portOwnerFlat");__publicField(this,"usedDiagFlat");__publicField(this,"penalty2d");__publicField(this,"visitedStamp");__publicField(this,"sharedCrossRootPortCells");__publicField(this,"stamp",0);__publicField(this,"viaOffsetsDr");__publicField(this,"viaOffsetsDc");__publicField(this,"viaOffsetsLen");__publicField(this,"minViaRow");__publicField(this,"maxViaRow");__publicField(this,"minViaCol");__publicField(this,"maxViaCol");__publicField(this,"usedIndicesByConn");__publicField(this,"usedDiagIndicesByConn");__publicField(this,"unsolvedSegs");__publicField(this,"solvedRoutes");__publicField(this,"activeConnSeg",null);__publicField(this,"activeConnId",-1);__publicField(this,"crossLayerSearch",!1);__publicField(this,"nodePool");__publicField(this,"heap");__publicField(this,"seqCounter",0);__publicField(this,"_viaOccs",[]);__publicField(this,"ripCount");__publicField(this,"totalRipEvents",0);__publicField(this,"searchIterations",0);__publicField(this,"consecutiveSkips",0);__publicField(this,"penaltyCap");__publicField(this,"baseSearchBudgetIters");__publicField(this,"_moveCost",0);__publicField(this,"_moveRipped",null);this.nodeWithPortPoints=props.nodeWithPortPoints,this.cellSizeMm=props.cellSizeMm,this.viaDiameter=props.viaDiameter,this.maxCellCount=props.maxCellCount,this.traceThickness=props.traceThickness??.1,this.traceMargin=props.traceMargin??.15,this.viaMinDistFromBorder=props.viaMinDistFromBorder??.15,this.showPenaltyMap=props.showPenaltyMap??!1,this.showUsedCellMap=props.showUsedCellMap??!1,this.effort=props.effort??1,this.stepMultiplier=Math.max(1,Math.floor(props.stepMultiplier??1)),this.hyperParameters={shuffleSeed:0,ripCost:10,ripTracePenalty:.5,ripViaPenalty:.75,viaBaseCost:.1,greedyMultiplier:1.5,...props.hyperParameters},this.MAX_ITERATIONS=1e8,this.MAX_RIPS=200,this.initialPenaltyFn=props.initialPenaltyFn}get unsolvedConnections(){return this.unsolvedSegs}get solvedConnectionsMap(){return this.solvedRoutes}get activeConnection(){if(!this.activeConnSeg)return null;let s3=this.activeConnSeg;return{connectionName:this.connIdToName[s3.connId]??"",start:{row:s3.startRow,col:s3.startCol,z:s3.startZ,x:0,y:0},end:{row:s3.endRow,col:s3.endCol,z:s3.endZ,x:0,y:0}}}get openSet(){return{length:this.heap?.size??0}}get gridStats(){return{cells:this.planeSize||0,layers:this.layers||0,states:(this.planeSize||0)*(this.layers||0)}}getConstructorParams(){return[{nodeWithPortPoints:this.nodeWithPortPoints,cellSizeMm:this.cellSizeMm,viaDiameter:this.viaDiameter,maxCellCount:this.maxCellCount,stepMultiplier:this.stepMultiplier,traceThickness:this.traceThickness,traceMargin:this.traceMargin,viaMinDistFromBorder:this.viaMinDistFromBorder,showPenaltyMap:this.showPenaltyMap,showUsedCellMap:this.showUsedCellMap,effort:this.effort,hyperParameters:this.hyperParameters,initialPenaltyFn:this.initialPenaltyFn}]}_setup(){let{nodeWithPortPoints,cellSizeMm}=this,{width,height,center:center2}=nodeWithPortPoints;this.availableZ=nodeWithPortPoints.availableZ??[...new Set(nodeWithPortPoints.portPoints.map(pp3=>pp3.z))].sort((a3,b3)=>a3-b3),this.rows=Math.floor(height/cellSizeMm),this.cols=Math.floor(width/cellSizeMm),this.layers=this.availableZ.length,this.planeSize=this.rows*this.cols;let totalCells=this.layers*this.planeSize;if(this.maxCellCount!==void 0&&totalCells>this.maxCellCount){this.error=`Cell count ${totalCells} exceeds maxCellCount ${this.maxCellCount}`,this.failed=!0;return}let totalDiags=this.layers*Math.max(0,this.rows-1)*Math.max(0,this.cols-1)*2;this.zToLayer=new Map,this.layerToZ=new Map;for(let i3=0;i3<this.availableZ.length;i3++){let z4=this.availableZ[i3];this.zToLayer.set(z4,i3),this.layerToZ.set(i3,z4)}if(this.gridOrigin={x:center2.x-width/2,y:center2.y-height/2},this.gridToBoundsTransform=computeGridToAffineTransform({originX:this.gridOrigin.x,originY:this.gridOrigin.y,rows:this.rows,cols:this.cols,cellSizeMm,width,height}),this.connNameToId=new Map,this.connIdToName=[],this.connIdToRootNet=[],this.overlapFriendlyRootNets=new Set,this.penalty2d=new Float64Array(this.planeSize),this.initialPenaltyFn)for(let row=0;row<this.rows;row++){let rowBase=row*this.cols;for(let col=0;col<this.cols;col++){let x4=this.gridOrigin.x+(col+.5)*cellSizeMm,y4=this.gridOrigin.y+(row+.5)*cellSizeMm,px3=(col+.5)/this.cols,py3=(row+.5)/this.rows;this.penalty2d[rowBase+col]=this.initialPenaltyFn({x:x4,y:y4,px:px3,py:py3,row,col})}}this.usedCellsFlat=new Int32Array(totalCells).fill(-1),this.portOwnerFlat=new Int32Array(totalCells).fill(-1),this.usedDiagFlat=new Int32Array(totalDiags).fill(-1),this.visitedStamp=new Uint32Array(totalCells),this.stamp=0;let viaRadiusCells=Math.ceil(this.viaDiameter/2/cellSizeMm),r22=viaRadiusCells*viaRadiusCells,drList=[],dcList=[];for(let dr3=-viaRadiusCells;dr3<=viaRadiusCells;dr3++)for(let dc3=-viaRadiusCells;dc3<=viaRadiusCells;dc3++)dr3*dr3+dc3*dc3<=r22&&(drList.push(dr3),dcList.push(dc3));if(this.viaOffsetsLen=drList.length,this.viaOffsetsDr=new Int32Array(drList),this.viaOffsetsDc=new Int32Array(dcList),this.viaMinDistFromBorder>0){let borderCells=Math.ceil(this.viaMinDistFromBorder/cellSizeMm);this.minViaRow=borderCells,this.maxViaRow=this.rows-1-borderCells,this.minViaCol=borderCells,this.maxViaCol=this.cols-1-borderCells}else this.minViaRow=0,this.maxViaRow=this.rows-1,this.minViaCol=0,this.maxViaCol=this.cols-1;this.unsolvedSegs=this.buildConnectionSegs(),this.sharedCrossRootPortCells=new Set;let rootByPortFlat=new Map;for(let pp3 of this.nodeWithPortPoints.portPoints){let connId=this.connNameToId.get(pp3.connectionName);if(connId===void 0)continue;let cell=this.pointToCell(pp3),flatIdx=(cell.z*this.rows+cell.row)*this.cols+cell.col,rootNet=this.connIdToRootNet[connId],existingRoot=rootByPortFlat.get(flatIdx);existingRoot===void 0?rootByPortFlat.set(flatIdx,rootNet):existingRoot!==rootNet&&this.sharedCrossRootPortCells.add(flatIdx);let existing=this.portOwnerFlat[flatIdx];existing===-1||existing===connId?this.portOwnerFlat[flatIdx]=connId:this.portOwnerFlat[flatIdx]=-2}this.solvedRoutes=new Map,this.usedIndicesByConn=[],this.usedDiagIndicesByConn=[],this.ripCount=[],this.consecutiveSkips=0,this.penaltyCap=this.hyperParameters.ripCost*.5,this.shuffleConnections();let budget=computeMaxIterationsByNodeSizeAndConnectionCount({planeSize:this.planeSize,layers:this.layers,connectionCount:this.unsolvedSegs.length,effort:this.effort,maxIterations:this.MAX_ITERATIONS});this.baseSearchBudgetIters=budget.baseSearchBudgetIters,this.MAX_ITERATIONS=budget.maxIterationsIters,this.activeConnSeg=null,this.activeConnId=-1,this.nodePool=[],this.heap=new MinHeap,this.seqCounter=0}_step(){for(let i3=0;i3<this.stepMultiplier;i3++){if(this.solved||this.failed)return;this.stepOnce()}}stepOnce(){if(!this.activeConnSeg){if(this.unsolvedSegs.length===0){this.solved=!0;return}let next2=this.unsolvedSegs.shift();this.activeConnSeg=next2,this.activeConnId=next2.connId,this.crossLayerSearch=next2.startZ!==next2.endZ,this.nodePool=[],this.heap.clear(),this.seqCounter=0,this.searchIterations=0,this.nextStamp();let f3=this.computeH(next2.startZ,next2.startRow,next2.startCol,next2.endZ,next2.endRow,next2.endCol)*this.hyperParameters.greedyMultiplier;this.nodePool.push({z:next2.startZ,row:next2.startRow,col:next2.startCol,g:0,f:f3,parentIdx:-1,ripped:null}),this.heap.push(f3,this.seqCounter++,0);return}this.searchIterations++;let connRips=this.ripCount[this.activeConnId]??0,budget=Math.round(this.baseSearchBudgetIters*(1+Math.min(connRips,10)*.25));if(this.searchIterations>budget){let pen=this.penalty2d;for(let i3=0;i3<pen.length;i3++)pen[i3]=pen[i3]*.9;this.unsolvedSegs.push(this.activeConnSeg),this.activeConnSeg=null,this.activeConnId=-1,this.heap.clear(),this.nodePool=[],this.consecutiveSkips++,this.consecutiveSkips>=this.unsolvedSegs.length*3&&(this.error=`Convergence failure: ${this.unsolvedSegs.length} connections stuck`,this.failed=!0);return}if(this.heap.size===0){this.error=`No path found for ${this.connIdToName[this.activeConnId]}`,this.failed=!0;return}let nodeIdx=this.heap.pop(),node=this.nodePool[nodeIdx],{z:z4,row,col,g:g6,ripped}=node,cellIdx=(z4*this.rows+row)*this.cols+col;if(this.visitedStamp[cellIdx]===this.stamp)return;this.visitedStamp[cellIdx]=this.stamp;let seg=this.activeConnSeg;if(z4===seg.endZ&&row===seg.endRow&&col===seg.endCol){this.finalizeRoute(nodeIdx),this.activeConnSeg=null,this.activeConnId=-1;return}let endZ=seg.endZ,endRow=seg.endRow,endCol=seg.endCol,activeConn=this.activeConnId,rows=this.rows,cols=this.cols,cellSizeMm=this.cellSizeMm,visited=this.visitedStamp,stamp=this.stamp;for(let d4=0;d4<8;d4++){let nr3=row+DIRS_DR[d4],nc3=col+DIRS_DC[d4];if(nr3<0||nr3>=rows||nc3<0||nc3>=cols)continue;let nIdx=(z4*rows+nr3)*cols+nc3;if(visited[nIdx]===stamp||(this.computeMoveCostAndRips(activeConn,z4,row,col,z4,nr3,nc3,ripped),this._moveCost<0))continue;let g22=g6+this._moveCost,f22=g22+this.computeH(z4,nr3,nc3,endZ,endRow,endCol)*this.hyperParameters.greedyMultiplier,newNodeIdx=this.nodePool.length;this.nodePool.push({z:z4,row:nr3,col:nc3,g:g22,f:f22,parentIdx:nodeIdx,ripped:this._moveRipped}),this.heap.push(f22,this.seqCounter++,newNodeIdx)}if(row>=this.minViaRow&&row<=this.maxViaRow&&col>=this.minViaCol&&col<=this.maxViaCol)for(let nz2=0;nz2<this.layers;nz2++){if(nz2===z4)continue;let nIdx=(nz2*rows+row)*cols+col;if(visited[nIdx]===stamp||(this.computeMoveCostAndRips(activeConn,z4,row,col,nz2,row,col,ripped),this._moveCost<0))continue;let g22=g6+this._moveCost,f22=g22+this.computeH(nz2,row,col,endZ,endRow,endCol)*this.hyperParameters.greedyMultiplier,newNodeIdx=this.nodePool.length;this.nodePool.push({z:nz2,row,col,g:g22,f:f22,parentIdx:nodeIdx,ripped:this._moveRipped}),this.heap.push(f22,this.seqCounter++,newNodeIdx)}}computeMoveCostAndRips(activeConn,fromZ,fromRow,fromCol,toZ,toRow,toCol,ripped){let cost=0,r5=ripped,cols=this.cols;if(fromZ!==toZ){cost+=this.hyperParameters.viaBaseCost,cost+=Math.min(this.penalty2d[toRow*cols+toCol],this.penaltyCap);let toFlatIdx=(toZ*this.rows+toRow)*cols+toCol,fixedOwner=this.portOwnerFlat[toFlatIdx],allowFixedOverlap=this.connIdToRootNet[fixedOwner]===this.connIdToRootNet[activeConn]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[activeConn]),seg=this.activeConnSeg,isSegEnd=!!seg&&toZ===seg.endZ&&toRow===seg.endRow&&toCol===seg.endCol;if(fixedOwner>=0&&fixedOwner!==activeConn&&!allowFixedOverlap&&!isSegEnd){this._moveCost=-1,this._moveRipped=r5;return}this.fillViaOccupants(toRow,toCol,activeConn);let occs=this._viaOccs;for(let i3=0;i3<occs.length;i3++){let occ=occs[i3];rippedContains(r5,occ)||(cost+=this.hyperParameters.ripCost,r5={id:occ,prev:r5}),cost+=this.hyperParameters.ripViaPenalty}}else{let dr3=fromRow>toRow?fromRow-toRow:toRow-fromRow,dc3=fromCol>toCol?fromCol-toCol:toCol-fromCol;cost+=(dr3+dc3>1?Math.SQRT2:1)*this.cellSizeMm,cost+=Math.min(this.penalty2d[toRow*cols+toCol],this.penaltyCap);let flatIdx=(toZ*this.rows+toRow)*cols+toCol,fixedOwner=this.portOwnerFlat[flatIdx],allowFixedOverlap=this.connIdToRootNet[fixedOwner]===this.connIdToRootNet[activeConn]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[activeConn]),seg=this.activeConnSeg,isSegEnd=!!seg&&toZ===seg.endZ&&toRow===seg.endRow&&toCol===seg.endCol;if(fixedOwner>=0&&fixedOwner!==activeConn&&!allowFixedOverlap&&!isSegEnd){this._moveCost=-1,this._moveRipped=r5;return}let occ=this.usedCellsFlat[flatIdx],allowSameRootOverlap=this.connIdToRootNet[occ]===this.connIdToRootNet[activeConn]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[activeConn]);if(occ!==-1&&occ!==activeConn&&!allowSameRootOverlap&&(rippedContains(r5,occ)||(cost+=this.hyperParameters.ripCost,r5={id:occ,prev:r5}),cost+=this.hyperParameters.ripTracePenalty),dr3===1&&dc3===1){let sqRow=fromRow<toRow?fromRow:toRow,sqCol=fromCol<toCol?fromCol:toCol,crossingSlot=(fromRow<toRow&&fromCol<toCol||fromRow>toRow&&fromCol>toCol?0:1)^1,sqCols=this.cols-1,diagBase=((toZ*(this.rows-1)+sqRow)*sqCols+sqCol)*2,crossingOcc=this.usedDiagFlat[diagBase+crossingSlot],allowCrossingOverlap=this.connIdToRootNet[crossingOcc]===this.connIdToRootNet[activeConn]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[activeConn]);if(crossingOcc!==-1&&crossingOcc!==activeConn&&!allowCrossingOverlap){this._moveCost=-1,this._moveRipped=r5;return}}}this._moveCost=cost,this._moveRipped=r5}fillViaOccupants(row,col,activeConn){let occs=this._viaOccs;occs.length=0;let rows=this.rows,cols=this.cols,offDr=this.viaOffsetsDr,offDc=this.viaOffsetsDc,offLen=this.viaOffsetsLen,used=this.usedCellsFlat;for(let z4=0;z4<this.layers;z4++){let zBase=z4*this.planeSize;for(let i3=0;i3<offLen;i3++){let r5=row+offDr[i3],c4=col+offDc[i3];if(r5<0||c4<0||r5>=rows||c4>=cols)continue;let occ=used[zBase+r5*cols+c4];if(occ===-1||occ===activeConn||this.connIdToRootNet[occ]===this.connIdToRootNet[activeConn]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[activeConn]))continue;let seen=!1;for(let j4=0;j4<occs.length;j4++)if(occs[j4]===occ){seen=!0;break}seen||occs.push(occ)}}}shouldSkipFixedPortHalo(flatIdx,connId){let fixedOwner=this.portOwnerFlat[flatIdx];return fixedOwner===connId?!1:fixedOwner===-2?!0:fixedOwner<0?!1:!(this.connIdToRootNet[fixedOwner]===this.connIdToRootNet[connId]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[connId]))}nextStamp(){this.stamp=this.stamp+1>>>0,this.stamp===0&&(this.visitedStamp.fill(0),this.stamp=1)}computeH(z4,row,col,toZ,toRow,toCol){let dr3=Math.abs(row-toRow),dc3=Math.abs(col-toCol),manhattan=dr3+dc3;if(z4===toZ)return manhattan*this.cellSizeMm;if(!this.crossLayerSearch)return manhattan*this.cellSizeMm+this.hyperParameters.viaBaseCost;let vr1=Math.max(this.minViaRow,Math.min(this.maxViaRow,row)),vc1=Math.max(this.minViaCol,Math.min(this.maxViaCol,col)),vr22=Math.max(this.minViaRow,Math.min(this.maxViaRow,toRow)),vc22=Math.max(this.minViaCol,Math.min(this.maxViaCol,toCol)),via1=Math.abs(row-vr1)+Math.abs(col-vc1)+Math.abs(vr1-toRow)+Math.abs(vc1-toCol),via2=Math.abs(row-vr22)+Math.abs(col-vc22)+Math.abs(vr22-toRow)+Math.abs(vc22-toCol);return Math.max(Math.min(via1,via2),manhattan)*this.cellSizeMm+this.hyperParameters.viaBaseCost}internConn(name,rootNetName){let existing=this.connNameToId.get(name);if(existing!==void 0)return existing;let id2=this.connIdToName.length;return this.connIdToName.push(name),this.connIdToRootNet.push(toRootNetName(name,rootNetName)),this.connNameToId.set(name,id2),id2}buildConnectionSegs(){let byName=new Map;for(let pp3 of this.nodeWithPortPoints.portPoints){let name=pp3.connectionName;byName.has(name)||byName.set(name,{points:[],rootConnectionName:pp3.rootConnectionName}),byName.get(name).points.push(pp3)}let segs=[],seenSegmentKeys=new Set;for(let[name,conn]of byName){let pts=conn.points;if(pts.length<2)continue;let connId=this.internConn(name,conn.rootConnectionName);for(let i3=0;i3<pts.length-1;i3++){let s3=this.pointToCell(pts[i3]),e5=this.pointToCell(pts[i3+1]),endpointA=`${s3.z}:${s3.row}:${s3.col}`,endpointB=`${e5.z}:${e5.row}:${e5.col}`,orderedEndpoints=endpointA<endpointB?`${endpointA}|${endpointB}`:`${endpointB}|${endpointA}`,netName=conn.rootConnectionName??name,segKey=`${netName}|${orderedEndpoints}`;if(seenSegmentKeys.has(segKey)){this.overlapFriendlyRootNets.add(netName);continue}seenSegmentKeys.add(segKey),segs.push({connId,startZ:s3.z,startRow:s3.row,startCol:s3.col,startPoint:pts[i3],endZ:e5.z,endRow:e5.row,endCol:e5.col,endPoint:pts[i3+1]})}}return segs}pointToCell(pt3){let col=Math.max(0,Math.min(this.cols-1,Math.round((pt3.x-this.gridOrigin.x)/this.cellSizeMm-.5))),row=Math.max(0,Math.min(this.rows-1,Math.round((pt3.y-this.gridOrigin.y)/this.cellSizeMm-.5)));return{z:this.zToLayer.get(pt3.z)??0,row,col}}shuffleConnections(){let arr=this.unsolvedSegs,s3=this.hyperParameters.shuffleSeed,rng=()=>(s3=s3*1664525+1013904223&4294967295,(s3>>>0)/4294967295);for(let i3=arr.length-1;i3>0;i3--){let j4=Math.floor(rng()*(i3+1)),tmp=arr[i3];arr[i3]=arr[j4],arr[j4]=tmp}}finalizeRoute(goalNodeIdx){this.consecutiveSkips=Math.max(0,this.consecutiveSkips-1);let cells=[],idx=goalNodeIdx;for(;idx>=0;){let n4=this.nodePool[idx];cells.push({z:n4.z,row:n4.row,col:n4.col}),idx=n4.parentIdx}for(cells.reverse();cells.length>1;){let first=cells[0],firstFlat=(first.z*this.rows+first.row)*this.cols+first.col;if(!this.sharedCrossRootPortCells.has(firstFlat))break;cells.shift()}for(;cells.length>1;){let last=cells[cells.length-1],lastFlat=(last.z*this.rows+last.row)*this.cols+last.col;if(!this.sharedCrossRootPortCells.has(lastFlat))break;cells.pop()}let viaCells=[];for(let i3=1;i3<cells.length;i3++)cells[i3].z!==cells[i3-1].z&&viaCells.push({row:cells[i3].row,col:cells[i3].col});let firstCell=cells[0],lastCell=cells[cells.length-1],connId=this.activeConnId,goalNode=this.nodePool[goalNodeIdx],rippedIds=[];for(let cur=goalNode.ripped;cur;cur=cur.prev)rippedIds.push(cur.id);for(let i3=0;i3<rippedIds.length;i3++)if(this.ripTrace(rippedIds[i3]),this.failed)return;let marginCells=Math.ceil(this.traceMargin/this.cellSizeMm),indices=[],rows=this.rows,cols=this.cols,used=this.usedCellsFlat;for(let ci3=0;ci3<cells.length;ci3++){let cell=cells[ci3];for(let dr3=-marginCells;dr3<=marginCells;dr3++)for(let dc3=-marginCells;dc3<=marginCells;dc3++){let r5=cell.row+dr3,c4=cell.col+dc3;if(r5<0||r5>=rows||c4<0||c4>=cols)continue;let flatIdx=(cell.z*rows+r5)*cols+c4;if((r5!==cell.row||c4!==cell.col)&&this.shouldSkipFixedPortHalo(flatIdx,connId))continue;let existing=used[flatIdx],allowSameRootOverlap=this.connIdToRootNet[existing]===this.connIdToRootNet[connId]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[connId]);existing!==-1&&existing!==connId&&!allowSameRootOverlap||(used[flatIdx]=connId,indices.push(flatIdx))}}let displacedByVias=[],offDr=this.viaOffsetsDr,offDc=this.viaOffsetsDc,offLen=this.viaOffsetsLen;for(let vi3=0;vi3<viaCells.length;vi3++){let via=viaCells[vi3];for(let z4=0;z4<this.layers;z4++){let zBase=z4*this.planeSize;for(let oi3=0;oi3<offLen;oi3++){let r5=via.row+offDr[oi3],c4=via.col+offDc[oi3];if(r5<0||r5>=rows||c4<0||c4>=cols)continue;let flatIdx=zBase+r5*cols+c4;if((r5!==via.row||c4!==via.col)&&this.shouldSkipFixedPortHalo(flatIdx,connId))continue;let existing=used[flatIdx],allowSameRootOverlap=this.connIdToRootNet[existing]===this.connIdToRootNet[connId]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[connId]);if(existing!==-1&&existing!==connId&&!allowSameRootOverlap){let seen=!1;for(let k4=0;k4<displacedByVias.length;k4++)if(displacedByVias[k4]===existing){seen=!0;break}seen||displacedByVias.push(existing)}used[flatIdx]=connId,indices.push(flatIdx)}}}let diagIndices=[],sqCols=this.cols-1;for(let i3=1;i3<cells.length;i3++){let prev=cells[i3-1],curr=cells[i3];if(prev.z!==curr.z)continue;let dr3=prev.row>curr.row?prev.row-curr.row:curr.row-prev.row,dc3=prev.col>curr.col?prev.col-curr.col:curr.col-prev.col;if(dr3!==1||dc3!==1)continue;let sqRow=prev.row<curr.row?prev.row:curr.row,sqCol=prev.col<curr.col?prev.col:curr.col,diagSlot=prev.row<curr.row&&prev.col<curr.col||prev.row>curr.row&&prev.col>curr.col?0:1,crossingSlot=diagSlot^1,diagBase=((prev.z*(this.rows-1)+sqRow)*sqCols+sqCol)*2,crossingIdx=diagBase+crossingSlot,crossingOcc=this.usedDiagFlat[crossingIdx],allowCrossingOverlap=this.connIdToRootNet[crossingOcc]===this.connIdToRootNet[connId]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[connId]);if(crossingOcc!==-1&&crossingOcc!==connId&&!allowCrossingOverlap)continue;let diagIdx=diagBase+diagSlot;this.usedDiagFlat[diagIdx]=connId,diagIndices.push(diagIdx)}for(;this.usedIndicesByConn.length<=connId;)this.usedIndicesByConn.push([]);let usedIndices=this.usedIndicesByConn[connId]??[];for(usedIndices.push(...indices),this.usedIndicesByConn[connId]=usedIndices;this.usedDiagIndicesByConn.length<=connId;)this.usedDiagIndicesByConn.push([]);let usedDiagIndices=this.usedDiagIndicesByConn[connId]??[];usedDiagIndices.push(...diagIndices),this.usedDiagIndicesByConn[connId]=usedDiagIndices;let solvedRoutes=this.solvedRoutes.get(connId)??[];solvedRoutes.push({connId,startZ:firstCell.z,startRow:firstCell.row,startCol:firstCell.col,startPoint:this.activeConnSeg.startPoint,endZ:lastCell.z,endRow:lastCell.row,endCol:lastCell.col,endPoint:this.activeConnSeg.endPoint,cells,viaCells}),this.solvedRoutes.set(connId,solvedRoutes);for(let i3=0;i3<displacedByVias.length;i3++)if(this.ripTrace(displacedByVias[i3]),this.failed)return;if(rippedIds.length>0||displacedByVias.length>0){let pen=this.penalty2d,cap2=this.penaltyCap;if(this.totalRipEvents>50)for(let i3=0;i3<pen.length;i3++)pen[i3]=pen[i3]*.99;else for(let i3=0;i3<pen.length;i3++)pen[i3]>cap2&&(pen[i3]=pen[i3]*.5)}}ripTrace(connId){for(;this.ripCount.length<=connId;)this.ripCount.push(0);if(this.ripCount[connId]++,this.totalRipEvents++,this.totalRipEvents>=this.MAX_RIPS){this.error=`Convergence failure: exceeded MAX_RIPS ${this.MAX_RIPS}`,this.failed=!0;return}let routes=this.solvedRoutes.get(connId)??[];if(routes.length>0){let cols=this.cols;for(let route of routes){for(let i3=0;i3<route.cells.length;i3++){let cell=route.cells[i3],cellIdx=cell.row*cols+cell.col;this.penalty2d[cellIdx]=this.penalty2d[cellIdx]+this.hyperParameters.ripTracePenalty}for(let i3=0;i3<route.viaCells.length;i3++){let via=route.viaCells[i3],viaIdx=via.row*cols+via.col;this.penalty2d[viaIdx]=this.penalty2d[viaIdx]+this.hyperParameters.ripViaPenalty}}}let indices=this.usedIndicesByConn[connId];if(indices){let used=this.usedCellsFlat;for(let i3=0;i3<indices.length;i3++){let flatIdx=indices[i3];used[flatIdx]===connId&&(used[flatIdx]=-1)}this.usedIndicesByConn[connId]=[]}let diagIndices=this.usedDiagIndicesByConn[connId];if(diagIndices){let usedDiag=this.usedDiagFlat;for(let i3=0;i3<diagIndices.length;i3++){let flatIdx=diagIndices[i3];usedDiag[flatIdx]===connId&&(usedDiag[flatIdx]=-1)}this.usedDiagIndicesByConn[connId]=[]}if(routes.length>0){this.solvedRoutes.delete(connId);for(let route of routes)this.unsolvedSegs.push({connId,startZ:route.startZ,startRow:route.startRow,startCol:route.startCol,startPoint:route.startPoint,endZ:route.endZ,endRow:route.endRow,endCol:route.endCol,endPoint:route.endPoint})}}visualize(){let LAYER_COLORS2=["red","blue","orange","green"],points=[],lines=[],circles=[],rects=[],{width,height,center:center2}=this.nodeWithPortPoints;rects.push({center:{x:center2.x,y:center2.y},width,height,stroke:"gray"});let vt3=this.gridToBoundsTransform;if(this.showPenaltyMap&&this.penalty2d){let maxPenalty=0;for(let i3=0;i3<this.penalty2d.length;i3++)this.penalty2d[i3]>maxPenalty&&(maxPenalty=this.penalty2d[i3]);if(maxPenalty>0)for(let row=0;row<this.rows;row++)for(let col=0;col<this.cols;col++){let p4=this.penalty2d[row*this.cols+col];if(p4<=0)continue;let alpha=Math.min(.6,p4/maxPenalty*.6),tc3=applyAffineTransformToPoint(vt3,{x:this.gridOrigin.x+(col+.5)*this.cellSizeMm,y:this.gridOrigin.y+(row+.5)*this.cellSizeMm});rects.push({center:tc3,width:this.cellSizeMm*vt3.a,height:this.cellSizeMm*vt3.e,fill:`rgba(255,165,0,${alpha.toFixed(3)})`})}}if(this.showUsedCellMap&&this.usedCellsFlat)for(let z4=0;z4<this.layers;z4++)for(let row=0;row<this.rows;row++)for(let col=0;col<this.cols;col++){if(this.usedCellsFlat[(z4*this.rows+row)*this.cols+col]===-1)continue;let tc3=applyAffineTransformToPoint(vt3,{x:this.gridOrigin.x+(col+.5)*this.cellSizeMm,y:this.gridOrigin.y+(row+.5)*this.cellSizeMm});rects.push({center:tc3,width:this.cellSizeMm*vt3.a,height:this.cellSizeMm*vt3.e,fill:"rgba(0,0,255,0.5)"})}for(let pp3 of this.nodeWithPortPoints.portPoints)points.push({x:pp3.x,y:pp3.y,color:LAYER_COLORS2[pp3.z]??"gray",label:pp3.connectionName});let TRACE_COLORS3=["rgba(255,0,0,0.75)","rgba(0,0,255,0.75)","rgba(255,165,0,0.75)","rgba(0,128,0,0.75)"],transformedRoutes=this.getOutput();for(let route of transformedRoutes){if(route.route.length<2)continue;let segStart=0;for(let i3=1;i3<route.route.length;i3++){let prev=route.route[i3-1];route.route[i3].z!==prev.z&&(i3-segStart>=2&&lines.push({points:route.route.slice(segStart,i3).map(p4=>({x:p4.x,y:p4.y})),strokeColor:TRACE_COLORS3[prev.z]??"rgba(128,128,128,0.75)",strokeWidth:this.traceThickness}),segStart=i3)}if(route.route.length-segStart>=2){let lastZ=route.route[segStart].z;lines.push({points:route.route.slice(segStart).map(p4=>({x:p4.x,y:p4.y})),strokeColor:TRACE_COLORS3[lastZ]??"rgba(128,128,128,0.75)",strokeWidth:this.traceThickness})}}for(let route of transformedRoutes)for(let via of route.vias)circles.push({center:{x:via.x,y:via.y},radius:this.viaDiameter/2,fill:"rgba(0,0,0,0.3)",stroke:"black"});if(this.activeConnSeg&&this.visitedStamp){let currentStamp=this.stamp;for(let z4=0;z4<this.layers;z4++)for(let row=0;row<this.rows;row++)for(let col=0;col<this.cols;col++){if(this.visitedStamp[(z4*this.rows+row)*this.cols+col]!==currentStamp)continue;let tc3=applyAffineTransformToPoint(vt3,{x:this.gridOrigin.x+(col+.5)*this.cellSizeMm,y:this.gridOrigin.y+(row+.5)*this.cellSizeMm});points.push({x:tc3.x,y:tc3.y,color:"rgba(0,0,255,0.2)"})}}return{points,lines,circles,rects,coordinateSystem:"cartesian",title:`HighDensityA01 [${this.solvedRoutes?.size??0} solved, ${this.unsolvedSegs?.length??0} remaining]`}}getOutput(){let t52=this.gridToBoundsTransform,result=[];for(let[connId,routes]of this.solvedRoutes??[]){let connName=this.connIdToName[connId];for(let route of routes){let points=route.cells.map(cell=>{let rawX=this.gridOrigin.x+(cell.col+.5)*this.cellSizeMm,rawY=this.gridOrigin.y+(cell.row+.5)*this.cellSizeMm,tp3=applyAffineTransformToPoint(t52,{x:rawX,y:rawY});return{x:tp3.x,y:tp3.y,z:this.layerToZ.get(cell.z)??cell.z}});points.length>0&&(points[0]={...route.startPoint},points.length>1&&(points[points.length-1]={...route.endPoint})),result.push({connectionName:connName,rootConnectionName:this.connIdToRootNet[connId],traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,route:points,vias:route.viaCells.map(via=>{let rawX=this.gridOrigin.x+(via.col+.5)*this.cellSizeMm,rawY=this.gridOrigin.y+(via.row+.5)*this.cellSizeMm;return applyAffineTransformToPoint(t52,{x:rawX,y:rawY})})})}}return result}};var REGION_LEFT=0,REGION_TOP=1,REGION_RIGHT=2,REGION_BOTTOM=3,REGION_MIDDLE=4,REGION_NAMES=["left","top","right","bottom","middle"],TypedMinHeap2=class{constructor(){__publicField(this,"f",new Float64Array(1024));__publicField(this,"seq",new Uint32Array(1024));__publicField(this,"id",new Int32Array(1024));__publicField(this,"n",0)}push(f3,seq,id2){this.ensureCapacity(this.n+1);let i3=this.n++;for(this.f[i3]=f3,this.seq[i3]=seq,this.id[i3]=id2;i3>0;){let p4=i3-1>>1;if(this.less(p4,i3))break;this.swap(i3,p4),i3=p4}}pop(){let out=this.id[0];return this.n--,this.n>0&&(this.f[0]=this.f[this.n],this.seq[0]=this.seq[this.n],this.id[0]=this.id[this.n],this.siftDown(0)),out}get size(){return this.n}clear(){this.n=0}ensureCapacity(size3){if(size3<=this.f.length)return;let next2=this.f.length;for(;next2<size3;)next2*=2;let nf3=new Float64Array(next2);nf3.set(this.f),this.f=nf3;let ns3=new Uint32Array(next2);ns3.set(this.seq),this.seq=ns3;let ni3=new Int32Array(next2);ni3.set(this.id),this.id=ni3}siftDown(i3){for(;;){let l4=i3*2+1,r5=l4+1;if(l4>=this.n)return;let m4=l4;if(r5<this.n&&!this.less(l4,r5)&&(m4=r5),this.less(i3,m4))return;this.swap(i3,m4),i3=m4}}less(i3,j4){let fi3=this.f[i3],fj=this.f[j4];return fi3!==fj?fi3<fj:this.seq[i3]<this.seq[j4]}swap(i3,j4){let tf3=this.f[i3];this.f[i3]=this.f[j4],this.f[j4]=tf3;let ts3=this.seq[i3];this.seq[i3]=this.seq[j4],this.seq[j4]=ts3;let ti3=this.id[i3];this.id[i3]=this.id[j4],this.id[j4]=ti3}},TypedNodePool2=class{constructor(){__publicField(this,"z",new Int32Array(1024));__publicField(this,"cellId",new Int32Array(1024));__publicField(this,"g",new Float64Array(1024));__publicField(this,"parent",new Int32Array(1024));__publicField(this,"ripHead",new Int32Array(1024).fill(-1));__publicField(this,"ripCount",new Int32Array(1024));__publicField(this,"length",0)}clear(){this.length=0}push(z4,cellId,g6,parent,ripHead,ripCount){this.ensureCapacity(this.length+1);let idx=this.length++;return this.z[idx]=z4,this.cellId[idx]=cellId,this.g[idx]=g6,this.parent[idx]=parent,this.ripHead[idx]=ripHead,this.ripCount[idx]=ripCount,idx}ensureCapacity(size3){if(size3<=this.z.length)return;let next2=this.z.length;for(;next2<size3;)next2*=2;let nz2=new Int32Array(next2);nz2.set(this.z),this.z=nz2;let nc3=new Int32Array(next2);nc3.set(this.cellId),this.cellId=nc3;let ng3=new Float64Array(next2);ng3.set(this.g),this.g=ng3;let np2=new Int32Array(next2);np2.set(this.parent),this.parent=np2;let nr3=new Int32Array(next2);nr3.fill(-1),nr3.set(this.ripHead.subarray(0,this.length)),this.ripHead=nr3;let nrc=new Int32Array(next2);nrc.set(this.ripCount.subarray(0,this.length)),this.ripCount=nrc}},TypedRipChain2=class{constructor(){__publicField(this,"connId",new Int32Array(1024));__publicField(this,"prev",new Int32Array(1024).fill(-1));__publicField(this,"length",0)}clear(){this.length=0}append(prevHead,connId){this.ensureCapacity(this.length+1);let idx=this.length++;return this.connId[idx]=connId,this.prev[idx]=prevHead,idx}contains(head,connId){for(let cur=head;cur>=0;cur=this.prev[cur])if(this.connId[cur]===connId)return!0;return!1}collect(head,out){out.length=0;for(let cur=head;cur>=0;cur=this.prev[cur])out.push(this.connId[cur])}ensureCapacity(size3){if(size3<=this.connId.length)return;let next2=this.connId.length;for(;next2<size3;)next2*=2;let nc3=new Int32Array(next2);nc3.set(this.connId),this.connId=nc3;let np2=new Int32Array(next2);np2.fill(-1),np2.set(this.prev.subarray(0,this.length)),this.prev=np2}};function toRootNetName3(connectionName,rootConnectionName){return rootConnectionName??connectionName.replace(/_mst\d+$/,"")}function clamp32(value,min,max){return Math.max(min,Math.min(max,value))}function pushUnique2(arr,value){for(let i3=0;i3<arr.length;i3++)if(arr[i3]===value)return;arr.push(value)}function pushUniqueNeighbor2(arr,edge){for(let i3=0;i3<arr.length;i3++)if(arr[i3].cellId===edge.cellId)return;arr.push(edge)}function circleIntersectsRect2(cx3,cy3,r5,minX,minY,maxX,maxY){let qx3=clamp32(cx3,minX,maxX),qy3=clamp32(cy3,minY,maxY),dx3=cx3-qx3,dy3=cy3-qy3;return dx3*dx3+dy3*dy3<=r5*r5}var HighDensitySolverA03=class extends BaseSolver{constructor(props){super();__publicField(this,"nodeWithPortPoints");__publicField(this,"highResolutionCellSize");__publicField(this,"highResolutionCellThickness");__publicField(this,"lowResolutionCellSize");__publicField(this,"viaDiameter");__publicField(this,"MAX_RIPS");__publicField(this,"maxCellCount");__publicField(this,"traceThickness");__publicField(this,"traceMargin");__publicField(this,"viaMinDistFromBorder");__publicField(this,"showPenaltyMap");__publicField(this,"showUsedCellMap");__publicField(this,"effort");__publicField(this,"stepMultiplier");__publicField(this,"hyperParameters");__publicField(this,"initialPenaltyFn");__publicField(this,"boundsMinX");__publicField(this,"boundsMaxX");__publicField(this,"boundsMinY");__publicField(this,"boundsMaxY");__publicField(this,"gridToBoundsTransform");__publicField(this,"availableZ");__publicField(this,"zToLayer");__publicField(this,"layerToZ");__publicField(this,"layers");__publicField(this,"fineRows");__publicField(this,"fineCols");__publicField(this,"lowScale");__publicField(this,"bandRows");__publicField(this,"bandCols");__publicField(this,"regions");__publicField(this,"planeSize");__publicField(this,"cellCenterX");__publicField(this,"cellCenterY");__publicField(this,"cellMinX");__publicField(this,"cellMinY");__publicField(this,"cellMaxX");__publicField(this,"cellMaxY");__publicField(this,"cellWidth");__publicField(this,"cellHeight");__publicField(this,"cellRegion");__publicField(this,"cellRow");__publicField(this,"cellCol");__publicField(this,"viaAllowed");__publicField(this,"neighborOffset");__publicField(this,"neighborIds");__publicField(this,"neighborCosts");__publicField(this,"usedCellsFlat");__publicField(this,"sharedCellsFlat");__publicField(this,"portOwnerFlat");__publicField(this,"penalty2d");__publicField(this,"ripStateBuckets");__publicField(this,"visitedStamp");__publicField(this,"bestGStamp");__publicField(this,"bestGValue");__publicField(this,"visitedFlatStamp");__publicField(this,"sharedCrossRootPortFlat");__publicField(this,"stamp",0);__publicField(this,"connNameToId");__publicField(this,"connIdToName");__publicField(this,"connIdToRootNet");__publicField(this,"overlapFriendlyRootNets");__publicField(this,"usedIndicesByConn");__publicField(this,"unsolvedSegs");__publicField(this,"solvedRoutes");__publicField(this,"activeConnSeg",null);__publicField(this,"activeConnId",-1);__publicField(this,"nodePool");__publicField(this,"heap");__publicField(this,"ripChain");__publicField(this,"seqCounter",0);__publicField(this,"_viaOccs",[]);__publicField(this,"_cellOccs",[]);__publicField(this,"_rippedIds",[]);__publicField(this,"ripCount");__publicField(this,"totalRipEvents",0);__publicField(this,"searchIterations",0);__publicField(this,"consecutiveSkips",0);__publicField(this,"penaltyCap");__publicField(this,"baseSearchBudgetIters");__publicField(this,"_moveCost",0);__publicField(this,"_moveRippedHead",-1);__publicField(this,"_moveRipCount",0);__publicField(this,"traceKeepoutRadius");__publicField(this,"viaKeepoutRadius");this.nodeWithPortPoints=props.nodeWithPortPoints,this.highResolutionCellSize=props.highResolutionCellSize??.1,this.highResolutionCellThickness=Math.max(1,Math.floor(props.highResolutionCellThickness??8)),this.lowResolutionCellSize=props.lowResolutionCellSize??.4,this.viaDiameter=props.viaDiameter,this.maxCellCount=props.maxCellCount,this.traceThickness=props.traceThickness??.1,this.traceMargin=props.traceMargin??.15,this.viaMinDistFromBorder=props.viaMinDistFromBorder??.15,this.showPenaltyMap=props.showPenaltyMap??!1,this.showUsedCellMap=props.showUsedCellMap??!1,this.effort=props.effort??1,this.stepMultiplier=Math.max(1,Math.floor(props.stepMultiplier??1)),this.hyperParameters={shuffleSeed:0,ripCost:8,ripTracePenalty:.5,ripViaPenalty:.75,viaBaseCost:.1,greedyMultiplier:1.5,...props.hyperParameters},this.MAX_ITERATIONS=1e8,this.MAX_RIPS=200,this.initialPenaltyFn=props.initialPenaltyFn}get unsolvedConnections(){return this.unsolvedSegs}get solvedConnectionsMap(){let map=new Map;for(let connId=0;connId<this.solvedRoutes.length;connId++){let route=this.solvedRoutes[connId];route&&map.set(connId,route)}return map}get activeConnection(){if(!this.activeConnSeg)return null;let startCellId=this.activeConnSeg.startCellId,endCellId=this.activeConnSeg.endCellId;return{connectionName:this.connIdToName[this.activeConnSeg.connId]??"",start:{cellId:startCellId,region:REGION_NAMES[this.cellRegion[startCellId]],row:this.cellRow[startCellId],col:this.cellCol[startCellId],x:this.cellCenterX[startCellId],y:this.cellCenterY[startCellId],z:this.activeConnSeg.startZ},end:{cellId:endCellId,region:REGION_NAMES[this.cellRegion[endCellId]],row:this.cellRow[endCellId],col:this.cellCol[endCellId],x:this.cellCenterX[endCellId],y:this.cellCenterY[endCellId],z:this.activeConnSeg.endZ}}}get openSet(){return{length:this.heap?.size??0}}get gridStats(){return{cells:this.planeSize||0,layers:this.layers||0,states:(this.planeSize||0)*(this.layers||0),ripStateBuckets:this.ripStateBuckets||0,neighborEdges:this.neighborIds?.length??0,regionCounts:this.regions?Object.fromEntries(this.regions.map(region=>[region.name,region.rows*region.cols])):{}}}getConstructorParams(){return[{nodeWithPortPoints:this.nodeWithPortPoints,highResolutionCellSize:this.highResolutionCellSize,highResolutionCellThickness:this.highResolutionCellThickness,lowResolutionCellSize:this.lowResolutionCellSize,viaDiameter:this.viaDiameter,maxCellCount:this.maxCellCount,stepMultiplier:this.stepMultiplier,traceThickness:this.traceThickness,traceMargin:this.traceMargin,viaMinDistFromBorder:this.viaMinDistFromBorder,showPenaltyMap:this.showPenaltyMap,showUsedCellMap:this.showUsedCellMap,effort:this.effort,hyperParameters:this.hyperParameters,initialPenaltyFn:this.initialPenaltyFn}]}_setup(){let{nodeWithPortPoints}=this,{width,height,center:center2}=nodeWithPortPoints,rawScale=this.lowResolutionCellSize/this.highResolutionCellSize,roundedScale=Math.round(rawScale);if(!Number.isFinite(rawScale)||rawScale<=0||Math.abs(rawScale-roundedScale)>1e-9){this.error="lowResolutionCellSize must be a positive integer multiple of highResolutionCellSize",this.failed=!0;return}this.lowScale=Math.max(1,roundedScale),this.availableZ=nodeWithPortPoints.availableZ??[...new Set(nodeWithPortPoints.portPoints.map(pp3=>pp3.z))].sort((a3,b3)=>a3-b3),this.layers=this.availableZ.length,this.zToLayer=new Map,this.layerToZ=new Map;for(let i3=0;i3<this.availableZ.length;i3++){let z4=this.availableZ[i3];this.zToLayer.set(z4,i3),this.layerToZ.set(i3,z4)}this.boundsMinX=center2.x-width/2,this.boundsMaxX=center2.x+width/2,this.boundsMinY=center2.y-height/2,this.boundsMaxY=center2.y+height/2,this.traceKeepoutRadius=this.traceMargin+this.traceThickness/2,this.viaKeepoutRadius=this.viaDiameter/2+this.traceKeepoutRadius,this.buildFiveRegionGrid(width,height),this.gridToBoundsTransform=this.computeGridToBoundsTransform();let totalCells=this.layers*this.planeSize;if(this.maxCellCount!==void 0&&totalCells>this.maxCellCount){this.error=`Cell count ${totalCells} exceeds maxCellCount ${this.maxCellCount}`,this.failed=!0;return}this.connNameToId=new Map,this.connIdToName=[],this.connIdToRootNet=[],this.overlapFriendlyRootNets=new Set,this.unsolvedSegs=this.buildConnectionSegs(),this.penalty2d=new Float64Array(this.planeSize);let widthInv=width>0?1/width:0,heightInv=height>0?1/height:0;for(let cellId=0;cellId<this.planeSize;cellId++){let penalty=0;this.initialPenaltyFn&&(penalty+=this.initialPenaltyFn({x:this.cellCenterX[cellId],y:this.cellCenterY[cellId],px:(this.cellCenterX[cellId]-this.boundsMinX)*widthInv,py:(this.cellCenterY[cellId]-this.boundsMinY)*heightInv,cellId,region:REGION_NAMES[this.cellRegion[cellId]],row:this.cellRow[cellId],col:this.cellCol[cellId]})),this.penalty2d[cellId]=penalty}this.usedCellsFlat=new Int32Array(totalCells).fill(-1),this.sharedCellsFlat=Array.from({length:totalCells},()=>{}),this.portOwnerFlat=new Int32Array(totalCells).fill(-1),this.sharedCrossRootPortFlat=new Uint8Array(totalCells),this.ripStateBuckets=1;let searchStateCount=totalCells;this.visitedStamp=new Uint32Array(searchStateCount),this.bestGStamp=new Uint32Array(searchStateCount),this.bestGValue=new Float64Array(searchStateCount),this.visitedFlatStamp=new Uint32Array(totalCells),this.stamp=0;let rootByPortFlat=new Map;for(let pp3 of this.nodeWithPortPoints.portPoints){let connId=this.connNameToId.get(pp3.connectionName);if(connId===void 0)continue;let cell=this.pointToCell(pp3),flatIdx=cell.z*this.planeSize+cell.cellId,rootNet=this.connIdToRootNet[connId],existingRoot=rootByPortFlat.get(flatIdx);existingRoot===void 0?rootByPortFlat.set(flatIdx,rootNet):existingRoot!==rootNet&&(this.sharedCrossRootPortFlat[flatIdx]=1);let existing=this.portOwnerFlat[flatIdx];existing===-1||existing===connId?this.portOwnerFlat[flatIdx]=connId:this.portOwnerFlat[flatIdx]=-2}this.solvedRoutes=[],this.usedIndicesByConn=[],this.ripCount=[],this.consecutiveSkips=0,this.penaltyCap=this.hyperParameters.ripCost*.5,this.shuffleConnections();let budget=computeMaxIterationsByNodeSizeAndConnectionCount({planeSize:this.planeSize,layers:this.layers,connectionCount:this.unsolvedSegs.length,effort:this.effort,maxIterations:this.MAX_ITERATIONS});this.baseSearchBudgetIters=budget.baseSearchBudgetIters,this.MAX_ITERATIONS=budget.maxIterationsIters,this.activeConnSeg=null,this.activeConnId=-1,this.nodePool=new TypedNodePool2,this.heap=new TypedMinHeap2,this.ripChain=new TypedRipChain2,this.seqCounter=0}_step(){for(let i3=0;i3<this.stepMultiplier;i3++){if(this.solved||this.failed)return;this.stepOnce()}}buildFiveRegionGrid(width,height){this.fineCols=Math.max(1,Math.ceil(width/this.highResolutionCellSize)),this.fineRows=Math.max(1,Math.ceil(height/this.highResolutionCellSize)),this.bandCols=Math.min(this.highResolutionCellThickness,Math.floor(this.fineCols/2)),this.bandRows=Math.min(this.highResolutionCellThickness,Math.floor(this.fineRows/2));let middleFineCols=Math.max(0,this.fineCols-this.bandCols*2),middleFineRows=Math.max(0,this.fineRows-this.bandRows*2),topFineCols=middleFineCols,bottomFineCols=middleFineCols;this.regions=[{id:REGION_LEFT,name:"left",fineOriginRow:0,fineOriginCol:0,fineRows:this.fineRows,fineCols:this.bandCols,cellScale:1,rows:this.fineRows,cols:this.bandCols,offset:0},{id:REGION_TOP,name:"top",fineOriginRow:0,fineOriginCol:this.bandCols,fineRows:this.bandRows,fineCols:topFineCols,cellScale:1,rows:this.bandRows,cols:topFineCols,offset:0},{id:REGION_RIGHT,name:"right",fineOriginRow:0,fineOriginCol:this.fineCols-this.bandCols,fineRows:this.fineRows,fineCols:this.bandCols,cellScale:1,rows:this.fineRows,cols:this.bandCols,offset:0},{id:REGION_BOTTOM,name:"bottom",fineOriginRow:this.fineRows-this.bandRows,fineOriginCol:this.bandCols,fineRows:this.bandRows,fineCols:bottomFineCols,cellScale:1,rows:this.bandRows,cols:bottomFineCols,offset:0},{id:REGION_MIDDLE,name:"middle",fineOriginRow:this.bandRows,fineOriginCol:this.bandCols,fineRows:middleFineRows,fineCols:middleFineCols,cellScale:this.lowScale,rows:middleFineRows>0?Math.ceil(middleFineRows/this.lowScale):0,cols:middleFineCols>0?Math.ceil(middleFineCols/this.lowScale):0,offset:0}];let offset=0;for(let i3=0;i3<this.regions.length;i3++)this.regions[i3].offset=offset,offset+=this.regions[i3].rows*this.regions[i3].cols;this.planeSize=offset,this.cellCenterX=new Float64Array(this.planeSize),this.cellCenterY=new Float64Array(this.planeSize),this.cellMinX=new Float64Array(this.planeSize),this.cellMinY=new Float64Array(this.planeSize),this.cellMaxX=new Float64Array(this.planeSize),this.cellMaxY=new Float64Array(this.planeSize),this.cellWidth=new Float64Array(this.planeSize),this.cellHeight=new Float64Array(this.planeSize),this.cellRegion=new Uint8Array(this.planeSize),this.cellRow=new Int32Array(this.planeSize),this.cellCol=new Int32Array(this.planeSize),this.viaAllowed=new Uint8Array(this.planeSize);for(let regionIdx=0;regionIdx<this.regions.length;regionIdx++){let region=this.regions[regionIdx];for(let row=0;row<region.rows;row++){let fineRow0=region.fineOriginRow+row*region.cellScale,fineRow1=Math.min(region.fineOriginRow+region.fineRows,fineRow0+region.cellScale),minY=this.boundsMinY+fineRow0*this.highResolutionCellSize,maxY=Math.min(this.boundsMaxY,this.boundsMinY+fineRow1*this.highResolutionCellSize);for(let col=0;col<region.cols;col++){let fineCol0=region.fineOriginCol+col*region.cellScale,fineCol1=Math.min(region.fineOriginCol+region.fineCols,fineCol0+region.cellScale),minX=this.boundsMinX+fineCol0*this.highResolutionCellSize,maxX=Math.min(this.boundsMaxX,this.boundsMinX+fineCol1*this.highResolutionCellSize),cellId=this.cellIdFor(region.id,row,col);this.cellCenterX[cellId]=(minX+maxX)/2,this.cellCenterY[cellId]=(minY+maxY)/2,this.cellMinX[cellId]=minX,this.cellMinY[cellId]=minY,this.cellMaxX[cellId]=maxX,this.cellMaxY[cellId]=maxY,this.cellWidth[cellId]=maxX-minX,this.cellHeight[cellId]=maxY-minY,this.cellRegion[cellId]=region.id,this.cellRow[cellId]=row,this.cellCol[cellId]=col;let minBorderDist=Math.min(this.cellCenterX[cellId]-this.boundsMinX,this.boundsMaxX-this.cellCenterX[cellId],this.cellCenterY[cellId]-this.boundsMinY,this.boundsMaxY-this.cellCenterY[cellId]);this.viaAllowed[cellId]=minBorderDist>=this.viaMinDistFromBorder?1:0}}}let neighbors=Array.from({length:this.planeSize},()=>[]),addBidirectionalEdge=(a3,b3)=>{if(a3===b3||a3<0||b3<0)return;let dx3=this.cellCenterX[a3]-this.cellCenterX[b3],dy3=this.cellCenterY[a3]-this.cellCenterY[b3],cost=Math.hypot(dx3,dy3);pushUniqueNeighbor2(neighbors[a3],{cellId:b3,cost}),pushUniqueNeighbor2(neighbors[b3],{cellId:a3,cost})};for(let regionIdx=0;regionIdx<this.regions.length;regionIdx++){let region=this.regions[regionIdx];for(let row=0;row<region.rows;row++)for(let col=0;col<region.cols;col++){let cellId=this.cellIdFor(region.id,row,col);row+1<region.rows&&addBidirectionalEdge(cellId,this.cellIdFor(region.id,row+1,col)),col+1<region.cols&&addBidirectionalEdge(cellId,this.cellIdFor(region.id,row,col+1))}}let left=this.regions[REGION_LEFT],top=this.regions[REGION_TOP],right=this.regions[REGION_RIGHT],bottom=this.regions[REGION_BOTTOM],middle=this.regions[REGION_MIDDLE],hasLeft=left.rows>0&&left.cols>0,hasTop=top.rows>0&&top.cols>0,hasRight=right.rows>0&&right.cols>0,hasBottom=bottom.rows>0&&bottom.cols>0,hasMiddle=middle.rows>0&&middle.cols>0;if(hasLeft&&hasTop)for(let globalRow=0;globalRow<this.bandRows;globalRow++)addBidirectionalEdge(this.cellIdFor(REGION_LEFT,globalRow,left.cols-1),this.cellIdFor(REGION_TOP,globalRow,0));if(hasTop&&hasRight)for(let globalRow=0;globalRow<this.bandRows;globalRow++)addBidirectionalEdge(this.cellIdFor(REGION_TOP,globalRow,top.cols-1),this.cellIdFor(REGION_RIGHT,globalRow,0));if(hasLeft&&hasBottom)for(let globalRow=this.fineRows-this.bandRows;globalRow<this.fineRows;globalRow++)addBidirectionalEdge(this.cellIdFor(REGION_LEFT,globalRow,left.cols-1),this.cellIdFor(REGION_BOTTOM,globalRow-(this.fineRows-this.bandRows),0));if(hasBottom&&hasRight)for(let globalRow=this.fineRows-this.bandRows;globalRow<this.fineRows;globalRow++)addBidirectionalEdge(this.cellIdFor(REGION_BOTTOM,globalRow-(this.fineRows-this.bandRows),bottom.cols-1),this.cellIdFor(REGION_RIGHT,globalRow,0));if(hasLeft&&hasMiddle)for(let globalRow=this.bandRows;globalRow<this.fineRows-this.bandRows;globalRow++)addBidirectionalEdge(this.cellIdFor(REGION_LEFT,globalRow,left.cols-1),this.cellIdFor(REGION_MIDDLE,Math.floor((globalRow-this.bandRows)/this.lowScale),0));if(hasRight&&hasMiddle)for(let globalRow=this.bandRows;globalRow<this.fineRows-this.bandRows;globalRow++)addBidirectionalEdge(this.cellIdFor(REGION_MIDDLE,Math.floor((globalRow-this.bandRows)/this.lowScale),middle.cols-1),this.cellIdFor(REGION_RIGHT,globalRow,0));if(hasTop&&hasMiddle)for(let globalCol=this.bandCols;globalCol<this.fineCols-this.bandCols;globalCol++)addBidirectionalEdge(this.cellIdFor(REGION_TOP,top.rows-1,globalCol-this.bandCols),this.cellIdFor(REGION_MIDDLE,0,Math.floor((globalCol-this.bandCols)/this.lowScale)));if(hasBottom&&hasMiddle)for(let globalCol=this.bandCols;globalCol<this.fineCols-this.bandCols;globalCol++)addBidirectionalEdge(this.cellIdFor(REGION_MIDDLE,middle.rows-1,Math.floor((globalCol-this.bandCols)/this.lowScale)),this.cellIdFor(REGION_BOTTOM,0,globalCol-this.bandCols));if(!hasMiddle&&!hasTop&&!hasBottom&&hasLeft&&hasRight)for(let row=0;row<Math.min(left.rows,right.rows);row++)addBidirectionalEdge(this.cellIdFor(REGION_LEFT,row,left.cols-1),this.cellIdFor(REGION_RIGHT,row,0));if(!hasMiddle&&!hasLeft&&!hasRight&&hasTop&&hasBottom)for(let col=0;col<Math.min(top.cols,bottom.cols);col++)addBidirectionalEdge(this.cellIdFor(REGION_TOP,top.rows-1,col),this.cellIdFor(REGION_BOTTOM,0,col));let flattened=this.flattenNeighborLists(neighbors);this.neighborOffset=flattened.offset,this.neighborIds=flattened.ids,this.neighborCosts=flattened.costs}cellIdFor(regionId,row,col){let region=this.regions[regionId];return region.offset+row*region.cols+col}stepOnce(){if(!this.activeConnSeg){if(this.unsolvedSegs.length===0){this.solved=!0;return}let next2=this.unsolvedSegs.shift();this.activeConnSeg=next2,this.activeConnId=next2.connId,this.nodePool.clear(),this.ripChain.clear(),this.heap.clear(),this.seqCounter=0,this.searchIterations=0,this.nextStamp();let f3=this.computeH(next2.startZ,next2.startCellId,next2.endZ,next2.endCellId)*this.hyperParameters.greedyMultiplier,startIdx=this.nodePool.push(next2.startZ,next2.startCellId,0,-1,-1,0),startFlatIdx=next2.startZ*this.planeSize+next2.startCellId,startStateIdx=this.getSearchStateIdx(startFlatIdx,0);this.bestGStamp[startStateIdx]=this.stamp,this.bestGValue[startStateIdx]=0,this.heap.push(f3,this.seqCounter++,startIdx);return}this.searchIterations++;let connRips=this.ripCount[this.activeConnId]??0,budget=Math.round(this.baseSearchBudgetIters*(1+Math.min(connRips,10)*.25));if(this.searchIterations>budget){let pen=this.penalty2d;for(let i3=0;i3<pen.length;i3++)pen[i3]=pen[i3]*.9;this.unsolvedSegs.push(this.activeConnSeg),this.activeConnSeg=null,this.activeConnId=-1,this.heap.clear(),this.nodePool.clear(),this.consecutiveSkips++,this.consecutiveSkips>=Math.max(3,this.unsolvedSegs.length*3)&&(this.error=`Convergence failure: ${this.unsolvedSegs.length} connections stuck`,this.failed=!0);return}if(this.heap.size===0){this.error=`No path found for ${this.connIdToName[this.activeConnId]}`,this.failed=!0;return}let nodeIdx=this.heap.pop(),z4=this.nodePool.z[nodeIdx],cellId=this.nodePool.cellId[nodeIdx],g6=this.nodePool.g[nodeIdx],rippedHead=this.nodePool.ripHead[nodeIdx],ripCount=this.nodePool.ripCount[nodeIdx],flatIdx=z4*this.planeSize+cellId,searchStateIdx=this.getSearchStateIdx(flatIdx,ripCount);if(this.visitedStamp[searchStateIdx]===this.stamp)return;this.visitedStamp[searchStateIdx]=this.stamp,this.visitedFlatStamp[flatIdx]=this.stamp;let seg=this.activeConnSeg;if(z4===seg.endZ&&cellId===seg.endCellId){this.finalizeRoute(nodeIdx),this.activeConnSeg=null,this.activeConnId=-1;return}let visited=this.visitedStamp,stamp=this.stamp,activeConn=this.activeConnId,endZ=seg.endZ,endCellId=seg.endCellId,neighborStart=this.neighborOffset[cellId],neighborEnd=this.neighborOffset[cellId+1];for(let i3=neighborStart;i3<neighborEnd;i3++){let neighborCellId=this.neighborIds[i3],nextFlatIdx=z4*this.planeSize+neighborCellId;if(this.computeMoveCostAndRips(activeConn,z4,neighborCellId,!1,rippedHead,ripCount,this.neighborCosts[i3]),this._moveCost<0)continue;let nextStateIdx=this.getSearchStateIdx(nextFlatIdx,this._moveRipCount);if(visited[nextStateIdx]===stamp)continue;let g22=g6+this._moveCost;if(this.bestGStamp[nextStateIdx]===stamp&&g22>=this.bestGValue[nextStateIdx])continue;this.bestGStamp[nextStateIdx]=stamp,this.bestGValue[nextStateIdx]=g22;let f22=g22+this.computeH(z4,neighborCellId,endZ,endCellId)*this.hyperParameters.greedyMultiplier,newNodeIdx=this.nodePool.push(z4,neighborCellId,g22,nodeIdx,this._moveRippedHead,this._moveRipCount);this.heap.push(f22,this.seqCounter++,newNodeIdx)}if(this.viaAllowed[cellId])for(let nz2=0;nz2<this.layers;nz2++){if(nz2===z4)continue;let nextFlatIdx=nz2*this.planeSize+cellId;if(this.computeMoveCostAndRips(activeConn,nz2,cellId,!0,rippedHead,ripCount,0),this._moveCost<0)continue;let nextStateIdx=this.getSearchStateIdx(nextFlatIdx,this._moveRipCount);if(visited[nextStateIdx]===stamp)continue;let g22=g6+this._moveCost;if(this.bestGStamp[nextStateIdx]===stamp&&g22>=this.bestGValue[nextStateIdx])continue;this.bestGStamp[nextStateIdx]=stamp,this.bestGValue[nextStateIdx]=g22;let f22=g22+this.computeH(nz2,cellId,endZ,endCellId)*this.hyperParameters.greedyMultiplier,newNodeIdx=this.nodePool.push(nz2,cellId,g22,nodeIdx,this._moveRippedHead,this._moveRipCount);this.heap.push(f22,this.seqCounter++,newNodeIdx)}}computeMoveCostAndRips(activeConn,toZ,toCellId,isVia,rippedHead,currentRipCount,lateralCost){let cost=0,head=rippedHead,ripCount=currentRipCount,toFlatIdx=toZ*this.planeSize+toCellId;if(isVia){cost+=this.hyperParameters.viaBaseCost,cost+=Math.min(this.penalty2d[toCellId],this.penaltyCap);let fixedOwner=this.portOwnerFlat[toFlatIdx],allowFixedOverlap=this.allowSharedUse(activeConn,fixedOwner),seg=this.activeConnSeg,isSegEnd=!!seg&&toZ===seg.endZ&&toCellId===seg.endCellId;if(fixedOwner>=0&&fixedOwner!==activeConn&&!allowFixedOverlap&&!isSegEnd){this._moveCost=-1,this._moveRippedHead=head;return}this.fillViaOccupants(toCellId,activeConn);let occs=this._viaOccs;for(let i3=0;i3<occs.length;i3++){let occ=occs[i3];this.ripChain.contains(head,occ)||(cost+=this.hyperParameters.ripCost,head=this.ripChain.append(head,occ),ripCount++),cost+=this.hyperParameters.ripViaPenalty}}else{cost+=lateralCost,cost+=Math.min(this.penalty2d[toCellId],this.penaltyCap);let fixedOwner=this.portOwnerFlat[toFlatIdx],allowFixedOverlap=this.allowSharedUse(activeConn,fixedOwner),seg=this.activeConnSeg,isSegEnd=!!seg&&toZ===seg.endZ&&toCellId===seg.endCellId;if(fixedOwner>=0&&fixedOwner!==activeConn&&!allowFixedOverlap&&!isSegEnd){this._moveCost=-1,this._moveRippedHead=head;return}this.fillTraceOccupants(toFlatIdx,activeConn,this._cellOccs);for(let i3=0;i3<this._cellOccs.length;i3++){let occ=this._cellOccs[i3];this.ripChain.contains(head,occ)||(cost+=this.hyperParameters.ripCost,head=this.ripChain.append(head,occ),ripCount++),cost+=this.hyperParameters.ripTracePenalty}}this._moveCost=cost,this._moveRippedHead=head,this._moveRipCount=ripCount}fillViaOccupants(cellId,activeConn){let occs=this._viaOccs;occs.length=0;let cx3=this.cellCenterX[cellId],cy3=this.cellCenterY[cellId];this.forEachCellNearCircle(cx3,cy3,this.viaKeepoutRadius,occCellId=>{if(circleIntersectsRect2(cx3,cy3,this.viaKeepoutRadius,this.cellMinX[occCellId],this.cellMinY[occCellId],this.cellMaxX[occCellId],this.cellMaxY[occCellId]))for(let z4=0;z4<this.layers;z4++)this.pushFlatOccupants(z4*this.planeSize+occCellId,activeConn,occs)})}fillTraceOccupants(flatIdx,activeConn,out){out.length=0,this.pushFlatOccupants(flatIdx,activeConn,out)}pushFlatOccupants(flatIdx,activeConn,out){let primaryOcc=this.usedCellsFlat[flatIdx];primaryOcc!==-1&&primaryOcc!==activeConn&&!this.allowSharedUse(activeConn,primaryOcc)&&pushUnique2(out,primaryOcc);let sharedOccs=this.sharedCellsFlat[flatIdx];if(sharedOccs)for(let i3=0;i3<sharedOccs.length;i3++){let occ=sharedOccs[i3];occ!==activeConn&&(this.allowSharedUse(activeConn,occ)||pushUnique2(out,occ))}}addSharedOccupant(flatIdx,connId){if(this.usedCellsFlat[flatIdx]===connId)return;let sharedOccs=this.sharedCellsFlat[flatIdx];sharedOccs||(sharedOccs=[],this.sharedCellsFlat[flatIdx]=sharedOccs),pushUnique2(sharedOccs,connId)}replaceOccupants(flatIdx,connId){this.usedCellsFlat[flatIdx]=connId,this.sharedCellsFlat[flatIdx]=void 0}removeOccupant(flatIdx,connId){let sharedOccs=this.sharedCellsFlat[flatIdx];if(this.usedCellsFlat[flatIdx]===connId){sharedOccs&&sharedOccs.length>0?(this.usedCellsFlat[flatIdx]=sharedOccs.pop(),sharedOccs.length===0&&(this.sharedCellsFlat[flatIdx]=void 0)):this.usedCellsFlat[flatIdx]=-1;return}if(!sharedOccs)return;let idx=sharedOccs.indexOf(connId);idx!==-1&&(sharedOccs.splice(idx,1),sharedOccs.length===0&&(this.sharedCellsFlat[flatIdx]=void 0))}allowSharedUse(activeConn,existingConn){return existingConn<0?!1:this.connIdToRootNet[existingConn]===this.connIdToRootNet[activeConn]}shouldSkipFixedPortHalo(flatIdx,connId){let fixedOwner=this.portOwnerFlat[flatIdx];return fixedOwner===connId?!1:fixedOwner===-2?!0:fixedOwner<0?!1:!this.allowSharedUse(connId,fixedOwner)}nextStamp(){this.stamp=this.stamp+1>>>0,this.stamp===0&&(this.visitedStamp.fill(0),this.bestGStamp.fill(0),this.visitedFlatStamp.fill(0),this.stamp=1)}getSearchStateIdx(flatIdx,ripCount){return flatIdx}computeH(z4,cellId,toZ,toCellId){let dist=Math.hypot(this.cellCenterX[cellId]-this.cellCenterX[toCellId],this.cellCenterY[cellId]-this.cellCenterY[toCellId]);return z4===toZ?dist:dist+this.hyperParameters.viaBaseCost}internConn(name,rootNetName){let existing=this.connNameToId.get(name);if(existing!==void 0)return existing;let id2=this.connIdToName.length;return this.connIdToName.push(name),this.connIdToRootNet.push(toRootNetName3(name,rootNetName)),this.connNameToId.set(name,id2),id2}buildConnectionSegs(){let byName=new Map;for(let pp3 of this.nodeWithPortPoints.portPoints){let name=pp3.connectionName;byName.has(name)||byName.set(name,{points:[],rootConnectionName:pp3.rootConnectionName}),byName.get(name).points.push(pp3)}let segs=[],seenSegmentKeys=new Set;for(let[name,conn]of byName){let pts=conn.points;if(pts.length<2)continue;let connId=this.internConn(name,conn.rootConnectionName);for(let i3=0;i3<pts.length-1;i3++){let s3=this.pointToCell(pts[i3]),e5=this.pointToCell(pts[i3+1]),endpointA=`${s3.z}:${s3.cellId}`,endpointB=`${e5.z}:${e5.cellId}`,orderedEndpoints=endpointA<endpointB?`${endpointA}|${endpointB}`:`${endpointB}|${endpointA}`,netName=conn.rootConnectionName??name,segKey=`${netName}|${orderedEndpoints}`;if(seenSegmentKeys.has(segKey)){this.overlapFriendlyRootNets.add(netName);continue}seenSegmentKeys.add(segKey),segs.push({connId,startZ:s3.z,startCellId:s3.cellId,startPoint:pts[i3],endZ:e5.z,endCellId:e5.cellId,endPoint:pts[i3+1]})}}return segs}pointToCell(pt3){let fineCol=clamp32(Math.floor((pt3.x-this.boundsMinX)/this.highResolutionCellSize),0,this.fineCols-1),fineRow=clamp32(Math.floor((pt3.y-this.boundsMinY)/this.highResolutionCellSize),0,this.fineRows-1),regionId=REGION_MIDDLE;fineCol<this.bandCols?regionId=REGION_LEFT:fineCol>=this.fineCols-this.bandCols?regionId=REGION_RIGHT:fineRow<this.bandRows?regionId=REGION_TOP:fineRow>=this.fineRows-this.bandRows&&(regionId=REGION_BOTTOM);let region=this.regions[regionId],localFineRow=fineRow-region.fineOriginRow,localFineCol=fineCol-region.fineOriginCol,row=clamp32(Math.floor(localFineRow/region.cellScale),0,Math.max(0,region.rows-1)),col=clamp32(Math.floor(localFineCol/region.cellScale),0,Math.max(0,region.cols-1));return{z:this.zToLayer.get(pt3.z)??0,cellId:this.cellIdFor(regionId,row,col)}}shuffleConnections(){let arr=this.unsolvedSegs,s3=this.hyperParameters.shuffleSeed>>>0,rng=()=>(s3=Math.imul(s3,1664525)+1013904223>>>0,s3/4294967295);for(let i3=arr.length-1;i3>0;i3--){let j4=Math.floor(rng()*(i3+1)),tmp=arr[i3];arr[i3]=arr[j4],arr[j4]=tmp}}finalizeRoute(goalNodeIdx){this.consecutiveSkips=Math.max(0,this.consecutiveSkips-1);let states=[],idx=goalNodeIdx;for(;idx>=0;){let z4=this.nodePool.z[idx],cellId=this.nodePool.cellId[idx];states.push(z4*this.planeSize+cellId),idx=this.nodePool.parent[idx]}for(states.reverse();states.length>1&&this.sharedCrossRootPortFlat[states[0]];)states.shift();for(;states.length>1&&this.sharedCrossRootPortFlat[states[states.length-1]];)states.pop();let viaCellIds=this.extractViaCellIds(states),connId=this.activeConnId;this.ripChain.collect(this.nodePool.ripHead[goalNodeIdx],this._rippedIds);for(let i3=0;i3<this._rippedIds.length;i3++)if(this.ripTrace(this._rippedIds[i3]),this.failed)return;let indices=[];for(let i3=0;i3<states.length;i3++){let state2=states[i3],z4=Math.floor(state2/this.planeSize),cellId=state2-z4*this.planeSize;this.markTraceFootprint(connId,z4,cellId,indices)}let displacedByVias=[];for(let i3=0;i3<viaCellIds.length;i3++)this.markViaFootprint(connId,viaCellIds[i3],indices,displacedByVias);for(;this.usedIndicesByConn.length<=connId;)this.usedIndicesByConn.push(void 0);for(this.usedIndicesByConn[connId]=indices;this.solvedRoutes.length<=connId;)this.solvedRoutes.push(void 0);this.solvedRoutes[connId]={connId,states:Int32Array.from(states),viaCellIds:Int32Array.from(viaCellIds),startPoint:this.activeConnSeg.startPoint,endPoint:this.activeConnSeg.endPoint};for(let i3=0;i3<displacedByVias.length;i3++)if(this.ripTrace(displacedByVias[i3]),this.failed)return;if(this._rippedIds.length>0||displacedByVias.length>0){let pen=this.penalty2d,cap2=this.penaltyCap;if(this.totalRipEvents>50)for(let i3=0;i3<pen.length;i3++)pen[i3]=pen[i3]*.99;else for(let i3=0;i3<pen.length;i3++)pen[i3]>cap2&&(pen[i3]=pen[i3]*.5)}}extractViaCellIds(states){let viaCellIds=[];for(let i3=1;i3<states.length;i3++){let prevState=states[i3-1],nextState=states[i3],prevZ=Math.floor(prevState/this.planeSize),nextZ=Math.floor(nextState/this.planeSize);prevZ!==nextZ&&viaCellIds.push(nextState-nextZ*this.planeSize)}return viaCellIds}markTraceFootprint(connId,z4,sourceCellId,indices){let cx3=this.cellCenterX[sourceCellId],cy3=this.cellCenterY[sourceCellId];this.forEachCellNearCircle(cx3,cy3,this.traceKeepoutRadius,cellId=>{if(!circleIntersectsRect2(cx3,cy3,this.traceKeepoutRadius,this.cellMinX[cellId],this.cellMinY[cellId],this.cellMaxX[cellId],this.cellMaxY[cellId]))return;let flatIdx=z4*this.planeSize+cellId;if(cellId!==sourceCellId&&this.shouldSkipFixedPortHalo(flatIdx,connId))return;let existing=this.usedCellsFlat[flatIdx],allowSameRootOverlap=this.allowSharedUse(connId,existing);existing!==-1&&existing!==connId&&!allowSameRootOverlap||(existing!==-1&&existing!==connId?this.addSharedOccupant(flatIdx,connId):this.usedCellsFlat[flatIdx]=connId,indices.push(flatIdx))})}markViaFootprint(connId,sourceCellId,indices,displacedByVias){let cx3=this.cellCenterX[sourceCellId],cy3=this.cellCenterY[sourceCellId];this.forEachCellNearCircle(cx3,cy3,this.viaKeepoutRadius,cellId=>{if(circleIntersectsRect2(cx3,cy3,this.viaKeepoutRadius,this.cellMinX[cellId],this.cellMinY[cellId],this.cellMaxX[cellId],this.cellMaxY[cellId]))for(let z4=0;z4<this.layers;z4++){let flatIdx=z4*this.planeSize+cellId;if(cellId!==sourceCellId&&this.shouldSkipFixedPortHalo(flatIdx,connId))continue;if(this.fillTraceOccupants(flatIdx,connId,this._cellOccs),this._cellOccs.length>0){for(let i3=0;i3<this._cellOccs.length;i3++)pushUnique2(displacedByVias,this._cellOccs[i3]);this.replaceOccupants(flatIdx,connId),indices.push(flatIdx);continue}let existing=this.usedCellsFlat[flatIdx];existing!==-1&&existing!==connId?this.addSharedOccupant(flatIdx,connId):this.usedCellsFlat[flatIdx]=connId,indices.push(flatIdx)}})}forEachCellNearCircle(cx3,cy3,radius,visitor){let minFineCol=clamp32(Math.floor((cx3-radius-this.boundsMinX)/this.highResolutionCellSize),0,this.fineCols-1),maxFineCol=clamp32(Math.floor((cx3+radius-this.boundsMinX)/this.highResolutionCellSize),0,this.fineCols-1),minFineRow=clamp32(Math.floor((cy3-radius-this.boundsMinY)/this.highResolutionCellSize),0,this.fineRows-1),maxFineRow=clamp32(Math.floor((cy3+radius-this.boundsMinY)/this.highResolutionCellSize),0,this.fineRows-1);for(let regionIdx=0;regionIdx<this.regions.length;regionIdx++){let region=this.regions[regionIdx];if(region.rows===0||region.cols===0)continue;let regionFineRowMin=Math.max(minFineRow,region.fineOriginRow),regionFineRowMax=Math.min(maxFineRow,region.fineOriginRow+region.fineRows-1),regionFineColMin=Math.max(minFineCol,region.fineOriginCol),regionFineColMax=Math.min(maxFineCol,region.fineOriginCol+region.fineCols-1);if(regionFineRowMin>regionFineRowMax||regionFineColMin>regionFineColMax)continue;let localRowMin=Math.floor((regionFineRowMin-region.fineOriginRow)/region.cellScale),localRowMax=Math.floor((regionFineRowMax-region.fineOriginRow)/region.cellScale),localColMin=Math.floor((regionFineColMin-region.fineOriginCol)/region.cellScale),localColMax=Math.floor((regionFineColMax-region.fineOriginCol)/region.cellScale);for(let row=localRowMin;row<=localRowMax;row++)for(let col=localColMin;col<=localColMax;col++)visitor(this.cellIdFor(region.id,row,col))}}ripTrace(connId){for(;this.ripCount.length<=connId;)this.ripCount.push(0);if(this.ripCount[connId]++,this.totalRipEvents++,this.totalRipEvents>=this.MAX_RIPS){this.error=`Convergence failure: exceeded MAX_RIPS ${this.MAX_RIPS}`,this.failed=!0;return}let route=this.solvedRoutes[connId];if(route){for(let i3=0;i3<route.states.length;i3++){let cellId=route.states[i3]%this.planeSize;this.penalty2d[cellId]=this.penalty2d[cellId]+this.hyperParameters.ripTracePenalty}for(let i3=0;i3<route.viaCellIds.length;i3++){let cellId=route.viaCellIds[i3];this.penalty2d[cellId]=this.penalty2d[cellId]+this.hyperParameters.ripViaPenalty}}let indices=this.usedIndicesByConn[connId];if(indices){for(let i3=0;i3<indices.length;i3++)this.removeOccupant(indices[i3],connId);this.usedIndicesByConn[connId]=void 0}if(route){this.solvedRoutes[connId]=void 0;let first=route.states[0],last=route.states[route.states.length-1],startZ=Math.floor(first/this.planeSize),endZ=Math.floor(last/this.planeSize);this.unsolvedSegs.push({connId,startZ,startCellId:first-startZ*this.planeSize,startPoint:route.startPoint,endZ,endCellId:last-endZ*this.planeSize,endPoint:route.endPoint})}}flattenNeighborLists(neighbors){let offset=new Int32Array(neighbors.length+1),total=0;for(let i3=0;i3<neighbors.length;i3++)offset[i3]=total,total+=neighbors[i3].length;offset[neighbors.length]=total;let ids=new Int32Array(total),costs=new Float32Array(total),cursor=0;for(let i3=0;i3<neighbors.length;i3++){let edges=neighbors[i3];for(let j4=0;j4<edges.length;j4++){let edge=edges[j4];ids[cursor]=edge.cellId,costs[cursor]=edge.cost,cursor++}}return{offset,ids,costs}}visualize(){let LAYER_COLORS2=["red","blue","orange","green"],vt3=this.gridToBoundsTransform,points=[],lines=[],circles=[],rects=[];if(rects.push({center:{x:this.nodeWithPortPoints.center.x,y:this.nodeWithPortPoints.center.y},width:this.nodeWithPortPoints.width,height:this.nodeWithPortPoints.height,stroke:"gray"}),this.showPenaltyMap&&this.penalty2d){let maxPenalty=0;for(let i3=0;i3<this.penalty2d.length;i3++)this.penalty2d[i3]>maxPenalty&&(maxPenalty=this.penalty2d[i3]);if(maxPenalty>0)for(let cellId=0;cellId<this.planeSize;cellId++){let penalty=this.penalty2d[cellId];if(penalty<=0)continue;let tc3=applyAffineTransformToPoint(vt3,{x:this.cellCenterX[cellId],y:this.cellCenterY[cellId]}),alpha=Math.min(.6,penalty/maxPenalty*.6);rects.push({center:tc3,width:this.cellWidth[cellId]*vt3.a,height:this.cellHeight[cellId]*vt3.e,fill:`rgba(255,165,0,${alpha.toFixed(3)})`})}}if(this.showUsedCellMap&&this.usedCellsFlat)for(let z4=0;z4<this.layers;z4++){let zBase=z4*this.planeSize;for(let cellId=0;cellId<this.planeSize;cellId++){if(this.usedCellsFlat[zBase+cellId]===-1)continue;let tc3=applyAffineTransformToPoint(vt3,{x:this.cellCenterX[cellId],y:this.cellCenterY[cellId]});rects.push({center:tc3,width:this.cellWidth[cellId]*vt3.a,height:this.cellHeight[cellId]*vt3.e,fill:"rgba(0,0,255,0.5)"})}}for(let pp3 of this.nodeWithPortPoints.portPoints)points.push({x:pp3.x,y:pp3.y,color:LAYER_COLORS2[pp3.z]??"gray",label:pp3.connectionName});let TRACE_COLORS3=["rgba(255,0,0,0.75)","rgba(0,0,255,0.75)","rgba(255,165,0,0.75)","rgba(0,128,0,0.75)"],transformedRoutes=this.getOutput();for(let route of transformedRoutes){if(route.route.length<2)continue;let segStart=0;for(let i3=1;i3<route.route.length;i3++){let prev=route.route[i3-1];route.route[i3].z!==prev.z&&(i3-segStart>=2&&lines.push({points:route.route.slice(segStart,i3).map(p4=>({x:p4.x,y:p4.y})),strokeColor:TRACE_COLORS3[prev.z]??"rgba(128,128,128,0.75)",strokeWidth:this.traceThickness}),segStart=i3)}if(route.route.length-segStart>=2){let lastZ=route.route[segStart].z;lines.push({points:route.route.slice(segStart).map(p4=>({x:p4.x,y:p4.y})),strokeColor:TRACE_COLORS3[lastZ]??"rgba(128,128,128,0.75)",strokeWidth:this.traceThickness})}}for(let route of transformedRoutes)for(let via of route.vias)circles.push({center:{x:via.x,y:via.y},radius:this.viaDiameter/2,fill:"rgba(0,0,0,0.3)",stroke:"black"});if(this.activeConnSeg&&this.visitedFlatStamp){let currentStamp=this.stamp;for(let z4=0;z4<this.layers;z4++){let zBase=z4*this.planeSize;for(let cellId=0;cellId<this.planeSize;cellId++){if(this.visitedFlatStamp[zBase+cellId]!==currentStamp)continue;let tc3=applyAffineTransformToPoint(vt3,{x:this.cellCenterX[cellId],y:this.cellCenterY[cellId]});points.push({x:tc3.x,y:tc3.y,color:"rgba(0,0,255,0.2)"})}}}return{points,lines,circles,rects,coordinateSystem:"cartesian",title:`HighDensityA03 [${this.getSolvedRouteCount()} solved, ${this.unsolvedSegs?.length??0} remaining]`}}getOutput(){let t52=this.gridToBoundsTransform,result=[];for(let connId=0;connId<this.solvedRoutes.length;connId++){let route=this.solvedRoutes[connId];if(!route)continue;let connName=this.connIdToName[connId],points=Array.from(route.states,state2=>{let z4=Math.floor(state2/this.planeSize),cellId=state2-z4*this.planeSize,tp3=applyAffineTransformToPoint(t52,{x:this.cellCenterX[cellId],y:this.cellCenterY[cellId]});return{x:tp3.x,y:tp3.y,z:this.layerToZ.get(z4)??z4}});points.length>0&&(points[0]={...route.startPoint},points.length>1&&(points[points.length-1]={...route.endPoint})),result.push({connectionName:connName,traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,route:points,vias:Array.from(route.viaCellIds,cellId=>applyAffineTransformToPoint(t52,{x:this.cellCenterX[cellId],y:this.cellCenterY[cellId]}))})}return result}getSolvedRouteCount(){let count=0;for(let i3=0;i3<this.solvedRoutes.length;i3++)this.solvedRoutes[i3]&&count++;return count}computeGridToBoundsTransform(){let minCenterX=1/0,maxCenterX=-1/0,minCenterY=1/0,maxCenterY=-1/0;for(let cellId=0;cellId<this.planeSize;cellId++){let centerX=this.cellCenterX[cellId],centerY=this.cellCenterY[cellId];centerX<minCenterX&&(minCenterX=centerX),centerX>maxCenterX&&(maxCenterX=centerX),centerY<minCenterY&&(minCenterY=centerY),centerY>maxCenterY&&(maxCenterY=centerY)}let xSpan=maxCenterX-minCenterX,ySpan=maxCenterY-minCenterY,width=this.boundsMaxX-this.boundsMinX,height=this.boundsMaxY-this.boundsMinY,a3=xSpan>0?width/xSpan:1,e5=ySpan>0?height/ySpan:1,c4=xSpan>0?this.boundsMinX-a3*minCenterX:(this.boundsMinX+this.boundsMaxX)/2-minCenterX,f3=ySpan>0?this.boundsMinY-e5*minCenterY:(this.boundsMinY+this.boundsMaxY)/2-minCenterY;return{a:a3,b:0,c:c4,d:0,e:e5,f:f3}}};var ROUNDING_PRECISION=1e3;var BOUNDARY_INSET=1/ROUNDING_PRECISION;var VIA_BORDER_EXTRA_CLEARANCE=.15,VIA_SEGMENT_TARGET_CLEARANCE=.4;var VIA_BORDER_TARGET_CLEARANCE=VIA_SEGMENT_TARGET_CLEARANCE+VIA_BORDER_EXTRA_CLEARANCE+.1,VIA_BORDER_FALLOFF_DISTANCE=VIA_BORDER_TARGET_CLEARANCE+.05;var defaultParams={cellSizeMm:.1,traceMargin:.15,traceThickness:.1,viaDiameter:.3,viaMinDistFromBorder:.15},defaultA03Params={highResolutionCellSize:.1,highResolutionCellThickness:8,lowResolutionCellSize:.4,traceMargin:.15,traceThickness:.1,viaDiameter:.3,viaMinDistFromBorder:.15},defaultA08Params={...defaultParams,stepMultiplier:1,showPenaltyMap:!1,showUsedCellMap:!1,effort:1,initialRectMarginMm:.2,rectShrinkStepMm:.1,breakoutTraceMarginMm:.1,breakoutSegmentCount:2,breakoutMaxIterationsPerRect:60,breakoutForceStepSize:.2,breakoutRepulsionStrength:1.8,breakoutSmoothingStrength:.16,breakoutAttractionStrength:.06,innerPortSpreadFactor:1},defaultA09Params={...defaultA03Params,effort:1,boundaryBonus:.18,boundaryBonusSigma:.22,portShadowStrength:.55,portShadowTangentSigma:.18,portShadowDepthSigma:.5,fullOrderSearchConnectionCountLimit:6,priorityHeadSize:4,maxCandidateOrders:720};var import_object_hash=__toESM(require_object_hash(),1),import_object_hash2=__toESM(require_object_hash(),1),import_object_hash3=__toESM(require_object_hash(),1);var t3=Object.create,e4=Object.defineProperty,n3=Object.getOwnPropertyDescriptor,o3=Object.getOwnPropertyNames,i2=Object.getPrototypeOf,s2=Object.prototype.hasOwnProperty,r4=(t52,e5)=>function(){return e5||(0,t52[o3(t52)[0]])((e5={exports:{}}).exports,e5),e5.exports},a2=(t52,n4)=>{for(var o4 in n4)e4(t52,o4,{get:n4[o4],enumerable:!0})},c3=(r5,a3,c4)=>(c4=r5!=null?t3(i2(r5)):{},((t52,i3,r6,a4)=>{if(i3&&typeof i3=="object"||typeof i3=="function")for(let c5 of o3(i3))s2.call(t52,c5)||c5===r6||e4(t52,c5,{get:()=>i3[c5],enumerable:!(a4=n3(i3,c5))||a4.enumerable});return t52})(!a3&&r5&&r5.__esModule?c4:e4(c4,"default",{value:r5,enumerable:!0}),r5)),l3=r4({"node_modules/is-buffer/index.js"(t52,e5){function n4(t53){return!!t53.constructor&&typeof t53.constructor.isBuffer=="function"&&t53.constructor.isBuffer(t53)}e5.exports=function(t53){return t53!=null&&(n4(t53)||(function(t54){return typeof t54.readFloatLE=="function"&&typeof t54.slice=="function"&&n4(t54.slice(0,0))})(t53)||!!t53._isBuffer)}}}),h4=r4({"node_modules/kind-of/index.js"(t52,e5){var n4=l3(),o4=Object.prototype.toString;e5.exports=function(t53){if(t53===void 0)return"undefined";if(t53===null)return"null";if(t53===!0||t53===!1||t53 instanceof Boolean)return"boolean";if(typeof t53=="string"||t53 instanceof String)return"string";if(typeof t53=="number"||t53 instanceof Number)return"number";if(typeof t53=="function"||t53 instanceof Function)return"function";if(Array.isArray!==void 0&&Array.isArray(t53))return"array";if(t53 instanceof RegExp)return"regexp";if(t53 instanceof Date)return"date";var e6=o4.call(t53);return e6==="[object RegExp]"?"regexp":e6==="[object Date]"?"date":e6==="[object Arguments]"?"arguments":e6==="[object Error]"?"error":n4(t53)?"buffer":e6==="[object Set]"?"set":e6==="[object WeakSet]"?"weakset":e6==="[object Map]"?"map":e6==="[object WeakMap]"?"weakmap":e6==="[object Symbol]"?"symbol":e6==="[object Int8Array]"?"int8array":e6==="[object Uint8Array]"?"uint8array":e6==="[object Uint8ClampedArray]"?"uint8clampedarray":e6==="[object Int16Array]"?"int16array":e6==="[object Uint16Array]"?"uint16array":e6==="[object Int32Array]"?"int32array":e6==="[object Uint32Array]"?"uint32array":e6==="[object Float32Array]"?"float32array":e6==="[object Float64Array]"?"float64array":"object"}}}),d3=r4({"node_modules/rename-keys/index.js"(t52,e5){(function(){function t53(t54,e6){if(typeof e6!="function")return t54;var n4={};for(var o4 in t54)Object.prototype.hasOwnProperty.call(t54,o4)&&(n4[e6(o4,t54[o4])||o4]=t54[o4]);return n4}e5!==void 0&&e5.exports?e5.exports=t53:typeof define=="function"&&define.amd?define([],function(){return t53}):window.rename=t53})()}}),u4=r4({"node_modules/deep-rename-keys/index.js"(t52,e5){var n4=h4(),o4=d3();e5.exports=function t53(e6,i3){var s3=n4(e6);if(s3!=="object"&&s3!=="array")throw new Error("expected an object");var r5=[];for(var a3 in s3==="object"&&(e6=o4(e6,i3),r5={}),e6)if(e6.hasOwnProperty(a3)){var c4=e6[a3];n4(c4)==="object"||n4(c4)==="array"?r5[a3]=t53(c4,i3):r5[a3]=c4}return r5}}}),p3=r4({"node_modules/xml-reader/node_modules/eventemitter3/index.js"(t52,e5){var n4=Object.prototype.hasOwnProperty,o4="~";function i3(){}function s3(t53,e6,n5){this.fn=t53,this.context=e6,this.once=n5||!1}function r5(){this._events=new i3,this._eventsCount=0}Object.create&&(i3.prototype=Object.create(null),new i3().__proto__||(o4=!1)),r5.prototype.eventNames=function(){var t53,e6,i4=[];if(this._eventsCount===0)return i4;for(e6 in t53=this._events)n4.call(t53,e6)&&i4.push(o4?e6.slice(1):e6);return Object.getOwnPropertySymbols?i4.concat(Object.getOwnPropertySymbols(t53)):i4},r5.prototype.listeners=function(t53,e6){var n5=o4?o4+t53:t53,i4=this._events[n5];if(e6)return!!i4;if(!i4)return[];if(i4.fn)return[i4.fn];for(var s4=0,r6=i4.length,a3=new Array(r6);s4<r6;s4++)a3[s4]=i4[s4].fn;return a3},r5.prototype.emit=function(t53,e6,n5,i4,s4,r6){var a3=o4?o4+t53:t53;if(!this._events[a3])return!1;var c4,l4,h6=this._events[a3],d4=arguments.length;if(h6.fn){switch(h6.once&&this.removeListener(t53,h6.fn,void 0,!0),d4){case 1:return h6.fn.call(h6.context),!0;case 2:return h6.fn.call(h6.context,e6),!0;case 3:return h6.fn.call(h6.context,e6,n5),!0;case 4:return h6.fn.call(h6.context,e6,n5,i4),!0;case 5:return h6.fn.call(h6.context,e6,n5,i4,s4),!0;case 6:return h6.fn.call(h6.context,e6,n5,i4,s4,r6),!0}for(l4=1,c4=new Array(d4-1);l4<d4;l4++)c4[l4-1]=arguments[l4];h6.fn.apply(h6.context,c4)}else{var u5,p4=h6.length;for(l4=0;l4<p4;l4++)switch(h6[l4].once&&this.removeListener(t53,h6[l4].fn,void 0,!0),d4){case 1:h6[l4].fn.call(h6[l4].context);break;case 2:h6[l4].fn.call(h6[l4].context,e6);break;case 3:h6[l4].fn.call(h6[l4].context,e6,n5);break;case 4:h6[l4].fn.call(h6[l4].context,e6,n5,i4);break;default:if(!c4)for(u5=1,c4=new Array(d4-1);u5<d4;u5++)c4[u5-1]=arguments[u5];h6[l4].fn.apply(h6[l4].context,c4)}}return!0},r5.prototype.on=function(t53,e6,n5){var i4=new s3(e6,n5||this),r6=o4?o4+t53:t53;return this._events[r6]?this._events[r6].fn?this._events[r6]=[this._events[r6],i4]:this._events[r6].push(i4):(this._events[r6]=i4,this._eventsCount++),this},r5.prototype.once=function(t53,e6,n5){var i4=new s3(e6,n5||this,!0),r6=o4?o4+t53:t53;return this._events[r6]?this._events[r6].fn?this._events[r6]=[this._events[r6],i4]:this._events[r6].push(i4):(this._events[r6]=i4,this._eventsCount++),this},r5.prototype.removeListener=function(t53,e6,n5,s4){var r6=o4?o4+t53:t53;if(!this._events[r6])return this;if(!e6)return--this._eventsCount===0?this._events=new i3:delete this._events[r6],this;var a3=this._events[r6];if(a3.fn)a3.fn!==e6||s4&&!a3.once||n5&&a3.context!==n5||(--this._eventsCount===0?this._events=new i3:delete this._events[r6]);else{for(var c4=0,l4=[],h6=a3.length;c4<h6;c4++)(a3[c4].fn!==e6||s4&&!a3[c4].once||n5&&a3[c4].context!==n5)&&l4.push(a3[c4]);l4.length?this._events[r6]=l4.length===1?l4[0]:l4:--this._eventsCount===0?this._events=new i3:delete this._events[r6]}return this},r5.prototype.removeAllListeners=function(t53){var e6;return t53?(e6=o4?o4+t53:t53,this._events[e6]&&(--this._eventsCount===0?this._events=new i3:delete this._events[e6])):(this._events=new i3,this._eventsCount=0),this},r5.prototype.off=r5.prototype.removeListener,r5.prototype.addListener=r5.prototype.on,r5.prototype.setMaxListeners=function(){return this},r5.prefixed=o4,r5.EventEmitter=r5,e5!==void 0&&(e5.exports=r5)}}),m3=r4({"node_modules/xml-lexer/node_modules/eventemitter3/index.js"(t52,e5){var n4=Object.prototype.hasOwnProperty,o4="~";function i3(){}function s3(t53,e6,n5){this.fn=t53,this.context=e6,this.once=n5||!1}function r5(){this._events=new i3,this._eventsCount=0}Object.create&&(i3.prototype=Object.create(null),new i3().__proto__||(o4=!1)),r5.prototype.eventNames=function(){var t53,e6,i4=[];if(this._eventsCount===0)return i4;for(e6 in t53=this._events)n4.call(t53,e6)&&i4.push(o4?e6.slice(1):e6);return Object.getOwnPropertySymbols?i4.concat(Object.getOwnPropertySymbols(t53)):i4},r5.prototype.listeners=function(t53,e6){var n5=o4?o4+t53:t53,i4=this._events[n5];if(e6)return!!i4;if(!i4)return[];if(i4.fn)return[i4.fn];for(var s4=0,r6=i4.length,a3=new Array(r6);s4<r6;s4++)a3[s4]=i4[s4].fn;return a3},r5.prototype.emit=function(t53,e6,n5,i4,s4,r6){var a3=o4?o4+t53:t53;if(!this._events[a3])return!1;var c4,l4,h6=this._events[a3],d4=arguments.length;if(h6.fn){switch(h6.once&&this.removeListener(t53,h6.fn,void 0,!0),d4){case 1:return h6.fn.call(h6.context),!0;case 2:return h6.fn.call(h6.context,e6),!0;case 3:return h6.fn.call(h6.context,e6,n5),!0;case 4:return h6.fn.call(h6.context,e6,n5,i4),!0;case 5:return h6.fn.call(h6.context,e6,n5,i4,s4),!0;case 6:return h6.fn.call(h6.context,e6,n5,i4,s4,r6),!0}for(l4=1,c4=new Array(d4-1);l4<d4;l4++)c4[l4-1]=arguments[l4];h6.fn.apply(h6.context,c4)}else{var u5,p4=h6.length;for(l4=0;l4<p4;l4++)switch(h6[l4].once&&this.removeListener(t53,h6[l4].fn,void 0,!0),d4){case 1:h6[l4].fn.call(h6[l4].context);break;case 2:h6[l4].fn.call(h6[l4].context,e6);break;case 3:h6[l4].fn.call(h6[l4].context,e6,n5);break;case 4:h6[l4].fn.call(h6[l4].context,e6,n5,i4);break;default:if(!c4)for(u5=1,c4=new Array(d4-1);u5<d4;u5++)c4[u5-1]=arguments[u5];h6[l4].fn.apply(h6[l4].context,c4)}}return!0},r5.prototype.on=function(t53,e6,n5){var i4=new s3(e6,n5||this),r6=o4?o4+t53:t53;return this._events[r6]?this._events[r6].fn?this._events[r6]=[this._events[r6],i4]:this._events[r6].push(i4):(this._events[r6]=i4,this._eventsCount++),this},r5.prototype.once=function(t53,e6,n5){var i4=new s3(e6,n5||this,!0),r6=o4?o4+t53:t53;return this._events[r6]?this._events[r6].fn?this._events[r6]=[this._events[r6],i4]:this._events[r6].push(i4):(this._events[r6]=i4,this._eventsCount++),this},r5.prototype.removeListener=function(t53,e6,n5,s4){var r6=o4?o4+t53:t53;if(!this._events[r6])return this;if(!e6)return--this._eventsCount===0?this._events=new i3:delete this._events[r6],this;var a3=this._events[r6];if(a3.fn)a3.fn!==e6||s4&&!a3.once||n5&&a3.context!==n5||(--this._eventsCount===0?this._events=new i3:delete this._events[r6]);else{for(var c4=0,l4=[],h6=a3.length;c4<h6;c4++)(a3[c4].fn!==e6||s4&&!a3[c4].once||n5&&a3[c4].context!==n5)&&l4.push(a3[c4]);l4.length?this._events[r6]=l4.length===1?l4[0]:l4:--this._eventsCount===0?this._events=new i3:delete this._events[r6]}return this},r5.prototype.removeAllListeners=function(t53){var e6;return t53?(e6=o4?o4+t53:t53,this._events[e6]&&(--this._eventsCount===0?this._events=new i3:delete this._events[e6])):(this._events=new i3,this._eventsCount=0),this},r5.prototype.off=r5.prototype.removeListener,r5.prototype.addListener=r5.prototype.on,r5.prototype.setMaxListeners=function(){return this},r5.prefixed=o4,r5.EventEmitter=r5,e5!==void 0&&(e5.exports=r5)}}),g4=r4({"node_modules/xml-lexer/dist/lexer.js"(t52,e5){function n4(t53,e6,n5){return e6 in t53?Object.defineProperty(t53,e6,{value:n5,enumerable:!0,configurable:!0,writable:!0}):t53[e6]=n5,t53}var o4=m3(),i3=function(){},s3={data:"state-data",cdata:"state-cdata",tagBegin:"state-tag-begin",tagName:"state-tag-name",tagEnd:"state-tag-end",attributeNameStart:"state-attribute-name-start",attributeName:"state-attribute-name",attributeNameEnd:"state-attribute-name-end",attributeValueBegin:"state-attribute-value-begin",attributeValue:"state-attribute-value"},r5={lt:"action-lt",gt:"action-gt",space:"action-space",equal:"action-equal",quote:"action-quote",slash:"action-slash",char:"action-char",error:"action-error"},a3={text:"text",openTag:"open-tag",closeTag:"close-tag",attributeName:"attribute-name",attributeValue:"attribute-value"},c4={" ":r5.space," ":r5.space,"\n":r5.space,"\r":r5.space,"<":r5.lt,">":r5.gt,'"':r5.quote,"'":r5.quote,"=":r5.equal,"/":r5.slash};e5.exports={State:s3,Action:r5,Type:a3,create:function(t53){var e6,l4,h6,d4,u5,p4,m4,g6,f3,_4;t53=Object.assign({debug:!1},t53);var y4=new o4,b3=s3.data,x4="",v4="",S3="",I4="",P4="",M4="",N4=function(e7,n5){if(v4[0]!=="?"&&v4[0]!=="!"){var o6={type:e7,value:n5};t53.debug&&console.log("emit:",o6),y4.emit("data",o6)}};y4.stateMachine=(n4(_4={},s3.data,(n4(e6={},r5.lt,function(){x4.trim()&&N4(a3.text,x4),v4="",P4=!1,b3=s3.tagBegin}),n4(e6,r5.char,function(t54){x4+=t54}),e6)),n4(_4,s3.cdata,n4({},r5.char,function(t54){(x4+=t54).substr(-3)==="]]>"&&(N4(a3.text,x4.slice(0,-3)),x4="",b3=s3.data)})),n4(_4,s3.tagBegin,(n4(l4={},r5.space,i3),n4(l4,r5.char,function(t54){v4=t54,b3=s3.tagName}),n4(l4,r5.slash,function(){v4="",P4=!0}),l4)),n4(_4,s3.tagName,(n4(h6={},r5.space,function(){P4?b3=s3.tagEnd:(b3=s3.attributeNameStart,N4(a3.openTag,v4))}),n4(h6,r5.gt,function(){N4(P4?a3.closeTag:a3.openTag,v4),x4="",b3=s3.data}),n4(h6,r5.slash,function(){b3=s3.tagEnd,N4(a3.openTag,v4)}),n4(h6,r5.char,function(t54){(v4+=t54)==="![CDATA["&&(b3=s3.cdata,x4="",v4="")}),h6)),n4(_4,s3.tagEnd,(n4(d4={},r5.gt,function(){N4(a3.closeTag,v4),x4="",b3=s3.data}),n4(d4,r5.char,i3),d4)),n4(_4,s3.attributeNameStart,(n4(u5={},r5.char,function(t54){S3=t54,b3=s3.attributeName}),n4(u5,r5.gt,function(){x4="",b3=s3.data}),n4(u5,r5.space,i3),n4(u5,r5.slash,function(){P4=!0,b3=s3.tagEnd}),u5)),n4(_4,s3.attributeName,(n4(p4={},r5.space,function(){b3=s3.attributeNameEnd}),n4(p4,r5.equal,function(){N4(a3.attributeName,S3),b3=s3.attributeValueBegin}),n4(p4,r5.gt,function(){I4="",N4(a3.attributeName,S3),N4(a3.attributeValue,I4),x4="",b3=s3.data}),n4(p4,r5.slash,function(){P4=!0,I4="",N4(a3.attributeName,S3),N4(a3.attributeValue,I4),b3=s3.tagEnd}),n4(p4,r5.char,function(t54){S3+=t54}),p4)),n4(_4,s3.attributeNameEnd,(n4(m4={},r5.space,i3),n4(m4,r5.equal,function(){N4(a3.attributeName,S3),b3=s3.attributeValueBegin}),n4(m4,r5.gt,function(){I4="",N4(a3.attributeName,S3),N4(a3.attributeValue,I4),x4="",b3=s3.data}),n4(m4,r5.char,function(t54){I4="",N4(a3.attributeName,S3),N4(a3.attributeValue,I4),S3=t54,b3=s3.attributeName}),m4)),n4(_4,s3.attributeValueBegin,(n4(g6={},r5.space,i3),n4(g6,r5.quote,function(t54){M4=t54,I4="",b3=s3.attributeValue}),n4(g6,r5.gt,function(){N4(a3.attributeValue,I4=""),x4="",b3=s3.data}),n4(g6,r5.char,function(t54){M4="",I4=t54,b3=s3.attributeValue}),g6)),n4(_4,s3.attributeValue,(n4(f3={},r5.space,function(t54){M4?I4+=t54:(N4(a3.attributeValue,I4),b3=s3.attributeNameStart)}),n4(f3,r5.quote,function(t54){M4===t54?(N4(a3.attributeValue,I4),b3=s3.attributeNameStart):I4+=t54}),n4(f3,r5.gt,function(t54){M4?I4+=t54:(N4(a3.attributeValue,I4),x4="",b3=s3.data)}),n4(f3,r5.slash,function(t54){M4?I4+=t54:(N4(a3.attributeValue,I4),P4=!0,b3=s3.tagEnd)}),n4(f3,r5.char,function(t54){I4+=t54}),f3)),_4);var C4=function(e7){t53.debug&&console.log(b3,e7);var n5=y4.stateMachine[b3],o6=n5[(function(t54){return c4[t54]||r5.char})(e7)]||n5[r5.error]||n5[r5.char];o6(e7)};return y4.write=function(t54){for(var e7=t54.length,n5=0;n5<e7;n5++)C4(t54[n5])},y4}}}}),f2=r4({"node_modules/xml-reader/dist/reader.js"(t52,e5){var n4=p3(),o4=g4(),i3=o4.Type,s3={element:"element",text:"text"},r5=function(t53){return Object.assign({name:"",type:s3.element,value:"",parent:null,attributes:{},children:[]},t53)},a3=function(t53){t53=Object.assign({stream:!1,parentNodes:!0,doneEvent:"done",tagPrefix:"tag:",emitTopLevelOnly:!1,debug:!1},t53);var e6=void 0,a4=void 0,c4=void 0,l4=void 0,h6=new n4,d4=function(n5){switch(n5.type){case i3.openTag:if(c4===null)(c4=a4).name=n5.value;else{var o6=r5({name:n5.value,parent:c4});c4.children.push(o6),c4=o6}break;case i3.closeTag:var d5=c4.parent;if(t53.parentNodes||(c4.parent=null),c4.name!==n5.value)break;t53.stream&&d5===a4&&(a4.children=[],c4.parent=null),t53.emitTopLevelOnly&&d5!==a4||(h6.emit(t53.tagPrefix+c4.name,c4),h6.emit("tag",c4.name,c4)),c4===a4&&(e6.removeAllListeners("data"),h6.emit(t53.doneEvent,c4),a4=null),c4=d5;break;case i3.text:c4&&c4.children.push(r5({type:s3.text,value:n5.value,parent:t53.parentNodes?c4:null}));break;case i3.attributeName:l4=n5.value,c4.attributes[l4]="";break;case i3.attributeValue:c4.attributes[l4]=n5.value}};return h6.reset=function(){(e6=o4.create({debug:t53.debug})).on("data",d4),a4=r5(),c4=null,l4="",h6.parse=e6.write},h6.reset(),h6};e5.exports={parseSync:function(t53,e6){e6=Object.assign({},e6,{stream:!1,tagPrefix:":"});var n5=a3(e6),o6=void 0;return n5.on("done",function(t54){o6=t54}),n5.parse(t53),o6},create:a3,NodeType:s3}}}),_3=r4({"node_modules/binary-search-bounds/search-bounds.js"(t52,e5){function n4(t53,e6,n5,o6,i4){for(var s4=i4+1;o6<=i4;){var r6=o6+i4>>>1,a4=t53[r6];(n5!==void 0?n5(a4,e6):a4-e6)>=0?(s4=r6,i4=r6-1):o6=r6+1}return s4}function o4(t53,e6,n5,o6,i4){for(var s4=i4+1;o6<=i4;){var r6=o6+i4>>>1,a4=t53[r6];(n5!==void 0?n5(a4,e6):a4-e6)>0?(s4=r6,i4=r6-1):o6=r6+1}return s4}function i3(t53,e6,n5,o6,i4){for(var s4=o6-1;o6<=i4;){var r6=o6+i4>>>1,a4=t53[r6];(n5!==void 0?n5(a4,e6):a4-e6)<0?(s4=r6,o6=r6+1):i4=r6-1}return s4}function s3(t53,e6,n5,o6,i4){for(var s4=o6-1;o6<=i4;){var r6=o6+i4>>>1,a4=t53[r6];(n5!==void 0?n5(a4,e6):a4-e6)<=0?(s4=r6,o6=r6+1):i4=r6-1}return s4}function r5(t53,e6,n5,o6,i4){for(;o6<=i4;){var s4=o6+i4>>>1,r6=t53[s4],a4=n5!==void 0?n5(r6,e6):r6-e6;if(a4===0)return s4;a4<=0?o6=s4+1:i4=s4-1}return-1}function a3(t53,e6,n5,o6,i4,s4){return typeof n5=="function"?s4(t53,e6,n5,o6===void 0?0:0|o6,i4===void 0?t53.length-1:0|i4):s4(t53,e6,void 0,n5===void 0?0:0|n5,o6===void 0?t53.length-1:0|o6)}e5.exports={ge:function(t53,e6,o6,i4,s4){return a3(t53,e6,o6,i4,s4,n4)},gt:function(t53,e6,n5,i4,s4){return a3(t53,e6,n5,i4,s4,o4)},lt:function(t53,e6,n5,o6,s4){return a3(t53,e6,n5,o6,s4,i3)},le:function(t53,e6,n5,o6,i4){return a3(t53,e6,n5,o6,i4,s3)},eq:function(t53,e6,n5,o6,i4){return a3(t53,e6,n5,o6,i4,r5)}}}}),y=r4({"node_modules/two-product/two-product.js"(t52,e5){e5.exports=function(t53,e6,o4){var i3=t53*e6,s3=n4*t53,r5=s3-(s3-t53),a3=t53-r5,c4=n4*e6,l4=c4-(c4-e6),h6=e6-l4,d4=a3*h6-(i3-r5*l4-a3*l4-r5*h6);return o4?(o4[0]=d4,o4[1]=i3,o4):[d4,i3]};var n4=+(Math.pow(2,27)+1)}}),b=r4({"node_modules/robust-sum/robust-sum.js"(t52,e5){e5.exports=function(t53,e6){var n4=0|t53.length,o4=0|e6.length;if(n4===1&&o4===1)return(function(t54,e7){var n5=t54+e7,o6=n5-t54,i4=n5-o6,s4=e7-o6,r6=t54-i4,a4=r6+s4;return a4?[a4,n5]:[n5]})(t53[0],e6[0]);var i3,s3,r5=new Array(n4+o4),a3=0,c4=0,l4=0,h6=Math.abs,d4=t53[c4],u5=h6(d4),p4=e6[l4],m4=h6(p4);u5<m4?(s3=d4,(c4+=1)<n4&&(u5=h6(d4=t53[c4]))):(s3=p4,(l4+=1)<o4&&(m4=h6(p4=e6[l4]))),c4<n4&&u5<m4||l4>=o4?(i3=d4,(c4+=1)<n4&&(u5=h6(d4=t53[c4]))):(i3=p4,(l4+=1)<o4&&(m4=h6(p4=e6[l4])));for(var g6,f3,_4=i3+s3,y4=_4-i3,b3=s3-y4,x4=b3,v4=_4;c4<n4&&l4<o4;)u5<m4?(i3=d4,(c4+=1)<n4&&(u5=h6(d4=t53[c4]))):(i3=p4,(l4+=1)<o4&&(m4=h6(p4=e6[l4]))),(b3=(s3=x4)-(y4=(_4=i3+s3)-i3))&&(r5[a3++]=b3),x4=v4-((g6=v4+_4)-(f3=g6-v4))+(_4-f3),v4=g6;for(;c4<n4;)(b3=(s3=x4)-(y4=(_4=(i3=d4)+s3)-i3))&&(r5[a3++]=b3),x4=v4-((g6=v4+_4)-(f3=g6-v4))+(_4-f3),v4=g6,(c4+=1)<n4&&(d4=t53[c4]);for(;l4<o4;)(b3=(s3=x4)-(y4=(_4=(i3=p4)+s3)-i3))&&(r5[a3++]=b3),x4=v4-((g6=v4+_4)-(f3=g6-v4))+(_4-f3),v4=g6,(l4+=1)<o4&&(p4=e6[l4]);return x4&&(r5[a3++]=x4),v4&&(r5[a3++]=v4),a3||(r5[a3++]=0),r5.length=a3,r5}}}),x3=r4({"node_modules/two-sum/two-sum.js"(t52,e5){e5.exports=function(t53,e6,n4){var o4=t53+e6,i3=o4-t53,s3=e6-i3,r5=t53-(o4-i3);return n4?(n4[0]=r5+s3,n4[1]=o4,n4):[r5+s3,o4]}}}),v3=r4({"node_modules/robust-scale/robust-scale.js"(t52,e5){var n4=y(),o4=x3();e5.exports=function(t53,e6){var i3=t53.length;if(i3===1){var s3=n4(t53[0],e6);return s3[0]?s3:[s3[1]]}var r5=new Array(2*i3),a3=[.1,.1],c4=[.1,.1],l4=0;n4(t53[0],e6,a3),a3[0]&&(r5[l4++]=a3[0]);for(var h6=1;h6<i3;++h6){n4(t53[h6],e6,c4);var d4=a3[1];o4(d4,c4[0],a3),a3[0]&&(r5[l4++]=a3[0]);var u5=c4[1],p4=a3[1],m4=u5+p4,g6=p4-(m4-u5);a3[1]=m4,g6&&(r5[l4++]=g6)}return a3[1]&&(r5[l4++]=a3[1]),l4===0&&(r5[l4++]=0),r5.length=l4,r5}}}),S2=r4({"node_modules/robust-subtract/robust-diff.js"(t52,e5){e5.exports=function(t53,e6){var n4=0|t53.length,o4=0|e6.length;if(n4===1&&o4===1)return(function(t54,e7){var n5=t54+e7,o6=n5-t54,i4=n5-o6,s4=e7-o6,r6=t54-i4,a4=r6+s4;return a4?[a4,n5]:[n5]})(t53[0],-e6[0]);var i3,s3,r5=new Array(n4+o4),a3=0,c4=0,l4=0,h6=Math.abs,d4=t53[c4],u5=h6(d4),p4=-e6[l4],m4=h6(p4);u5<m4?(s3=d4,(c4+=1)<n4&&(u5=h6(d4=t53[c4]))):(s3=p4,(l4+=1)<o4&&(m4=h6(p4=-e6[l4]))),c4<n4&&u5<m4||l4>=o4?(i3=d4,(c4+=1)<n4&&(u5=h6(d4=t53[c4]))):(i3=p4,(l4+=1)<o4&&(m4=h6(p4=-e6[l4])));for(var g6,f3,_4=i3+s3,y4=_4-i3,b3=s3-y4,x4=b3,v4=_4;c4<n4&&l4<o4;)u5<m4?(i3=d4,(c4+=1)<n4&&(u5=h6(d4=t53[c4]))):(i3=p4,(l4+=1)<o4&&(m4=h6(p4=-e6[l4]))),(b3=(s3=x4)-(y4=(_4=i3+s3)-i3))&&(r5[a3++]=b3),x4=v4-((g6=v4+_4)-(f3=g6-v4))+(_4-f3),v4=g6;for(;c4<n4;)(b3=(s3=x4)-(y4=(_4=(i3=d4)+s3)-i3))&&(r5[a3++]=b3),x4=v4-((g6=v4+_4)-(f3=g6-v4))+(_4-f3),v4=g6,(c4+=1)<n4&&(d4=t53[c4]);for(;l4<o4;)(b3=(s3=x4)-(y4=(_4=(i3=p4)+s3)-i3))&&(r5[a3++]=b3),x4=v4-((g6=v4+_4)-(f3=g6-v4))+(_4-f3),v4=g6,(l4+=1)<o4&&(p4=-e6[l4]);return x4&&(r5[a3++]=x4),v4&&(r5[a3++]=v4),a3||(r5[a3++]=0),r5.length=a3,r5}}}),I3=r4({"node_modules/robust-orientation/orientation.js"(t52,e5){var n4=y(),o4=b(),i3=v3(),s3=S2();function r5(t53,e6,n5,o6){return function(n6,i4,s4){var r6=t53(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),t53(e6(n6[1],i4[0]),e6(-i4[1],n6[0]))),a4=t53(e6(n6[1],s4[0]),e6(-s4[1],n6[0])),c5=o6(r6,a4);return c5[c5.length-1]}}function a3(t53,e6,n5,o6){return function(i4,s4,r6,a4){var c5=t53(t53(n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),s4[2]),t53(n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),-r6[2]),n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),a4[2]))),t53(n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),a4[2])))),l5=t53(t53(n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),i4[2]),t53(n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),-r6[2]),n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),a4[2]))),t53(n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),r6[2])))),h7=o6(c5,l5);return h7[h7.length-1]}}function c4(t53,e6,n5,o6){return function(i4,s4,r6,a4,c5){var l5=t53(t53(t53(n5(t53(n5(t53(e6(a4[1],c5[0]),e6(-c5[1],a4[0])),r6[2]),t53(n5(t53(e6(r6[1],c5[0]),e6(-c5[1],r6[0])),-a4[2]),n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),c5[2]))),s4[3]),t53(n5(t53(n5(t53(e6(a4[1],c5[0]),e6(-c5[1],a4[0])),s4[2]),t53(n5(t53(e6(s4[1],c5[0]),e6(-c5[1],s4[0])),-a4[2]),n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),c5[2]))),-r6[3]),n5(t53(n5(t53(e6(r6[1],c5[0]),e6(-c5[1],r6[0])),s4[2]),t53(n5(t53(e6(s4[1],c5[0]),e6(-c5[1],s4[0])),-r6[2]),n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),c5[2]))),a4[3]))),t53(n5(t53(n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),s4[2]),t53(n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),-r6[2]),n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),a4[2]))),-c5[3]),t53(n5(t53(n5(t53(e6(a4[1],c5[0]),e6(-c5[1],a4[0])),s4[2]),t53(n5(t53(e6(s4[1],c5[0]),e6(-c5[1],s4[0])),-a4[2]),n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),c5[2]))),i4[3]),n5(t53(n5(t53(e6(a4[1],c5[0]),e6(-c5[1],a4[0])),i4[2]),t53(n5(t53(e6(i4[1],c5[0]),e6(-c5[1],i4[0])),-a4[2]),n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),c5[2]))),-s4[3])))),t53(t53(n5(t53(n5(t53(e6(s4[1],c5[0]),e6(-c5[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],c5[0]),e6(-c5[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),c5[2]))),a4[3]),t53(n5(t53(n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),a4[2]))),-c5[3]),n5(t53(n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),s4[2]),t53(n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),-r6[2]),n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),a4[2]))),i4[3]))),t53(n5(t53(n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),i4[2]),t53(n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),-r6[2]),n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),a4[2]))),-s4[3]),t53(n5(t53(n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),a4[2]))),r6[3]),n5(t53(n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),r6[2]))),-a4[3]))))),h7=t53(t53(t53(n5(t53(n5(t53(e6(a4[1],c5[0]),e6(-c5[1],a4[0])),r6[2]),t53(n5(t53(e6(r6[1],c5[0]),e6(-c5[1],r6[0])),-a4[2]),n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),c5[2]))),i4[3]),n5(t53(n5(t53(e6(a4[1],c5[0]),e6(-c5[1],a4[0])),i4[2]),t53(n5(t53(e6(i4[1],c5[0]),e6(-c5[1],i4[0])),-a4[2]),n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),c5[2]))),-r6[3])),t53(n5(t53(n5(t53(e6(r6[1],c5[0]),e6(-c5[1],r6[0])),i4[2]),t53(n5(t53(e6(i4[1],c5[0]),e6(-c5[1],i4[0])),-r6[2]),n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),c5[2]))),a4[3]),n5(t53(n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),i4[2]),t53(n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),-r6[2]),n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),a4[2]))),-c5[3]))),t53(t53(n5(t53(n5(t53(e6(r6[1],c5[0]),e6(-c5[1],r6[0])),s4[2]),t53(n5(t53(e6(s4[1],c5[0]),e6(-c5[1],s4[0])),-r6[2]),n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),c5[2]))),i4[3]),n5(t53(n5(t53(e6(r6[1],c5[0]),e6(-c5[1],r6[0])),i4[2]),t53(n5(t53(e6(i4[1],c5[0]),e6(-c5[1],i4[0])),-r6[2]),n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),c5[2]))),-s4[3])),t53(n5(t53(n5(t53(e6(s4[1],c5[0]),e6(-c5[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],c5[0]),e6(-c5[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),c5[2]))),r6[3]),n5(t53(n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),r6[2]))),-c5[3])))),d5=o6(l5,h7);return d5[d5.length-1]}}function l4(t53){return(t53===3?r5:t53===4?a3:c4)(o4,n4,i3,s3)}var h6=l4(3),d4=l4(4),u5=[function(){return 0},function(){return 0},function(t53,e6){return e6[0]-t53[0]},function(t53,e6,n5){var o6,i4=(t53[1]-n5[1])*(e6[0]-n5[0]),s4=(t53[0]-n5[0])*(e6[1]-n5[1]),r6=i4-s4;if(i4>0){if(s4<=0)return r6;o6=i4+s4}else{if(!(i4<0)||s4>=0)return r6;o6=-(i4+s4)}var a4=33306690738754716e-32*o6;return r6>=a4||r6<=-a4?r6:h6(t53,e6,n5)},function(t53,e6,n5,o6){var i4=t53[0]-o6[0],s4=e6[0]-o6[0],r6=n5[0]-o6[0],a4=t53[1]-o6[1],c5=e6[1]-o6[1],l5=n5[1]-o6[1],h7=t53[2]-o6[2],u6=e6[2]-o6[2],p5=n5[2]-o6[2],m6=s4*l5,g6=r6*c5,f3=r6*a4,_4=i4*l5,y4=i4*c5,b3=s4*a4,x4=h7*(m6-g6)+u6*(f3-_4)+p5*(y4-b3),v4=7771561172376103e-31*((Math.abs(m6)+Math.abs(g6))*Math.abs(h7)+(Math.abs(f3)+Math.abs(_4))*Math.abs(u6)+(Math.abs(y4)+Math.abs(b3))*Math.abs(p5));return x4>v4||-x4>v4?x4:d4(t53,e6,n5,o6)}];function p4(t53){var e6=u5[t53.length];return e6||(e6=u5[t53.length]=l4(t53.length)),e6.apply(void 0,t53)}function m4(t53,e6,n5,o6,i4,s4,r6){return function(e7,n6,a4,c5,l5){switch(arguments.length){case 0:case 1:return 0;case 2:return o6(e7,n6);case 3:return i4(e7,n6,a4);case 4:return s4(e7,n6,a4,c5);case 5:return r6(e7,n6,a4,c5,l5)}for(var h7=new Array(arguments.length),d5=0;d5<arguments.length;++d5)h7[d5]=arguments[d5];return t53(h7)}}(function(){for(;u5.length<=5;)u5.push(l4(u5.length));e5.exports=m4.apply(void 0,[p4].concat(u5));for(var t53=0;t53<=5;++t53)e5.exports[t53]=u5[t53]})()}}),P2=r4({"node_modules/cdt2d/lib/monotone.js"(t52,e5){var n4=_3(),o4=I3()[3];function i3(t53,e6,n5,o6,i4){this.a=t53,this.b=e6,this.idx=n5,this.lowerIds=o6,this.upperIds=i4}function s3(t53,e6,n5,o6){this.a=t53,this.b=e6,this.type=n5,this.idx=o6}function r5(t53,e6){var n5=t53.a[0]-e6.a[0]||t53.a[1]-e6.a[1]||t53.type-e6.type;return n5||(t53.type!==0&&(n5=o4(t53.a,t53.b,e6.b))?n5:t53.idx-e6.idx)}function a3(t53,e6){return o4(t53.a,t53.b,e6)}function c4(t53,e6,i4,s4,r6){for(var c5=n4.lt(e6,s4,a3),l5=n4.gt(e6,s4,a3),h7=c5;h7<l5;++h7){for(var d5=e6[h7],u5=d5.lowerIds,p4=u5.length;p4>1&&o4(i4[u5[p4-2]],i4[u5[p4-1]],s4)>0;)t53.push([u5[p4-1],u5[p4-2],r6]),p4-=1;u5.length=p4,u5.push(r6);var m4=d5.upperIds;for(p4=m4.length;p4>1&&o4(i4[m4[p4-2]],i4[m4[p4-1]],s4)<0;)t53.push([m4[p4-2],m4[p4-1],r6]),p4-=1;m4.length=p4,m4.push(r6)}}function l4(t53,e6){var n5;return(n5=t53.a[0]<e6.a[0]?o4(t53.a,t53.b,e6.a):o4(e6.b,e6.a,t53.a))?n5:(n5=e6.b[0]<t53.b[0]?o4(t53.a,t53.b,e6.b):o4(e6.b,e6.a,t53.b))||t53.idx-e6.idx}function h6(t53,e6,o6){var s4=n4.le(t53,o6,l4),r6=t53[s4],a4=r6.upperIds,c5=a4[a4.length-1];r6.upperIds=[c5],t53.splice(s4+1,0,new i3(o6.a,o6.b,o6.idx,[c5],a4))}function d4(t53,e6,o6){var i4=o6.a;o6.a=o6.b,o6.b=i4;var s4=n4.eq(t53,o6,l4),r6=t53[s4];t53[s4-1].upperIds=r6.upperIds,t53.splice(s4,1)}e5.exports=function(t53,e6){for(var n5=t53.length,o6=e6.length,a4=[],l5=0;l5<n5;++l5)a4.push(new s3(t53[l5],null,0,l5));for(l5=0;l5<o6;++l5){var u5=e6[l5],p4=t53[u5[0]],m4=t53[u5[1]];p4[0]<m4[0]?a4.push(new s3(p4,m4,2,l5),new s3(m4,p4,1,l5)):p4[0]>m4[0]&&a4.push(new s3(m4,p4,2,l5),new s3(p4,m4,1,l5))}a4.sort(r5);for(var g6=a4[0].a[0]-(1+Math.abs(a4[0].a[0]))*Math.pow(2,-52),f3=[new i3([g6,1],[g6,0],-1,[],[],[],[])],_4=[],y4=(l5=0,a4.length);l5<y4;++l5){var b3=a4[l5],x4=b3.type;x4===0?c4(_4,f3,t53,b3.a,b3.idx):x4===2?h6(f3,t53,b3):d4(f3,t53,b3)}return _4}}}),M3=r4({"node_modules/cdt2d/lib/triangulation.js"(t52,e5){var n4=_3();function o4(t53,e6){this.stars=t53,this.edges=e6}e5.exports=function(t53,e6){for(var n5=new Array(t53),i4=0;i4<t53;++i4)n5[i4]=[];return new o4(n5,e6)};var i3=o4.prototype;function s3(t53,e6,n5){for(var o6=1,i4=t53.length;o6<i4;o6+=2)if(t53[o6-1]===e6&&t53[o6]===n5)return t53[o6-1]=t53[i4-2],t53[o6]=t53[i4-1],void(t53.length=i4-2)}i3.isConstraint=(function(){var t53=[0,0];function e6(t54,e7){return t54[0]-e7[0]||t54[1]-e7[1]}return function(o6,i4){return t53[0]=Math.min(o6,i4),t53[1]=Math.max(o6,i4),n4.eq(this.edges,t53,e6)>=0}})(),i3.removeTriangle=function(t53,e6,n5){var o6=this.stars;s3(o6[t53],e6,n5),s3(o6[e6],n5,t53),s3(o6[n5],t53,e6)},i3.addTriangle=function(t53,e6,n5){var o6=this.stars;o6[t53].push(e6,n5),o6[e6].push(n5,t53),o6[n5].push(t53,e6)},i3.opposite=function(t53,e6){for(var n5=this.stars[e6],o6=1,i4=n5.length;o6<i4;o6+=2)if(n5[o6]===t53)return n5[o6-1];return-1},i3.flip=function(t53,e6){var n5=this.opposite(t53,e6),o6=this.opposite(e6,t53);this.removeTriangle(t53,e6,n5),this.removeTriangle(e6,t53,o6),this.addTriangle(t53,o6,n5),this.addTriangle(e6,n5,o6)},i3.edges=function(){for(var t53=this.stars,e6=[],n5=0,o6=t53.length;n5<o6;++n5)for(var i4=t53[n5],s4=0,r5=i4.length;s4<r5;s4+=2)e6.push([i4[s4],i4[s4+1]]);return e6},i3.cells=function(){for(var t53=this.stars,e6=[],n5=0,o6=t53.length;n5<o6;++n5)for(var i4=t53[n5],s4=0,r5=i4.length;s4<r5;s4+=2){var a3=i4[s4],c4=i4[s4+1];n5<Math.min(a3,c4)&&e6.push([n5,a3,c4])}return e6}}}),N3=r4({"node_modules/robust-in-sphere/in-sphere.js"(t52,e5){var n4=y(),o4=b(),i3=S2(),s3=v3();function r5(t53){return(t53===3?a3:t53===4?c4:t53===5?l4:h6)(o4,i3,n4,s3)}function a3(t53,e6,n5,o6){return function(i4,s4,r6){var a4=n5(i4[0],i4[0]),c5=o6(a4,s4[0]),l5=o6(a4,r6[0]),h7=n5(s4[0],s4[0]),d5=o6(h7,i4[0]),u6=o6(h7,r6[0]),p5=n5(r6[0],r6[0]),m4=o6(p5,i4[0]),g6=o6(p5,s4[0]),f3=t53(e6(g6,u6),e6(d5,c5)),_4=e6(m4,l5),y4=e6(f3,_4);return y4[y4.length-1]}}function c4(t53,e6,n5,o6){return function(i4,s4,r6,a4){var c5=t53(n5(i4[0],i4[0]),n5(i4[1],i4[1])),l5=o6(c5,s4[0]),h7=o6(c5,r6[0]),d5=o6(c5,a4[0]),u6=t53(n5(s4[0],s4[0]),n5(s4[1],s4[1])),p5=o6(u6,i4[0]),m4=o6(u6,r6[0]),g6=o6(u6,a4[0]),f3=t53(n5(r6[0],r6[0]),n5(r6[1],r6[1])),_4=o6(f3,i4[0]),y4=o6(f3,s4[0]),b3=o6(f3,a4[0]),x4=t53(n5(a4[0],a4[0]),n5(a4[1],a4[1])),v4=o6(x4,i4[0]),S3=o6(x4,s4[0]),I4=o6(x4,r6[0]),P4=t53(t53(o6(e6(I4,b3),s4[1]),t53(o6(e6(S3,g6),-r6[1]),o6(e6(y4,m4),a4[1]))),t53(o6(e6(S3,g6),i4[1]),t53(o6(e6(v4,d5),-s4[1]),o6(e6(p5,l5),a4[1])))),M4=t53(t53(o6(e6(I4,b3),i4[1]),t53(o6(e6(v4,d5),-r6[1]),o6(e6(_4,h7),a4[1]))),t53(o6(e6(y4,m4),i4[1]),t53(o6(e6(_4,h7),-s4[1]),o6(e6(p5,l5),r6[1])))),N4=e6(P4,M4);return N4[N4.length-1]}}function l4(t53,e6,n5,o6){return function(i4,s4,r6,a4,c5){var l5=t53(n5(i4[0],i4[0]),t53(n5(i4[1],i4[1]),n5(i4[2],i4[2]))),h7=o6(l5,s4[0]),d5=o6(l5,r6[0]),u6=o6(l5,a4[0]),p5=o6(l5,c5[0]),m4=t53(n5(s4[0],s4[0]),t53(n5(s4[1],s4[1]),n5(s4[2],s4[2]))),g6=o6(m4,i4[0]),f3=o6(m4,r6[0]),_4=o6(m4,a4[0]),y4=o6(m4,c5[0]),b3=t53(n5(r6[0],r6[0]),t53(n5(r6[1],r6[1]),n5(r6[2],r6[2]))),x4=o6(b3,i4[0]),v4=o6(b3,s4[0]),S3=o6(b3,a4[0]),I4=o6(b3,c5[0]),P4=t53(n5(a4[0],a4[0]),t53(n5(a4[1],a4[1]),n5(a4[2],a4[2]))),M4=o6(P4,i4[0]),N4=o6(P4,s4[0]),C4=o6(P4,r6[0]),T4=o6(P4,c5[0]),w4=t53(n5(c5[0],c5[0]),t53(n5(c5[1],c5[1]),n5(c5[2],c5[2]))),R3=o6(w4,i4[0]),E3=o6(w4,s4[0]),A4=o6(w4,r6[0]),O3=o6(w4,a4[0]),L3=t53(t53(t53(o6(t53(o6(e6(O3,T4),r6[1]),t53(o6(e6(A4,I4),-a4[1]),o6(e6(C4,S3),c5[1]))),s4[2]),t53(o6(t53(o6(e6(O3,T4),s4[1]),t53(o6(e6(E3,y4),-a4[1]),o6(e6(N4,_4),c5[1]))),-r6[2]),o6(t53(o6(e6(A4,I4),s4[1]),t53(o6(e6(E3,y4),-r6[1]),o6(e6(v4,f3),c5[1]))),a4[2]))),t53(o6(t53(o6(e6(C4,S3),s4[1]),t53(o6(e6(N4,_4),-r6[1]),o6(e6(v4,f3),a4[1]))),-c5[2]),t53(o6(t53(o6(e6(O3,T4),s4[1]),t53(o6(e6(E3,y4),-a4[1]),o6(e6(N4,_4),c5[1]))),i4[2]),o6(t53(o6(e6(O3,T4),i4[1]),t53(o6(e6(R3,p5),-a4[1]),o6(e6(M4,u6),c5[1]))),-s4[2])))),t53(t53(o6(t53(o6(e6(E3,y4),i4[1]),t53(o6(e6(R3,p5),-s4[1]),o6(e6(g6,h7),c5[1]))),a4[2]),t53(o6(t53(o6(e6(N4,_4),i4[1]),t53(o6(e6(M4,u6),-s4[1]),o6(e6(g6,h7),a4[1]))),-c5[2]),o6(t53(o6(e6(C4,S3),s4[1]),t53(o6(e6(N4,_4),-r6[1]),o6(e6(v4,f3),a4[1]))),i4[2]))),t53(o6(t53(o6(e6(C4,S3),i4[1]),t53(o6(e6(M4,u6),-r6[1]),o6(e6(x4,d5),a4[1]))),-s4[2]),t53(o6(t53(o6(e6(N4,_4),i4[1]),t53(o6(e6(M4,u6),-s4[1]),o6(e6(g6,h7),a4[1]))),r6[2]),o6(t53(o6(e6(v4,f3),i4[1]),t53(o6(e6(x4,d5),-s4[1]),o6(e6(g6,h7),r6[1]))),-a4[2]))))),D4=t53(t53(t53(o6(t53(o6(e6(O3,T4),r6[1]),t53(o6(e6(A4,I4),-a4[1]),o6(e6(C4,S3),c5[1]))),i4[2]),o6(t53(o6(e6(O3,T4),i4[1]),t53(o6(e6(R3,p5),-a4[1]),o6(e6(M4,u6),c5[1]))),-r6[2])),t53(o6(t53(o6(e6(A4,I4),i4[1]),t53(o6(e6(R3,p5),-r6[1]),o6(e6(x4,d5),c5[1]))),a4[2]),o6(t53(o6(e6(C4,S3),i4[1]),t53(o6(e6(M4,u6),-r6[1]),o6(e6(x4,d5),a4[1]))),-c5[2]))),t53(t53(o6(t53(o6(e6(A4,I4),s4[1]),t53(o6(e6(E3,y4),-r6[1]),o6(e6(v4,f3),c5[1]))),i4[2]),o6(t53(o6(e6(A4,I4),i4[1]),t53(o6(e6(R3,p5),-r6[1]),o6(e6(x4,d5),c5[1]))),-s4[2])),t53(o6(t53(o6(e6(E3,y4),i4[1]),t53(o6(e6(R3,p5),-s4[1]),o6(e6(g6,h7),c5[1]))),r6[2]),o6(t53(o6(e6(v4,f3),i4[1]),t53(o6(e6(x4,d5),-s4[1]),o6(e6(g6,h7),r6[1]))),-c5[2])))),k4=e6(L3,D4);return k4[k4.length-1]}}function h6(t53,e6,n5,o6){return function(i4,s4,r6,a4,c5,l5){var h7=t53(t53(n5(i4[0],i4[0]),n5(i4[1],i4[1])),t53(n5(i4[2],i4[2]),n5(i4[3],i4[3]))),d5=o6(h7,s4[0]),u6=o6(h7,r6[0]),p5=o6(h7,a4[0]),m4=o6(h7,c5[0]),g6=o6(h7,l5[0]),f3=t53(t53(n5(s4[0],s4[0]),n5(s4[1],s4[1])),t53(n5(s4[2],s4[2]),n5(s4[3],s4[3]))),_4=o6(f3,i4[0]),y4=o6(f3,r6[0]),b3=o6(f3,a4[0]),x4=o6(f3,c5[0]),v4=o6(f3,l5[0]),S3=t53(t53(n5(r6[0],r6[0]),n5(r6[1],r6[1])),t53(n5(r6[2],r6[2]),n5(r6[3],r6[3]))),I4=o6(S3,i4[0]),P4=o6(S3,s4[0]),M4=o6(S3,a4[0]),N4=o6(S3,c5[0]),C4=o6(S3,l5[0]),T4=t53(t53(n5(a4[0],a4[0]),n5(a4[1],a4[1])),t53(n5(a4[2],a4[2]),n5(a4[3],a4[3]))),w4=o6(T4,i4[0]),R3=o6(T4,s4[0]),E3=o6(T4,r6[0]),A4=o6(T4,c5[0]),O3=o6(T4,l5[0]),L3=t53(t53(n5(c5[0],c5[0]),n5(c5[1],c5[1])),t53(n5(c5[2],c5[2]),n5(c5[3],c5[3]))),D4=o6(L3,i4[0]),k4=o6(L3,s4[0]),z4=o6(L3,r6[0]),j4=o6(L3,a4[0]),F4=o6(L3,l5[0]),$5=t53(t53(n5(l5[0],l5[0]),n5(l5[1],l5[1])),t53(n5(l5[2],l5[2]),n5(l5[3],l5[3]))),B4=o6($5,i4[0]),Y4=o6($5,s4[0]),X4=o6($5,r6[0]),H4=o6($5,a4[0]),W5=o6($5,c5[0]),V4=t53(t53(t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),a4[1]),t53(o6(e6(H4,O3),-c5[1]),o6(e6(j4,A4),l5[1]))),r6[2]),o6(t53(o6(e6(W5,F4),r6[1]),t53(o6(e6(X4,C4),-c5[1]),o6(e6(z4,N4),l5[1]))),-a4[2])),t53(o6(t53(o6(e6(H4,O3),r6[1]),t53(o6(e6(X4,C4),-a4[1]),o6(e6(E3,M4),l5[1]))),c5[2]),o6(t53(o6(e6(j4,A4),r6[1]),t53(o6(e6(z4,N4),-a4[1]),o6(e6(E3,M4),c5[1]))),-l5[2]))),s4[3]),t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),a4[1]),t53(o6(e6(H4,O3),-c5[1]),o6(e6(j4,A4),l5[1]))),s4[2]),o6(t53(o6(e6(W5,F4),s4[1]),t53(o6(e6(Y4,v4),-c5[1]),o6(e6(k4,x4),l5[1]))),-a4[2])),t53(o6(t53(o6(e6(H4,O3),s4[1]),t53(o6(e6(Y4,v4),-a4[1]),o6(e6(R3,b3),l5[1]))),c5[2]),o6(t53(o6(e6(j4,A4),s4[1]),t53(o6(e6(k4,x4),-a4[1]),o6(e6(R3,b3),c5[1]))),-l5[2]))),-r6[3]),o6(t53(t53(o6(t53(o6(e6(W5,F4),r6[1]),t53(o6(e6(X4,C4),-c5[1]),o6(e6(z4,N4),l5[1]))),s4[2]),o6(t53(o6(e6(W5,F4),s4[1]),t53(o6(e6(Y4,v4),-c5[1]),o6(e6(k4,x4),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),s4[1]),t53(o6(e6(Y4,v4),-r6[1]),o6(e6(P4,y4),l5[1]))),c5[2]),o6(t53(o6(e6(z4,N4),s4[1]),t53(o6(e6(k4,x4),-r6[1]),o6(e6(P4,y4),c5[1]))),-l5[2]))),a4[3]))),t53(t53(o6(t53(t53(o6(t53(o6(e6(H4,O3),r6[1]),t53(o6(e6(X4,C4),-a4[1]),o6(e6(E3,M4),l5[1]))),s4[2]),o6(t53(o6(e6(H4,O3),s4[1]),t53(o6(e6(Y4,v4),-a4[1]),o6(e6(R3,b3),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),s4[1]),t53(o6(e6(Y4,v4),-r6[1]),o6(e6(P4,y4),l5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),s4[1]),t53(o6(e6(R3,b3),-r6[1]),o6(e6(P4,y4),a4[1]))),-l5[2]))),-c5[3]),o6(t53(t53(o6(t53(o6(e6(j4,A4),r6[1]),t53(o6(e6(z4,N4),-a4[1]),o6(e6(E3,M4),c5[1]))),s4[2]),o6(t53(o6(e6(j4,A4),s4[1]),t53(o6(e6(k4,x4),-a4[1]),o6(e6(R3,b3),c5[1]))),-r6[2])),t53(o6(t53(o6(e6(z4,N4),s4[1]),t53(o6(e6(k4,x4),-r6[1]),o6(e6(P4,y4),c5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),s4[1]),t53(o6(e6(R3,b3),-r6[1]),o6(e6(P4,y4),a4[1]))),-c5[2]))),l5[3])),t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),a4[1]),t53(o6(e6(H4,O3),-c5[1]),o6(e6(j4,A4),l5[1]))),s4[2]),o6(t53(o6(e6(W5,F4),s4[1]),t53(o6(e6(Y4,v4),-c5[1]),o6(e6(k4,x4),l5[1]))),-a4[2])),t53(o6(t53(o6(e6(H4,O3),s4[1]),t53(o6(e6(Y4,v4),-a4[1]),o6(e6(R3,b3),l5[1]))),c5[2]),o6(t53(o6(e6(j4,A4),s4[1]),t53(o6(e6(k4,x4),-a4[1]),o6(e6(R3,b3),c5[1]))),-l5[2]))),i4[3]),o6(t53(t53(o6(t53(o6(e6(W5,F4),a4[1]),t53(o6(e6(H4,O3),-c5[1]),o6(e6(j4,A4),l5[1]))),i4[2]),o6(t53(o6(e6(W5,F4),i4[1]),t53(o6(e6(B4,g6),-c5[1]),o6(e6(D4,m4),l5[1]))),-a4[2])),t53(o6(t53(o6(e6(H4,O3),i4[1]),t53(o6(e6(B4,g6),-a4[1]),o6(e6(w4,p5),l5[1]))),c5[2]),o6(t53(o6(e6(j4,A4),i4[1]),t53(o6(e6(D4,m4),-a4[1]),o6(e6(w4,p5),c5[1]))),-l5[2]))),-s4[3])))),t53(t53(t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),s4[1]),t53(o6(e6(Y4,v4),-c5[1]),o6(e6(k4,x4),l5[1]))),i4[2]),o6(t53(o6(e6(W5,F4),i4[1]),t53(o6(e6(B4,g6),-c5[1]),o6(e6(D4,m4),l5[1]))),-s4[2])),t53(o6(t53(o6(e6(Y4,v4),i4[1]),t53(o6(e6(B4,g6),-s4[1]),o6(e6(_4,d5),l5[1]))),c5[2]),o6(t53(o6(e6(k4,x4),i4[1]),t53(o6(e6(D4,m4),-s4[1]),o6(e6(_4,d5),c5[1]))),-l5[2]))),a4[3]),o6(t53(t53(o6(t53(o6(e6(H4,O3),s4[1]),t53(o6(e6(Y4,v4),-a4[1]),o6(e6(R3,b3),l5[1]))),i4[2]),o6(t53(o6(e6(H4,O3),i4[1]),t53(o6(e6(B4,g6),-a4[1]),o6(e6(w4,p5),l5[1]))),-s4[2])),t53(o6(t53(o6(e6(Y4,v4),i4[1]),t53(o6(e6(B4,g6),-s4[1]),o6(e6(_4,d5),l5[1]))),a4[2]),o6(t53(o6(e6(R3,b3),i4[1]),t53(o6(e6(w4,p5),-s4[1]),o6(e6(_4,d5),a4[1]))),-l5[2]))),-c5[3])),t53(o6(t53(t53(o6(t53(o6(e6(j4,A4),s4[1]),t53(o6(e6(k4,x4),-a4[1]),o6(e6(R3,b3),c5[1]))),i4[2]),o6(t53(o6(e6(j4,A4),i4[1]),t53(o6(e6(D4,m4),-a4[1]),o6(e6(w4,p5),c5[1]))),-s4[2])),t53(o6(t53(o6(e6(k4,x4),i4[1]),t53(o6(e6(D4,m4),-s4[1]),o6(e6(_4,d5),c5[1]))),a4[2]),o6(t53(o6(e6(R3,b3),i4[1]),t53(o6(e6(w4,p5),-s4[1]),o6(e6(_4,d5),a4[1]))),-c5[2]))),l5[3]),o6(t53(t53(o6(t53(o6(e6(H4,O3),r6[1]),t53(o6(e6(X4,C4),-a4[1]),o6(e6(E3,M4),l5[1]))),s4[2]),o6(t53(o6(e6(H4,O3),s4[1]),t53(o6(e6(Y4,v4),-a4[1]),o6(e6(R3,b3),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),s4[1]),t53(o6(e6(Y4,v4),-r6[1]),o6(e6(P4,y4),l5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),s4[1]),t53(o6(e6(R3,b3),-r6[1]),o6(e6(P4,y4),a4[1]))),-l5[2]))),i4[3]))),t53(t53(o6(t53(t53(o6(t53(o6(e6(H4,O3),r6[1]),t53(o6(e6(X4,C4),-a4[1]),o6(e6(E3,M4),l5[1]))),i4[2]),o6(t53(o6(e6(H4,O3),i4[1]),t53(o6(e6(B4,g6),-a4[1]),o6(e6(w4,p5),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),i4[1]),t53(o6(e6(B4,g6),-r6[1]),o6(e6(I4,u6),l5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),i4[1]),t53(o6(e6(w4,p5),-r6[1]),o6(e6(I4,u6),a4[1]))),-l5[2]))),-s4[3]),o6(t53(t53(o6(t53(o6(e6(H4,O3),s4[1]),t53(o6(e6(Y4,v4),-a4[1]),o6(e6(R3,b3),l5[1]))),i4[2]),o6(t53(o6(e6(H4,O3),i4[1]),t53(o6(e6(B4,g6),-a4[1]),o6(e6(w4,p5),l5[1]))),-s4[2])),t53(o6(t53(o6(e6(Y4,v4),i4[1]),t53(o6(e6(B4,g6),-s4[1]),o6(e6(_4,d5),l5[1]))),a4[2]),o6(t53(o6(e6(R3,b3),i4[1]),t53(o6(e6(w4,p5),-s4[1]),o6(e6(_4,d5),a4[1]))),-l5[2]))),r6[3])),t53(o6(t53(t53(o6(t53(o6(e6(X4,C4),s4[1]),t53(o6(e6(Y4,v4),-r6[1]),o6(e6(P4,y4),l5[1]))),i4[2]),o6(t53(o6(e6(X4,C4),i4[1]),t53(o6(e6(B4,g6),-r6[1]),o6(e6(I4,u6),l5[1]))),-s4[2])),t53(o6(t53(o6(e6(Y4,v4),i4[1]),t53(o6(e6(B4,g6),-s4[1]),o6(e6(_4,d5),l5[1]))),r6[2]),o6(t53(o6(e6(P4,y4),i4[1]),t53(o6(e6(I4,u6),-s4[1]),o6(e6(_4,d5),r6[1]))),-l5[2]))),-a4[3]),o6(t53(t53(o6(t53(o6(e6(E3,M4),s4[1]),t53(o6(e6(R3,b3),-r6[1]),o6(e6(P4,y4),a4[1]))),i4[2]),o6(t53(o6(e6(E3,M4),i4[1]),t53(o6(e6(w4,p5),-r6[1]),o6(e6(I4,u6),a4[1]))),-s4[2])),t53(o6(t53(o6(e6(R3,b3),i4[1]),t53(o6(e6(w4,p5),-s4[1]),o6(e6(_4,d5),a4[1]))),r6[2]),o6(t53(o6(e6(P4,y4),i4[1]),t53(o6(e6(I4,u6),-s4[1]),o6(e6(_4,d5),r6[1]))),-a4[2]))),l5[3]))))),U3=t53(t53(t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),a4[1]),t53(o6(e6(H4,O3),-c5[1]),o6(e6(j4,A4),l5[1]))),r6[2]),o6(t53(o6(e6(W5,F4),r6[1]),t53(o6(e6(X4,C4),-c5[1]),o6(e6(z4,N4),l5[1]))),-a4[2])),t53(o6(t53(o6(e6(H4,O3),r6[1]),t53(o6(e6(X4,C4),-a4[1]),o6(e6(E3,M4),l5[1]))),c5[2]),o6(t53(o6(e6(j4,A4),r6[1]),t53(o6(e6(z4,N4),-a4[1]),o6(e6(E3,M4),c5[1]))),-l5[2]))),i4[3]),t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),a4[1]),t53(o6(e6(H4,O3),-c5[1]),o6(e6(j4,A4),l5[1]))),i4[2]),o6(t53(o6(e6(W5,F4),i4[1]),t53(o6(e6(B4,g6),-c5[1]),o6(e6(D4,m4),l5[1]))),-a4[2])),t53(o6(t53(o6(e6(H4,O3),i4[1]),t53(o6(e6(B4,g6),-a4[1]),o6(e6(w4,p5),l5[1]))),c5[2]),o6(t53(o6(e6(j4,A4),i4[1]),t53(o6(e6(D4,m4),-a4[1]),o6(e6(w4,p5),c5[1]))),-l5[2]))),-r6[3]),o6(t53(t53(o6(t53(o6(e6(W5,F4),r6[1]),t53(o6(e6(X4,C4),-c5[1]),o6(e6(z4,N4),l5[1]))),i4[2]),o6(t53(o6(e6(W5,F4),i4[1]),t53(o6(e6(B4,g6),-c5[1]),o6(e6(D4,m4),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),i4[1]),t53(o6(e6(B4,g6),-r6[1]),o6(e6(I4,u6),l5[1]))),c5[2]),o6(t53(o6(e6(z4,N4),i4[1]),t53(o6(e6(D4,m4),-r6[1]),o6(e6(I4,u6),c5[1]))),-l5[2]))),a4[3]))),t53(t53(o6(t53(t53(o6(t53(o6(e6(H4,O3),r6[1]),t53(o6(e6(X4,C4),-a4[1]),o6(e6(E3,M4),l5[1]))),i4[2]),o6(t53(o6(e6(H4,O3),i4[1]),t53(o6(e6(B4,g6),-a4[1]),o6(e6(w4,p5),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),i4[1]),t53(o6(e6(B4,g6),-r6[1]),o6(e6(I4,u6),l5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),i4[1]),t53(o6(e6(w4,p5),-r6[1]),o6(e6(I4,u6),a4[1]))),-l5[2]))),-c5[3]),o6(t53(t53(o6(t53(o6(e6(j4,A4),r6[1]),t53(o6(e6(z4,N4),-a4[1]),o6(e6(E3,M4),c5[1]))),i4[2]),o6(t53(o6(e6(j4,A4),i4[1]),t53(o6(e6(D4,m4),-a4[1]),o6(e6(w4,p5),c5[1]))),-r6[2])),t53(o6(t53(o6(e6(z4,N4),i4[1]),t53(o6(e6(D4,m4),-r6[1]),o6(e6(I4,u6),c5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),i4[1]),t53(o6(e6(w4,p5),-r6[1]),o6(e6(I4,u6),a4[1]))),-c5[2]))),l5[3])),t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),r6[1]),t53(o6(e6(X4,C4),-c5[1]),o6(e6(z4,N4),l5[1]))),s4[2]),o6(t53(o6(e6(W5,F4),s4[1]),t53(o6(e6(Y4,v4),-c5[1]),o6(e6(k4,x4),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),s4[1]),t53(o6(e6(Y4,v4),-r6[1]),o6(e6(P4,y4),l5[1]))),c5[2]),o6(t53(o6(e6(z4,N4),s4[1]),t53(o6(e6(k4,x4),-r6[1]),o6(e6(P4,y4),c5[1]))),-l5[2]))),i4[3]),o6(t53(t53(o6(t53(o6(e6(W5,F4),r6[1]),t53(o6(e6(X4,C4),-c5[1]),o6(e6(z4,N4),l5[1]))),i4[2]),o6(t53(o6(e6(W5,F4),i4[1]),t53(o6(e6(B4,g6),-c5[1]),o6(e6(D4,m4),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),i4[1]),t53(o6(e6(B4,g6),-r6[1]),o6(e6(I4,u6),l5[1]))),c5[2]),o6(t53(o6(e6(z4,N4),i4[1]),t53(o6(e6(D4,m4),-r6[1]),o6(e6(I4,u6),c5[1]))),-l5[2]))),-s4[3])))),t53(t53(t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),s4[1]),t53(o6(e6(Y4,v4),-c5[1]),o6(e6(k4,x4),l5[1]))),i4[2]),o6(t53(o6(e6(W5,F4),i4[1]),t53(o6(e6(B4,g6),-c5[1]),o6(e6(D4,m4),l5[1]))),-s4[2])),t53(o6(t53(o6(e6(Y4,v4),i4[1]),t53(o6(e6(B4,g6),-s4[1]),o6(e6(_4,d5),l5[1]))),c5[2]),o6(t53(o6(e6(k4,x4),i4[1]),t53(o6(e6(D4,m4),-s4[1]),o6(e6(_4,d5),c5[1]))),-l5[2]))),r6[3]),o6(t53(t53(o6(t53(o6(e6(X4,C4),s4[1]),t53(o6(e6(Y4,v4),-r6[1]),o6(e6(P4,y4),l5[1]))),i4[2]),o6(t53(o6(e6(X4,C4),i4[1]),t53(o6(e6(B4,g6),-r6[1]),o6(e6(I4,u6),l5[1]))),-s4[2])),t53(o6(t53(o6(e6(Y4,v4),i4[1]),t53(o6(e6(B4,g6),-s4[1]),o6(e6(_4,d5),l5[1]))),r6[2]),o6(t53(o6(e6(P4,y4),i4[1]),t53(o6(e6(I4,u6),-s4[1]),o6(e6(_4,d5),r6[1]))),-l5[2]))),-c5[3])),t53(o6(t53(t53(o6(t53(o6(e6(z4,N4),s4[1]),t53(o6(e6(k4,x4),-r6[1]),o6(e6(P4,y4),c5[1]))),i4[2]),o6(t53(o6(e6(z4,N4),i4[1]),t53(o6(e6(D4,m4),-r6[1]),o6(e6(I4,u6),c5[1]))),-s4[2])),t53(o6(t53(o6(e6(k4,x4),i4[1]),t53(o6(e6(D4,m4),-s4[1]),o6(e6(_4,d5),c5[1]))),r6[2]),o6(t53(o6(e6(P4,y4),i4[1]),t53(o6(e6(I4,u6),-s4[1]),o6(e6(_4,d5),r6[1]))),-c5[2]))),l5[3]),o6(t53(t53(o6(t53(o6(e6(j4,A4),r6[1]),t53(o6(e6(z4,N4),-a4[1]),o6(e6(E3,M4),c5[1]))),s4[2]),o6(t53(o6(e6(j4,A4),s4[1]),t53(o6(e6(k4,x4),-a4[1]),o6(e6(R3,b3),c5[1]))),-r6[2])),t53(o6(t53(o6(e6(z4,N4),s4[1]),t53(o6(e6(k4,x4),-r6[1]),o6(e6(P4,y4),c5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),s4[1]),t53(o6(e6(R3,b3),-r6[1]),o6(e6(P4,y4),a4[1]))),-c5[2]))),i4[3]))),t53(t53(o6(t53(t53(o6(t53(o6(e6(j4,A4),r6[1]),t53(o6(e6(z4,N4),-a4[1]),o6(e6(E3,M4),c5[1]))),i4[2]),o6(t53(o6(e6(j4,A4),i4[1]),t53(o6(e6(D4,m4),-a4[1]),o6(e6(w4,p5),c5[1]))),-r6[2])),t53(o6(t53(o6(e6(z4,N4),i4[1]),t53(o6(e6(D4,m4),-r6[1]),o6(e6(I4,u6),c5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),i4[1]),t53(o6(e6(w4,p5),-r6[1]),o6(e6(I4,u6),a4[1]))),-c5[2]))),-s4[3]),o6(t53(t53(o6(t53(o6(e6(j4,A4),s4[1]),t53(o6(e6(k4,x4),-a4[1]),o6(e6(R3,b3),c5[1]))),i4[2]),o6(t53(o6(e6(j4,A4),i4[1]),t53(o6(e6(D4,m4),-a4[1]),o6(e6(w4,p5),c5[1]))),-s4[2])),t53(o6(t53(o6(e6(k4,x4),i4[1]),t53(o6(e6(D4,m4),-s4[1]),o6(e6(_4,d5),c5[1]))),a4[2]),o6(t53(o6(e6(R3,b3),i4[1]),t53(o6(e6(w4,p5),-s4[1]),o6(e6(_4,d5),a4[1]))),-c5[2]))),r6[3])),t53(o6(t53(t53(o6(t53(o6(e6(z4,N4),s4[1]),t53(o6(e6(k4,x4),-r6[1]),o6(e6(P4,y4),c5[1]))),i4[2]),o6(t53(o6(e6(z4,N4),i4[1]),t53(o6(e6(D4,m4),-r6[1]),o6(e6(I4,u6),c5[1]))),-s4[2])),t53(o6(t53(o6(e6(k4,x4),i4[1]),t53(o6(e6(D4,m4),-s4[1]),o6(e6(_4,d5),c5[1]))),r6[2]),o6(t53(o6(e6(P4,y4),i4[1]),t53(o6(e6(I4,u6),-s4[1]),o6(e6(_4,d5),r6[1]))),-c5[2]))),-a4[3]),o6(t53(t53(o6(t53(o6(e6(E3,M4),s4[1]),t53(o6(e6(R3,b3),-r6[1]),o6(e6(P4,y4),a4[1]))),i4[2]),o6(t53(o6(e6(E3,M4),i4[1]),t53(o6(e6(w4,p5),-r6[1]),o6(e6(I4,u6),a4[1]))),-s4[2])),t53(o6(t53(o6(e6(R3,b3),i4[1]),t53(o6(e6(w4,p5),-s4[1]),o6(e6(_4,d5),a4[1]))),r6[2]),o6(t53(o6(e6(P4,y4),i4[1]),t53(o6(e6(I4,u6),-s4[1]),o6(e6(_4,d5),r6[1]))),-a4[2]))),c5[3]))))),Z3=e6(V4,U3);return Z3[Z3.length-1]}}var d4=[function(){return 0},function(){return 0},function(){return 0}];function u5(t53){var e6=d4[t53.length];return e6||(e6=d4[t53.length]=r5(t53.length)),e6.apply(void 0,t53)}function p4(t53,e6,n5,o6,i4,s4,r6,a4){return function(e7,n6,c5,l5,h7,d5){switch(arguments.length){case 0:case 1:return 0;case 2:return o6(e7,n6);case 3:return i4(e7,n6,c5);case 4:return s4(e7,n6,c5,l5);case 5:return r6(e7,n6,c5,l5,h7);case 6:return a4(e7,n6,c5,l5,h7,d5)}for(var u6=new Array(arguments.length),p5=0;p5<arguments.length;++p5)u6[p5]=arguments[p5];return t53(u6)}}(function(){for(;d4.length<=6;)d4.push(r5(d4.length));e5.exports=p4.apply(void 0,[u5].concat(d4));for(var t53=0;t53<=6;++t53)e5.exports[t53]=d4[t53]})()}}),C3=r4({"node_modules/cdt2d/lib/delaunay.js"(t52,e5){var n4=N3()[4];_3();function o4(t53,e6,o6,i3,s3,r5){var a3=e6.opposite(i3,s3);if(!(a3<0)){if(s3<i3){var c4=i3;i3=s3,s3=c4,c4=r5,r5=a3,a3=c4}e6.isConstraint(i3,s3)||n4(t53[i3],t53[s3],t53[r5],t53[a3])<0&&o6.push(i3,s3)}}e5.exports=function(t53,e6){for(var i3=[],s3=t53.length,r5=e6.stars,a3=0;a3<s3;++a3)for(var c4=r5[a3],l4=1;l4<c4.length;l4+=2)if(!((p4=c4[l4])<a3)&&!e6.isConstraint(a3,p4)){for(var h6=c4[l4-1],d4=-1,u5=1;u5<c4.length;u5+=2)if(c4[u5-1]===p4){d4=c4[u5];break}d4<0||n4(t53[a3],t53[p4],t53[h6],t53[d4])<0&&i3.push(a3,p4)}for(;i3.length>0;){for(var p4=i3.pop(),m4=(h6=-1,d4=-1,c4=r5[a3=i3.pop()],1);m4<c4.length;m4+=2){var g6=c4[m4-1],f3=c4[m4];g6===p4?d4=f3:f3===p4&&(h6=g6)}h6<0||d4<0||n4(t53[a3],t53[p4],t53[h6],t53[d4])>=0||(e6.flip(a3,p4),o4(t53,e6,i3,h6,a3,d4),o4(t53,e6,i3,a3,d4,h6),o4(t53,e6,i3,d4,p4,h6),o4(t53,e6,i3,p4,h6,d4))}}}}),T3=r4({"node_modules/cdt2d/lib/filter.js"(t52,e5){var n4=_3();function o4(t53,e6,n5,o6,i4,s3,r5){this.cells=t53,this.neighbor=e6,this.flags=o6,this.constraint=n5,this.active=i4,this.next=s3,this.boundary=r5}function i3(t53,e6){return t53[0]-e6[0]||t53[1]-e6[1]||t53[2]-e6[2]}e5.exports=function(t53,e6,n5){var s3=(function(t54,e7){for(var n6=t54.cells(),s4=n6.length,r6=0;r6<s4;++r6){var a4=(_5=n6[r6])[0],c5=_5[1],l5=_5[2];c5<l5?c5<a4&&(_5[0]=c5,_5[1]=l5,_5[2]=a4):l5<a4&&(_5[0]=l5,_5[1]=a4,_5[2]=c5)}n6.sort(i3);var h7=new Array(s4);for(r6=0;r6<h7.length;++r6)h7[r6]=0;var d5=[],u6=[],p5=new Array(3*s4),m6=new Array(3*s4),g7=null;e7&&(g7=[]);var f4=new o4(n6,p5,m6,h7,d5,u6,g7);for(r6=0;r6<s4;++r6)for(var _5=n6[r6],y4=0;y4<3;++y4){a4=_5[y4],c5=_5[(y4+1)%3];var b3=p5[3*r6+y4]=f4.locate(c5,a4,t54.opposite(c5,a4)),x4=m6[3*r6+y4]=t54.isConstraint(a4,c5);b3<0&&(x4?u6.push(r6):(d5.push(r6),h7[r6]=1),e7&&g7.push([c5,a4,-1]))}return f4})(t53,n5);if(e6===0)return n5?s3.cells.concat(s3.boundary):s3.cells;for(var r5=1,a3=s3.active,c4=s3.next,l4=s3.flags,h6=s3.cells,d4=s3.constraint,u5=s3.neighbor;a3.length>0||c4.length>0;){for(;a3.length>0;){var p4=a3.pop();if(l4[p4]!==-r5){l4[p4]=r5,h6[p4];for(var m4=0;m4<3;++m4){var g6=u5[3*p4+m4];g6>=0&&l4[g6]===0&&(d4[3*p4+m4]?c4.push(g6):(a3.push(g6),l4[g6]=r5))}}}var f3=c4;c4=a3,a3=f3,c4.length=0,r5=-r5}var _4=(function(t54,e7,n6){for(var o6=0,i4=0;i4<t54.length;++i4)e7[i4]===n6&&(t54[o6++]=t54[i4]);return t54.length=o6,t54})(h6,l4,e6);return n5?_4.concat(s3.boundary):_4},o4.prototype.locate=(function(){var t53=[0,0,0];return function(e6,o6,s3){var r5=e6,a3=o6,c4=s3;return o6<s3?o6<e6&&(r5=o6,a3=s3,c4=e6):s3<e6&&(r5=s3,a3=e6,c4=o6),r5<0?-1:(t53[0]=r5,t53[1]=a3,t53[2]=c4,n4.eq(this.cells,t53,i3))}})()}}),w3=r4({"node_modules/cdt2d/cdt2d.js"(t52,e5){var n4=P2(),o4=M3(),i3=C3(),s3=T3();function r5(t53){return[Math.min(t53[0],t53[1]),Math.max(t53[0],t53[1])]}function a3(t53,e6){return t53[0]-e6[0]||t53[1]-e6[1]}function c4(t53,e6,n5){return e6 in t53?t53[e6]:n5}e5.exports=function(t53,e6,l4){Array.isArray(e6)?(l4=l4||{},e6=e6||[]):(l4=e6||{},e6=[]);var h6=!!c4(l4,"delaunay",!0),d4=!!c4(l4,"interior",!0),u5=!!c4(l4,"exterior",!0),p4=!!c4(l4,"infinity",!1);if(!d4&&!u5||t53.length===0)return[];var m4=n4(t53,e6);if(h6||d4!==u5||p4){for(var g6=o4(t53.length,(function(t54){return t54.map(r5).sort(a3)})(e6)),f3=0;f3<m4.length;++f3){var _4=m4[f3];g6.addTriangle(_4[0],_4[1],_4[2])}return h6&&i3(t53,g6),u5?d4?p4?s3(g6,0,p4):g6.cells():s3(g6,1,p4):s3(g6,-1)}return m4}}}),R2={0:"M0.301025 0.257813 L0.206593 0.283385 L0.122042 0.361307 L0.075923 0.474441 L0.064942 0.642221 L0.091296 0.78289 L0.159376 0.899463 L0.257104 0.961214 L0.344948 0.961214 L0.442678 0.899463 L0.510757 0.78289 L0.537111 0.642221 L0.526131 0.474441 L0.480012 0.361307 L0.39546 0.283385 L0.301025 0.257813",1:"M0.220426 0.40845 L0.381626 0.270996 L0.381626 0.948966",2:"M0.110409 0.39212 L0.125621 0.342293 L0.170571 0.295823 L0.244237 0.26431 L0.291518 0.257813 L0.373319 0.263799 L0.434683 0.290705 L0.468239 0.331966 L0.480292 0.379913 L0.479492 0.411806 L0.465088 0.465192 L0.402571 0.568988 L0.245134 0.766438 L0.07959 0.948045 L0.522462 0.948045",3:"M0.081606 0.345073 L0.119154 0.315633 L0.178996 0.284091 L0.255265 0.257813 L0.349133 0.263062 L0.43127 0.289348 L0.48994 0.336662 L0.525141 0.394491 L0.513407 0.457577 L0.466472 0.504892 L0.384334 0.541692 L0.290464 0.56272 L0.20833 0.573235 L0.290464 0.583749 L0.384334 0.610035 L0.466472 0.652092 L0.519274 0.709922 L0.531007 0.773007 L0.50754 0.841351 L0.454738 0.899179 L0.3726 0.946494 L0.310412 0.961214 L0.209503 0.959111 L0.127367 0.946494 L0.071046 0.929671",4:"M0.418494 0.270996 L0.048828 0.724199 L0.553224 0.724199 M0.414181 0.578167 L0.414181 0.94897",5:"M0.074951 0.270996 L0.074951 0.614701 L0.267655 0.5695 L0.405247 0.586502 L0.460002 0.617189 L0.498028 0.660731 L0.527101 0.779401 L0.513352 0.841049 L0.477274 0.889568 L0.406378 0.93463 L0.324445 0.958337 L0.247399 0.962139 L0.182516 0.949767 L0.130068 0.925508 L0.074951 0.875607 M0.074951 0.270996 L0.527101 0.270996",6:"M0.428549 0.257813 L0.341433 0.285053 L0.26073 0.312099 L0.192188 0.360182 L0.138902 0.410969 L0.098219 0.500422 L0.070249 0.584267 L0.067264 0.670716 L0.065164 0.756863 L0.087163 0.820973 L0.108168 0.861042 L0.157916 0.913131 L0.210981 0.948192 L0.29279 0.961214 L0.384548 0.956206 L0.456409 0.924151 L0.507262 0.881077 L0.5349 0.821975 L0.537111 0.771889 L0.521634 0.718798 L0.498418 0.67372 L0.463042 0.636657 L0.414398 0.613617 L0.34696 0.598591 L0.28284 0.595587 L0.215403 0.605604 L0.145756 0.641665 L0.109274 0.678729 L0.064942 0.724006",7:"M0.071534 0.270996 L0.530519 0.270996 L0.495935 0.291702 L0.477752 0.305407 L0.435186 0.346112 L0.412067 0.374136 L0.388565 0.40796 L0.365315 0.448098 L0.342943 0.495062 L0.322081 0.549366 L0.303364 0.611524 L0.287416 0.68205 L0.270077 0.80465 L0.26253 0.94897",8:"M0.286761 0.257813 L0.210684 0.27162 L0.1414 0.305622 L0.092494 0.382125 L0.111513 0.450128 L0.16857 0.502193 L0.228345 0.539382 L0.377781 0.594635 L0.470161 0.645637 L0.52586 0.706203 L0.538087 0.792269 L0.506841 0.87621 L0.438915 0.927212 L0.339743 0.961214 L0.263666 0.959089 L0.174004 0.929337 L0.102003 0.881523 L0.063965 0.811395 L0.066682 0.741266 L0.102003 0.671139 L0.180797 0.608448 L0.259591 0.580822 L0.358762 0.548945 L0.456576 0.49688 L0.486463 0.446941 L0.487822 0.362999 L0.453859 0.302434 L0.384574 0.265245 L0.286761 0.257813",9:"M0.511026 0.437812 L0.491026 0.347812 L0.451026 0.297812 L0.391026 0.267812 L0.311026 0.257813 L0.231026 0.267812 L0.161026 0.297812 L0.111026 0.347812 L0.091026 0.417812 L0.111026 0.487812 L0.161026 0.537812 L0.231026 0.567812 L0.311026 0.577812 L0.391026 0.557812 L0.451026 0.517812 L0.491026 0.477812 L0.511026 0.437812 M0.510026 0.438812 L0.434026 0.636812 L0.381026 0.777812 L0.337026 0.879812 L0.301026 0.957812","!":"M0.301026 0.270996 L0.301026 0.749566 M0.251466 0.94897 L0.350587 0.94897",'"':"M0.16504 0.270996 L0.16504 0.523022 M0.437013 0.270996 L0.437013 0.523022","#":"M0.20958 0.282227 L0.146515 0.949754 M0.461844 0.282227 L0.398779 0.949754 M0.032999 0.526969 L0.600587 0.452796 M0.001465 0.82366 L0.569055 0.749486",$:"M0.307121 0.240234 L0.307121 1.083502 M0.490031 0.415915 L0.404676 0.328075 L0.23396 0.310507 L0.136407 0.398347 L0.099828 0.521324 L0.124213 0.591596 L0.197379 0.644299 L0.429061 0.697003 L0.502224 0.749708 L0.526613 0.837547 L0.477836 0.960526 L0.355897 1.013228 L0.197379 0.99566 L0.112021 0.942957 L0.07544 0.837547","'":"M0.301026 0.270996 L0.301026 0.523022","(":"M0.413087 0.241211 L0.372337 0.28347 L0.331589 0.334184 L0.290838 0.393349 L0.25009 0.460965 L0.219528 0.528584 L0.199153 0.5962 L0.188966 0.655364 L0.199153 0.714529 L0.219528 0.782146 L0.25009 0.849764 L0.290838 0.91738 L0.331589 0.976544 L0.372337 1.027258 L0.413087 1.069491",")":"M0.188966 0.241211 L0.229716 0.28347 L0.270466 0.334184 L0.311213 0.393349 L0.351964 0.460965 L0.382526 0.528584 L0.4029 0.5962 L0.413087 0.655364 L0.4029 0.714529 L0.382526 0.782146 L0.351964 0.849764 L0.311213 0.91738 L0.270466 0.976544 L0.229716 1.027258 L0.188966 1.069491","*":"M0.301026 0.458702 L0.301026 0.681942 M0.301026 0.458702 L0.520997 0.536834 M0.301026 0.458702 L0.439954 0.257813 M0.301026 0.458702 L0.162098 0.257813 M0.301026 0.458702 L0.081055 0.536834","+":"M0.042969 0.66845 L0.559083 0.66845 M0.301023 0.428223 L0.301023 0.908661",",":"M0.38672 0.852051 L0.215333 1.030661 L0.301025 1.119971","-":"M0.173829 0.686035 L0.428224 0.686035",".":"M0.362549 0.851074 L0.239503 0.851074","/":"M0.062501 1.035249 L0.539551 0.270996","<":"M0.559083 0.441895 L0.042969 0.66939 L0.042969 0.66939 L0.559083 0.896902","=":"M0.042969 0.545898 L0.559083 0.545898 M0.042969 0.80837 L0.559083 0.80837",">":"M0.042969 0.441895 L0.559083 0.66939 L0.559083 0.66939 L0.042969 0.896902",A:"M0.018067 0.94897 L0.290179 0.270996 L0.583986 0.94897 M0.155303 0.684521 L0.433548 0.684521",B:"M0.063965 0.94897 L0.063965 0.278953 L0.209356 0.270996 L0.342486 0.294394 L0.432179 0.37292 L0.418224 0.48773 L0.312686 0.549166 L0.084728 0.575531 L0.306377 0.589434 L0.468877 0.647456 L0.538087 0.736658 L0.5324 0.85202 L0.501247 0.902983 L0.42355 0.944398 L0.063965 0.94897",C:"M0.529054 0.419847 L0.498425 0.345196 L0.442238 0.292341 L0.33583 0.257813 L0.257199 0.268357 L0.187906 0.303748 L0.120243 0.385432 L0.072998 0.599844 L0.110073 0.815385 L0.165381 0.902183 L0.222883 0.942801 L0.334904 0.961214 L0.43253 0.937679 L0.504816 0.868999 L0.529054 0.772065",D:"M0.064454 0.94897 L0.071838 0.285078 L0.171217 0.270996 L0.247348 0.272633 L0.37101 0.306078 L0.462461 0.378304 L0.514748 0.475555 L0.535591 0.576392 L0.537599 0.652313 L0.528065 0.717381 L0.508562 0.772419 L0.445948 0.855695 L0.362356 0.90871 L0.225203 0.945862 L0.064454 0.94897",E:"M0.080078 0.270996 L0.080078 0.94897 M0.080078 0.270996 L0.521974 0.270996 M0.080078 0.609981 L0.389405 0.609981 M0.080078 0.94897 L0.521974 0.94897",F:"M0.086426 0.270996 L0.086426 0.94897 M0.091304 0.275607 L0.515626 0.275607 M0.091304 0.607677 L0.447344 0.607677",G:"M0.498034 0.284943 L0.374621 0.257813 L0.244219 0.268648 L0.160577 0.311997 L0.094556 0.398116 L0.056397 0.58404 L0.076752 0.785532 L0.120865 0.858197 L0.188947 0.916734 L0.271008 0.953591 L0.357069 0.961214 L0.43715 0.932047 L0.501262 0.858539 L0.545656 0.648611 L0.329595 0.648131",H:"M0.066895 0.270996 L0.066895 0.94897 M0.066895 0.595658 L0.530009 0.595658 M0.535157 0.270996 L0.535157 0.94897",I:"M0.301026 0.270996 L0.301026 0.94897",J:"M0.506839 0.270996 L0.507814 0.782193 L0.498468 0.846168 L0.480733 0.880789 L0.455864 0.90832 L0.426095 0.929408 L0.360746 0.954812 L0.302508 0.962139 L0.223573 0.953638 L0.16538 0.930312 L0.137072 0.907715 L0.116428 0.880312 L0.102822 0.848819 L0.095633 0.813947 L0.094239 0.776413",K:"M0.035401 0.270996 L0.035401 0.94897 M0.502258 0.316194 L0.035401 0.687823 M0.212484 0.582361 L0.566652 0.933903",L:"M0.07544 0.270996 L0.07544 0.94897 L0.526613 0.94897",M:"M0.042481 0.94897 L0.042481 0.270996 L0.301027 0.712492 L0.559571 0.270996 L0.559571 0.94897",N:"M0.067871 0.94897 L0.067871 0.270996 L0.534181 0.94897 L0.525031 0.270996",O:"M0.287293 0.961214 L0.19843 0.933567 L0.1172 0.849451 L0.057129 0.563945 L0.114348 0.350255 L0.18455 0.289392 L0.306101 0.257813 L0.42054 0.29572 L0.487543 0.365003 L0.544923 0.625294 L0.516366 0.789624 L0.465476 0.884596 L0.375084 0.949287 L0.287293 0.961214",P:"M0.070557 0.94897 L0.070557 0.28379 L0.20704 0.270996 L0.329134 0.278993 L0.408525 0.300514 L0.444022 0.317908 L0.500637 0.368929 L0.525796 0.423728 L0.531496 0.50384 L0.508934 0.554205 L0.473724 0.582043 L0.417577 0.604365 L0.336375 0.620372 L0.226014 0.629268 L0.082368 0.630258",Q:"M0.282435 1.050813 L0.195447 1.019646 L0.115933 0.924817 L0.057129 0.602943 L0.113139 0.362034 L0.18186 0.293418 L0.300844 0.257813 L0.412868 0.300553 L0.478457 0.37866 L0.534625 0.672103 L0.506671 0.857367 L0.456855 0.964437 L0.368371 1.037368 L0.282435 1.050813 M0.341225 0.815559 L0.544923 1.070653",R:"M0.034912 0.944112 L0.034912 0.288556 L0.227127 0.270996 L0.362038 0.276867 L0.443423 0.294907 L0.477644 0.309614 L0.505809 0.328757 L0.526616 0.352817 L0.544963 0.418061 L0.543241 0.475921 L0.524463 0.517817 L0.49076 0.546518 L0.444265 0.564799 L0.355195 0.578739 L0.047653 0.589627 M0.303054 0.617306 L0.56714 0.94897",S:"M0.483037 0.364333 L0.407613 0.267477 L0.22883 0.257813 L0.128623 0.327565 L0.087712 0.455539 L0.104656 0.518727 L0.168054 0.573307 L0.41928 0.617318 L0.503796 0.669342 L0.535157 0.759324 L0.493846 0.900055 L0.367668 0.961214 L0.205436 0.956661 L0.116711 0.907038 L0.066895 0.790334",T:"M0.022949 0.270996 L0.579103 0.270996 M0.309284 0.270996 L0.309284 0.94897",U:"M0.072022 0.270996 L0.07308 0.648875 L0.080372 0.75167 L0.099024 0.827813 L0.134786 0.885729 L0.181571 0.924023 L0.251464 0.95168 L0.339655 0.962139 L0.401553 0.951668 L0.45232 0.924086 L0.482701 0.891771 L0.495745 0.870529 L0.515699 0.81637 L0.525014 0.744626 L0.530031 0.272017",V:"M0.027832 0.270996 L0.320083 0.94897 L0.57422 0.270996",W:"M0 0.270996 L0.079799 0.940377 L0.285198 0.472884 L0.505255 0.94897 L0.602052 0.270996",X:"M0.009034 0.270996 L0.586805 0.94897 M0.593019 0.270996 L0.015246 0.94897",Y:"M0.018067 0.270996 L0.293132 0.574135 M0.583986 0.271959 L0.294954 0.57606 L0.305277 0.94897",Z:"M0.053711 0.270996 L0.548341 0.270996 L0.053711 0.94897 L0.548341 0.94897","[":"M0.404542 0.240234 L0.197511 0.240234 L0.197511 1.069424 L0.404542 1.069424","\\":"M0.062501 0.270996 L0.539551 1.035249","]":"M0.19751 0.240234 L0.404542 0.240234 L0.404542 1.069424 L0.19751 1.069424","^":"M0.035156 0.523931 L0.301024 0.270996 L0.566896 0.523931",_:"M0 1.160601 L0.602052 1.160601",a:"M0.527101 0.439941 L0.527101 0.973965 M0.527101 0.553824 L0.451366 0.477535 L0.376759 0.439941 L0.263722 0.439941 L0.187989 0.477535 L0.112255 0.553824 L0.074951 0.66881 L0.074951 0.745099 L0.112255 0.85898 L0.187989 0.93527 L0.263722 0.973965 L0.376759 0.973965 L0.451366 0.93527 L0.527101 0.85898",b:"M0.07666 0.240234 L0.07666 0.959985 M0.07666 0.582737 L0.151822 0.514237 L0.225865 0.480483 L0.338045 0.480483 L0.413211 0.514237 L0.488374 0.582737 L0.525392 0.685983 L0.525392 0.754485 L0.488374 0.856739 L0.413211 0.92524 L0.338045 0.959985 L0.225865 0.959985 L0.151822 0.92524 L0.07666 0.856739",c:"M0.512452 0.553823 L0.441624 0.477535 L0.371854 0.439941 L0.26614 0.439941 L0.195312 0.477535 L0.124486 0.553823 L0.0896 0.668808 L0.0896 0.745099 L0.124486 0.858979 L0.195312 0.93527 L0.26614 0.973965 L0.371854 0.973965 L0.441624 0.93527 L0.512452 0.858979",d:"M0.525392 0.240234 L0.525392 0.959985 M0.525392 0.582737 L0.450232 0.514237 L0.376189 0.480483 L0.264006 0.480483 L0.188844 0.514237 L0.11368 0.582737 L0.076661 0.685983 L0.076661 0.754485 L0.11368 0.856739 L0.188844 0.92524 L0.264006 0.959985 L0.376189 0.959985 L0.450232 0.92524 L0.525392 0.856739",e:"M0.059571 0.668808 L0.542482 0.668808 M0.542482 0.592521 L0.502641 0.516231 L0.461594 0.477535 L0.381914 0.439941 L0.261186 0.439941 L0.180299 0.477535 L0.099412 0.553823 L0.059571 0.668808 L0.059571 0.745099 L0.099412 0.858979 L0.180299 0.93527 L0.261186 0.973965 L0.381914 0.973965 L0.461594 0.93527 L0.542482 0.858979",f:"M0.512941 0.240234 L0.406984 0.240234 L0.301026 0.274346 L0.248047 0.374731 L0.248047 0.946817 M0.089112 0.476088 L0.459965 0.476088",g:"M0.525392 0.439941 L0.525392 0.989395 L0.488373 1.091918 L0.45023 1.126757 L0.376189 1.160601 L0.264004 1.160601 L0.188844 1.126757 L0.113681 1.058075 L0.076661 0.954555 M0.525392 0.542467 L0.45023 0.473786 L0.376189 0.439941 L0.264004 0.439941 L0.188844 0.473786 L0.113681 0.542467 L0.076661 0.645988 L0.076661 0.714669 L0.113681 0.817193 L0.188844 0.885875 L0.264004 0.920713 L0.376189 0.920713 L0.45023 0.885875 L0.525392 0.817193",h:"M0.092041 0.240234 L0.092041 0.946817 M0.092041 0.61058 L0.205937 0.509225 L0.282214 0.476086 L0.396109 0.476086 L0.47187 0.509225 L0.510011 0.61058 L0.510011 0.946817",i:"M0.261026 0.240234 L0.341026 0.240234 M0.300978 0.476089 L0.300978 0.946817",j:"M0.3853 0.240234 L0.447023 0.240234 M0.416159 0.465708 L0.416159 1.011689 L0.383887 1.108586 L0.252832 1.140264 L0.15503 1.108586",k:"M0.065186 0.240234 L0.065186 0.946817 M0.493824 0.476086 L0.065186 0.812323 M0.236758 0.677829 L0.536867 0.946817",l:"M0.301026 0.234863 L0.301026 0.946441",m:"M0.050538 0.439941 L0.050538 0.960796 M0.050538 0.588758 L0.114405 0.476607 L0.157178 0.439941 L0.236864 0.439941 L0.279637 0.476607 L0.32241 0.588758 L0.32241 0.960796 M0.32241 0.588758 L0.386281 0.476607 L0.428467 0.439941 L0.50874 0.439941 L0.551515 0.476607 L0.551515 0.960796",n:"M0.092041 0.439941 L0.092041 0.960796 M0.092041 0.588758 L0.205936 0.476607 L0.282216 0.439941 L0.396113 0.439941 L0.471871 0.476607 L0.510011 0.588758 L0.510011 0.960796",o:"M0.247175 0.439941 L0.175178 0.477535 L0.103186 0.553823 L0.066895 0.668808 L0.066895 0.745099 L0.103186 0.858979 L0.175178 0.93527 L0.247175 0.973965 L0.354874 0.973965 L0.426872 0.93527 L0.498866 0.858979 L0.535157 0.745099 L0.535157 0.668808 L0.498866 0.553823 L0.426872 0.477535 L0.354874 0.439941 L0.247175 0.439941",p:"M0.076904 0.439941 L0.076904 1.154244 M0.076904 0.541563 L0.151986 0.473487 L0.225944 0.439941 L0.338005 0.439941 L0.413087 0.473487 L0.488166 0.541563 L0.525148 0.644169 L0.525148 0.712246 L0.488166 0.813866 L0.413087 0.881942 L0.338005 0.916471 L0.225944 0.916471 L0.151986 0.881942 L0.076904 0.813866",q:"M0.525148 0.441895 L0.525148 1.156195 M0.525148 0.5435 L0.450067 0.47544 L0.376106 0.441895 L0.264042 0.441895 L0.188966 0.47544 L0.113885 0.5435 L0.076905 0.646108 L0.076905 0.714187 L0.113885 0.815809 L0.188966 0.883886 L0.264042 0.918418 L0.376106 0.918418 L0.450067 0.883886 L0.525148 0.815809",r:"M0.107422 0.439941 L0.107422 0.960796 M0.107422 0.663164 L0.155824 0.551014 L0.252626 0.476607 L0.349428 0.439941 L0.49463 0.439941",s:"M0.475556 0.477535 L0.400757 0.439941 L0.276092 0.439941 L0.176361 0.477535 L0.101563 0.553823 L0.101563 0.630112 L0.176361 0.668808 L0.301024 0.668808 L0.425688 0.745099 L0.50049 0.821387 L0.50049 0.897677 L0.425688 0.93527 L0.325956 0.973965 L0.201295 0.973965 L0.126496 0.93527 L0.101563 0.858979",t:"M0.246032 0.297852 L0.246032 0.826549 L0.301023 0.919323 L0.411011 0.950848 L0.520997 0.950848 M0.081055 0.515799 L0.466004 0.515799",u:"M0.092041 0.454102 L0.092041 0.826134 L0.13018 0.937211 L0.205936 0.974954 L0.319832 0.974954 L0.396113 0.937211 L0.510011 0.826134 M0.510011 0.454102 L0.510011 0.974954",v:"M0.048828 0.453125 L0.301026 0.961719 M0.553224 0.453125 L0.301026 0.961719",w:"M0 0.453125 L0.150512 0.961719 M0.301024 0.453125 L0.150512 0.961719 M0.301024 0.453125 L0.451539 0.961719 M0.602052 0.453125 L0.451539 0.961719",x:"M0.03711 0.453125 L0.564943 0.961719 M0.564943 0.453125 L0.03711 0.961719",y:"M0.084618 0.453125 L0.320232 0.921476 M0.55713 0.453125 L0.320232 0.921476 L0.242119 1.055289 L0.163369 1.122196 L0.084618 1.155166 L0.044922 1.155166",z:"M0.505373 0.452148 L0.09668 0.961651 M0.09668 0.452148 L0.505373 0.452148 M0.09668 0.961651 L0.505373 0.961651"},E2={};for(let t52 in R2){E2[t52]=[];let e5=R2[t52].split("M").slice(1).map(t53=>t53.split("L").map(t54=>t54.trim().split(" ").map(parseFloat)));for(let n4 of e5)for(let e6=0;e6<n4.length-1;e6++)E2[t52].push({x1:n4[e6][0],y1:1-n4[e6][1],x2:n4[e6+1][0],y2:1-n4[e6+1][1]})}new TextEncoder,(()=>{let t52=new Uint8Array(4);new Uint32Array(t52.buffer)[0]=1,t52[0]})(),globalThis.Int8Array,globalThis.Uint8Array,globalThis.Int16Array,globalThis.Uint16Array,globalThis.Int32Array,globalThis.Uint32Array,globalThis.BigUint64Array,globalThis.BigInt64Array,globalThis.Float32Array,globalThis.Float64Array;var A3=[];for(let t52=0;t52<256;t52++){let e5=t52;for(let t53=0;t53<8;t53++)1&e5?e5=3988292384^e5>>>1:e5>>>=1;A3[t52]=e5}var O2=new Uint16Array([255]),L2=(new Uint8Array(O2.buffer)[0],new Uint16Array([255]));new Uint8Array(L2.buffer)[0],new Uint8Array(0),Uint8Array.of(137,80,78,71,13,10,26,10),new TextDecoder("latin1");function D3(){return D3=Object.assign?Object.assign.bind():function(t52){for(var e5=1;e5<arguments.length;e5++){var n4=arguments[e5];for(var o4 in n4)({}).hasOwnProperty.call(n4,o4)&&(t52[o4]=n4[o4])}return t52},D3.apply(null,arguments)}function k3(t52,e5){return(k3=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t53,e6){return t53.__proto__=e6,t53})(t52,e5)}function z3(t52){return(z3=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t53){return t53.__proto__||Object.getPrototypeOf(t53)})(t52)}function j2(){try{var t52=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(j2=function(){return!!t52})()}function F3(t52){var e5=typeof Map=="function"?new Map:void 0;return F3=function(t53){if(t53===null||!(function(t54){try{return Function.toString.call(t54).indexOf("[native code]")!==-1}catch{return typeof t54=="function"}})(t53))return t53;if(typeof t53!="function")throw new TypeError("Super expression must either be null or a function");if(e5!==void 0){if(e5.has(t53))return e5.get(t53);e5.set(t53,n4)}function n4(){return(function(t54,e6,n5){if(j2())return Reflect.construct.apply(null,arguments);var o4=[null];o4.push.apply(o4,e6);var i3=new(t54.bind.apply(t54,o4));return n5&&k3(i3,n5.prototype),i3})(t53,arguments,z3(this).constructor)}return n4.prototype=Object.create(t53.prototype,{constructor:{value:n4,enumerable:!1,writable:!0,configurable:!0}}),k3(n4,t53)},F3(t52)}var $4={1:`Passed invalid arguments to hsl, please pass multiple numbers e.g. hsl(360, 0.75, 0.4) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75 }).
|
|
337
|
+
`)?.every(str2=>str2.includes("LINESTRING"))}function isWktString(str){return str.startsWith("POINT")||isArrayOfPoints(str)||str.startsWith("LINESTRING")||isArrayOfLines(str)||str.startsWith("MULTILINESTRING")||str.startsWith("POLYGON")||str.startsWith("MULTIPOINT")||str.startsWith("MULTIPOLYGON")||str.startsWith("GEOMETRYCOLLECTION")}Flatten.isWktString=isWktString;Flatten.parseWKT=parseWKT;Flatten.BooleanOperations=BooleanOperations;Flatten.Relations=Relations;init_dist();init_dist5();var package_default={name:"@tscircuit/capacity-autorouter",main:"./dist/index.js",version:"0.0.529",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","run-sample":"bun scripts/run-sample.ts","repomix:lib":"repomix --ignore 'testing/**,**/TwoRouteHighDensitySolver/**,**/RouteStitchingSolver/**,solvers/CapacitySegmentPointOptimizer/CapacitySegmentPointOptimizer.ts' lib","bug-report":"bun run scripts/download-bug-report.ts","bug-report-with-test":"bun run scripts/create-bug-report-test.ts"},devDependencies:{"@biomejs/biome":"^1.9.4","@radix-ui/react-icons":"^1.3.2","@radix-ui/react-menubar":"^1.1.14","@react-hook/resize-observer":"^2.0.2","@resvg/resvg-js":"^2.6.2","@tsci/seveibar.dataset-srj13":"git+https://github.com/tscircuit/dataset-srj13.git#56db70039aeb28a76540fe951b5a96be60f9e949","@tsci/tscircuit.dataset-srj16-bga-breakouts":"git+https://github.com/tscircuit/dataset-srj16-bga-breakouts.git","@tsci/tscircuit.dataset-srj12-bus-routing":"git+https://github.com/tscircuit/dataset-srj12-bus-routing.git#ba82f86a7d1288566b7144eb8661ad2549c5f328","@tscircuit/autorouting-dataset-01":"^1.0.32","@tscircuit/checks":"^0.0.126","@tscircuit/circuit-json-util":"^0.0.94","@tscircuit/core":"^0.0.337","@tscircuit/curvy-trace-solver":"^0.0.10","@tscircuit/dataset-srj05":"git+https://github.com/tscircuit/dataset-srj05.git#9a49c126a89c083dc4d2b72cd17184735f637762","@tscircuit/fixed-via-hypergraph-solver":"https://codeload.github.com/tscircuit/fixed-via-hypergraph-solver/tar.gz/bed37a6201b5dd07c9cc68b828917ecc20d6d049","@tscircuit/hypergraph":"^0.0.71","@tscircuit/jumper-topology-generator":"^0.0.4","@tscircuit/krt-wasm":"^0.1.0","@tscircuit/math-utils":"^0.0.36","@tscircuit/rectdiff":"git+https://github.com/tscircuit/rectdiff.git#4af388d","@tscircuit/solver-utils":"^0.0.16","@types/bun":"^1.2.23","@types/fast-json-stable-stringify":"^2.1.2","@types/object-hash":"^3.0.6","@types/rbush":"^4.0.0","@types/react":"^19.0.8","@types/react-dom":"^19.0.3","@vercel/node":"^5.1.7","@vitejs/plugin-react":"^4.3.4","bun-match-svg":"^0.0.14","circuit-json-to-connectivity-map":"^0.0.19","circuit-json":"^0.0.419","circuit-to-svg":"^0.0.220",clsx:"^2.1.1","dataset-srj11-45-degree":"git+https://github.com/tscircuit/dataset-srj11-45-degree.git#0add61e6a0e6b59f6defc36f257052f773e2d685",flatbush:"^4.4.0","graphics-debug":"0.0.94","high-density-dataset-z04":"git+https://github.com/tscircuit/high-density-dataset-z04.git#b9128ed52f5a50102b6526319be1d4ec33dca2c2",kleur:"^4.1.5","looks-same":"9","pcb-poly-hyper-graph":"https://codeload.github.com/tscircuit/pcb-poly-hyper-graph/tar.gz/80db1463c4a47506eeda15b2c14d59679de900f8",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","tiny-hypergraph":"git+https://github.com/tscircuit/tiny-hypergraph.git#78db8cb1dc78bfb3569ea6cb86bacc86d04c7338","tiny-hypergraph-poly":"git+https://github.com/tscircuit/tiny-hypergraph.git#7b93b4c",tsup:"^8.3.6",typescript:"^5.9.3","use-mouse-matrix-transform":"^1.3.0",vite:"^6.0.11","vite-tsconfig-paths":"^5.1.4","zdwiel-dataset":"git+https://github.com/dwiel/tscircuit-benchmark.git#be36518b5bf51755dae92c230061ab3cf4e3e063","high-density-repair01":"git+https://github.com/tscircuit/high-density-repair01.git#f4804e26d6da845cb985e4681ebd528b7c5f2ce8","high-density-repair02":"https://codeload.github.com/tscircuit/high-density-repair02/tar.gz/2afc0cbba3bf2f7eb6b9cd33615d21e9ad9352d4","high-density-repair03":"git+https://github.com/tscircuit/high-density-repair03.git#db73a5f"},dependencies:{"@tscircuit/high-density-a01":"^0.0.37","fast-json-stable-stringify":"^2.1.0","object-hash":"^3.0.0"}};init_dist();init_dist3();var import_react=__toESM(require_react(),1),import_react_reconciler=__toESM(require_react_reconciler(),1),import_constants=__toESM(require_constants(),1);init_zod();init_dist();init_dist();init_zod();init_dist();init_dist();init_zod();init_dist();var e2={a:1,b:0,c:0,d:1,e:0,f:0,m11:1,m12:0,m13:0,m14:0,m21:0,m22:1,m23:0,m24:0,m31:0,m32:0,m33:1,m34:0,m41:0,m42:0,m43:0,m44:1,is2D:!0,isIdentity:!0},t=e5=>(e5 instanceof Float64Array||e5 instanceof Float32Array||Array.isArray(e5)&&e5.every(e6=>typeof e6=="number"))&&[6,16].some(t52=>e5.length===t52),n=t52=>t52 instanceof DOMMatrix||t52 instanceof h||typeof t52=="object"&&Object.keys(e2).every(e5=>t52&&e5 in t52),r3=e5=>{let n4=new h,r5=Array.from(e5);if(!t(r5))throw TypeError(`CSSMatrix: "${r5.join(",")}" must be an array with 6/16 numbers.`);if(r5.length===16){let[e6,t52,i3,a3,o4,s3,c4,l4,u5,d4,f3,p4,m4,h6,g6,_4]=r5;n4.m11=e6,n4.a=e6,n4.m21=o4,n4.c=o4,n4.m31=u5,n4.m41=m4,n4.e=m4,n4.m12=t52,n4.b=t52,n4.m22=s3,n4.d=s3,n4.m32=d4,n4.m42=h6,n4.f=h6,n4.m13=i3,n4.m23=c4,n4.m33=f3,n4.m43=g6,n4.m14=a3,n4.m24=l4,n4.m34=p4,n4.m44=_4}else if(r5.length===6){let[e6,t52,i3,a3,o4,s3]=r5;n4.m11=e6,n4.a=e6,n4.m12=t52,n4.b=t52,n4.m21=i3,n4.c=i3,n4.m22=a3,n4.d=a3,n4.m41=o4,n4.e=o4,n4.m42=s3,n4.f=s3}return n4},i=e5=>{if(n(e5))return r3([e5.m11,e5.m12,e5.m13,e5.m14,e5.m21,e5.m22,e5.m23,e5.m24,e5.m31,e5.m32,e5.m33,e5.m34,e5.m41,e5.m42,e5.m43,e5.m44]);throw TypeError(`CSSMatrix: "${JSON.stringify(e5)}" is not a DOMMatrix / CSSMatrix / JSON compatible object.`)},a=e5=>{if(typeof e5!="string")throw TypeError(`CSSMatrix: "${JSON.stringify(e5)}" is not a string.`);let t52=String(e5).replace(/\s/g,""),n4=new h,i3=`CSSMatrix: invalid transform string "${e5}"`;return t52.split(")").filter(e6=>e6).forEach(e6=>{let[t53,a3]=e6.split("(");if(!a3)throw TypeError(i3);let o4=a3.split(",").map(e7=>e7.includes("rad")?180/Math.PI*parseFloat(e7):parseFloat(e7)),[s3,c4,l4,u5]=o4,d4=[s3,c4,l4],f3=[s3,c4,l4,u5];if(t53==="perspective"&&s3&&[c4,l4].every(e7=>e7===void 0))n4.m34=-1/s3;else if(t53.includes("matrix")&&[6,16].includes(o4.length)&&o4.every(e7=>!Number.isNaN(+e7))){let e7=o4.map(e8=>Math.abs(e8)<1e-6?0:e8);n4.multiplySelf(r3(e7))}else if(t53==="translate3d"&&d4.every(e7=>!Number.isNaN(+e7)))n4.translateSelf(s3,c4,l4);else if(t53==="translate"&&s3&&l4===void 0)n4.translateSelf(s3,c4||0,0);else if(t53==="rotate3d"&&f3.every(e7=>!Number.isNaN(+e7))&&u5)n4.rotateAxisAngleSelf(s3,c4,l4,u5);else if(t53==="rotate"&&s3&&[c4,l4].every(e7=>e7===void 0))n4.rotateSelf(0,0,s3);else if(t53==="scale3d"&&d4.every(e7=>!Number.isNaN(+e7))&&d4.some(e7=>e7!==1))n4.scaleSelf(s3,c4,l4);else if(t53==="scale"&&!Number.isNaN(s3)&&(s3!==1||c4!==1)&&l4===void 0){let e7=Number.isNaN(+c4)?s3:c4;n4.scaleSelf(s3,e7,1)}else if(t53==="skew"&&(s3||!Number.isNaN(s3)&&c4)&&l4===void 0)n4.skewSelf(s3,c4||0);else if(["translate","rotate","scale","skew"].some(e7=>t53.includes(e7))&&/[XYZ]/.test(t53)&&s3&&[c4,l4].every(e7=>e7===void 0))if(t53==="skewX"||t53==="skewY")n4[t53==="skewX"?"skewXSelf":"skewYSelf"](s3);else{let e7=t53.replace(/[XYZ]/,""),r5=t53.replace(e7,""),i4=["X","Y","Z"].indexOf(r5),a4=e7==="scale"?1:0,o6=e7+"Self",c5=[i4===0?s3:a4,i4===1?s3:a4,i4===2?s3:a4];n4[o6](...c5)}else throw TypeError(i3)}),n4},o=(e5,t52)=>t52?[e5.a,e5.b,e5.c,e5.d,e5.e,e5.f]:[e5.m11,e5.m12,e5.m13,e5.m14,e5.m21,e5.m22,e5.m23,e5.m24,e5.m31,e5.m32,e5.m33,e5.m34,e5.m41,e5.m42,e5.m43,e5.m44],s=(e5,t52,n4)=>{let r5=new h;return r5.m41=e5,r5.e=e5,r5.m42=t52,r5.f=t52,r5.m43=n4,r5},c=(e5,t52,n4)=>{let r5=new h,i3=Math.PI/180,a3=e5*i3,o4=t52*i3,s3=n4*i3,c4=Math.cos(a3),l4=-Math.sin(a3),u5=Math.cos(o4),d4=-Math.sin(o4),f3=Math.cos(s3),p4=-Math.sin(s3),m4=u5*f3,g6=-u5*p4;r5.m11=m4,r5.a=m4,r5.m12=g6,r5.b=g6,r5.m13=d4;let _4=l4*d4*f3+c4*p4;r5.m21=_4,r5.c=_4;let v4=c4*f3-l4*d4*p4;return r5.m22=v4,r5.d=v4,r5.m23=-l4*u5,r5.m31=l4*p4-c4*d4*f3,r5.m32=l4*f3+c4*d4*p4,r5.m33=c4*u5,r5},l=(e5=0,t52=0,n4=0,r5=0)=>{let i3=new h,a3=Math.sqrt(e5*e5+t52*t52+n4*n4);if(a3===0)return i3;let o4=e5/a3,s3=t52/a3,c4=n4/a3,l4=Math.PI/360*r5,u5=Math.sin(l4),d4=Math.cos(l4),f3=u5*u5,p4=o4*o4,m4=s3*s3,g6=c4*c4,_4=1-2*(m4+g6)*f3;i3.m11=_4,i3.a=_4;let v4=2*(o4*s3*f3+c4*u5*d4);i3.m12=v4,i3.b=v4,i3.m13=2*(o4*c4*f3-s3*u5*d4);let y4=2*(s3*o4*f3-c4*u5*d4);i3.m21=y4,i3.c=y4;let b3=1-2*(g6+p4)*f3;return i3.m22=b3,i3.d=b3,i3.m23=2*(s3*c4*f3+o4*u5*d4),i3.m31=2*(c4*o4*f3+s3*u5*d4),i3.m32=2*(c4*s3*f3-o4*u5*d4),i3.m33=1-2*(p4+m4)*f3,i3},u3=(e5,t52,n4)=>{let r5=new h;return r5.m11=e5,r5.a=e5,r5.m22=t52,r5.d=t52,r5.m33=n4,r5},d=(e5,t52)=>{let n4=new h;if(e5){let t53=e5*Math.PI/180,r5=Math.tan(t53);n4.m21=r5,n4.c=r5}if(t52){let e6=t52*Math.PI/180,r5=Math.tan(e6);n4.m12=r5,n4.b=r5}return n4},f=e5=>d(e5,0),p=e5=>d(0,e5),m=(e5,t52)=>r3([t52.m11*e5.m11+t52.m12*e5.m21+t52.m13*e5.m31+t52.m14*e5.m41,t52.m11*e5.m12+t52.m12*e5.m22+t52.m13*e5.m32+t52.m14*e5.m42,t52.m11*e5.m13+t52.m12*e5.m23+t52.m13*e5.m33+t52.m14*e5.m43,t52.m11*e5.m14+t52.m12*e5.m24+t52.m13*e5.m34+t52.m14*e5.m44,t52.m21*e5.m11+t52.m22*e5.m21+t52.m23*e5.m31+t52.m24*e5.m41,t52.m21*e5.m12+t52.m22*e5.m22+t52.m23*e5.m32+t52.m24*e5.m42,t52.m21*e5.m13+t52.m22*e5.m23+t52.m23*e5.m33+t52.m24*e5.m43,t52.m21*e5.m14+t52.m22*e5.m24+t52.m23*e5.m34+t52.m24*e5.m44,t52.m31*e5.m11+t52.m32*e5.m21+t52.m33*e5.m31+t52.m34*e5.m41,t52.m31*e5.m12+t52.m32*e5.m22+t52.m33*e5.m32+t52.m34*e5.m42,t52.m31*e5.m13+t52.m32*e5.m23+t52.m33*e5.m33+t52.m34*e5.m43,t52.m31*e5.m14+t52.m32*e5.m24+t52.m33*e5.m34+t52.m34*e5.m44,t52.m41*e5.m11+t52.m42*e5.m21+t52.m43*e5.m31+t52.m44*e5.m41,t52.m41*e5.m12+t52.m42*e5.m22+t52.m43*e5.m32+t52.m44*e5.m42,t52.m41*e5.m13+t52.m42*e5.m23+t52.m43*e5.m33+t52.m44*e5.m43,t52.m41*e5.m14+t52.m42*e5.m24+t52.m43*e5.m34+t52.m44*e5.m44]),_a3,h=(_a3=class{constructor(e5){return this.a=1,this.b=0,this.c=0,this.d=1,this.e=0,this.f=0,this.m11=1,this.m12=0,this.m13=0,this.m14=0,this.m21=0,this.m22=1,this.m23=0,this.m24=0,this.m31=0,this.m32=0,this.m33=1,this.m34=0,this.m41=0,this.m42=0,this.m43=0,this.m44=1,e5?this.setMatrixValue(e5):this}get isIdentity(){return this.m11===1&&this.m12===0&&this.m13===0&&this.m14===0&&this.m21===0&&this.m22===1&&this.m23===0&&this.m24===0&&this.m31===0&&this.m32===0&&this.m33===1&&this.m34===0&&this.m41===0&&this.m42===0&&this.m43===0&&this.m44===1}get is2D(){return this.m31===0&&this.m32===0&&this.m33===1&&this.m34===0&&this.m43===0&&this.m44===1}setMatrixValue(e5){return typeof e5=="string"&&e5.length&&e5!=="none"?a(e5):Array.isArray(e5)||e5 instanceof Float64Array||e5 instanceof Float32Array?r3(e5):typeof e5=="object"?i(e5):this}toFloat32Array(e5){return Float32Array.from(o(this,e5))}toFloat64Array(e5){return Float64Array.from(o(this,e5))}toString(){let{is2D:e5}=this,t52=this.toFloat64Array(e5).join(", ");return`${e5?"matrix":"matrix3d"}(${t52})`}toJSON(){let{is2D:e5,isIdentity:t52}=this;return{...this,is2D:e5,isIdentity:t52}}multiply(e5){return m(this,e5)}translate(e5,t52,n4){return this.multiply(s(e5,t52??0,n4??0))}scale(e5,t52,n4){return this.multiply(u3(e5,t52??e5,n4??1))}rotate(e5,t52,n4){let r5=e5,i3=t52||0,a3=n4||0;return typeof e5=="number"&&t52===void 0&&n4===void 0&&(a3=r5,r5=0,i3=0),this.multiply(c(r5,i3,a3))}rotateAxisAngle(e5=0,t52=0,n4=0,r5=0){if([e5,t52,n4,r5].some(e6=>!Number.isFinite(e6)))throw TypeError("CSSMatrix: expecting 4 values");return Math.sqrt(e5*e5+t52*t52+n4*n4)===0?i(this):this.multiply(l(e5,t52,n4,r5))}skewX(e5){return this.multiply(f(e5))}skewY(e5){return this.multiply(p(e5))}skew(e5,t52){return this.multiply(d(e5,t52))}multiplySelf(e5){let t52=m(this,e5);return Object.assign(this,t52),this}translateSelf(e5,t52,n4){return this.multiplySelf(s(e5,t52??0,n4??0))}scaleSelf(e5,t52,n4){return this.multiplySelf(u3(e5,t52??e5,n4??1))}rotateSelf(e5,t52,n4){let r5=e5,i3=t52||0,a3=n4||0;return typeof e5=="number"&&t52===void 0&&n4===void 0&&(a3=r5,r5=0,i3=0),this.multiplySelf(c(r5,i3,a3))}rotateAxisAngleSelf(e5=0,t52=0,n4=0,r5=0){if([e5,t52,n4,r5].some(e6=>!Number.isFinite(e6)))throw TypeError("CSSMatrix: expecting 4 values");return Math.sqrt(e5*e5+t52*t52+n4*n4)===0?this:this.multiplySelf(l(e5,t52,n4,r5))}skewXSelf(e5){return this.multiplySelf(f(e5))}skewYSelf(e5){return this.multiplySelf(p(e5))}skewSelf(e5,t52){return this.multiplySelf(d(e5,t52))}transformPoint(e5){let t52=this.m11*e5.x+this.m21*e5.y+this.m31*e5.z+this.m41*e5.w,n4=this.m12*e5.x+this.m22*e5.y+this.m32*e5.z+this.m42*e5.w,r5=this.m13*e5.x+this.m23*e5.y+this.m33*e5.z+this.m43*e5.w,i3=this.m14*e5.x+this.m24*e5.y+this.m34*e5.z+this.m44*e5.w;return e5 instanceof DOMPoint?new DOMPoint(t52,n4,r5,i3):{x:t52,y:n4,z:r5,w:i3}}},__publicField(_a3,"Translate",s),__publicField(_a3,"Rotate",c),__publicField(_a3,"RotateAxisAngle",l),__publicField(_a3,"Scale",u3),__publicField(_a3,"SkewX",f),__publicField(_a3,"SkewY",p),__publicField(_a3,"Skew",d),__publicField(_a3,"Multiply",m),__publicField(_a3,"fromArray",r3),__publicField(_a3,"fromMatrix",i),__publicField(_a3,"fromString",a),__publicField(_a3,"toArray",o),__publicField(_a3,"isCompatibleArray",t),__publicField(_a3,"isCompatibleObject",n),_a3);var version="2.2.1",midPoint=([ax3,ay3],[bx3,by3],t52)=>[ax3+(bx3-ax3)*t52,ay3+(by3-ay3)*t52],distanceSquareRoot=(a3,b3)=>Math.sqrt((a3[0]-b3[0])*(a3[0]-b3[0])+(a3[1]-b3[1])*(a3[1]-b3[1])),getLineLength=(x12,y12,x22,y22)=>distanceSquareRoot([x12,y12],[x22,y22]),getPointAtLineLength=(x12,y12,x22,y22,distance8)=>{let point7={x:x12,y:y12};if(typeof distance8=="number"){let length4=distanceSquareRoot([x12,y12],[x22,y22]);if(distance8<=0)point7={x:x12,y:y12};else if(distance8>=length4)point7={x:x22,y:y22};else{let[x4,y4]=midPoint([x12,y12],[x22,y22],distance8/length4);point7={x:x4,y:y4}}}return point7},getLineBBox=(x12,y12,x22,y22)=>{let{min,max}=Math;return[min(x12,x22),min(y12,y22),max(x12,x22),max(y12,y22)]},lineTools={getLineBBox,getLineLength,getPointAtLineLength},arcLength=(rx3,ry3,theta)=>{let halfTheta=theta/2,sinHalfTheta=Math.sin(halfTheta),cosHalfTheta=Math.cos(halfTheta),term1=rx3**2*sinHalfTheta**2,term2=ry3**2*cosHalfTheta**2,length4=Math.sqrt(term1+term2)*theta;return Math.abs(length4)},arcPoint=(cx3,cy3,rx3,ry3,alpha,theta)=>{let{sin:sin6,cos:cos6}=Math,cosA=cos6(alpha),sinA=sin6(alpha),x4=rx3*cos6(theta),y4=ry3*sin6(theta);return[cx3+cosA*x4-sinA*y4,cy3+sinA*x4+cosA*y4]},angleBetween=(v02,v12)=>{let{x:v0x,y:v0y}=v02,{x:v1x,y:v1y}=v12,p4=v0x*v1x+v0y*v1y,n4=Math.sqrt((v0x**2+v0y**2)*(v1x**2+v1y**2));return(v0x*v1y-v0y*v1x<0?-1:1)*Math.acos(p4/n4)},getArcProps=(x12,y12,RX,RY2,angle,LAF,SF,x4,y4)=>{let{abs,sin:sin6,cos:cos6,sqrt,PI:PI7}=Math,rx3=abs(RX),ry3=abs(RY2),xRotRad=(angle%360+360)%360*(PI7/180);if(x12===x4&&y12===y4)return{rx:rx3,ry:ry3,startAngle:0,endAngle:0,center:{x:x4,y:y4}};if(rx3===0||ry3===0)return{rx:rx3,ry:ry3,startAngle:0,endAngle:0,center:{x:(x4+x12)/2,y:(y4+y12)/2}};let dx3=(x12-x4)/2,dy3=(y12-y4)/2,transformedPoint={x:cos6(xRotRad)*dx3+sin6(xRotRad)*dy3,y:-sin6(xRotRad)*dx3+cos6(xRotRad)*dy3},radiiCheck=transformedPoint.x**2/rx3**2+transformedPoint.y**2/ry3**2;radiiCheck>1&&(rx3*=sqrt(radiiCheck),ry3*=sqrt(radiiCheck));let cRadicand=(rx3**2*ry3**2-rx3**2*transformedPoint.y**2-ry3**2*transformedPoint.x**2)/(rx3**2*transformedPoint.y**2+ry3**2*transformedPoint.x**2);cRadicand=cRadicand<0?0:cRadicand;let cCoef=(LAF!==SF?1:-1)*sqrt(cRadicand),transformedCenter={x:cCoef*(rx3*transformedPoint.y/ry3),y:cCoef*(-(ry3*transformedPoint.x)/rx3)},center2={x:cos6(xRotRad)*transformedCenter.x-sin6(xRotRad)*transformedCenter.y+(x12+x4)/2,y:sin6(xRotRad)*transformedCenter.x+cos6(xRotRad)*transformedCenter.y+(y12+y4)/2},startVector={x:(transformedPoint.x-transformedCenter.x)/rx3,y:(transformedPoint.y-transformedCenter.y)/ry3},startAngle=angleBetween({x:1,y:0},startVector),sweepAngle=angleBetween(startVector,{x:(-transformedPoint.x-transformedCenter.x)/rx3,y:(-transformedPoint.y-transformedCenter.y)/ry3});return!SF&&sweepAngle>0?sweepAngle-=2*PI7:SF&&sweepAngle<0&&(sweepAngle+=2*PI7),sweepAngle%=2*PI7,{center:center2,startAngle,endAngle:startAngle+sweepAngle,rx:rx3,ry:ry3}},getArcLength=(x12,y12,RX,RY2,angle,LAF,SF,x4,y4)=>{let{rx:rx3,ry:ry3,startAngle,endAngle}=getArcProps(x12,y12,RX,RY2,angle,LAF,SF,x4,y4);return arcLength(rx3,ry3,endAngle-startAngle)},getPointAtArcLength=(x12,y12,RX,RY2,angle,LAF,SF,x4,y4,distance8)=>{let point7={x:x12,y:y12},{center:center2,rx:rx3,ry:ry3,startAngle,endAngle}=getArcProps(x12,y12,RX,RY2,angle,LAF,SF,x4,y4);if(typeof distance8=="number"){let length4=arcLength(rx3,ry3,endAngle-startAngle);if(distance8<=0)point7={x:x12,y:y12};else if(distance8>=length4)point7={x:x4,y:y4};else{if(x12===x4&&y12===y4)return{x:x4,y:y4};if(rx3===0||ry3===0)return getPointAtLineLength(x12,y12,x4,y4,distance8);let{PI:PI7,cos:cos6,sin:sin6}=Math,sweepAngle=endAngle-startAngle,xRotRad=(angle%360+360)%360*(PI7/180),alpha=startAngle+sweepAngle*(distance8/length4),ellipseComponentX=rx3*cos6(alpha),ellipseComponentY=ry3*sin6(alpha);point7={x:cos6(xRotRad)*ellipseComponentX-sin6(xRotRad)*ellipseComponentY+center2.x,y:sin6(xRotRad)*ellipseComponentX+cos6(xRotRad)*ellipseComponentY+center2.y}}}return point7},getArcBBox=(x12,y12,RX,RY2,angle,LAF,SF,x4,y4)=>{let{center:center2,rx:rx3,ry:ry3,startAngle,endAngle}=getArcProps(x12,y12,RX,RY2,angle,LAF,SF,x4,y4),deltaAngle=endAngle-startAngle,{min,max,tan:tan6,atan2,PI:PI7}=Math,{x:cx3,y:cy3}=center2,alpha=angle*PI7/180,tangent=tan6(alpha),theta=atan2(-ry3*tangent,rx3),angle1=theta,angle2=theta+PI7,angle3=atan2(ry3,rx3*tangent),angle4=angle3+PI7,xArray=[x4],yArray=[y4],xMin=min(x12,x4),xMax=max(x12,x4),yMin=min(y12,y4),yMax=max(y12,y4),pP2=arcPoint(cx3,cy3,rx3,ry3,alpha,endAngle-deltaAngle*1e-5),pP3=arcPoint(cx3,cy3,rx3,ry3,alpha,endAngle-deltaAngle*.99999);if(pP2[0]>xMax||pP3[0]>xMax){let p12=arcPoint(cx3,cy3,rx3,ry3,alpha,angle1);xArray.push(p12[0]),yArray.push(p12[1])}if(pP2[0]<xMin||pP3[0]<xMin){let p22=arcPoint(cx3,cy3,rx3,ry3,alpha,angle2);xArray.push(p22[0]),yArray.push(p22[1])}if(pP2[1]<yMin||pP3[1]<yMin){let p4=arcPoint(cx3,cy3,rx3,ry3,alpha,angle4);xArray.push(p4[0]),yArray.push(p4[1])}if(pP2[1]>yMax||pP3[1]>yMax){let p32=arcPoint(cx3,cy3,rx3,ry3,alpha,angle3);xArray.push(p32[0]),yArray.push(p32[1])}return xMin=min.apply([],xArray),yMin=min.apply([],yArray),xMax=max.apply([],xArray),yMax=max.apply([],yArray),[xMin,yMin,xMax,yMax]},arcTools={angleBetween,arcLength,arcPoint,getArcBBox,getArcLength,getArcProps,getPointAtArcLength},Tvalues=[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213],Cvalues=[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872],deriveBezier=points=>{let dpoints=[];for(let p4=points,d4=p4.length,c4=d4-1;d4>1;d4-=1,c4-=1){let list=[];for(let j4=0;j4<c4;j4+=1)list.push({x:c4*(p4[j4+1].x-p4[j4].x),y:c4*(p4[j4+1].y-p4[j4].y),t:0});dpoints.push(list),p4=list}return dpoints},computeBezier=(points,t52)=>{if(t52===0)return points[0].t=0,points[0];let order=points.length-1;if(t52===1)return points[order].t=1,points[order];let mt3=1-t52,p4=points;if(order===0)return points[0].t=t52,points[0];if(order===1)return{x:mt3*p4[0].x+t52*p4[1].x,y:mt3*p4[0].y+t52*p4[1].y,t:t52};let mt22=mt3*mt3,t210=t52*t52,a3=0,b3=0,c4=0,d4=0;return order===2?(p4=[p4[0],p4[1],p4[2],{x:0,y:0}],a3=mt22,b3=mt3*t52*2,c4=t210):order===3&&(a3=mt22*mt3,b3=mt22*t52*3,c4=mt3*t210*3,d4=t52*t210),{x:a3*p4[0].x+b3*p4[1].x+c4*p4[2].x+d4*p4[3].x,y:a3*p4[0].y+b3*p4[1].y+c4*p4[2].y+d4*p4[3].y,t:t52}},calculateBezier=(derivativeFn,t52)=>{let d4=derivativeFn(t52),l4=d4.x*d4.x+d4.y*d4.y;return Math.sqrt(l4)},bezierLength=derivativeFn=>{let len=Tvalues.length,sum=0;for(let i3=0,t52;i3<len;i3++)t52=.5*Tvalues[i3]+.5,sum+=Cvalues[i3]*calculateBezier(derivativeFn,t52);return .5*sum},getBezierLength=curve=>{let points=[];for(let idx=0,len=curve.length,step=2;idx<len;idx+=step)points.push({x:curve[idx],y:curve[idx+1]});let dpoints=deriveBezier(points);return bezierLength(t52=>computeBezier(dpoints[0],t52))},CBEZIER_MINMAX_EPSILON=1e-8,minmaxQ=([v12,cp2,v22])=>{let min=Math.min(v12,v22),max=Math.max(v12,v22);if(cp2>=v12?v22>=cp2:v22<=cp2)return[min,max];let E3=(v12*v22-cp2*cp2)/(v12-2*cp2+v22);return E3<min?[E3,max]:[min,E3]},minmaxC=([v12,cp1,cp2,v22])=>{let K3=v12-3*cp1+3*cp2-v22;if(Math.abs(K3)<1e-8)return v12===v22&&v12===cp1?[v12,v22]:minmaxQ([v12,-.5*v12+1.5*cp1,v12-3*cp1+3*cp2]);let T4=-v12*cp2+v12*v22-cp1*cp2-cp1*v22+cp1*cp1+cp2*cp2;if(T4<=0)return[Math.min(v12,v22),Math.max(v12,v22)];let S3=Math.sqrt(T4),min=Math.min(v12,v22),max=Math.max(v12,v22),L3=v12-2*cp1+cp2;for(let R3=(L3+S3)/K3,i3=1;i3<=2;R3=(L3-S3)/K3,i3++)if(R3>0&&R3<1){let Q4=v12*(1-R3)*(1-R3)*(1-R3)+cp1*3*(1-R3)*(1-R3)*R3+cp2*3*(1-R3)*R3*R3+v22*R3*R3*R3;Q4<min&&(min=Q4),Q4>max&&(max=Q4)}return[min,max]},bezierTools={bezierLength,calculateBezier,CBEZIER_MINMAX_EPSILON,computeBezier,Cvalues,deriveBezier,getBezierLength,minmaxC,minmaxQ,Tvalues},getPointAtCubicSegmentLength=([x12,y12,c1x,c1y,c2x,c2y,x22,y22],t52)=>{let t110=1-t52;return{x:t110**3*x12+3*t110**2*t52*c1x+3*t110*t52**2*c2x+t52**3*x22,y:t110**3*y12+3*t110**2*t52*c1y+3*t110*t52**2*c2y+t52**3*y22}},getCubicLength=(x12,y12,c1x,c1y,c2x,c2y,x22,y22)=>getBezierLength([x12,y12,c1x,c1y,c2x,c2y,x22,y22]),getPointAtCubicLength=(x12,y12,c1x,c1y,c2x,c2y,x22,y22,distance8)=>{let distanceIsNumber=typeof distance8=="number",point7={x:x12,y:y12};if(distanceIsNumber){let currentLength=getBezierLength([x12,y12,c1x,c1y,c2x,c2y,x22,y22]);distance8<=0||(distance8>=currentLength?point7={x:x22,y:y22}:point7=getPointAtCubicSegmentLength([x12,y12,c1x,c1y,c2x,c2y,x22,y22],distance8/currentLength))}return point7},getCubicBBox=(x12,y12,c1x,c1y,c2x,c2y,x22,y22)=>{let cxMinMax=minmaxC([x12,c1x,c2x,x22]),cyMinMax=minmaxC([y12,c1y,c2y,y22]);return[cxMinMax[0],cyMinMax[0],cxMinMax[1],cyMinMax[1]]},cubicTools={getCubicBBox,getCubicLength,getPointAtCubicLength,getPointAtCubicSegmentLength},getPointAtQuadSegmentLength=([x12,y12,cx3,cy3,x22,y22],t52)=>{let t110=1-t52;return{x:t110**2*x12+2*t110*t52*cx3+t52**2*x22,y:t110**2*y12+2*t110*t52*cy3+t52**2*y22}},getQuadLength=(x12,y12,cx3,cy3,x22,y22)=>getBezierLength([x12,y12,cx3,cy3,x22,y22]),getPointAtQuadLength=(x12,y12,cx3,cy3,x22,y22,distance8)=>{let distanceIsNumber=typeof distance8=="number",point7={x:x12,y:y12};if(distanceIsNumber){let currentLength=getBezierLength([x12,y12,cx3,cy3,x22,y22]);distance8<=0||(distance8>=currentLength?point7={x:x22,y:y22}:point7=getPointAtQuadSegmentLength([x12,y12,cx3,cy3,x22,y22],distance8/currentLength))}return point7},getQuadBBox=(x12,y12,cx3,cy3,x22,y22)=>{let cxMinMax=minmaxQ([x12,cx3,x22]),cyMinMax=minmaxQ([y12,cy3,y22]);return[cxMinMax[0],cyMinMax[0],cxMinMax[1],cyMinMax[1]]},quadTools={getPointAtQuadLength,getPointAtQuadSegmentLength,getQuadBBox,getQuadLength},polygonArea=polygon2=>{let n4=polygon2.length,i3=-1,a3,b3=polygon2[n4-1],area=0;for(;++i3<n4;)a3=b3,b3=polygon2[i3],area+=a3[1]*b3[0]-a3[0]*b3[1];return area/2},polygonLength=polygon2=>polygon2.reduce((length4,point7,i3)=>i3?length4+distanceSquareRoot(polygon2[i3-1],point7):0,0),polygonCentroid=polygon2=>{if(polygon2.length===0)return[0,0];let sumX=0,sumY=0;for(let[x4,y4]of polygon2)sumX+=x4,sumY+=y4;let count=polygon2.length;return[sumX/count,sumY/count]},polygonTools={polygonArea,polygonLength,polygonCentroid},rotateVector=(x4,y4,rad)=>{let{sin:sin6,cos:cos6}=Math;return{x:x4*cos6(rad)-y4*sin6(rad),y:x4*sin6(rad)+y4*cos6(rad)}},roundTo=(n4,round)=>{let pow=round>=1?10**round:1;return round>0?Math.round(n4*pow)/pow:Math.round(n4)},defaultOptions2={origin:[0,0,0],round:4},paramsCounts={a:7,c:6,h:1,l:2,m:2,r:4,q:4,s:4,t:2,v:1,z:0},finalizeSegment=path=>{let pathCommand=path.pathValue[path.segmentStart],relativeCommand=pathCommand.toLowerCase(),{data}=path;for(;data.length>=paramsCounts[relativeCommand]&&(relativeCommand==="m"&&data.length>2?(path.segments.push([pathCommand].concat(data.splice(0,2))),relativeCommand="l",pathCommand=pathCommand==="m"?"l":"L"):path.segments.push([pathCommand].concat(data.splice(0,paramsCounts[relativeCommand]))),!!paramsCounts[relativeCommand]););},error="SVGPathCommanderError",scanFlag=path=>{let{index,pathValue}=path,code=pathValue.charCodeAt(index);if(code===48){path.param=0,path.index+=1;return}if(code===49){path.param=1,path.index+=1;return}path.err=`${error}: invalid Arc flag "${pathValue[index]}", expecting 0 or 1 at index ${index}`},isDigit=code=>code>=48&&code<=57,invalidPathValue="Invalid path value",scanParam=path=>{let{max,pathValue,index:start}=path,index=start,zeroFirst=!1,hasCeiling=!1,hasDecimal=!1,hasDot=!1,ch3;if(index>=max){path.err=`${error}: ${invalidPathValue} at index ${index}, "pathValue" is missing param`;return}if(ch3=pathValue.charCodeAt(index),(ch3===43||ch3===45)&&(index+=1,ch3=pathValue.charCodeAt(index)),!isDigit(ch3)&&ch3!==46){path.err=`${error}: ${invalidPathValue} at index ${index}, "${pathValue[index]}" is not a number`;return}if(ch3!==46){if(zeroFirst=ch3===48,index+=1,ch3=pathValue.charCodeAt(index),zeroFirst&&index<max&&ch3&&isDigit(ch3)){path.err=`${error}: ${invalidPathValue} at index ${start}, "${pathValue[start]}" illegal number`;return}for(;index<max&&isDigit(pathValue.charCodeAt(index));)index+=1,hasCeiling=!0;ch3=pathValue.charCodeAt(index)}if(ch3===46){for(hasDot=!0,index+=1;isDigit(pathValue.charCodeAt(index));)index+=1,hasDecimal=!0;ch3=pathValue.charCodeAt(index)}if(ch3===101||ch3===69){if(hasDot&&!hasCeiling&&!hasDecimal){path.err=`${error}: ${invalidPathValue} at index ${index}, "${pathValue[index]}" invalid float exponent`;return}if(index+=1,ch3=pathValue.charCodeAt(index),(ch3===43||ch3===45)&&(index+=1),index<max&&isDigit(pathValue.charCodeAt(index)))for(;index<max&&isDigit(pathValue.charCodeAt(index));)index+=1;else{path.err=`${error}: ${invalidPathValue} at index ${index}, "${pathValue[index]}" invalid integer exponent`;return}}path.index=index,path.param=+path.pathValue.slice(start,index)},isSpace=ch3=>[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279,10,13,8232,8233,32,9,11,12,160].includes(ch3),skipSpaces=path=>{let{pathValue,max}=path;for(;path.index<max&&isSpace(pathValue.charCodeAt(path.index));)path.index+=1},isPathCommand=code=>{switch(code|32){case 109:case 122:case 108:case 104:case 118:case 99:case 115:case 113:case 116:case 97:return!0;default:return!1}},isDigitStart=code=>isDigit(code)||code===43||code===45||code===46,isArcCommand=code=>(code|32)===97,isMoveCommand=code=>{switch(code|32){case 109:case 77:return!0;default:return!1}},scanSegment=path=>{let{max,pathValue,index,segments}=path,cmdCode=pathValue.charCodeAt(index),reqParams=paramsCounts[pathValue[index].toLowerCase()];if(path.segmentStart=index,!isPathCommand(cmdCode)){path.err=`${error}: ${invalidPathValue} "${pathValue[index]}" is not a path command at index ${index}`;return}let lastSegment=segments[segments.length-1];if(!isMoveCommand(cmdCode)&&lastSegment?.[0]?.toLocaleLowerCase()==="z"){path.err=`${error}: ${invalidPathValue} "${pathValue[index]}" is not a MoveTo path command at index ${index}`;return}if(path.index+=1,skipSpaces(path),path.data=[],!reqParams){finalizeSegment(path);return}for(;;){for(let i3=reqParams;i3>0;i3-=1){if(isArcCommand(cmdCode)&&(i3===3||i3===4)?scanFlag(path):scanParam(path),path.err.length)return;path.data.push(path.param),skipSpaces(path),path.index<max&&pathValue.charCodeAt(path.index)===44&&(path.index+=1,skipSpaces(path))}if(path.index>=path.max||!isDigitStart(pathValue.charCodeAt(path.index)))break}finalizeSegment(path)},PathParser=class{constructor(pathString){this.segments=[],this.pathValue=pathString,this.max=pathString.length,this.index=0,this.param=0,this.segmentStart=0,this.data=[],this.err=""}},parsePathString=pathInput=>{if(typeof pathInput!="string")return pathInput.slice(0);let path=new PathParser(pathInput);for(skipSpaces(path);path.index<path.max&&!path.err.length;)scanSegment(path);if(!path.err.length)path.segments.length&&(path.segments[0][0]="M");else throw TypeError(path.err);return path.segments},absolutizeSegment=(segment2,index,lastX,lastY)=>{let[pathCommand]=segment2,absCommand=pathCommand.toUpperCase();if(index===0||absCommand===pathCommand)return segment2;if(absCommand==="A")return[absCommand,segment2[1],segment2[2],segment2[3],segment2[4],segment2[5],segment2[6]+lastX,segment2[7]+lastY];if(absCommand==="V")return[absCommand,segment2[1]+lastY];if(absCommand==="H")return[absCommand,segment2[1]+lastX];if(absCommand==="L")return[absCommand,segment2[1]+lastX,segment2[2]+lastY];{let absValues=[],seglen=segment2.length;for(let j4=1;j4<seglen;j4+=1)absValues.push(segment2[j4]+(j4%2?lastX:lastY));return[absCommand].concat(absValues)}},iterate=(path,iterator)=>{let x4=0,y4=0,mx3=0,my3=0,i3=0;for(;i3<path.length;){let segment2=path[i3],[pathCommand]=segment2,absCommand=pathCommand.toUpperCase(),isRelative=absCommand!==pathCommand,iteratorResult=iterator(segment2,i3,x4,y4);if(iteratorResult===!1)break;if(absCommand==="Z")x4=mx3,y4=my3;else if(absCommand==="H")x4=segment2[1]+(isRelative?x4:0);else if(absCommand==="V")y4=segment2[1]+(isRelative?y4:0);else{let segLen=segment2.length;x4=segment2[segLen-2]+(isRelative?x4:0),y4=segment2[segLen-1]+(isRelative?y4:0),absCommand==="M"&&(mx3=x4,my3=y4)}iteratorResult&&(path[i3]=iteratorResult),i3+=1}return path},pathToAbsolute=pathInput=>iterate(parsePathString(pathInput),absolutizeSegment),relativizeSegment=(segment2,index,lastX,lastY)=>{let[pathCommand]=segment2,relCommand=pathCommand.toLowerCase();if(index===0||pathCommand===relCommand)return segment2;if(relCommand==="a")return[relCommand,segment2[1],segment2[2],segment2[3],segment2[4],segment2[5],segment2[6]-lastX,segment2[7]-lastY];if(relCommand==="v")return[relCommand,segment2[1]-lastY];if(relCommand==="h")return[relCommand,segment2[1]-lastX];if(relCommand==="l")return[relCommand,segment2[1]-lastX,segment2[2]-lastY];{let relValues=[],seglen=segment2.length;for(let j4=1;j4<seglen;j4+=1)relValues.push(segment2[j4]-(j4%2?lastX:lastY));return[relCommand].concat(relValues)}},pathToRelative=pathInput=>iterate(parsePathString(pathInput),relativizeSegment),arcToCubic=(X12,Y12,RX,RY2,angle,LAF,SF,X22,Y22,recursive)=>{let x12=X12,y12=Y12,rx3=RX,ry3=RY2,x22=X22,y22=Y22,d120=Math.PI*120/180,rad=Math.PI/180*(+angle||0),res2=[],xy3,f12,f22,cx3,cy3;if(recursive)[f12,f22,cx3,cy3]=recursive;else{xy3=rotateVector(x12,y12,-rad),x12=xy3.x,y12=xy3.y,xy3=rotateVector(x22,y22,-rad),x22=xy3.x,y22=xy3.y;let x4=(x12-x22)/2,y4=(y12-y22)/2,h6=x4*x4/(rx3*rx3)+y4*y4/(ry3*ry3);h6>1&&(h6=Math.sqrt(h6),rx3*=h6,ry3*=h6);let rx22=rx3*rx3,ry22=ry3*ry3,k4=(LAF===SF?-1:1)*Math.sqrt(Math.abs((rx22*ry22-rx22*y4*y4-ry22*x4*x4)/(rx22*y4*y4+ry22*x4*x4)));cx3=k4*rx3*y4/ry3+(x12+x22)/2,cy3=k4*-ry3*x4/rx3+(y12+y22)/2,f12=Math.asin(((y12-cy3)/ry3*10**9>>0)/10**9),f22=Math.asin(((y22-cy3)/ry3*10**9>>0)/10**9),f12=x12<cx3?Math.PI-f12:f12,f22=x22<cx3?Math.PI-f22:f22,f12<0&&(f12=Math.PI*2+f12),f22<0&&(f22=Math.PI*2+f22),SF&&f12>f22&&(f12-=Math.PI*2),!SF&&f22>f12&&(f22-=Math.PI*2)}let df3=f22-f12;if(Math.abs(df3)>d120){let f2old=f22,x2old=x22,y2old=y22;f22=f12+d120*(SF&&f22>f12?1:-1),x22=cx3+rx3*Math.cos(f22),y22=cy3+ry3*Math.sin(f22),res2=arcToCubic(x22,y22,rx3,ry3,angle,0,SF,x2old,y2old,[f22,f2old,cx3,cy3])}df3=f22-f12;let c12=Math.cos(f12),s12=Math.sin(f12),c22=Math.cos(f22),s22=Math.sin(f22),t52=Math.tan(df3/4),hx3=4/3*rx3*t52,hy3=4/3*ry3*t52,m12=[x12,y12],m22=[x12+hx3*s12,y12-hy3*c12],m32=[x22+hx3*s22,y22-hy3*c22],m4=[x22,y22];if(m22[0]=2*m12[0]-m22[0],m22[1]=2*m12[1]-m22[1],recursive)return[m22[0],m22[1],m32[0],m32[1],m4[0],m4[1]].concat(res2);res2=[m22[0],m22[1],m32[0],m32[1],m4[0],m4[1]].concat(res2);let newres=[];for(let i3=0,ii3=res2.length;i3<ii3;i3+=1)newres[i3]=i3%2?rotateVector(res2[i3-1],res2[i3],rad).y:rotateVector(res2[i3],res2[i3+1],rad).x;return newres},quadToCubic=(x12,y12,qx3,qy3,x22,y22)=>{let r13=.3333333333333333,r23=2/3;return[r13*x12+r23*qx3,r13*y12+r23*qy3,r13*x22+r23*qx3,r13*y22+r23*qy3,x22,y22]},lineToCubic=(x12,y12,x22,y22)=>{let c12=midPoint([x12,y12],[x22,y22],.3333333333333333),c22=midPoint([x12,y12],[x22,y22],2/3);return[c12[0],c12[1],c22[0],c22[1],x22,y22]},segmentToCubic=(segment2,params)=>{let pathCommand=segment2[0],values=segment2.slice(1).map(Number),[x4,y4]=values,{x1:px1,y1:py1}=params;return"TQ".includes(pathCommand)||(params.qx=null,params.qy=null),pathCommand==="M"?(params.mx=x4,params.my=y4,params.x=x4,params.y=y4,segment2):pathCommand==="A"?["C"].concat(arcToCubic(px1,py1,values[0],values[1],values[2],values[3],values[4],values[5],values[6])):pathCommand==="Q"?(params.qx=x4,params.qy=y4,["C"].concat(quadToCubic(px1,py1,values[0],values[1],values[2],values[3]))):pathCommand==="L"?["C"].concat(lineToCubic(px1,py1,x4,y4)):pathCommand==="Z"?["C"].concat(lineToCubic(px1,py1,params.mx,params.my)):segment2},normalizeSegment=(segment2,params)=>{let[pathCommand]=segment2,absCommand=pathCommand.toUpperCase(),isRelative=pathCommand!==absCommand,{x1:px1,y1:py1,x2:px22,y2:py22,x:x4,y:y4}=params,values=segment2.slice(1),absValues=values.map((n4,j4)=>n4+(isRelative?j4%2?y4:x4:0));if("TQ".includes(absCommand)||(params.qx=null,params.qy=null),absCommand==="A")return absValues=values.slice(0,-2).concat(values[5]+(isRelative?x4:0),values[6]+(isRelative?y4:0)),["A"].concat(absValues);if(absCommand==="H")return["L",segment2[1]+(isRelative?x4:0),py1];if(absCommand==="V")return["L",px1,segment2[1]+(isRelative?y4:0)];if(absCommand==="L")return["L",segment2[1]+(isRelative?x4:0),segment2[2]+(isRelative?y4:0)];if(absCommand==="M")return["M",segment2[1]+(isRelative?x4:0),segment2[2]+(isRelative?y4:0)];if(absCommand==="C")return["C"].concat(absValues);if(absCommand==="S"){let x12=px1*2-px22,y12=py1*2-py22;return params.x1=x12,params.y1=y12,["C",x12,y12].concat(absValues)}else if(absCommand==="T"){let qx3=px1*2-(params.qx?params.qx:0),qy3=py1*2-(params.qy?params.qy:0);return params.qx=qx3,params.qy=qy3,["Q",qx3,qy3].concat(absValues)}else if(absCommand==="Q"){let[nqx,nqy]=absValues;return params.qx=nqx,params.qy=nqy,["Q"].concat(absValues)}else if(absCommand==="Z")return["Z"];return segment2},paramsParser={mx:0,my:0,x1:0,y1:0,x2:0,y2:0,x:0,y:0,qx:null,qy:null},pathToCurve=pathInput=>{let params={...paramsParser},path=parsePathString(pathInput);return iterate(path,(seg,index,lastX,lastY)=>{params.x=lastX,params.y=lastY;let normalSegment=normalizeSegment(seg,params);normalSegment[0]==="M"&&(params.mx=normalSegment[1],params.my=normalSegment[2]);let result=segmentToCubic(normalSegment,params);result[0]==="C"&&result.length>7&&(path.splice(index+1,0,["C"].concat(result.slice(7))),result=result.slice(0,7));let seglen=result.length;return params.x1=+result[seglen-2],params.y1=+result[seglen-1],params.x2=+result[seglen-4]||params.x1,params.y2=+result[seglen-3]||params.y1,result})},pathToString=(path,roundOption)=>{let pathLen=path.length,{round}=defaultOptions2,segment2=path[0],result="";round=roundOption==="off"||typeof roundOption=="number"&&roundOption>=0?roundOption:typeof round=="number"&&round>=0?round:"off";for(let i3=0;i3<pathLen;i3+=1){segment2=path[i3];let[pathCommand]=segment2,values=segment2.slice(1);if(result+=pathCommand,round==="off")result+=values.join(" ");else{let j4=0,valLen=values.length;for(;j4<valLen;)result+=roundTo(values[j4],round),j4!==valLen-1&&(result+=" "),j4+=1}}return result},getPathBBox=pathInput=>{if(!pathInput)return{x:0,y:0,width:0,height:0,x2:0,y2:0,cx:0,cy:0,cz:0};let path=parsePathString(pathInput),pathCommand="M",mx3=0,my3=0,{max,min}=Math,xMin=1/0,yMin=1/0,xMax=-1/0,yMax=-1/0,minX=0,minY=0,maxX=0,maxY=0,paramX1=0,paramY1=0,paramX2=0,paramY2=0,paramQX=0,paramQY=0;iterate(path,(seg,index,lastX,lastY)=>{[pathCommand]=seg;let absCommand=pathCommand.toUpperCase(),absoluteSegment=absCommand!==pathCommand?absolutizeSegment(seg,index,lastX,lastY):seg.slice(0),normalSegment=absCommand==="V"?["L",lastX,absoluteSegment[1]]:absCommand==="H"?["L",absoluteSegment[1],lastY]:absoluteSegment;if([pathCommand]=normalSegment,"TQ".includes(absCommand)||(paramQX=0,paramQY=0),pathCommand==="M")[,mx3,my3]=normalSegment,minX=mx3,minY=my3,maxX=mx3,maxY=my3;else if(pathCommand==="L")[minX,minY,maxX,maxY]=getLineBBox(lastX,lastY,normalSegment[1],normalSegment[2]);else if(pathCommand==="A")[minX,minY,maxX,maxY]=getArcBBox(lastX,lastY,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4],normalSegment[5],normalSegment[6],normalSegment[7]);else if(pathCommand==="S"){let cp1x=paramX1*2-paramX2,cp1y=paramY1*2-paramY2;[minX,minY,maxX,maxY]=getCubicBBox(lastX,lastY,cp1x,cp1y,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4])}else pathCommand==="C"?[minX,minY,maxX,maxY]=getCubicBBox(lastX,lastY,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4],normalSegment[5],normalSegment[6]):pathCommand==="T"?(paramQX=paramX1*2-paramQX,paramQY=paramY1*2-paramQY,[minX,minY,maxX,maxY]=getQuadBBox(lastX,lastY,paramQX,paramQY,normalSegment[1],normalSegment[2])):pathCommand==="Q"?(paramQX=normalSegment[1],paramQY=normalSegment[2],[minX,minY,maxX,maxY]=getQuadBBox(lastX,lastY,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4])):pathCommand==="Z"&&([minX,minY,maxX,maxY]=getLineBBox(lastX,lastY,mx3,my3));xMin=min(minX,xMin),yMin=min(minY,yMin),xMax=max(maxX,xMax),yMax=max(maxY,yMax),[paramX1,paramY1]=pathCommand==="Z"?[mx3,my3]:normalSegment.slice(-2),[paramX2,paramY2]=pathCommand==="C"?[normalSegment[3],normalSegment[4]]:pathCommand==="S"?[normalSegment[1],normalSegment[2]]:[paramX1,paramY1]});let width=xMax-xMin,height=yMax-yMin;return{width,height,x:xMin,y:yMin,x2:xMax,y2:yMax,cx:xMin+width/2,cy:yMin+height/2,cz:Math.max(width,height)+Math.min(width,height)/2}},getTotalLength=pathInput=>{let path=parsePathString(pathInput),paramX1=0,paramY1=0,paramX2=0,paramY2=0,paramQX=0,paramQY=0,pathCommand="M",mx3=0,my3=0,totalLength=0;return iterate(path,(seg,index,lastX,lastY)=>{[pathCommand]=seg;let absCommand=pathCommand.toUpperCase(),absoluteSegment=absCommand!==pathCommand?absolutizeSegment(seg,index,lastX,lastY):seg.slice(0),normalSegment=absCommand==="V"?["L",lastX,absoluteSegment[1]]:absCommand==="H"?["L",absoluteSegment[1],lastY]:absoluteSegment;if([pathCommand]=normalSegment,"TQ".includes(absCommand)||(paramQX=0,paramQY=0),pathCommand==="M")[,mx3,my3]=normalSegment;else if(pathCommand==="L")totalLength+=getLineLength(lastX,lastY,normalSegment[1],normalSegment[2]);else if(pathCommand==="A")totalLength+=getArcLength(lastX,lastY,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4],normalSegment[5],normalSegment[6],normalSegment[7]);else if(pathCommand==="S"){let cp1x=paramX1*2-paramX2,cp1y=paramY1*2-paramY2;totalLength+=getCubicLength(lastX,lastY,cp1x,cp1y,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4])}else pathCommand==="C"?totalLength+=getCubicLength(lastX,lastY,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4],normalSegment[5],normalSegment[6]):pathCommand==="T"?(paramQX=paramX1*2-paramQX,paramQY=paramY1*2-paramQY,totalLength+=getQuadLength(lastX,lastY,paramQX,paramQY,normalSegment[1],normalSegment[2])):pathCommand==="Q"?(paramQX=normalSegment[1],paramQY=normalSegment[2],totalLength+=getQuadLength(lastX,lastY,normalSegment[1],normalSegment[2],normalSegment[3],normalSegment[4])):pathCommand==="Z"&&(totalLength+=getLineLength(lastX,lastY,mx3,my3));[paramX1,paramY1]=pathCommand==="Z"?[mx3,my3]:normalSegment.slice(-2),[paramX2,paramY2]=pathCommand==="C"?[normalSegment[3],normalSegment[4]]:pathCommand==="S"?[normalSegment[1],normalSegment[2]]:[paramX1,paramY1]}),totalLength},DISTANCE_EPSILON=1e-5,normalizePath=pathInput=>{let path=parsePathString(pathInput),params={...paramsParser};return iterate(path,(seg,_4,lastX,lastY)=>{params.x=lastX,params.y=lastY;let result=normalizeSegment(seg,params),seglen=result.length;return params.x1=+result[seglen-2],params.y1=+result[seglen-1],params.x2=+result[seglen-4]||params.x1,params.y2=+result[seglen-3]||params.y1,result})},getPointAtLength=(pathInput,distance8)=>{let path=normalizePath(pathInput),isM=!1,data=[],x4=0,y4=0,[mx3,my3]=path[0].slice(1),distanceIsNumber=typeof distance8=="number",point7={x:mx3,y:my3},length4=0,POINT=point7,totalLength=0;return!distanceIsNumber||distance8<1e-5?point7:(iterate(path,(seg,_4,lastX,lastY)=>{let pathCommand=seg[0];if(isM=pathCommand==="M",data=isM?data:[lastX,lastY].concat(seg.slice(1)),isM?([,mx3,my3]=seg,point7={x:mx3,y:my3},length4=0):pathCommand==="L"?(point7=getPointAtLineLength(data[0],data[1],data[2],data[3],distance8-totalLength),length4=getLineLength(data[0],data[1],data[2],data[3])):pathCommand==="A"?(point7=getPointAtArcLength(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7],data[8],distance8-totalLength),length4=getArcLength(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7],data[8])):pathCommand==="C"?(point7=getPointAtCubicLength(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7],distance8-totalLength),length4=getCubicLength(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7])):pathCommand==="Q"?(point7=getPointAtQuadLength(data[0],data[1],data[2],data[3],data[4],data[5],distance8-totalLength),length4=getQuadLength(data[0],data[1],data[2],data[3],data[4],data[5])):pathCommand==="Z"&&(data=[lastX,lastY,mx3,my3],point7={x:mx3,y:my3},length4=getLineLength(data[0],data[1],data[2],data[3])),[x4,y4]=data.slice(-2),totalLength<distance8)POINT=point7;else return!1;totalLength+=length4}),distance8>totalLength-1e-5?{x:x4,y:y4}:POINT)},getPropertiesAtLength=(pathInput,distance8)=>{let pathArray=parsePathString(pathInput),pathTemp=pathArray.slice(0),pathLength4=getTotalLength(pathTemp),index=pathTemp.length-1,lengthAtSegment=0,length4=0,segment2=pathArray[0];if(index<=0||!distance8||!Number.isFinite(distance8))return{segment:segment2,index:0,length:length4,lengthAtSegment};if(distance8>=pathLength4)return pathTemp=pathArray.slice(0,-1),lengthAtSegment=getTotalLength(pathTemp),length4=pathLength4-lengthAtSegment,segment2=pathArray[index],{segment:segment2,index,length:length4,lengthAtSegment};let segments=[];for(;index>0;)segment2=pathTemp[index],pathTemp=pathTemp.slice(0,-1),lengthAtSegment=getTotalLength(pathTemp),length4=pathLength4-lengthAtSegment,pathLength4=lengthAtSegment,segments.push({segment:segment2,index,length:length4,lengthAtSegment}),index-=1;return segments.find(({lengthAtSegment:l4})=>l4<=distance8)},getPropertiesAtPoint=(pathInput,point7)=>{let path=parsePathString(pathInput),normalPath=normalizePath(path),pathLength4=getTotalLength(normalPath),distanceTo=p4=>{let dx3=p4.x-point7.x,dy3=p4.y-point7.y;return dx3*dx3+dy3*dy3},precision=8,scan,closest={x:0,y:0},scanDistance=0,bestLength=0,bestDistance=1/0;for(let scanLength=0;scanLength<=pathLength4;scanLength+=precision)scan=getPointAtLength(normalPath,scanLength),scanDistance=distanceTo(scan),scanDistance<bestDistance&&(closest=scan,bestLength=scanLength,bestDistance=scanDistance);precision/=2;let before,after,beforeLength=0,afterLength=0,beforeDistance=0,afterDistance=0;for(;precision>1e-6&&(beforeLength=bestLength-precision,before=getPointAtLength(normalPath,beforeLength),beforeDistance=distanceTo(before),afterLength=bestLength+precision,after=getPointAtLength(normalPath,afterLength),afterDistance=distanceTo(after),beforeLength>=0&&beforeDistance<bestDistance?(closest=before,bestLength=beforeLength,bestDistance=beforeDistance):afterLength<=pathLength4&&afterDistance<bestDistance?(closest=after,bestLength=afterLength,bestDistance=afterDistance):precision/=2,!(precision<1e-5)););let segment2=getPropertiesAtLength(path,bestLength);return{closest,distance:Math.sqrt(bestDistance),segment:segment2}},getClosestPoint=(pathInput,point7)=>getPropertiesAtPoint(pathInput,point7).closest,getCubicSegArea=(x12,y12,c1x,c1y,c2x,c2y,x22,y22)=>3*((y22-y12)*(c1x+c2x)-(x22-x12)*(c1y+c2y)+c1y*(x12-c2x)-c1x*(y12-c2y)+y22*(c2x+x12/3)-x22*(c2y+y12/3))/20,getPathArea=path=>{let x4=0,y4=0,len=0;return pathToCurve(path).map(seg=>seg[0]==="M"?([,x4,y4]=seg,0):(len=getCubicSegArea(x4,y4,seg[1],seg[2],seg[3],seg[4],seg[5],seg[6]),[x4,y4]=seg.slice(-2),len)).reduce((a3,b3)=>a3+b3,0)},getDrawDirection=path=>getPathArea(pathToCurve(path))>=0,getSegmentAtLength=(pathInput,distance8)=>getPropertiesAtLength(pathInput,distance8).segment,getSegmentOfPoint=(path,point7)=>getPropertiesAtPoint(path,point7).segment,isPathArray=path=>Array.isArray(path)&&path.every(seg=>{let lk2=seg[0].toLowerCase();return paramsCounts[lk2]===seg.length-1&&"achlmqstvz".includes(lk2)&&seg.slice(1).every(Number.isFinite)})&&path.length>0,isAbsoluteArray=path=>isPathArray(path)&&path.every(([x4])=>x4===x4.toUpperCase()),isNormalizedArray=path=>isAbsoluteArray(path)&&path.every(([pc3])=>"ACLMQZ".includes(pc3)),isPolygonArray=path=>isNormalizedArray(path)&&path.every(([pc3])=>"MLVHZ".includes(pc3)),isCurveArray=path=>isNormalizedArray(path)&&path.every(([pc3])=>"MC".includes(pc3)),isPointInStroke=(pathInput,point7)=>{let{distance:distance8}=getPropertiesAtPoint(pathInput,point7);return Math.abs(distance8)<DISTANCE_EPSILON},isRelativeArray=path=>isPathArray(path)&&path.slice(1).every(([pc3])=>pc3===pc3.toLowerCase()),isValidPath=pathString=>{if(typeof pathString!="string"||!pathString.length)return!1;let path=new PathParser(pathString);for(skipSpaces(path);path.index<path.max&&!path.err.length;)scanSegment(path);return!path.err.length&&"mM".includes(path.segments[0][0])};function samplePolygon(path){let points=[],[mx3,my3]=[0,0];return iterate(path,seg=>{let cmd=seg[0];if(cmd==="M")[mx3,my3]=[seg[1],seg[2]],points.push([mx3,my3]);else if(cmd==="L")points.push([seg[1],seg[2]]);else if(cmd==="C")points.push([seg[5],seg[6]]);else if(cmd==="A")points.push([seg[6],seg[7]]);else if(cmd==="Z")points.push([mx3,my3]);else throw new TypeError(`${error}: path command "${cmd}" is not supported`)}),points}var shapeParams={line:["x1","y1","x2","y2"],circle:["cx","cy","r"],ellipse:["cx","cy","rx","ry"],rect:["width","height","x","y","rx","ry"],polygon:["points"],polyline:["points"],glyph:["d"]},isElement=node=>node!=null&&typeof node=="object"&&node.nodeType===1,getLinePath=attr=>{let{x1:x12,y1:y12,x2:x22,y2:y22}=attr;return[x12,y12,x22,y22]=[x12,y12,x22,y22].map(a3=>+a3),[["M",x12,y12],["L",x22,y22]]},getPolyPath=attr=>{let pathArray=[],points=(attr.points||"").trim().split(/[\s|,]/).map(a3=>+a3),index=0;for(;index<points.length;)pathArray.push([index?"L":"M",points[index],points[index+1]]),index+=2;return attr.type==="polygon"?[...pathArray,["z"]]:pathArray},getCirclePath=attr=>{let{cx:cx3,cy:cy3,r:r5}=attr;return[cx3,cy3,r5]=[cx3,cy3,r5].map(a3=>+a3),[["M",cx3-r5,cy3],["a",r5,r5,0,1,0,2*r5,0],["a",r5,r5,0,1,0,-2*r5,0]]},getEllipsePath=attr=>{let{cx:cx3,cy:cy3}=attr,rx3=attr.rx||0,ry3=attr.ry||rx3;return[cx3,cy3,rx3,ry3]=[cx3,cy3,rx3,ry3].map(a3=>+a3),[["M",cx3-rx3,cy3],["a",rx3,ry3,0,1,0,2*rx3,0],["a",rx3,ry3,0,1,0,-2*rx3,0]]},getRectanglePath=attr=>{let x4=+attr.x||0,y4=+attr.y||0,w4=+attr.width,h6=+attr.height,rx3=+(attr.rx||0),ry3=+(attr.ry||rx3);return rx3||ry3?(rx3*2>w4&&(rx3-=(rx3*2-w4)/2),ry3*2>h6&&(ry3-=(ry3*2-h6)/2),[["M",x4+rx3,y4],["h",w4-rx3*2],["s",rx3,0,rx3,ry3],["v",h6-ry3*2],["s",0,ry3,-rx3,ry3],["h",-w4+rx3*2],["s",-rx3,0,-rx3,-ry3],["v",-h6+ry3*2],["s",0,-ry3,rx3,-ry3]]):[["M",x4,y4],["h",w4],["v",h6],["H",x4],["Z"]]},shapeToPathArray=element=>{let supportedShapes=Object.keys(shapeParams),targetIsElement=isElement(element),tagName=targetIsElement?element.tagName:null;if(tagName&&[...supportedShapes,"path"].every(s3=>tagName!==s3))throw TypeError(`${error}: "${tagName}" is not SVGElement`);let type=targetIsElement?tagName:element.type,shapeAttrs=shapeParams[type],config={type};targetIsElement?shapeAttrs.forEach(p4=>{config[p4]=element.getAttribute(p4)}):Object.assign(config,element);let pathArray=[];return type==="circle"?pathArray=getCirclePath(config):type==="ellipse"?pathArray=getEllipsePath(config):["polyline","polygon"].includes(type)?pathArray=getPolyPath(config):type==="rect"?pathArray=getRectanglePath(config):type==="line"?pathArray=getLinePath(config):["glyph","path"].includes(type)&&(pathArray=parsePathString(targetIsElement?element.getAttribute("d")||"":element.d||"")),isPathArray(pathArray)&&pathArray.length?pathArray:!1},shapeToPath=(element,replace,ownerDocument)=>{let doc=ownerDocument||document,supportedShapes=Object.keys(shapeParams),targetIsElement=isElement(element),tagName=targetIsElement?element.tagName:null;if(tagName==="path")throw TypeError(`${error}: "${tagName}" is already SVGPathElement`);if(tagName&&supportedShapes.every(s3=>tagName!==s3))throw TypeError(`${error}: "${tagName}" is not SVGElement`);let path=doc.createElementNS("http://www.w3.org/2000/svg","path"),type=targetIsElement?tagName:element.type,shapeAttrs=shapeParams[type],config={type},round=defaultOptions2.round,pathArray=shapeToPathArray(element),description=pathArray&&pathArray.length?pathToString(pathArray,round):"";if(targetIsElement){shapeAttrs.forEach(p4=>{config[p4]=element.getAttribute(p4)});for(let i3=0;i3<element.attributes.length;i3++){let attr=element.attributes[i3];attr&&!shapeAttrs.includes(attr.name)&&path.setAttribute(attr.name,attr.value)}}else Object.assign(config,element),Object.keys(config).forEach(k4=>{!shapeAttrs.includes(k4)&&k4!=="type"&&path.setAttribute(k4.replace(/[A-Z]/g,m4=>`-${m4.toLowerCase()}`),config[k4])});return isValidPath(description)?(path.setAttribute("d",description),replace&&targetIsElement&&(element.before(path,element),element.remove()),path):!1},isMultiPath=path=>{if(typeof path=="string"){let matches=path.match(/[Mm]/g);return matches?matches.length>1:!1}if(isPathArray(path)){let moveCount=0;for(let segment2 of path)if(segment2[0].toUpperCase()==="M"&&(moveCount++,moveCount>1))return!0;return!1}throw new TypeError(error+": expected string or PathArray")};function isPolylineArray(path){return isNormalizedArray(path)&&path.every(([pc3])=>"MLVH".includes(pc3))}var isClosedPath=path=>path[path.length-1][0].toUpperCase()==="Z",shortenSegment=(segment2,normalSegment,params,prevCommand)=>{let[pathCommand]=segment2,{round:defaultRound}=defaultOptions2,round=typeof defaultRound=="number"?defaultRound:4,normalValues=normalSegment.slice(1),{x1:x12,y1:y12,x2:x22,y2:y22,x:x4,y:y4}=params,[nx3,ny3]=normalValues.slice(-2),result=segment2;if("TQ".includes(pathCommand)||(params.qx=null,params.qy=null),pathCommand==="L"){if(roundTo(x4,round)===roundTo(nx3,round))return["V",ny3];if(roundTo(y4,round)===roundTo(ny3,round))return["H",nx3]}else if(pathCommand==="C"){let[nx1,ny1]=normalValues;if(params.x1=nx1,params.y1=ny1,"CS".includes(prevCommand)&&(roundTo(nx1,round)===roundTo(x12*2-x22,round)&&roundTo(ny1,round)===roundTo(y12*2-y22,round)||roundTo(x12,round)===roundTo(x22*2-x4,round)&&roundTo(y12,round)===roundTo(y22*2-y4,round)))return["S",normalValues[2],normalValues[3],normalValues[4],normalValues[5]]}else if(pathCommand==="Q"){let[qx3,qy3]=normalValues;if(params.qx=qx3,params.qy=qy3,"QT".includes(prevCommand)&&roundTo(qx3,round)===roundTo(x12*2-x22,round)&&roundTo(qy3,round)===roundTo(y12*2-y22,round))return["T",normalValues[2],normalValues[3]]}return result},roundSegment=(segment2,roundOption)=>{let values=segment2.slice(1).map(n4=>roundTo(n4,roundOption));return[segment2[0]].concat(values)},optimizePath=(pathInput,roundOption)=>{let path=pathToAbsolute(pathInput),round=typeof roundOption=="number"&&roundOption>=0?roundOption:2,optimParams={...paramsParser},allPathCommands=[],pathCommand="M",prevCommand="Z";return iterate(path,(seg,i3,lastX,lastY)=>{optimParams.x=lastX,optimParams.y=lastY;let normalizedSegment=normalizeSegment(seg,optimParams),result=seg;if(pathCommand=seg[0],allPathCommands[i3]=pathCommand,i3){prevCommand=allPathCommands[i3-1];let shortSegment=shortenSegment(seg,normalizedSegment,optimParams,prevCommand),absSegment=roundSegment(shortSegment,round),absString=absSegment.join(""),relSegment=roundSegment(relativizeSegment(shortSegment,i3,lastX,lastY),round),relString=relSegment.join("");result=absString.length<relString.length?absSegment:relSegment}let seglen=normalizedSegment.length;return optimParams.x1=+normalizedSegment[seglen-2],optimParams.y1=+normalizedSegment[seglen-1],optimParams.x2=+normalizedSegment[seglen-4]||optimParams.x1,optimParams.y2=+normalizedSegment[seglen-3]||optimParams.y1,result})},reversePath=pathInput=>{let absolutePath=pathToAbsolute(pathInput),normalizedPath=normalizePath(absolutePath),pLen=absolutePath.length,isClosed=absolutePath[pLen-1][0]==="Z",reversedPath=iterate(absolutePath,(segment2,i3)=>{let normalizedSegment=normalizedPath[i3],prevSeg=i3&&absolutePath[i3-1],prevCommand=prevSeg&&prevSeg[0],nextSeg=absolutePath[i3+1],nextCommand=nextSeg&&nextSeg[0],pathCommand=segment2[0],[x4,y4]=normalizedPath[i3?i3-1:pLen-1].slice(-2),result=segment2;switch(pathCommand){case"M":result=isClosed?["Z"]:[pathCommand,x4,y4];break;case"A":result=[pathCommand,segment2[1],segment2[2],segment2[3],segment2[4],segment2[5]===1?0:1,x4,y4];break;case"C":nextSeg&&nextCommand==="S"?result=["S",segment2[1],segment2[2],x4,y4]:result=[pathCommand,segment2[3],segment2[4],segment2[1],segment2[2],x4,y4];break;case"S":prevCommand&&"CS".includes(prevCommand)&&(!nextSeg||nextCommand!=="S")?result=["C",normalizedSegment[3],normalizedSegment[4],normalizedSegment[1],normalizedSegment[2],x4,y4]:result=[pathCommand,normalizedSegment[1],normalizedSegment[2],x4,y4];break;case"Q":nextSeg&&nextCommand==="T"?result=["T",x4,y4]:result=[pathCommand,segment2[1],segment2[2],x4,y4];break;case"T":prevCommand&&"QT".includes(prevCommand)&&(!nextSeg||nextCommand!=="T")?result=["Q",normalizedSegment[1],normalizedSegment[2],x4,y4]:result=[pathCommand,x4,y4];break;case"Z":result=["M",x4,y4];break;case"H":result=[pathCommand,x4];break;case"V":result=[pathCommand,y4];break;default:result=[pathCommand].concat(segment2.slice(1,-2),x4,y4)}return result});return isClosed?reversedPath.reverse():[reversedPath[0]].concat(reversedPath.slice(1).reverse())},splitPath=pathInput=>{let composite=[],parsedPath=parsePathString(pathInput),path=[],pi3=-1,x4=0,y4=0,mx3=0,my3=0;return iterate(parsedPath,(seg,_4,prevX,prevY)=>{let cmd=seg[0],absCommand=cmd.toUpperCase(),isRelative=cmd===cmd.toLowerCase(),values=seg.slice(1);absCommand==="M"?(pi3+=1,[x4,y4]=values,x4+=isRelative?prevX:0,y4+=isRelative?prevY:0,mx3=x4,my3=y4,path=[isRelative?[absCommand,mx3,my3]:seg]):(absCommand==="Z"?(x4=mx3,y4=my3):absCommand==="H"?([,x4]=seg,x4+=isRelative?prevX:0):absCommand==="V"?([,y4]=seg,y4+=isRelative?prevY:0):([x4,y4]=seg.slice(-2),x4+=isRelative?prevX:0,y4+=isRelative?prevY:0),path.push(seg)),composite[pi3]=path}),composite},getSVGMatrix=transform6=>{let matrix2=new h,{origin}=transform6,[originX,originY]=origin,{translate:translate5}=transform6,{rotate:rotate4}=transform6,{skew}=transform6,{scale:scale5}=transform6;return Array.isArray(translate5)&&translate5.length>=2&&translate5.every(x4=>!Number.isNaN(+x4))&&translate5.some(x4=>x4!==0)?matrix2=matrix2.translate(...translate5):typeof translate5=="number"&&!Number.isNaN(translate5)&&(matrix2=matrix2.translate(translate5)),(rotate4||skew||scale5)&&(matrix2=matrix2.translate(originX,originY),Array.isArray(rotate4)&&rotate4.length>=2&&rotate4.every(x4=>!Number.isNaN(+x4))&&rotate4.some(x4=>x4!==0)?matrix2=matrix2.rotate(...rotate4):typeof rotate4=="number"&&!Number.isNaN(rotate4)&&(matrix2=matrix2.rotate(rotate4)),Array.isArray(skew)&&skew.length===2&&skew.every(x4=>!Number.isNaN(+x4))&&skew.some(x4=>x4!==0)?(matrix2=skew[0]?matrix2.skewX(skew[0]):matrix2,matrix2=skew[1]?matrix2.skewY(skew[1]):matrix2):typeof skew=="number"&&!Number.isNaN(skew)&&(matrix2=matrix2.skewX(skew)),Array.isArray(scale5)&&scale5.length>=2&&scale5.every(x4=>!Number.isNaN(+x4))&&scale5.some(x4=>x4!==1)?matrix2=matrix2.scale(...scale5):typeof scale5=="number"&&!Number.isNaN(scale5)&&(matrix2=matrix2.scale(scale5)),matrix2=matrix2.translate(-originX,-originY)),matrix2},translatePoint=(cssm,v4)=>{let m4=h.Translate(v4[0],v4[1],v4[2]);return[,,,m4.m44]=v4,m4=cssm.multiply(m4),[m4.m41,m4.m42,m4.m43,m4.m44]},projection2d=(m4,point2D,origin)=>{let[originX,originY,originZ]=origin,[x4,y4,z4]=translatePoint(m4,[point2D[0],point2D[1],0,1]),relativePositionX=x4-originX,relativePositionY=y4-originY,relativePositionZ=z4-originZ;return[relativePositionX*(Math.abs(originZ)/Math.abs(relativePositionZ)||1)+originX,relativePositionY*(Math.abs(originZ)/Math.abs(relativePositionZ)||1)+originY]},transformPath=(pathInput,transform6)=>{let x4=0,y4=0,lx3=0,ly3=0,j4=0,jj2=0,path=parsePathString(pathInput),transformProps=transform6&&Object.keys(transform6);if(!transform6||transformProps&&!transformProps.length)return path.slice(0);transform6.origin||Object.assign(transform6,{origin:defaultOptions2.origin});let origin=transform6.origin,matrixInstance=getSVGMatrix(transform6);return matrixInstance.isIdentity?path.slice(0):iterate(path,(seg,index,lastX,lastY)=>{let[pathCommand]=seg,absCommand=pathCommand.toUpperCase(),absoluteSegment=absCommand!==pathCommand?absolutizeSegment(seg,index,lastX,lastY):seg.slice(0),result=absCommand==="A"?["C"].concat(arcToCubic(lastX,lastY,absoluteSegment[1],absoluteSegment[2],absoluteSegment[3],absoluteSegment[4],absoluteSegment[5],absoluteSegment[6],absoluteSegment[7])):absCommand==="V"?["L",lastX,absoluteSegment[1]]:absCommand==="H"?["L",absoluteSegment[1],lastY]:absoluteSegment;pathCommand=result[0];let isLongArc=pathCommand==="C"&&result.length>7,tempSegment=isLongArc?result.slice(0,7):result.slice(0);if(isLongArc&&(path.splice(index+1,0,["C"].concat(result.slice(7))),result=tempSegment),pathCommand==="L")[lx3,ly3]=projection2d(matrixInstance,[result[1],result[2]],origin),x4!==lx3&&y4!==ly3?result=["L",lx3,ly3]:y4===ly3?result=["H",lx3]:x4===lx3&&(result=["V",ly3]);else for(j4=1,jj2=result.length;j4<jj2;j4+=2)[lx3,ly3]=projection2d(matrixInstance,[+result[j4],+result[j4+1]],origin),result[j4]=lx3,result[j4+1]=ly3;return x4=lx3,y4=ly3,result})},reverseCurve=path=>{let rotatedCurve=path.slice(1).map((x4,i3,curveOnly)=>i3?curveOnly[i3-1].slice(-2).concat(x4.slice(1)):path[0].slice(1).concat(x4.slice(1))).map(x4=>x4.map((_4,i3)=>x4[x4.length-i3-2*(1-i3%2)])).reverse();return[["M"].concat(rotatedCurve[0].slice(0,2))].concat(rotatedCurve.map(x4=>["C"].concat(x4.slice(2))))},roundPath=(path,roundOption)=>{let{round}=defaultOptions2;return round=roundOption==="off"||typeof roundOption=="number"&&roundOption>=0?roundOption:typeof round=="number"&&round>=0?round:"off",round==="off"?path.slice(0):iterate(path,segment2=>roundSegment(segment2,round))},fixPath=pathInput=>{let pathArray=parsePathString(pathInput);if(isClosedPath(pathArray)){let normalArray=normalizePath(pathArray),length4=pathArray.length,segBeforeZ=length4-2,[mx3,my3]=normalArray[0].slice(1),[x4,y4]=normalArray[segBeforeZ].slice(-2);mx3===x4&&my3===y4&&pathArray.splice(length4-1,1)}};function splitCubicSegment(x12,y12,x22,y22,x32,y32,x4,y4,t52){let[px01,py01]=midPoint([x12,y12],[x22,y22],t52),[px12,py12]=midPoint([x22,y22],[x32,y32],t52),[px23,py23]=midPoint([x32,y32],[x4,y4],t52),[cx0,cy0]=midPoint([px01,py01],[px12,py12],t52),[cx1,cy1]=midPoint([px12,py12],[px23,py23],t52),[px3,py3]=midPoint([cx0,cy0],[cx1,cy1],t52);return[[x12,y12,px01,py01,cx0,cy0,px3,py3],[px3,py3,cx1,cy1,px23,py23,x4,y4]]}var pathToPolyline=path=>{let normal=normalizePath(path);if(!isPolygonArray(normal)&&!isPolylineArray(normal))throw TypeError(`${error}: pathValue is not a polyline/polygon`);if(!isClosedPath(normal))return normal;let result=[normal[0]],[mx3,my3]=normal[0].slice(1);for(let i3=1;i3<normal.length;i3++){let seg=normal[i3];seg[0].toUpperCase()==="Z"?result.push(["L",mx3,my3]):result.push(seg)}return result};function splitLineToCount(x12,y12,x22,y22,count){if(count<=1)return[[x12,y12,x22,y22]];let result=[],dx3=x22-x12,dy3=y22-y12,currentX=x12,currentY=y12,i3=0;for(;i3<count;){let t52=1/(count-i3),nextX=x12+t52*dx3,nextY=y12+t52*dy3;result.push([currentX,currentY,nextX,nextY]),currentX=nextX,currentY=nextY,i3++}return result}function getPathSplits(path,target){if(target<=1)throw new TypeError(`${error}: target must be >= 2`);let totalLength=getTotalLength(path);if(totalLength===0)return Array(path.length).fill(1);let idealSegLen=totalLength/target,isPoly=isPolylineArray(path),splits=[1],lengths=[0];iterate(path,(seg,i3,prevX,prevY)=>{if(i3>0){let[endX,endY]=seg.slice(-2),segLen=isPoly?getLineLength(prevX,prevY,endX,endY):getCubicLength(prevX,prevY,seg[1],seg[2],seg[3],seg[4],seg[5],seg[6]);lengths.push(segLen),splits.push(1)}});let totalAllocated=1;for(let i3=1;i3<lengths.length;i3++){let segLen=lengths[i3],desired=segLen>idealSegLen?Math.round(segLen/idealSegLen):1;splits[i3]=desired,totalAllocated+=desired}let diff=target-totalAllocated;if(diff!==0){let candidates=[];for(let i3=1;i3<lengths.length;i3++)lengths[i3]>0&&candidates.push([i3,lengths[i3]]);let cLen=candidates.length;if(diff<0){candidates.sort((a3,b3)=>a3[1]-b3[1]);for(let i3=0;i3<cLen;i3++){let idx=candidates[i3][0];if(splits[idx]>1&&candidates[i3][1]>0&&(splits[idx]--,diff++),diff===0)break;i3===cLen-1&&(i3=0)}}else if(diff>0){candidates.sort((a3,b3)=>b3[1]-a3[1]);for(let i3=0;i3<cLen;i3++){let idx=candidates[i3][0];if(candidates[i3][1]>0&&(splits[idx]++,diff--),diff===0)break;i3===cLen-1&&(i3=0)}}}return splits}function splitLinePathToCount(path,target){if(path.length<2||target<=1)return path;let splits=getPathSplits(path,target),totalAdded=0,newPath=[path[0]],pathLen=path.length,currentX=path[0][1],currentY=path[0][2];for(let i3=1;i3<pathLen;i3++){let[endX,endY]=path[i3].slice(1),count=splits[i3];if(count>=1){let subLines=splitLineToCount(currentX,currentY,endX,endY,count);for(let sub of subLines)newPath.push(["L",sub[2],sub[3]]),totalAdded++}currentX=endX,currentY=endY}return newPath.length!==target&&console.warn(`${error}: requested ${target} segments, got ${newPath.length}. Adjusted on last segment.`),newPath}function splitCubicToCount(x12,y12,x22,y22,x32,y32,x4,y4,count){if(count<=1)return[[x12,y12,x22,y22,x32,y32,x4,y4]];let result=[],cx1=x12,cy1=y12,cx22=x22,cy22=y22,cx3=x32,cy3=y32,cx4=x4,cy4=y4,i3=0;for(;i3<count;){let t52=1/(count-i3),[first,second]=splitCubicSegment(cx1,cy1,cx22,cy22,cx3,cy3,cx4,cy4,t52);result.push(first),[cx1,cy1,cx22,cy22,cx3,cy3,cx4,cy4]=second,i3++}return result}function splitCurvePathToCount(path,target){if(path.length<2||target<=1)return path;let splits=getPathSplits(path,target),totalAdded=0,newPath=[path[0]],pathLen=path.length,currentX=path[0][1],currentY=path[0][2];for(let i3=1;i3<pathLen;i3++){let seg=path[i3],[endX,endY]=seg.slice(-2),count=splits[i3];if(count>=1){let subs=splitCubicToCount(currentX,currentY,seg[1],seg[2],seg[3],seg[4],seg[5],seg[6],count);for(let sub of subs)newPath.push(["C",sub[2],sub[3],sub[4],sub[5],sub[6],sub[7]]),totalAdded++}currentX=endX,currentY=endY}return newPath.length!==target&&console.warn(`${error}: requested ${target} segments, got ${newPath.length}.`),newPath}function getRotations(a3){let pathLen=a3.length,pointCount=pathLen-1,path,result=[];for(let idx=0;idx<pathLen;idx++){path=[];for(let i3=0;i3<pathLen;i3++){let oldSegIdx=idx+i3,seg;if(i3===0||a3[oldSegIdx]&&a3[oldSegIdx][0]==="M"){seg=a3[oldSegIdx],path.push(["M",...seg.slice(-2)]);continue}oldSegIdx>=pathLen&&(oldSegIdx-=pointCount),path.push(a3[oldSegIdx])}result.push(path)}return result}function getRotatedPath(pathA,pathB,computedRotations){let rotations=computedRotations||getRotations(pathA);if(pathA.length!==pathB.length)throw new TypeError(error+": paths must have the same number of segments after equalization");let bestIndex=0,minDistanceSq=1/0;for(let ri3=0;ri3<rotations.length;ri3++){let rotation5=rotations[ri3],rLen=rotation5.length,sumDistSq=0;for(let i3=0;i3<rLen;i3++){let segA=rotation5[i3],segB=pathB[i3],endA=segA.slice(-2),endB=segB.slice(-2),dx3=endA[0]-endB[0],dy3=endA[1]-endB[1];sumDistSq+=dx3*dx3+dy3*dy3}sumDistSq<minDistanceSq&&(minDistanceSq=sumDistSq,bestIndex=ri3)}return rotations[bestIndex]}var equalizeSegmentsDefaults={mode:"auto",sampleSize:10,roundValues:4,reverse:!0,close:!1,target:void 0},equalizeSegments=(path1,path2,initialCfg={})=>{let{close,mode,reverse,roundValues,target:initialTarget}=Object.assign(equalizeSegmentsDefaults,initialCfg),p12=normalizePath(path1),p22=normalizePath(path2);fixPath(p12),fixPath(p22);let bothPoly=(isPolygonArray(p12)||isPolylineArray(p12))&&(isPolygonArray(p22)||isPolylineArray(p22));bothPoly&&mode==="auto"?(p12=pathToPolyline(p12),p22=pathToPolyline(p22)):(bothPoly=!1,p12=pathToCurve(p12),p22=pathToCurve(p22));let area1=polygonArea(samplePolygon(p12)),area2=polygonArea(samplePolygon(p22));reverse!==!1&&Math.sign(area1)!==Math.sign(area2)&&(p22=reversePath(p22));let segCount1=p12.length,segCount2=p22.length,minTarget=Math.max(segCount1,segCount2),target=minTarget;if(typeof initialTarget!="number"){let avgLen=(getTotalLength(p12)+getTotalLength(p22))/2,avgSegLen=avgLen/Math.max(segCount1,segCount2),idealSegCount=Math.max(minTarget,Math.round(avgLen/Math.max(avgSegLen,1)));target=Math.min(idealSegCount,Math.max(segCount1,segCount2)*3)}else initialTarget>=minTarget?target=initialTarget:console.warn('equalizeSegments "target" option: '+initialTarget+", expected >= "+minTarget);let equalP1=p12,equalP2=p22;return bothPoly?(equalP1=splitLinePathToCount(p12,target),equalP2=splitLinePathToCount(p22,target)):(equalP1=splitCurvePathToCount(p12,target),equalP2=splitCurvePathToCount(p22,target)),equalP2=getRotatedPath(equalP2,equalP1),typeof roundValues=="number"&&roundValues!==4&&(equalP1=roundPath(equalP1,roundValues),equalP2=roundPath(equalP2,roundValues)),close&&(equalP1.push(["Z"]),equalP2.push(["Z"])),[equalP1,equalP2]},isPointInsideBBox=(bbox,[x4,y4])=>{let[minX,minY,maxX,maxY]=bbox;return x4>=minX&&x4<=maxX&&y4>=minY&&y4<=maxY},boundingBoxIntersect=(a3,b3)=>{let[ax1,ay1,ax22,ay22]=a3,[bx1,by1,bx22,by22]=b3;return isPointInsideBBox(b3,[ax1,ay1])||isPointInsideBBox(b3,[ax22,ay1])||isPointInsideBBox(b3,[ax1,ay22])||isPointInsideBBox(b3,[ax22,ay22])||isPointInsideBBox(a3,[bx1,by1])||isPointInsideBBox(a3,[bx22,by1])||isPointInsideBBox(a3,[bx1,by22])||isPointInsideBBox(a3,[bx22,by22])||(ax1<bx22&&ax1>bx1||bx1<ax22&&bx1>ax1)&&(ay1<by22&&ay1>by1||by1<ay22&&by1>ay1)},createPlaceholder=([atx,aty])=>[["M",atx,aty],["L",atx+.001,aty],["L",atx+.001,aty+.001],["L",atx,aty+.001],["L",atx,aty],["Z"]];function getBestMatch(target,candidates){let targetBBox=target.bbox,potentialCandidates=[];for(let i3=0;i3<candidates.length;i3++){let{bbox,size:size3}=candidates[i3],dx3=targetBBox.cx-bbox.cx,dy3=targetBBox.cy-bbox.cy,centeredDistance=Math.sqrt(dx3*dx3+dy3*dy3),sizeDifference=Math.abs(target.size-size3)/Math.max(target.size,size3,1e-6),hasOverlap=isPointInsideBBox([targetBBox.x,targetBBox.y,targetBBox.x2,targetBBox.y2],[bbox.cx,bbox.cy])||isPointInsideBBox([bbox.x,bbox.y,bbox.x2,bbox.y2],[targetBBox.cx,targetBBox.cy]),boxIntersect=boundingBoxIntersect([targetBBox.x,targetBBox.y,targetBBox.x2,targetBBox.y2],[bbox.x,bbox.y,bbox.x2,bbox.y2]);potentialCandidates.push({index:i3,hasOverlap,boxIntersect,sizeDifference,centeredDistance})}let overlaping=potentialCandidates.filter(c4=>c4.hasOverlap&&c4.boxIntersect);if(overlaping.length>0){let best=overlaping[0];for(let i3=1;i3<overlaping.length;i3++)overlaping[i3].centeredDistance<best.centeredDistance&&(best=overlaping[i3]);return candidates.splice(best.index,1)[0]}return null}function matchPaths(fromPaths,toPaths){let pairs5=[];for(fromPaths.sort((a3,b3)=>b3.size-a3.size),toPaths.sort((a3,b3)=>b3.size-a3.size);fromPaths.length>0;){let from=fromPaths.shift(),bestTo=getBestMatch(from,toPaths);if(bestTo)pairs5.push([from.path,bestTo.path]);else{let fromCentroid=[from.bbox.cx,from.bbox.cy];pairs5.push([from.path,createPlaceholder(fromCentroid)])}}for(;toPaths.length>0;){let to3=toPaths.shift(),toCentroid=[to3.bbox.cx,to3.bbox.cy];pairs5.push([createPlaceholder(toCentroid),to3.path])}return pairs5}var classifyPaths=paths=>{let outers=[],inners=[];for(let path of paths){let signedArea3=polygonArea(samplePolygon(path)),bbox=getPathBBox(path),feature={isPoly:isPolygonArray(path)||isPolylineArray(path),size:bbox.width*bbox.height,path,signedArea:signedArea3,area:Math.abs(signedArea3),bbox};signedArea3>0?outers.push(feature):inners.push(feature)}return{outers,inners}},equalizePathsDefaults={mode:"auto",roundValues:4,close:!1,sampleSize:10},equalizePaths=(pathInput1,pathInput2,initialCfg={})=>{let cfg=Object.assign(equalizePathsDefaults,initialCfg),p12=normalizePath(pathInput1),p22=normalizePath(pathInput2),multi1=isMultiPath(p12),multi2=isMultiPath(p22);if(!multi1&&!multi2)return equalizeSegments(p12,p22,cfg);let globalArea1=polygonArea(samplePolygon(p12)),globalArea2=polygonArea(samplePolygon(p22)),path1=p12,path2=p22;Math.sign(globalArea1)<0&&(path1=reversePath(path1)),Math.sign(globalArea2)<0&&(path2=reversePath(path2));let multiPath1=splitPath(path1),multiPath2=splitPath(path2),{outers:outers1,inners:inners1}=classifyPaths(multiPath1),{outers:outers2,inners:inners2}=classifyPaths(multiPath2),outerPairs=matchPaths(outers1,outers2),innerPairs=matchPaths(inners1,inners2),equalizedPairs=[];for(let[from,to3]of[...outerPairs,...innerPairs]){let[eqFrom,eqTo]=equalizeSegments(from,to3,{...cfg,reverse:!1});equalizedPairs.push([eqFrom,eqTo])}return[equalizedPairs.map(p4=>p4[0]).flat(),equalizedPairs.map(p4=>p4[1]).flat()]},intersect2=(x12,y12,x22,y22,x32,y32,x4,y4)=>{if(Math.max(x12,x22)<Math.min(x32,x4)||Math.min(x12,x22)>Math.max(x32,x4)||Math.max(y12,y22)<Math.min(y32,y4)||Math.min(y12,y22)>Math.max(y32,y4))return;let nx3=(x12*y22-y12*x22)*(x32-x4)-(x12-x22)*(x32*y4-y32*x4),ny3=(x12*y22-y12*x22)*(y32-y4)-(y12-y22)*(x32*y4-y32*x4),denominator=(x12-x22)*(y32-y4)-(y12-y22)*(x32-x4);if(!denominator)return;let px3=nx3/denominator,py3=ny3/denominator,px22=roundTo(px3,2),py22=roundTo(py3,2);if(!(px22<roundTo(Math.min(x12,x22),2)||px22>roundTo(Math.max(x12,x22),2)||px22<roundTo(Math.min(x32,x4),2)||px22>roundTo(Math.max(x32,x4),2)||py22<roundTo(Math.min(y12,y22),2)||py22>roundTo(Math.max(y12,y22),2)||py22<roundTo(Math.min(y32,y4),2)||py22>roundTo(Math.max(y32,y4),2)))return{x:px3,y:py3}},interHelper=(bez1,bez2,config)=>{let bbox1=getCubicBBox(...bez1),bbox2=getCubicBBox(...bez2),{justCount,epsilon}=Object.assign({justCount:!0,epsilon:DISTANCE_EPSILON},config);if(!boundingBoxIntersect(bbox1,bbox2))return justCount?0:[];let l12=getCubicLength(...bez1),l22=getCubicLength(...bez2),n12=Math.max(l12/5>>0,1),n22=Math.max(l22/5>>0,1),points1=[],points2=[],xy3={},res2=justCount?0:[];for(let i3=0;i3<n12+1;i3++){let p4=getPointAtCubicLength(...bez1,i3/n12*l12);points1.push({x:p4.x,y:p4.y,t:i3/n12})}for(let i3=0;i3<n22+1;i3++){let p4=getPointAtCubicLength(...bez2,i3/n22*l22);points2.push({x:p4.x,y:p4.y,t:i3/n22})}for(let i3=0;i3<n12;i3++)for(let j4=0;j4<n22;j4++){let maxLimit=1+epsilon,di3=points1[i3],di1=points1[i3+1],dj2=points2[j4],dj1=points2[j4+1],ci3=Math.abs(di1.x-di3.x)<.001?"y":"x",cj2=Math.abs(dj1.x-dj2.x)<.001?"y":"x",is4=intersect2(di3.x,di3.y,di1.x,di1.y,dj2.x,dj2.y,dj1.x,dj1.y);if(is4){if(xy3[is4.x.toFixed(4)]==is4.y.toFixed(4))continue;xy3[is4.x.toFixed(4)]=is4.y.toFixed(4);let t110=di3.t+Math.abs((is4[ci3]-di3[ci3])/(di1[ci3]-di3[ci3]))*(di1.t-di3.t),t210=dj2.t+Math.abs((is4[cj2]-dj2[cj2])/(dj1[cj2]-dj2[cj2]))*(dj1.t-dj2.t);t110>=0&&t110<=maxLimit&&t210>=0&&t210<=maxLimit&&(justCount?res2++:res2.push({x:is4.x,y:is4.y,t1:Math.min(t110,1),t2:Math.min(t210,1)}))}}return res2},pathsIntersection=(pathInput1,pathInput2,justCount=!0)=>{let path1=pathToCurve(pathInput1),path2=pathToCurve(pathInput2),x12=0,y12=0,x22=0,y22=0,x1m=0,y1m=0,x2m=0,y2m=0,bez1=[x12,y12,x12,y12,x1m,y1m,x1m,y1m],bez2=[x22,y22,x22,y22,x2m,y2m,x2m,y2m],countResult=0,pointsResult=[],pathLen1=path1.length,pathLen2=path2.length;for(let i3=0;i3<pathLen1;i3++){let seg1=path1[i3];if(seg1[0]=="M")x12=seg1[1],y12=seg1[2],x1m=x12,y1m=y12;else{seg1[0]=="C"?(bez1=[x12,y12,seg1[1],seg1[2],seg1[3],seg1[4],seg1[5],seg1[6]],x12=bez1[6],y12=bez1[7]):(bez1=[x12,y12,x12,y12,x1m,y1m,x1m,y1m],x12=x1m,y12=y1m);for(let j4=0;j4<pathLen2;j4++){let seg2=path2[j4];seg2[0]=="M"?(x22=seg2[1],y22=seg2[2],x2m=x22,y2m=y22):seg2[0]=="C"&&(bez2=[x22,y22,seg2[1],seg2[2],seg2[3],seg2[4],seg2[5],seg2[6]],x22=bez2[6],y22=bez2[7]);let intr=interHelper(bez1,bez2,{justCount});justCount?countResult+=intr:pointsResult.push(...intr)}}}return justCount?countResult:pointsResult},_a4,SVGPathCommander=(_a4=class{constructor(pathValue,config){let instanceOptions=config||{},undefPath=typeof pathValue>"u";if(undefPath||!pathValue.length)throw TypeError(`${error}: "pathValue" is ${undefPath?"undefined":"empty"}`);this.segments=parsePathString(pathValue);let{round:roundOption,origin:originOption}=instanceOptions,round;Number.isInteger(roundOption)||roundOption==="off"?round=roundOption:round=defaultOptions2.round;let origin=defaultOptions2.origin;if(Array.isArray(originOption)&&originOption.length>=2){let[originX,originY,originZ]=originOption.map(Number);origin=[Number.isNaN(originX)?0:originX,Number.isNaN(originY)?0:originY,Number.isNaN(originZ)?0:originZ]}return this.round=round,this.origin=origin,this}get bbox(){return getPathBBox(this.segments)}get length(){return getTotalLength(this.segments)}getBBox(){return this.bbox}getTotalLength(){return this.length}getPointAtLength(length4){return getPointAtLength(this.segments,length4)}toAbsolute(){let{segments}=this;return this.segments=pathToAbsolute(segments),this}toRelative(){let{segments}=this;return this.segments=pathToRelative(segments),this}toCurve(){let{segments}=this;return this.segments=pathToCurve(segments),this}reverse(onlySubpath){let{segments}=this,split=splitPath(segments),subPath=split.length>1?split:!1,absoluteMultiPath=subPath?subPath.map((x4,i3)=>onlySubpath?i3?reversePath(x4):x4.slice(0):reversePath(x4)):segments.slice(0),path=[];return subPath?path=absoluteMultiPath.flat(1):path=onlySubpath?segments:reversePath(segments),this.segments=path.slice(0),this}normalize(){let{segments}=this;return this.segments=normalizePath(segments),this}optimize(){let{segments}=this;return this.segments=optimizePath(segments,this.round==="off"?2:this.round),this}transform(source){if(!source||typeof source!="object"||typeof source=="object"&&!["translate","rotate","skew","scale"].some(x4=>x4 in source))return this;let{segments,origin:[cx3,cy3,cz2]}=this,transform6={};for(let[k4,v4]of Object.entries(source))k4==="skew"&&Array.isArray(v4)||(k4==="rotate"||k4==="translate"||k4==="origin"||k4==="scale")&&Array.isArray(v4)?transform6[k4]=v4.map(Number):k4!=="origin"&&typeof Number(v4)=="number"&&(transform6[k4]=Number(v4));let{origin}=transform6;if(Array.isArray(origin)&&origin.length>=2){let[originX,originY,originZ]=origin.map(Number);transform6.origin=[Number.isNaN(originX)?cx3:originX,Number.isNaN(originY)?cy3:originY,originZ||cz2]}else transform6.origin=[cx3,cy3,cz2];return this.segments=transformPath(segments,transform6),this}flipX(){let{cx:cx3,cy:cy3}=this.bbox;return this.transform({rotate:[0,180,0],origin:[cx3,cy3,0]}),this}flipY(){let{cx:cx3,cy:cy3}=this.bbox;return this.transform({rotate:[180,0,0],origin:[cx3,cy3,0]}),this}toString(){return pathToString(this.segments,this.round)}dispose(){Object.keys(this).forEach(key=>delete this[key])}},__publicField(_a4,"options",defaultOptions2),__publicField(_a4,"CSSMatrix",h),__publicField(_a4,"arcTools",arcTools),__publicField(_a4,"bezierTools",bezierTools),__publicField(_a4,"cubicTools",cubicTools),__publicField(_a4,"lineTools",lineTools),__publicField(_a4,"polygonTools",polygonTools),__publicField(_a4,"quadTools",quadTools),__publicField(_a4,"pathToAbsolute",pathToAbsolute),__publicField(_a4,"pathToRelative",pathToRelative),__publicField(_a4,"pathToCurve",pathToCurve),__publicField(_a4,"pathToString",pathToString),__publicField(_a4,"distanceSquareRoot",distanceSquareRoot),__publicField(_a4,"midPoint",midPoint),__publicField(_a4,"rotateVector",rotateVector),__publicField(_a4,"roundTo",roundTo),__publicField(_a4,"parsePathString",parsePathString),__publicField(_a4,"finalizeSegment",finalizeSegment),__publicField(_a4,"invalidPathValue",invalidPathValue),__publicField(_a4,"isArcCommand",isArcCommand),__publicField(_a4,"isDigit",isDigit),__publicField(_a4,"isDigitStart",isDigitStart),__publicField(_a4,"isMoveCommand",isMoveCommand),__publicField(_a4,"isPathCommand",isPathCommand),__publicField(_a4,"isSpace",isSpace),__publicField(_a4,"paramsCount",paramsCounts),__publicField(_a4,"paramsParser",paramsParser),__publicField(_a4,"PathParser",PathParser),__publicField(_a4,"scanFlag",scanFlag),__publicField(_a4,"scanParam",scanParam),__publicField(_a4,"scanSegment",scanSegment),__publicField(_a4,"skipSpaces",skipSpaces),__publicField(_a4,"distanceEpsilon",DISTANCE_EPSILON),__publicField(_a4,"fixPath",fixPath),__publicField(_a4,"getClosestPoint",getClosestPoint),__publicField(_a4,"getDrawDirection",getDrawDirection),__publicField(_a4,"getPathArea",getPathArea),__publicField(_a4,"getPathBBox",getPathBBox),__publicField(_a4,"getPointAtLength",getPointAtLength),__publicField(_a4,"getPropertiesAtLength",getPropertiesAtLength),__publicField(_a4,"getPropertiesAtPoint",getPropertiesAtPoint),__publicField(_a4,"getSegmentAtLength",getSegmentAtLength),__publicField(_a4,"getSegmentOfPoint",getSegmentOfPoint),__publicField(_a4,"getTotalLength",getTotalLength),__publicField(_a4,"isAbsoluteArray",isAbsoluteArray),__publicField(_a4,"isCurveArray",isCurveArray),__publicField(_a4,"isPolygonArray",isPolygonArray),__publicField(_a4,"isNormalizedArray",isNormalizedArray),__publicField(_a4,"isPathArray",isPathArray),__publicField(_a4,"isPointInStroke",isPointInStroke),__publicField(_a4,"isRelativeArray",isRelativeArray),__publicField(_a4,"isValidPath",isValidPath),__publicField(_a4,"samplePolygon",samplePolygon),__publicField(_a4,"shapeParams",shapeParams),__publicField(_a4,"shapeToPath",shapeToPath),__publicField(_a4,"shapeToPathArray",shapeToPathArray),__publicField(_a4,"absolutizeSegment",absolutizeSegment),__publicField(_a4,"arcToCubic",arcToCubic),__publicField(_a4,"getSVGMatrix",getSVGMatrix),__publicField(_a4,"iterate",iterate),__publicField(_a4,"lineToCubic",lineToCubic),__publicField(_a4,"normalizePath",normalizePath),__publicField(_a4,"normalizeSegment",normalizeSegment),__publicField(_a4,"optimizePath",optimizePath),__publicField(_a4,"projection2d",projection2d),__publicField(_a4,"quadToCubic",quadToCubic),__publicField(_a4,"relativizeSegment",relativizeSegment),__publicField(_a4,"reverseCurve",reverseCurve),__publicField(_a4,"reversePath",reversePath),__publicField(_a4,"roundPath",roundPath),__publicField(_a4,"roundSegment",roundSegment),__publicField(_a4,"segmentToCubic",segmentToCubic),__publicField(_a4,"shortenSegment",shortenSegment),__publicField(_a4,"splitPath",splitPath),__publicField(_a4,"equalizePaths",equalizePaths),__publicField(_a4,"equalizeSegments",equalizeSegments),__publicField(_a4,"splitCubicSegment",splitCubicSegment),__publicField(_a4,"transformPath",transformPath),__publicField(_a4,"isPointInsideBBox",isPointInsideBBox),__publicField(_a4,"pathsIntersection",pathsIntersection),__publicField(_a4,"boundingBoxIntersect",boundingBoxIntersect),__publicField(_a4,"isMultiPath",isMultiPath),__publicField(_a4,"isClosedPath",isClosedPath),__publicField(_a4,"isPolylineArray",isPolylineArray),__publicField(_a4,"version",version),_a4),src_default=SVGPathCommander;init_dist();init_dist4();init_dist();var import_react2=__toESM(require_react(),1);init_dist4();init_zod();init_zod();init_dist();function createMap(){return new IndexedMap}var IndexedMap=class _IndexedMap{constructor(){__publicField(this,"index",{});__publicField(this,"array",[])}size(){return this.array.length}empty(){return this.array.length===0}itemAt(index){return this.array[index]}contains(key){return this.index[key.id()]!==void 0}find(key){let i3=this.index[key.id()];return i3===void 0?void 0:this.array[i3]}setDefault(key,factory){let i3=this.index[key.id()];if(i3===void 0){let pair=new Pair(key,factory());return this.index[key.id()]=this.array.length,this.array.push(pair),pair}else return this.array[i3]}insert(key,value){let pair=new Pair(key,value),i3=this.index[key.id()];return i3===void 0?(this.index[key.id()]=this.array.length,this.array.push(pair)):this.array[i3]=pair,pair}erase(key){let i3=this.index[key.id()];if(i3===void 0)return;this.index[key.id()]=void 0;let pair=this.array[i3],last=this.array.pop();return pair!==last&&(this.array[i3]=last,this.index[last.first.id()]=i3),pair}copy(){let copy=new _IndexedMap;for(let i3=0;i3<this.array.length;i3++){let pair=this.array[i3].copy();copy.array[i3]=pair,copy.index[pair.first.id()]=i3}return copy}},Pair=class _Pair{constructor(first,second){__publicField(this,"first");__publicField(this,"second");this.first=first,this.second=second}copy(){return new _Pair(this.first,this.second)}};var Variable=class{constructor(name=""){__publicField(this,"_name");__publicField(this,"_value",0);__publicField(this,"_context",null);__publicField(this,"_id",VarId++);this._name=name}id(){return this._id}name(){return this._name}setName(name){this._name=name}context(){return this._context}setContext(context){this._context=context}value(){return this._value}setValue(value){this._value=value}plus(value){return new Expression(this,value)}minus(value){return new Expression(this,typeof value=="number"?-value:[-1,value])}multiply(coefficient){return new Expression([coefficient,this])}divide(coefficient){return new Expression([1/coefficient,this])}toJSON(){return{name:this._name,value:this._value}}toString(){return this._context+"["+this._name+":"+this._value+"]"}},VarId=0;var Expression=class _Expression{constructor(){__publicField(this,"_terms");__publicField(this,"_constant");let parsed=parseArgs(arguments);this._terms=parsed.terms,this._constant=parsed.constant}terms(){return this._terms}constant(){return this._constant}value(){let result=this._constant;for(let i3=0,n4=this._terms.size();i3<n4;i3++){let pair=this._terms.itemAt(i3);result+=pair.first.value()*pair.second}return result}plus(value){return new _Expression(this,value)}minus(value){return new _Expression(this,typeof value=="number"?-value:[-1,value])}multiply(coefficient){return new _Expression([coefficient,this])}divide(coefficient){return new _Expression([1/coefficient,this])}isConstant(){return this._terms.size()==0}toString(){let result=this._terms.array.map(function(pair){return pair.second+"*"+pair.first.toString()}).join(" + ");return!this.isConstant()&&this._constant!==0&&(result+=" + "),result+=this._constant,result}};function parseArgs(args){let constant=0,factory=()=>0,terms=createMap();for(let i3=0,n4=args.length;i3<n4;++i3){let item=args[i3];if(typeof item=="number")constant+=item;else if(item instanceof Variable)terms.setDefault(item,factory).second+=1;else if(item instanceof Expression){constant+=item.constant();let terms2=item.terms();for(let j4=0,k4=terms2.size();j4<k4;j4++){let termPair=terms2.itemAt(j4);terms.setDefault(termPair.first,factory).second+=termPair.second}}else if(item instanceof Array){if(item.length!==2)throw new Error("array must have length 2");let value=item[0],value2=item[1];if(typeof value!="number")throw new Error("array item 0 must be a number");if(value2 instanceof Variable)terms.setDefault(value2,factory).second+=value;else if(value2 instanceof Expression){constant+=value2.constant()*value;let terms2=value2.terms();for(let j4=0,k4=terms2.size();j4<k4;j4++){let termPair=terms2.itemAt(j4);terms.setDefault(termPair.first,factory).second+=termPair.second*value}}else throw new Error("array item 1 must be a variable or expression")}else throw new Error("invalid Expression argument: "+item)}return{terms,constant}}var _Strength=class _Strength{static create(a3,b3,c4,w4=1){let result=0;return result+=Math.max(0,Math.min(1e3,a3*w4))*1e6,result+=Math.max(0,Math.min(1e3,b3*w4))*1e3,result+=Math.max(0,Math.min(1e3,c4*w4)),result}static clip(value){return Math.max(0,Math.min(_Strength.required,value))}};__publicField(_Strength,"required",_Strength.create(1e3,1e3,1e3)),__publicField(_Strength,"strong",_Strength.create(1,0,0)),__publicField(_Strength,"medium",_Strength.create(0,1,0)),__publicField(_Strength,"weak",_Strength.create(0,0,1));var Strength=_Strength;var Operator;(function(Operator2){Operator2[Operator2.Le=0]="Le",Operator2[Operator2.Ge=1]="Ge",Operator2[Operator2.Eq=2]="Eq"})(Operator||(Operator={}));var Constraint=class{constructor(expression,operator,rhs,strength=Strength.required){__publicField(this,"_expression");__publicField(this,"_operator");__publicField(this,"_strength");__publicField(this,"_id",CnId++);this._operator=operator,this._strength=Strength.clip(strength),rhs===void 0&&expression instanceof Expression?this._expression=expression:this._expression=expression.minus(rhs)}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()+")"}},CnId=0;var Solver=class{constructor(){__publicField(this,"maxIterations",1e3);__publicField(this,"_cnMap",createCnMap());__publicField(this,"_rowMap",createRowMap());__publicField(this,"_varMap",createVarMap());__publicField(this,"_editMap",createEditMap());__publicField(this,"_infeasibleRows",[]);__publicField(this,"_objective",new Row);__publicField(this,"_artificial",null);__publicField(this,"_idTick",0)}createConstraint(lhs,operator,rhs,strength=Strength.required){let cn3=new Constraint(lhs,operator,rhs,strength);return this.addConstraint(cn3),cn3}addConstraint(constraint){if(this._cnMap.find(constraint)!==void 0)throw new Error("duplicate constraint");let data=this._createRow(constraint),row=data.row,tag=data.tag,subject=this._chooseSubject(row,tag);if(subject.type()===SymbolType.Invalid&&row.allDummies())if(nearZero(row.constant()))subject=tag.marker;else throw new Error("unsatisfiable constraint");if(subject.type()===SymbolType.Invalid){if(!this._addWithArtificialVariable(row))throw new Error("unsatisfiable constraint")}else row.solveFor(subject),this._substitute(subject,row),this._rowMap.insert(subject,row);this._cnMap.insert(constraint,tag),this._optimize(this._objective)}removeConstraint(constraint){let cnPair=this._cnMap.erase(constraint);if(cnPair===void 0)throw new Error("unknown constraint");this._removeConstraintEffects(constraint,cnPair.second);let marker=cnPair.second.marker,rowPair=this._rowMap.erase(marker);if(rowPair===void 0){let leaving=this._getMarkerLeavingSymbol(marker);if(leaving.type()===SymbolType.Invalid)throw new Error("failed to find leaving row");rowPair=this._rowMap.erase(leaving),rowPair.second.solveForEx(leaving,marker),this._substitute(marker,rowPair.second)}this._optimize(this._objective)}hasConstraint(constraint){return this._cnMap.contains(constraint)}getConstraints(){return this._cnMap.array.map(({first})=>first)}addEditVariable(variable,strength){if(this._editMap.find(variable)!==void 0)throw new Error("duplicate edit variable");if(strength=Strength.clip(strength),strength===Strength.required)throw new Error("bad required strength");let expr=new Expression(variable),cn3=new Constraint(expr,Operator.Eq,void 0,strength);this.addConstraint(cn3);let info={tag:this._cnMap.find(cn3).second,constraint:cn3,constant:0};this._editMap.insert(variable,info)}removeEditVariable(variable){let editPair=this._editMap.erase(variable);if(editPair===void 0)throw new Error("unknown edit variable");this.removeConstraint(editPair.second.constraint)}hasEditVariable(variable){return this._editMap.contains(variable)}suggestValue(variable,value){let editPair=this._editMap.find(variable);if(editPair===void 0)throw new Error("unknown edit variable");let rows=this._rowMap,info=editPair.second,delta=value-info.constant;info.constant=value;let marker=info.tag.marker,rowPair=rows.find(marker);if(rowPair!==void 0){rowPair.second.add(-delta)<0&&this._infeasibleRows.push(marker),this._dualOptimize();return}let other=info.tag.other;if(rowPair=rows.find(other),rowPair!==void 0){rowPair.second.add(delta)<0&&this._infeasibleRows.push(other),this._dualOptimize();return}for(let i3=0,n4=rows.size();i3<n4;++i3){let rowPair2=rows.itemAt(i3),row=rowPair2.second,coeff=row.coefficientFor(marker);coeff!==0&&row.add(delta*coeff)<0&&rowPair2.first.type()!==SymbolType.External&&this._infeasibleRows.push(rowPair2.first)}this._dualOptimize()}updateVariables(){let vars=this._varMap,rows=this._rowMap;for(let i3=0,n4=vars.size();i3<n4;++i3){let pair=vars.itemAt(i3),rowPair=rows.find(pair.second);rowPair!==void 0?pair.first.setValue(rowPair.second.constant()):pair.first.setValue(0)}}_getVarSymbol(variable){let factory=()=>this._makeSymbol(SymbolType.External);return this._varMap.setDefault(variable,factory).second}_createRow(constraint){let expr=constraint.expression(),row=new Row(expr.constant()),terms=expr.terms();for(let i3=0,n4=terms.size();i3<n4;++i3){let termPair=terms.itemAt(i3);if(!nearZero(termPair.second)){let symbol=this._getVarSymbol(termPair.first),basicPair=this._rowMap.find(symbol);basicPair!==void 0?row.insertRow(basicPair.second,termPair.second):row.insertSymbol(symbol,termPair.second)}}let objective=this._objective,strength=constraint.strength(),tag={marker:INVALID_SYMBOL,other:INVALID_SYMBOL};switch(constraint.op()){case Operator.Le:case Operator.Ge:{let coeff=constraint.op()===Operator.Le?1:-1,slack=this._makeSymbol(SymbolType.Slack);if(tag.marker=slack,row.insertSymbol(slack,coeff),strength<Strength.required){let error2=this._makeSymbol(SymbolType.Error);tag.other=error2,row.insertSymbol(error2,-coeff),objective.insertSymbol(error2,strength)}break}case Operator.Eq:{if(strength<Strength.required){let errplus=this._makeSymbol(SymbolType.Error),errminus=this._makeSymbol(SymbolType.Error);tag.marker=errplus,tag.other=errminus,row.insertSymbol(errplus,-1),row.insertSymbol(errminus,1),objective.insertSymbol(errplus,strength),objective.insertSymbol(errminus,strength)}else{let dummy=this._makeSymbol(SymbolType.Dummy);tag.marker=dummy,row.insertSymbol(dummy)}break}}return row.constant()<0&&row.reverseSign(),{row,tag}}_chooseSubject(row,tag){let cells=row.cells();for(let i3=0,n4=cells.size();i3<n4;++i3){let pair=cells.itemAt(i3);if(pair.first.type()===SymbolType.External)return pair.first}let type=tag.marker.type();return(type===SymbolType.Slack||type===SymbolType.Error)&&row.coefficientFor(tag.marker)<0?tag.marker:(type=tag.other.type(),(type===SymbolType.Slack||type===SymbolType.Error)&&row.coefficientFor(tag.other)<0?tag.other:INVALID_SYMBOL)}_addWithArtificialVariable(row){let art=this._makeSymbol(SymbolType.Slack);this._rowMap.insert(art,row.copy()),this._artificial=row.copy(),this._optimize(this._artificial);let success=nearZero(this._artificial.constant());this._artificial=null;let pair=this._rowMap.erase(art);if(pair!==void 0){let basicRow=pair.second;if(basicRow.isConstant())return success;let entering=this._anyPivotableSymbol(basicRow);if(entering.type()===SymbolType.Invalid)return!1;basicRow.solveForEx(art,entering),this._substitute(entering,basicRow),this._rowMap.insert(entering,basicRow)}let rows=this._rowMap;for(let i3=0,n4=rows.size();i3<n4;++i3)rows.itemAt(i3).second.removeSymbol(art);return this._objective.removeSymbol(art),success}_substitute(symbol,row){let rows=this._rowMap;for(let i3=0,n4=rows.size();i3<n4;++i3){let pair=rows.itemAt(i3);pair.second.substitute(symbol,row),pair.second.constant()<0&&pair.first.type()!==SymbolType.External&&this._infeasibleRows.push(pair.first)}this._objective.substitute(symbol,row),this._artificial&&this._artificial.substitute(symbol,row)}_optimize(objective){let iterations=0;for(;iterations<this.maxIterations;){let entering=this._getEnteringSymbol(objective);if(entering.type()===SymbolType.Invalid)return;let leaving=this._getLeavingSymbol(entering);if(leaving.type()===SymbolType.Invalid)throw new Error("the objective is unbounded");let row=this._rowMap.erase(leaving).second;row.solveForEx(leaving,entering),this._substitute(entering,row),this._rowMap.insert(entering,row),iterations++}throw new Error("solver iterations exceeded")}_dualOptimize(){let rows=this._rowMap,infeasible=this._infeasibleRows;for(;infeasible.length!==0;){let leaving=infeasible.pop(),pair=rows.find(leaving);if(pair!==void 0&&pair.second.constant()<0){let entering=this._getDualEnteringSymbol(pair.second);if(entering.type()===SymbolType.Invalid)throw new Error("dual optimize failed");let row=pair.second;rows.erase(leaving),row.solveForEx(leaving,entering),this._substitute(entering,row),rows.insert(entering,row)}}}_getEnteringSymbol(objective){let cells=objective.cells();for(let i3=0,n4=cells.size();i3<n4;++i3){let pair=cells.itemAt(i3),symbol=pair.first;if(pair.second<0&&symbol.type()!==SymbolType.Dummy)return symbol}return INVALID_SYMBOL}_getDualEnteringSymbol(row){let ratio=Number.MAX_VALUE,entering=INVALID_SYMBOL,cells=row.cells();for(let i3=0,n4=cells.size();i3<n4;++i3){let pair=cells.itemAt(i3),symbol=pair.first,c4=pair.second;if(c4>0&&symbol.type()!==SymbolType.Dummy){let r5=this._objective.coefficientFor(symbol)/c4;r5<ratio&&(ratio=r5,entering=symbol)}}return entering}_getLeavingSymbol(entering){let ratio=Number.MAX_VALUE,found=INVALID_SYMBOL,rows=this._rowMap;for(let i3=0,n4=rows.size();i3<n4;++i3){let pair=rows.itemAt(i3),symbol=pair.first;if(symbol.type()!==SymbolType.External){let row=pair.second,temp=row.coefficientFor(entering);if(temp<0){let temp_ratio=-row.constant()/temp;temp_ratio<ratio&&(ratio=temp_ratio,found=symbol)}}}return found}_getMarkerLeavingSymbol(marker){let dmax=Number.MAX_VALUE,r12=dmax,r22=dmax,invalid=INVALID_SYMBOL,first=invalid,second=invalid,third=invalid,rows=this._rowMap;for(let i3=0,n4=rows.size();i3<n4;++i3){let pair=rows.itemAt(i3),row=pair.second,c4=row.coefficientFor(marker);if(c4===0)continue;let symbol=pair.first;if(symbol.type()===SymbolType.External)third=symbol;else if(c4<0){let r5=-row.constant()/c4;r5<r12&&(r12=r5,first=symbol)}else{let r5=row.constant()/c4;r5<r22&&(r22=r5,second=symbol)}}return first!==invalid?first:second!==invalid?second:third}_removeConstraintEffects(cn3,tag){tag.marker.type()===SymbolType.Error&&this._removeMarkerEffects(tag.marker,cn3.strength()),tag.other.type()===SymbolType.Error&&this._removeMarkerEffects(tag.other,cn3.strength())}_removeMarkerEffects(marker,strength){let pair=this._rowMap.find(marker);pair!==void 0?this._objective.insertRow(pair.second,-strength):this._objective.insertSymbol(marker,-strength)}_anyPivotableSymbol(row){let cells=row.cells();for(let i3=0,n4=cells.size();i3<n4;++i3){let pair=cells.itemAt(i3),type=pair.first.type();if(type===SymbolType.Slack||type===SymbolType.Error)return pair.first}return INVALID_SYMBOL}_makeSymbol(type){return new Symbol2(type,this._idTick++)}};function nearZero(value){let eps=1e-8;return value<0?-value<eps:value<eps}function createCnMap(){return createMap()}function createRowMap(){return createMap()}function createVarMap(){return createMap()}function createEditMap(){return createMap()}var SymbolType;(function(SymbolType2){SymbolType2[SymbolType2.Invalid=0]="Invalid",SymbolType2[SymbolType2.External=1]="External",SymbolType2[SymbolType2.Slack=2]="Slack",SymbolType2[SymbolType2.Error=3]="Error",SymbolType2[SymbolType2.Dummy=4]="Dummy"})(SymbolType||(SymbolType={}));var Symbol2=class{constructor(type,id2){__publicField(this,"_id");__publicField(this,"_type");this._id=id2,this._type=type}id(){return this._id}type(){return this._type}},INVALID_SYMBOL=new Symbol2(SymbolType.Invalid,-1),Row=class _Row{constructor(constant=0){__publicField(this,"_cellMap",createMap());__publicField(this,"_constant");this._constant=constant}cells(){return this._cellMap}constant(){return this._constant}isConstant(){return this._cellMap.empty()}allDummies(){let cells=this._cellMap;for(let i3=0,n4=cells.size();i3<n4;++i3)if(cells.itemAt(i3).first.type()!==SymbolType.Dummy)return!1;return!0}copy(){let theCopy=new _Row(this._constant);return theCopy._cellMap=this._cellMap.copy(),theCopy}add(value){return this._constant+=value}insertSymbol(symbol,coefficient=1){let pair=this._cellMap.setDefault(symbol,()=>0);nearZero(pair.second+=coefficient)&&this._cellMap.erase(symbol)}insertRow(other,coefficient=1){this._constant+=other._constant*coefficient;let cells=other._cellMap;for(let i3=0,n4=cells.size();i3<n4;++i3){let pair=cells.itemAt(i3);this.insertSymbol(pair.first,pair.second*coefficient)}}removeSymbol(symbol){this._cellMap.erase(symbol)}reverseSign(){this._constant=-this._constant;let cells=this._cellMap;for(let i3=0,n4=cells.size();i3<n4;++i3){let pair=cells.itemAt(i3);pair.second=-pair.second}}solveFor(symbol){let cells=this._cellMap,coeff=-1/cells.erase(symbol).second;this._constant*=coeff;for(let i3=0,n4=cells.size();i3<n4;++i3)cells.itemAt(i3).second*=coeff}solveForEx(lhs,rhs){this.insertSymbol(lhs,-1),this.solveFor(rhs)}coefficientFor(symbol){let pair=this._cellMap.find(symbol);return pair!==void 0?pair.second:0}substitute(symbol,row){let pair=this._cellMap.erase(symbol);pair!==void 0&&this.insertRow(row,pair.second)}};var import_debug9=__toESM(require_browser(),1);init_dist6();var import_react3=__toESM(require_react(),1);init_dist();var import_debug10=__toESM(require_browser(),1);init_dist6();init_dist();init_dist3();init_dist6();init_dist6();init_dist6();init_dist3();init_dist();init_dist6();init_dist6();init_src();init_dist6();init_dist3();init_dist6();init_dist3();init_dist6();init_dist3();init_dist3();init_dist6();init_dist6();init_dist3();init_dist6();init_dist6();init_dist3();init_dist6();init_dist6();init_dist3();init_dist6();init_dist3();init_dist6();init_dist6();init_dist6();init_dist6();init_dist6();init_dist3();function distance5(x12,y12,x22,y22){return Math.sqrt((x22-x12)**2+(y22-y12)**2)}var addStartAndEndPortIdsIfMissing=soup=>{let pcbPorts=soup.filter(item=>item.type==="pcb_port"),pcbSmtPads=soup.filter(item=>item.type==="pcb_smtpad"),pcbTraces=soup.filter(item=>item.type==="pcb_trace");function findPortIdOverlappingPoint(point7,options={}){let traceWidth=options.traceWidth||0,directPort=pcbPorts.find(port=>distance5(port.x,port.y,point7.x,point7.y)<.01);if(directPort)return directPort.pcb_port_id;if(options.isFirstOrLastPoint){let smtPad=pcbSmtPads.find(pad2=>{if(pad2.shape==="rect")return Math.abs(point7.x-pad2.x)<pad2.width/2+traceWidth/2&&Math.abs(point7.y-pad2.y)<pad2.height/2+traceWidth/2;if(pad2.shape==="circle")return distance5(point7.x,point7.y,pad2.x,pad2.y)<pad2.radius});if(smtPad)return smtPad.pcb_port_id??null}return null}for(let trace of pcbTraces)for(let index=0;index<trace.route.length;index++){let segment2=trace.route[index],isFirstOrLastPoint=index===0||index===trace.route.length-1;if(segment2.route_type==="wire"){if(!segment2.start_pcb_port_id&&index===0){let startPortId=findPortIdOverlappingPoint(segment2,{isFirstOrLastPoint,traceWidth:segment2.width});startPortId&&(segment2.start_pcb_port_id=startPortId)}if(!segment2.end_pcb_port_id&&index===trace.route.length-1){let endPortId=findPortIdOverlappingPoint(segment2,{isFirstOrLastPoint,traceWidth:segment2.width});endPortId&&(segment2.end_pcb_port_id=endPortId)}}}},CIRCUIT_JSON_ID_PATTERN=/\b(?:pcb|source|schematic|subcircuit)_[a-z0-9_]+\b/i,sanitizeReadableName=(candidate,id2,fallbackLabel)=>!candidate||candidate===id2||CIRCUIT_JSON_ID_PATTERN.test(candidate)?fallbackLabel:candidate,firstReadableName=(candidates,id2)=>{for(let candidate of candidates){let readableName=sanitizeReadableName(candidate,id2,"");if(readableName)return readableName}return""},getReadableNameForComponent=(circuitJson,pcbComponentId)=>sanitizeReadableName(getReadableNameForElement(circuitJson,pcbComponentId),pcbComponentId,"component"),getReadableNameForPort=(circuitJson,pcbPortId)=>{let pcbPort=circuitJson.find(element=>element.type==="pcb_port"&&element.pcb_port_id===pcbPortId);if(pcbPort?.type==="pcb_port"){let sourcePort=circuitJson.find(element=>element.type==="source_port"&&element.source_port_id===pcbPort.source_port_id),sourceComponent=sourcePort?.type==="source_port"?circuitJson.find(element=>element.type==="source_component"&&element.source_component_id===sourcePort.source_component_id):null,readableSourceComponentName=firstReadableName([sourceComponent?.type==="source_component"?sourceComponent.name:null],sourceComponent?.type==="source_component"?sourceComponent.source_component_id:""),readableSourcePortName=firstReadableName([sourcePort?.type==="source_port"?sourcePort.name:null,sourcePort?.type==="source_port"?sourcePort.pin_number?.toString():null,sourcePort?.type==="source_port"?sourcePort.port_hints?.[0]:null],sourcePort?.type==="source_port"?sourcePort.source_port_id:"");if(readableSourceComponentName&&readableSourcePortName)return`${readableSourceComponentName}.${readableSourcePortName}`;if(readableSourcePortName)return readableSourcePortName}return sanitizeReadableName(getReadableNameForPcbPort(circuitJson,pcbPortId)??getReadableNameForElement(circuitJson,pcbPortId),pcbPortId,"port")};var getReadableNameForElementId=(circuitJson,elementId)=>sanitizeReadableName(getReadableNameForElement(circuitJson,elementId),elementId,"element"),containsCircuitJsonId=message=>CIRCUIT_JSON_ID_PATTERN.test(message);function checkEachPcbPortConnectedToPcbTraces(circuitJson){addStartAndEndPortIdsIfMissing(circuitJson);let sourceTraces=circuitJson.filter(item=>item.type==="source_trace"),pcbPorts=circuitJson.filter(item=>item.type==="pcb_port"),errors=[],connectivityMap=getFullConnectivityMapFromCircuitJson(circuitJson),sourcePortToPcbPort=new Map;for(let pcbPort of pcbPorts)sourcePortToPcbPort.set(pcbPort.source_port_id,pcbPort);for(let sourceTrace of sourceTraces){let connectedSourcePortIds=sourceTrace.connected_source_port_ids;if(connectedSourcePortIds.length<2)continue;let pcbPortsInTrace=[],missingPcbPorts=[];for(let sourcePortId of connectedSourcePortIds){let pcbPort=sourcePortToPcbPort.get(sourcePortId);pcbPort?pcbPortsInTrace.push(pcbPort):missingPcbPorts.push(sourcePortId)}if(pcbPortsInTrace.length<2)continue;let firstPcbPort=pcbPortsInTrace[0],referenceNetId=connectivityMap.getNetConnectedToId(firstPcbPort.pcb_port_id);connectivityMap.getIdsConnectedToNet(referenceNetId).filter(id2=>circuitJson.some(element=>element.type==="pcb_trace"&&("pcb_trace_id"in element&&element.pcb_trace_id===id2||"route_id"in element&&element.route_id===id2))).length===0&&new Set(pcbPortsInTrace.map(p4=>p4.pcb_component_id)).size>1&&errors.push({type:"pcb_port_not_connected_error",message:`Ports [${pcbPortsInTrace.map(p4=>getReadableNameForPort(circuitJson,p4.pcb_port_id)).join(", ")}] are not connected together through the same net.`,error_type:"pcb_port_not_connected_error",pcb_port_ids:pcbPortsInTrace.map(p4=>p4.pcb_port_id),pcb_component_ids:pcbPortsInTrace.map(p4=>p4.pcb_component_id).filter(id2=>id2!==void 0),pcb_port_not_connected_error_id:`pcb_port_not_connected_error_trace_${sourceTrace.source_trace_id}`})}return errors}var SpatialObjectIndex=class{constructor({objects,getBounds:getBounds3,getId,CELL_SIZE}){__publicField(this,"buckets");__publicField(this,"objectsById");__publicField(this,"getBounds");__publicField(this,"getId");__publicField(this,"CELL_SIZE",.4);__publicField(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=getBounds3,this.getId=getId??(()=>this._getNextId()),this.CELL_SIZE=CELL_SIZE??this.CELL_SIZE;for(let obj of objects)this.addObject(obj)}_getNextId(){return`${this._idCounter++}`}addObject(obj){let bounds=this.getBounds(obj),spatialIndexId=this.getId(obj),objWithId={...obj,spatialIndexId};this.objectsById.set(spatialIndexId,objWithId);let minBucketX=Math.floor(bounds.minX/this.CELL_SIZE),minBucketY=Math.floor(bounds.minY/this.CELL_SIZE),maxBucketX=Math.floor(bounds.maxX/this.CELL_SIZE),maxBucketY=Math.floor(bounds.maxY/this.CELL_SIZE);for(let bx3=minBucketX;bx3<=maxBucketX;bx3++)for(let by3=minBucketY;by3<=maxBucketY;by3++){let bucketKey=`${bx3}x${by3}`,bucket=this.buckets.get(bucketKey);bucket?bucket.push(objWithId):this.buckets.set(bucketKey,[objWithId])}}removeObject(id2){let obj=this.objectsById.get(id2);if(!obj)return!1;this.objectsById.delete(id2);let bounds=this.getBounds(obj),minBucketX=Math.floor(bounds.minX/this.CELL_SIZE),minBucketY=Math.floor(bounds.minY/this.CELL_SIZE),maxBucketX=Math.floor(bounds.maxX/this.CELL_SIZE),maxBucketY=Math.floor(bounds.maxY/this.CELL_SIZE);for(let bx3=minBucketX;bx3<=maxBucketX;bx3++)for(let by3=minBucketY;by3<=maxBucketY;by3++){let bucketKey=`${bx3}x${by3}`,bucket=this.buckets.get(bucketKey);if(bucket){let index=bucket.findIndex(item=>item.spatialIndexId===id2);index!==-1&&(bucket.splice(index,1),bucket.length===0&&this.buckets.delete(bucketKey))}}return!0}getBucketKey(x4,y4){return`${Math.floor(x4/this.CELL_SIZE)}x${Math.floor(y4/this.CELL_SIZE)}`}getObjectsInBounds(bounds,margin=0){let objects=[],addedIds=new Set,minBucketX=Math.floor((bounds.minX-margin)/this.CELL_SIZE),minBucketY=Math.floor((bounds.minY-margin)/this.CELL_SIZE),maxBucketX=Math.floor((bounds.maxX+margin)/this.CELL_SIZE),maxBucketY=Math.floor((bounds.maxY+margin)/this.CELL_SIZE);for(let bx3=minBucketX;bx3<=maxBucketX;bx3++)for(let by3=minBucketY;by3<=maxBucketY;by3++){let bucketKey=`${bx3}x${by3}`,bucket=this.buckets.get(bucketKey)||[];for(let obj of bucket){let id2=obj.spatialIndexId;addedIds.has(id2)||(addedIds.add(id2),objects.push(obj))}}return objects}},jlcMinTolerances={min_trace_width:.1,min_via_hole_edge_to_via_hole_edge_clearance:.1,min_plated_hole_drill_edge_to_drill_edge_clearance:.15,min_trace_to_pad_edge_clearance:.1,min_pad_edge_to_pad_edge_clearance:.1,min_board_edge_clearance:.2,min_via_hole_diameter:.2,min_via_pad_diameter:.3},DEFAULT_TRACE_MARGIN=.1,DEFAULT_TRACE_THICKNESS=jlcMinTolerances.min_trace_width,DEFAULT_VIA_DIAMETER=jlcMinTolerances.min_via_pad_diameter,DEFAULT_VIA_BOARD_MARGIN=jlcMinTolerances.min_board_edge_clearance,DEFAULT_SAME_NET_VIA_MARGIN=jlcMinTolerances.min_via_hole_edge_to_via_hole_edge_clearance,DEFAULT_DIFFERENT_NET_VIA_MARGIN=jlcMinTolerances.min_via_hole_edge_to_via_hole_edge_clearance,DEFAULT_PAD_PAD_CLEARANCE=jlcMinTolerances.min_pad_edge_to_pad_edge_clearance,DEFAULT_PAD_TRACE_CLEARANCE=jlcMinTolerances.min_trace_to_pad_edge_clearance,EPSILON2=.005,getPcbBoard=circuitJson=>circuitJson.find(el3=>el3.type==="pcb_board"),getBoardDrcValue=(board,key)=>board?.[key];function getLayersOfPcbElement(obj){return obj.type==="pcb_trace_segment"?[obj.layer]:obj.type==="pcb_smtpad"?[obj.layer]:obj.type==="pcb_plated_hole"?Array.isArray(obj.layers)?obj.layers:[...all_layers]:obj.type==="pcb_hole"?[...all_layers]:obj.type==="pcb_via"?Array.isArray(obj.layers)?obj.layers:[...all_layers]:obj.type==="pcb_keepout"?Array.isArray(obj.layers)?obj.layers:[]:[]}var getClosestPointBetweenSegmentAndBounds=(segment2,bounds)=>{let p12={x:segment2.x1,y:segment2.y1},p22={x:segment2.x2,y:segment2.y2},minX=bounds.minX,minY=bounds.minY,maxX=bounds.maxX,maxY=bounds.maxY;if(p12.x===p22.x&&p12.y===p22.y){let closestX=Math.max(minX,Math.min(maxX,p12.x)),closestY=Math.max(minY,Math.min(maxY,p12.y));return closestX===p12.x&&closestY===p12.y?{x:p12.x,y:p12.y}:{x:closestX,y:closestY}}let dx3=p22.x-p12.x,dy3=p22.y-p12.y,tMinX=dx3!==0?(minX-p12.x)/dx3:Number.NEGATIVE_INFINITY,tMaxX=dx3!==0?(maxX-p12.x)/dx3:Number.POSITIVE_INFINITY,tMinY=dy3!==0?(minY-p12.y)/dy3:Number.NEGATIVE_INFINITY,tMaxY=dy3!==0?(maxY-p12.y)/dy3:Number.POSITIVE_INFINITY,tEnter=Math.max(Math.min(tMinX,tMaxX),Math.min(tMinY,tMaxY)),tExit=Math.min(Math.max(tMinX,tMaxX),Math.max(tMinY,tMaxY));if(tEnter<=tExit&&tExit>=0&&tEnter<=1){let t52=Math.max(0,Math.min(1,tEnter));return{x:p12.x+t52*dx3,y:p12.y+t52*dy3}}let closestToP1={x:Math.max(minX,Math.min(maxX,p12.x)),y:Math.max(minY,Math.min(maxY,p12.y))},closestToP2={x:Math.max(minX,Math.min(maxX,p22.x)),y:Math.max(minY,Math.min(maxY,p22.y))},distToP1Squared=(closestToP1.x-p12.x)**2+(closestToP1.y-p12.y)**2,distToP2Squared=(closestToP2.x-p22.x)**2+(closestToP2.y-p22.y)**2,edges=[{start:{x:minX,y:minY},end:{x:maxX,y:minY}},{start:{x:maxX,y:minY},end:{x:maxX,y:maxY}},{start:{x:maxX,y:maxY},end:{x:minX,y:maxY}},{start:{x:minX,y:maxY},end:{x:minX,y:minY}}],minDistance=Math.min(distToP1Squared,distToP2Squared),closestPoint=distToP1Squared<=distToP2Squared?closestToP1:closestToP2,clamp22=(value,min,max)=>Math.max(min,Math.min(max,value));for(let edge of edges){let va3={x:p22.x-p12.x,y:p22.y-p12.y},vb3={x:edge.end.x-edge.start.x,y:edge.end.y-edge.start.y},w4={x:p12.x-edge.start.x,y:p12.y-edge.start.y},dotAA=va3.x*va3.x+va3.y*va3.y,dotAB=va3.x*vb3.x+va3.y*vb3.y,dotAW=va3.x*w4.x+va3.y*w4.y,dotBB=vb3.x*vb3.x+vb3.y*vb3.y,dotBW=vb3.x*w4.x+vb3.y*w4.y,denominator=dotAA*dotBB-dotAB*dotAB;if(Math.abs(denominator)<1e-10)continue;let tA2=(dotAB*dotBW-dotBB*dotAW)/denominator,tB=(dotAA*dotBW-dotAB*dotAW)/denominator;tA2=clamp22(tA2,0,1),tB=clamp22(tB,0,1);let closestOnSegment={x:p12.x+tA2*va3.x,y:p12.y+tA2*va3.y},closestOnEdge={x:edge.start.x+tB*vb3.x,y:edge.start.y+tB*vb3.y},dx22=closestOnSegment.x-closestOnEdge.x,dy22=closestOnSegment.y-closestOnEdge.y,distSquared=dx22*dx22+dy22*dy22;distSquared<minDistance&&(minDistance=distSquared,closestPoint={x:(closestOnSegment.x+closestOnEdge.x)/2,y:(closestOnSegment.y+closestOnEdge.y)/2})}return closestPoint},getClosestPointBetweenSegments=(segmentA,segmentB)=>{let a12={x:segmentA.x1,y:segmentA.y1},a22={x:segmentA.x2,y:segmentA.y2},b12={x:segmentB.x1,y:segmentB.y1},b22={x:segmentB.x2,y:segmentB.y2},va3={x:a22.x-a12.x,y:a22.y-a12.y},vb3={x:b22.x-b12.x,y:b22.y-b12.y},lenSqrA=va3.x*va3.x+va3.y*va3.y,lenSqrB=vb3.x*vb3.x+vb3.y*vb3.y;if(lenSqrA===0||lenSqrB===0){if(lenSqrA===0&&lenSqrB===0)return{x:(a12.x+b12.x)/2,y:(a12.y+b12.y)/2};if(lenSqrA===0){let t210=clamp4(((a12.x-b12.x)*vb3.x+(a12.y-b12.y)*vb3.y)/lenSqrB,0,1),closestOnB2={x:b12.x+t210*vb3.x,y:b12.y+t210*vb3.y};return{x:(a12.x+closestOnB2.x)/2,y:(a12.y+closestOnB2.y)/2}}let t52=clamp4(((b12.x-a12.x)*va3.x+(b12.y-a12.y)*va3.y)/lenSqrA,0,1),closestOnA2={x:a12.x+t52*va3.x,y:a12.y+t52*va3.y};return{x:(closestOnA2.x+b12.x)/2,y:(closestOnA2.y+b12.y)/2}}let w4={x:a12.x-b12.x,y:a12.y-b12.y},dotAA=va3.x*va3.x+va3.y*va3.y,dotAB=va3.x*vb3.x+va3.y*vb3.y,dotAW=va3.x*w4.x+va3.y*w4.y,dotBB=vb3.x*vb3.x+vb3.y*vb3.y,dotBW=vb3.x*w4.x+vb3.y*w4.y,denominator=dotAA*dotBB-dotAB*dotAB;if(denominator<1e-10)return closestPointsParallelSegments(a12,a22,b12,b22,va3,vb3,lenSqrA,lenSqrB);let tA2=(dotAB*dotBW-dotBB*dotAW)/denominator,tB=(dotAA*dotBW-dotAB*dotAW)/denominator;tA2=clamp4(tA2,0,1),tB=clamp4(tB,0,1),tB=(tA2*dotAB+dotBW)/dotBB,tB=clamp4(tB,0,1),tA2=(tB*dotAB-dotAW)/dotAA,tA2=clamp4(tA2,0,1);let closestOnA={x:a12.x+tA2*va3.x,y:a12.y+tA2*va3.y},closestOnB={x:b12.x+tB*vb3.x,y:b12.y+tB*vb3.y},dx3=closestOnA.x-closestOnB.x,dy3=closestOnA.y-closestOnB.y,distance32=Math.sqrt(dx3*dx3+dy3*dy3);return{x:(closestOnA.x+closestOnB.x)/2,y:(closestOnA.y+closestOnB.y)/2}},closestPointsParallelSegments=(a12,a22,b12,b22,va3,vb3,lenSqrA,lenSqrB)=>{let tA2=((b12.x-a12.x)*va3.x+(b12.y-a12.y)*va3.y)/lenSqrA;tA2=clamp4(tA2,0,1);let pointOnA1={x:a12.x+tA2*va3.x,y:a12.y+tA2*va3.y},tA22=((b22.x-a12.x)*va3.x+(b22.y-a12.y)*va3.y)/lenSqrA;tA22=clamp4(tA22,0,1);let pointOnA2={x:a12.x+tA22*va3.x,y:a12.y+tA22*va3.y},tB=((a12.x-b12.x)*vb3.x+(a12.y-b12.y)*vb3.y)/lenSqrB;tB=clamp4(tB,0,1);let pointOnB1={x:b12.x+tB*vb3.x,y:b12.y+tB*vb3.y},tB2=((a22.x-b12.x)*vb3.x+(a22.y-b12.y)*vb3.y)/lenSqrB;tB2=clamp4(tB2,0,1);let pointOnB2={x:b12.x+tB2*vb3.x,y:b12.y+tB2*vb3.y},closestPair=[{pointA:pointOnA1,pointB:b12,distance:Math.sqrt((pointOnA1.x-b12.x)**2+(pointOnA1.y-b12.y)**2)},{pointA:pointOnA2,pointB:b22,distance:Math.sqrt((pointOnA2.x-b22.x)**2+(pointOnA2.y-b22.y)**2)},{pointA:a12,pointB:pointOnB1,distance:Math.sqrt((a12.x-pointOnB1.x)**2+(a12.y-pointOnB1.y)**2)},{pointA:a22,pointB:pointOnB2,distance:Math.sqrt((a22.x-pointOnB2.x)**2+(a22.y-pointOnB2.y)**2)}].reduce((closest,current3)=>current3.distance<closest.distance?current3:closest);return{x:(closestPair.pointA.x+closestPair.pointB.x)/2,y:(closestPair.pointA.y+closestPair.pointB.y)/2}},clamp4=(value,min,max)=>Math.max(min,Math.min(max,value)),rotatePoint=(point7,angleDegrees)=>{let angle=angleDegrees*Math.PI/180;return{x:point7.x*Math.cos(angle)-point7.y*Math.sin(angle),y:point7.x*Math.sin(angle)+point7.y*Math.cos(angle)}},getRotatedRectPoints=({x:x4,y:y4,width,height,ccwRotation})=>{let halfWidth=width/2,halfHeight=height/2;return[{x:-halfWidth,y:-halfHeight},{x:halfWidth,y:-halfHeight},{x:halfWidth,y:halfHeight},{x:-halfWidth,y:halfHeight}].map(point7=>{let rotated=rotatePoint(point7,ccwRotation);return{x:x4+rotated.x,y:y4+rotated.y}})},getPolygonPointsForPad=pad2=>{if(pad2.type==="pcb_smtpad"){if(pad2.shape==="polygon")return pad2.points;if(pad2.shape==="rotated_rect")return getRotatedRectPoints({x:pad2.x,y:pad2.y,width:pad2.width,height:pad2.height,ccwRotation:pad2.ccw_rotation})}if(pad2.type==="pcb_plated_hole"&&"rect_pad_width"in pad2&&"rect_pad_height"in pad2)return getRotatedRectPoints({x:pad2.x,y:pad2.y,width:pad2.rect_pad_width,height:pad2.rect_pad_height,ccwRotation:"rect_ccw_rotation"in pad2&&typeof pad2.rect_ccw_rotation=="number"?pad2.rect_ccw_rotation:0});throw new Error(`Expected polygonal pad geometry, got ${pad2.type} with shape "${pad2.shape}"`)},getPolygonEdges3=points=>points.map((point7,index)=>[point7,points[(index+1)%points.length]]),getClosestPointsBetweenSegments=(a12,a22,b12,b22)=>{let intersection=getSegmentIntersection(a12,a22,b12,b22);if(intersection)return{distance:0,pointOnA:intersection,pointOnB:intersection,center:intersection};let candidates=[{pointOnA:a12,pointOnB:pointToSegmentClosestPoint(a12,b12,b22)},{pointOnA:a22,pointOnB:pointToSegmentClosestPoint(a22,b12,b22)},{pointOnA:pointToSegmentClosestPoint(b12,a12,a22),pointOnB:b12},{pointOnA:pointToSegmentClosestPoint(b22,a12,a22),pointOnB:b22}],best=candidates[0],bestDistanceSquared=distSq(best.pointOnA,best.pointOnB);for(let candidate of candidates.slice(1)){let candidateDistanceSquared=distSq(candidate.pointOnA,candidate.pointOnB);candidateDistanceSquared<bestDistanceSquared&&(best=candidate,bestDistanceSquared=candidateDistanceSquared)}return{distance:segmentToSegmentMinDistance(a12,a22,b12,b22),pointOnA:best.pointOnA,pointOnB:best.pointOnB,center:{x:(best.pointOnA.x+best.pointOnB.x)/2,y:(best.pointOnA.y+best.pointOnB.y)/2}}},getSegmentToPolygonClearance=(segment2,polygon2)=>{let start={x:segment2.x1,y:segment2.y1},end={x:segment2.x2,y:segment2.y2};if(polygon2.length<3)return{distance:Number.POSITIVE_INFINITY,center:start};let intersections=getPolygonEdges3(polygon2).map(([edgeStart,edgeEnd])=>getSegmentIntersection(start,end,edgeStart,edgeEnd)).filter(point7=>point7!==null);if(intersections.length>0){let dx3=end.x-start.x,dy3=end.y-start.y,lengthSquared=dx3*dx3+dy3*dy3;return intersections.sort((a3,b3)=>{let ta3=((a3.x-start.x)*dx3+(a3.y-start.y)*dy3)/lengthSquared,tb2=((b3.x-start.x)*dx3+(b3.y-start.y)*dy3)/lengthSquared;return ta3-tb2}),{distance:0,center:intersections[0]}}if(isPointInsidePolygon(start,polygon2)||isPointInsidePolygon(end,polygon2))return{distance:0,center:{x:(start.x+end.x)/2,y:(start.y+end.y)/2}};let best=getClosestPointsBetweenSegments(start,end,polygon2[0],polygon2[1]);for(let[edgeStart,edgeEnd]of getPolygonEdges3(polygon2).slice(1)){let candidate=getClosestPointsBetweenSegments(start,end,edgeStart,edgeEnd);candidate.distance<best.distance&&(best=candidate)}return{distance:best.distance,center:best.center}},getCollidableBounds=collidable=>{if(collidable.type==="pcb_trace_segment")return{minX:Math.min(collidable.x1,collidable.x2),minY:Math.min(collidable.y1,collidable.y2),maxX:Math.max(collidable.x1,collidable.x2),maxY:Math.max(collidable.y1,collidable.y2)};if((collidable.type==="pcb_smtpad"||collidable.type==="pcb_plated_hole")&&(collidable.type==="pcb_smtpad"&&(collidable.shape==="rotated_rect"||collidable.shape==="polygon")||collidable.type==="pcb_plated_hole"&&"rect_pad_width"in collidable&&"rect_pad_height"in collidable)){let polygonPoints=getPolygonPointsForPad(collidable);return{minX:Math.min(...polygonPoints.map(point7=>point7.x)),minY:Math.min(...polygonPoints.map(point7=>point7.y)),maxX:Math.max(...polygonPoints.map(point7=>point7.x)),maxY:Math.max(...polygonPoints.map(point7=>point7.y))}}return getBoundsOfPcbElements([collidable])};function getPcbPortIdsConnectedToRoutePoint(routePoint){return routePoint.route_type!=="wire"?[]:[routePoint.start_pcb_port_id,routePoint.end_pcb_port_id].filter(portId=>!!portId)}function getPcbPortIdsConnectedToTrace(trace){let connectedPcbPorts=new Set;for(let segment2 of trace.route)for(let portId of getPcbPortIdsConnectedToRoutePoint(segment2))connectedPcbPorts.add(portId);return Array.from(connectedPcbPorts)}function getPcbPortIdsConnectedToTraces(traces){let connectedPorts=new Set;for(let trace of traces)for(let portId of getPcbPortIdsConnectedToTrace(trace))connectedPorts.add(portId);return Array.from(connectedPorts)}var getRadiusOfCircuitJsonElement=obj=>{if(obj.type==="pcb_via"||obj.type==="pcb_plated_hole"&&obj.shape==="circle")return obj.outer_diameter/2;if(obj.type==="pcb_hole"&&obj.hole_shape==="circle")return obj.hole_diameter/2;if(obj.type==="pcb_smtpad"&&obj.shape==="circle")return obj.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(obj)}`)};function checkEachPcbTraceNonOverlapping(circuitJson,{connMap,minClearance}={}){let errors=[];addStartAndEndPortIdsIfMissing(circuitJson),connMap??(connMap=getFullConnectivityMapFromCircuitJson(circuitJson));let board=getPcbBoard(circuitJson);minClearance??(minClearance=getBoardDrcValue(board,"min_trace_to_pad_edge_clearance")??DEFAULT_TRACE_MARGIN);let pcbTraceSegments=cju_default(circuitJson).pcb_trace.list().flatMap(pcbTrace=>{let segments=[];for(let i3=0;i3<pcbTrace.route.length-1;i3++){let p12=pcbTrace.route[i3],p22=pcbTrace.route[i3+1];p12.route_type==="wire"&&p22.route_type==="wire"&&p12.layer===p22.layer&&segments.push({type:"pcb_trace_segment",pcb_trace_id:pcbTrace.pcb_trace_id,_pcbTrace:pcbTrace,thickness:"width"in p12?p12.width:"width"in p22?p22.width:DEFAULT_TRACE_THICKNESS,layer:p12.layer,x1:p12.x,y1:p12.y,x2:p22.x,y2:p22.y})}return segments}),pcbSmtPads=cju_default(circuitJson).pcb_smtpad.list(),pcbPlatedHoles=cju_default(circuitJson).pcb_plated_hole.list(),pcbHoles=cju_default(circuitJson).pcb_hole.list(),pcbVias=cju_default(circuitJson).pcb_via.list(),pcbKeepouts=cju_default(circuitJson).pcb_keepout.list(),allObjects=[...pcbTraceSegments,...pcbSmtPads,...pcbPlatedHoles,...pcbHoles,...pcbVias,...pcbKeepouts],spatialIndex=new SpatialObjectIndex({objects:allObjects,getBounds:getCollidableBounds}),getReadableName=id2=>getReadableNameForElement(circuitJson,id2),constructErrorMessage=(traceName,otherName,gap)=>gap<0?`PCB trace ${traceName} overlaps with ${otherName} (accidental contact)`:`PCB trace ${traceName} is too close to ${otherName} (gap: ${gap.toFixed(3)}mm)`,errorIds=new Set;for(let segmentA of pcbTraceSegments){let requiredMargin=minClearance,bounds=getCollidableBounds(segmentA),nearbyObjects=spatialIndex.getObjectsInBounds(bounds,requiredMargin+segmentA.thickness/2);if(!(segmentA.x1===segmentA.x2&&segmentA.y1===segmentA.y2))for(let obj of nearbyObjects){if(!getLayersOfPcbElement(obj).includes(segmentA.layer))continue;if(obj.type==="pcb_trace_segment"){let segmentB=obj;if(segmentA.layer!==segmentB.layer||connMap.areIdsConnected(segmentA.pcb_trace_id,segmentB.pcb_trace_id))continue;let gap2=segmentToSegmentMinDistance({x:segmentA.x1,y:segmentA.y1},{x:segmentA.x2,y:segmentA.y2},{x:segmentB.x1,y:segmentB.y1},{x:segmentB.x2,y:segmentB.y2})-segmentA.thickness/2-segmentB.thickness/2;if(gap2>minClearance-EPSILON2)continue;let pcb_trace_error_id=`overlap_${segmentA.pcb_trace_id}_${segmentB.pcb_trace_id}`,pcb_trace_error_id_reverse=`overlap_${segmentB.pcb_trace_id}_${segmentA.pcb_trace_id}`;if(errorIds.has(pcb_trace_error_id)||errorIds.has(pcb_trace_error_id_reverse))continue;errorIds.add(pcb_trace_error_id),errors.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:constructErrorMessage(getReadableName(segmentA.pcb_trace_id),getReadableName(segmentB.pcb_trace_id),gap2),pcb_trace_id:segmentA.pcb_trace_id,source_trace_id:"",pcb_trace_error_id,pcb_component_ids:[],center:getClosestPointBetweenSegments(segmentA,segmentB),pcb_port_ids:getPcbPortIdsConnectedToTraces([segmentA._pcbTrace,segmentB._pcbTrace])});continue}let primaryObjId=getPrimaryId(obj);if(connMap.areIdsConnected(segmentA.pcb_trace_id,"pcb_trace_id"in obj?obj.pcb_trace_id:primaryObjId))continue;if(obj.type==="pcb_via"||obj.type==="pcb_plated_hole"&&obj.shape==="circle"||obj.type==="pcb_hole"||obj.type==="pcb_smtpad"&&obj.shape==="circle"){let radius=getRadiusOfCircuitJsonElement(obj),gap2=segmentToCircleMinDistance({x:segmentA.x1,y:segmentA.y1},{x:segmentA.x2,y:segmentA.y2},{x:obj.x,y:obj.y,radius})-segmentA.thickness/2;if(gap2>minClearance-EPSILON2)continue;let pcb_trace_error_id=`overlap_${segmentA.pcb_trace_id}_${primaryObjId}`;if(errorIds.has(pcb_trace_error_id))continue;errorIds.add(pcb_trace_error_id),errors.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:constructErrorMessage(getReadableName(segmentA.pcb_trace_id),`${obj.type} "${getReadableName(getPrimaryId(obj))}"`,gap2),pcb_trace_id:segmentA.pcb_trace_id,center:getClosestPointBetweenSegmentAndBounds(segmentA,getCollidableBounds(obj)),source_trace_id:"",pcb_trace_error_id,pcb_component_ids:["pcb_component_id"in obj?obj.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...getPcbPortIdsConnectedToTraces([segmentA._pcbTrace]),"pcb_port_id"in obj?obj.pcb_port_id:void 0].filter(Boolean)})}if(obj.type==="pcb_smtpad"&&(obj.shape==="rotated_rect"||obj.shape==="polygon")||obj.type==="pcb_plated_hole"&&"rect_pad_width"in obj&&"rect_pad_height"in obj){let padOutline=getPolygonPointsForPad(obj),{distance:distance32,center:center2}=getSegmentToPolygonClearance(segmentA,padOutline),gap2=distance32-segmentA.thickness/2;if(gap2>minClearance-EPSILON2)continue;let pcb_trace_error_id=`overlap_${segmentA.pcb_trace_id}_${primaryObjId}`;if(errorIds.has(pcb_trace_error_id))continue;errorIds.add(pcb_trace_error_id),errors.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:constructErrorMessage(getReadableName(segmentA.pcb_trace_id),`${obj.type} "${getReadableName(getPrimaryId(obj))}"`,gap2),pcb_trace_id:segmentA.pcb_trace_id,center:center2,source_trace_id:"",pcb_trace_error_id,pcb_component_ids:["pcb_component_id"in obj?obj.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...getPcbPortIdsConnectedToTraces([segmentA._pcbTrace]),"pcb_port_id"in obj?obj.pcb_port_id:void 0].filter(Boolean)});continue}let gap=segmentToBoundsMinDistance({x:segmentA.x1,y:segmentA.y1},{x:segmentA.x2,y:segmentA.y2},getCollidableBounds(obj))-segmentA.thickness/2;if(gap+EPSILON2<requiredMargin){let pcb_trace_error_id=`overlap_${segmentA.pcb_trace_id}_${primaryObjId}`;if(errorIds.has(pcb_trace_error_id))continue;errorIds.add(pcb_trace_error_id),errors.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:constructErrorMessage(getReadableName(segmentA.pcb_trace_id),`${obj.type} "${getReadableName(getPrimaryId(obj))}"`,gap),pcb_trace_id:segmentA.pcb_trace_id,source_trace_id:"",pcb_trace_error_id,pcb_component_ids:["pcb_component_id"in obj?obj.pcb_component_id:void 0].filter(Boolean),center:getClosestPointBetweenSegmentAndBounds(segmentA,getCollidableBounds(obj)),pcb_port_ids:[...getPcbPortIdsConnectedToTraces([segmentA._pcbTrace]),"pcb_port_id"in obj?obj.pcb_port_id:void 0].filter(Boolean)})}}}return errors}function checkViasOffBoard(circuitJson){let board=getPcbBoard(circuitJson);if(!board)return[];let vias=circuitJson.filter(el3=>el3.type==="pcb_via");if(vias.length===0)return[];if(board.width===void 0||board.height===void 0)return[];let boardEdgeClearance=getBoardDrcValue(board,"min_board_edge_clearance")??jlcMinTolerances.min_board_edge_clearance,boardMinX=board.center.x-board.width/2,boardMaxX=board.center.x+board.width/2,boardMinY=board.center.y-board.height/2,boardMaxY=board.center.y+board.height/2,errors=[];for(let via of vias){let viaRadius=via.outer_diameter/2,viaMinX=via.x-viaRadius,viaMaxX=via.x+viaRadius,viaMinY=via.y-viaRadius,viaMaxY=via.y+viaRadius;if(viaMinX<boardMinX+boardEdgeClearance||viaMaxX>boardMaxX-boardEdgeClearance||viaMinY<boardMinY+boardEdgeClearance||viaMaxY>boardMaxY-boardEdgeClearance){let viaName=getReadableNameForElement(circuitJson,via.pcb_via_id);errors.push({type:"pcb_placement_error",pcb_placement_error_id:`out_of_board_${via.pcb_via_id}`,message:`Via ${viaName} is outside or crossing the board boundary`,error_type:"pcb_placement_error"})}}return errors}function isPolygonCCW(poly){return poly.area()>=0}function rectanglePolygon({center:center2,size:size3,rotationDeg=0}){let cx3=center2.x,cy3=center2.y,hw3=size3.width/2,hh3=size3.height/2,corners=[new Point$3(cx3-hw3,cy3-hh3),new Point$3(cx3+hw3,cy3-hh3),new Point$3(cx3+hw3,cy3+hh3),new Point$3(cx3-hw3,cy3+hh3)],poly=new Polygon$1(corners);if(rotationDeg){let matrix2=rotateDEG(rotationDeg,cx3,cy3),rotatedCorners=corners.map(pt3=>{let p4=applyToPoint(matrix2,{x:pt3.x,y:pt3.y});return new Point$3(p4.x,p4.y)});poly=new Polygon$1(rotatedCorners)}return isPolygonCCW(poly)||poly.reverse(),poly}function boardToPolygon({board}){if(board.outline&&board.outline.length>0){let points=board.outline.map(p4=>new Point$3(p4.x,p4.y)),poly=new Polygon$1(points);return isPolygonCCW(poly)||poly.reverse(),poly}return board.center&&typeof board.width=="number"&&typeof board.height=="number"?rectanglePolygon({center:board.center,size:{width:board.width,height:board.height},rotationDeg:0}):null}function getComponentName({circuitJson,component}){if(component.source_component_id){let sourceComponent=circuitJson.find(el3=>el3.type==="source_component"&&el3.source_component_id===component.source_component_id);if(sourceComponent&&"name"in sourceComponent&&sourceComponent.name)return sourceComponent.name}return getReadableNameForComponent(circuitJson,component.pcb_component_id)}function computeOverlapDistance(compPoly,boardPoly,componentCenter,componentWidth,componentHeight,rotationDeg){let centerPoint=new Point$3(componentCenter.x,componentCenter.y);if(!boardPoly.contains(centerPoint)){let dist=boardPoly.distanceTo(centerPoint);return Array.isArray(dist)?dist[0]:Number(dist)||0}let hw3=componentWidth/2,hh3=componentHeight/2,corners=[{x:componentCenter.x-hw3,y:componentCenter.y-hh3},{x:componentCenter.x+hw3,y:componentCenter.y-hh3},{x:componentCenter.x+hw3,y:componentCenter.y+hh3},{x:componentCenter.x-hw3,y:componentCenter.y+hh3}],midpoints=[];for(let i3=0;i3<4;i3++){let next2=(i3+1)%4;midpoints.push({x:(corners[i3].x+corners[next2].x)/2,y:(corners[i3].y+corners[next2].y)/2})}let matrix2=rotateDEG(rotationDeg,componentCenter.x,componentCenter.y),rotatePoint22=pt3=>{let p4=applyToPoint(matrix2,pt3);return new Point$3(p4.x,p4.y)},rotatedPoints=corners.concat(midpoints).map(rotatePoint22),maxDistance=0;for(let pt3 of rotatedPoints)if(!boardPoly.contains(pt3)){let dist=boardPoly.distanceTo(pt3),d4=Array.isArray(dist)?dist[0]:Number(dist)||0;d4>maxDistance&&(maxDistance=d4)}if(maxDistance>0)return maxDistance;try{let intersection=BooleanOperations.intersect(compPoly,boardPoly),intersectionArea=0;intersection?Array.isArray(intersection)?intersectionArea=intersection.reduce((sum,p4)=>sum+(typeof p4.area=="function"?p4.area():0),0):typeof intersection.area=="function"?intersectionArea=intersection.area():intersectionArea=0:intersectionArea=0;let compArea=compPoly.area();if(intersectionArea>0&&intersectionArea<compArea){let overlapRatio=1-intersectionArea/compArea,compWidth=Math.abs(componentWidth),compHeight=Math.abs(componentHeight);return Math.min(compWidth,compHeight)*overlapRatio}else return .1}catch{return .1}}function getRepositionSuggestion({componentPoly,boardPoly}){let boardBox=boardPoly.box,componentBox=componentPoly.box,deltaX=0,deltaY=0;if(componentBox.xmin<boardBox.xmin?deltaX=boardBox.xmin-componentBox.xmin:componentBox.xmax>boardBox.xmax&&(deltaX=boardBox.xmax-componentBox.xmax),componentBox.ymin<boardBox.ymin?deltaY=boardBox.ymin-componentBox.ymin:componentBox.ymax>boardBox.ymax&&(deltaY=boardBox.ymax-componentBox.ymax),deltaX===0&&deltaY===0)return null;let xDir=deltaX>=0?"right":"left",yDir=deltaY>=0?"up":"down",absDx=Math.abs(Math.round(deltaX*100)/100),absDy=Math.abs(Math.round(deltaY*100)/100);return absDx>0&&absDy>0?`Try moving it ${absDx}mm ${xDir} and ${absDy}mm ${yDir} to fit within the board edge.`:absDx>0?`Try moving it ${absDx}mm ${xDir} to fit within the board edge.`:`Try moving it ${absDy}mm ${yDir} to fit within the board edge.`}function checkPcbComponentsOutOfBoard(circuitJson){let board=circuitJson.find(el3=>el3.type==="pcb_board");if(!board)return[];let boardPoly=boardToPolygon({board});if(!boardPoly)return[];let components=circuitJson.filter(el3=>el3.type==="pcb_component");if(components.length===0)return[];let errors=[];for(let c4 of components){if(c4.is_allowed_to_be_off_board||!c4.center||typeof c4.width!="number"||typeof c4.height!="number"||c4.width<=0||c4.height<=0)continue;let compPoly=rectanglePolygon({center:c4.center,size:{width:c4.width,height:c4.height},rotationDeg:0});if(compPoly.area()===0||boardPoly.contains(compPoly))continue;let overlapDistance=computeOverlapDistance(compPoly,boardPoly,c4.center,c4.width,c4.height,0),compName=getComponentName({circuitJson,component:c4}),overlapDistanceMm=Math.round(overlapDistance*100)/100,repositionSuggestion=getRepositionSuggestion({componentPoly:compPoly,boardPoly});errors.push({type:"pcb_component_outside_board_error",error_type:"pcb_component_outside_board_error",pcb_component_outside_board_error_id:`pcb_component_outside_board_${c4.pcb_component_id}`,message:`Component ${compName} extends outside board boundaries by ${overlapDistanceMm}mm.${repositionSuggestion?` ${repositionSuggestion}`:""}`,pcb_component_id:c4.pcb_component_id,pcb_board_id:board.pcb_board_id,component_center:c4.center,component_bounds:{min_x:compPoly.box.xmin,max_x:compPoly.box.xmax,min_y:compPoly.box.ymin,max_y:compPoly.box.ymax},subcircuit_id:c4.subcircuit_id,source_component_id:c4.source_component_id})}return errors}function distance22(a3,b3){return Math.hypot(a3.x-b3.x,a3.y-b3.y)}function viasAreAtSameLocation(a3,b3){return distance22(a3,b3)<=EPSILON2}function checkSameNetViaSpacing(circuitJson,{connMap,minClearance}={}){let vias=circuitJson.filter(el3=>el3.type==="pcb_via");if(vias.length<2)return[];let board=getPcbBoard(circuitJson);minClearance??(minClearance=getBoardDrcValue(board,"min_via_hole_edge_to_via_hole_edge_clearance")??jlcMinTolerances.min_via_hole_edge_to_via_hole_edge_clearance),connMap??(connMap=getFullConnectivityMapFromCircuitJson(circuitJson));let errors=[],reported=new Set;for(let i3=0;i3<vias.length;i3++)for(let j4=i3+1;j4<vias.length;j4++){let viaA=vias[i3],viaB=vias[j4];if(viasAreAtSameLocation(viaA,viaB)||!connMap.areIdsConnected(viaA.pcb_via_id,viaB.pcb_via_id))continue;let gap=distance22(viaA,viaB)-viaA.hole_diameter/2-viaB.hole_diameter/2;if(gap+EPSILON2>=minClearance)continue;let pairId=[viaA.pcb_via_id,viaB.pcb_via_id].sort().join("_");reported.has(pairId)||(reported.add(pairId),errors.push({type:"pcb_via_clearance_error",pcb_error_id:`same_net_vias_close_${pairId}`,message:`Vias ${getReadableNameForElement(circuitJson,viaA.pcb_via_id)} and ${getReadableNameForElement(circuitJson,viaB.pcb_via_id)} are too close together (gap: ${gap.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[viaA.pcb_via_id,viaB.pcb_via_id],minimum_clearance:minClearance,actual_clearance:gap,pcb_center:{x:(viaA.x+viaB.x)/2,y:(viaA.y+viaB.y)/2}}))}return errors}function checkDifferentNetViaSpacing(circuitJson,{connMap,minClearance}={}){let vias=circuitJson.filter(el3=>el3.type==="pcb_via");if(vias.length<2)return[];let board=getPcbBoard(circuitJson);minClearance??(minClearance=getBoardDrcValue(board,"min_via_hole_edge_to_via_hole_edge_clearance")??jlcMinTolerances.min_via_hole_edge_to_via_hole_edge_clearance),connMap??(connMap=getFullConnectivityMapFromCircuitJson(circuitJson));let errors=[],reported=new Set;for(let i3=0;i3<vias.length;i3++)for(let j4=i3+1;j4<vias.length;j4++){let viaA=vias[i3],viaB=vias[j4];if(viasAreAtSameLocation(viaA,viaB)||connMap.areIdsConnected(viaA.pcb_via_id,viaB.pcb_via_id))continue;let gap=distance22(viaA,viaB)-viaA.hole_diameter/2-viaB.hole_diameter/2;if(gap+EPSILON2>=minClearance)continue;let pairId=[viaA.pcb_via_id,viaB.pcb_via_id].sort().join("_");reported.has(pairId)||(reported.add(pairId),errors.push({type:"pcb_via_clearance_error",pcb_error_id:`different_net_vias_close_${pairId}`,message:`Vias ${getReadableNameForElement(circuitJson,viaA.pcb_via_id)} and ${getReadableNameForElement(circuitJson,viaB.pcb_via_id)} from different nets are too close together (gap: ${gap.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[viaA.pcb_via_id,viaB.pcb_via_id],minimum_clearance:minClearance,actual_clearance:gap,pcb_center:{x:(viaA.x+viaB.x)/2,y:(viaA.y+viaB.y)/2}}))}return errors}function checkSourceTracesHavePcbTraces(circuitJson){let errors=[],sourceTraces=circuitJson.filter(el3=>el3.type==="source_trace"),pcbTraces=circuitJson.filter(el3=>el3.type==="pcb_trace"),pcbPorts=circuitJson.filter(el3=>el3.type==="pcb_port"),sourcePortToPcbPort=new Map(pcbPorts.map(pcbPort=>[pcbPort.source_port_id,pcbPort])),connectivityMap=getFullConnectivityMapFromCircuitJson(circuitJson);for(let sourceTrace of sourceTraces){if(!sourceTrace.connected_source_port_ids?.length||(sourceTrace.connected_source_net_ids?.length??0)>0||sourceTrace.connected_source_port_ids.length<2)continue;if(!pcbTraces.some(pcbTrace=>connectivityMap.areIdsConnected(sourceTrace.source_trace_id,pcbTrace.pcb_trace_id))){let connectedPcbPorts=sourceTrace.connected_source_port_ids.map(sourcePortId=>sourcePortToPcbPort.get(sourcePortId)).filter(pcbPort=>pcbPort!==void 0),connectedPcbComponentIds=Array.from(new Set(connectedPcbPorts.map(port=>port.pcb_component_id).filter(id2=>id2!==void 0)));errors.push({type:"pcb_trace_missing_error",pcb_trace_missing_error_id:`pcb_trace_missing_${sourceTrace.source_trace_id}`,error_type:"pcb_trace_missing_error",message:`Trace [${sourceTrace.display_name&&!containsCircuitJsonId(sourceTrace.display_name)?sourceTrace.display_name:"trace"}] is not connected (it has no PCB trace)`,source_trace_id:sourceTrace.source_trace_id,pcb_component_ids:connectedPcbComponentIds,pcb_port_ids:connectedPcbPorts.map(port=>port.pcb_port_id)})}}return errors}function getBoardPolygonPoints(board){if(board.outline&&board.outline.length>0)return board.outline.map(p4=>({x:p4.x,y:p4.y}));if(board.center&&typeof board.width=="number"&&typeof board.height=="number"){let cx3=board.center.x,cy3=board.center.y,hw3=board.width/2,hh3=board.height/2;return[{x:cx3-hw3,y:cy3-hh3},{x:cx3+hw3,y:cy3-hh3},{x:cx3+hw3,y:cy3+hh3},{x:cx3-hw3,y:cy3+hh3}]}return null}function checkPcbTracesOutOfBoard(circuitJson,config={}){let errors=[],board=getPcbBoard(circuitJson);if(!board)return errors;let margin=config.margin??getBoardDrcValue(board,"min_board_edge_clearance")??jlcMinTolerances.min_board_edge_clearance,boardPoints=getBoardPolygonPoints(board);if(!boardPoints)return errors;let pcbTraces=cju_default(circuitJson).pcb_trace.list();for(let trace of pcbTraces)if(!(trace.route.length<2))for(let i3=0;i3<trace.route.length-1;i3++){let p12=trace.route[i3],p22=trace.route[i3+1];if(p12.route_type!=="wire"||p22.route_type!=="wire")continue;let traceWidth="width"in p12?p12.width:"width"in p22?p22.width:.1,segmentStart={x:p12.x,y:p12.y},segmentEnd={x:p22.x,y:p22.y},minDistance=Number.POSITIVE_INFINITY;for(let j4=0;j4<boardPoints.length;j4++){let edgeStart=boardPoints[j4],edgeEnd=boardPoints[(j4+1)%boardPoints.length],distance32=segmentToSegmentMinDistance(segmentStart,segmentEnd,edgeStart,edgeEnd);distance32<minDistance&&(minDistance=distance32)}let minimumDistance=traceWidth/2+margin;if(minDistance<minimumDistance){let error2={type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:`trace_too_close_to_board_${trace.pcb_trace_id}_segment_${i3}`,message:`Trace too close to board edge (${minDistance.toFixed(3)}mm < ${minimumDistance.toFixed(3)}mm required, margin: ${margin}mm)`,pcb_trace_id:trace.pcb_trace_id,source_trace_id:trace.source_trace_id||"",center:{x:(segmentStart.x+segmentEnd.x)/2,y:(segmentStart.y+segmentEnd.y)/2},pcb_component_ids:[],pcb_port_ids:[]};errors.push(error2)}}return errors}function getElementLayers(elem){return elem.type==="pcb_courtyard_circle"||elem.type==="pcb_courtyard_outline"||elem.type==="pcb_courtyard_polygon"||elem.type==="pcb_courtyard_rect"?[elem.layer]:getLayersOfPcbElement(elem)}function doLayersOverlap(layers1,layers2){return layers1.length===0||layers2.length===0?!0:layers1.some(l4=>layers2.includes(l4))}function doPcbElementsOverlap(elem1,elem2){let layers1=getElementLayers(elem1),layers2=getElementLayers(elem2);if(!doLayersOverlap(layers1,layers2))return!1;let bounds1=getBoundsOfPcbElements([elem1]),bounds2=getBoundsOfPcbElements([elem2]);return doBoundsOverlap(bounds1,bounds2)}var isCourtyardElement=element=>element.type==="pcb_courtyard_circle"||element.type==="pcb_courtyard_outline"||element.type==="pcb_courtyard_polygon"||element.type==="pcb_courtyard_rect",formatOverlapElementDescription=(circuitJson,element)=>{if("pcb_port_id"in element&&element.pcb_port_id)return getReadableNameForPort(circuitJson,element.pcb_port_id);let id2=getPrimaryId(element),readableName=getReadableNameForElementId(circuitJson,id2);return readableName==="element"?`[${id2}]`:readableName};function checkPcbComponentOverlap(circuitJson){let errors=[],connMap=getFullConnectivityMapFromCircuitJson(circuitJson),smtPads=cju_default(circuitJson).pcb_smtpad.list(),platedHoles=cju_default(circuitJson).pcb_plated_hole.list(),holes=cju_default(circuitJson).pcb_hole.list(),courtyards=circuitJson.filter(isCourtyardElement),componentMap=new Map;for(let pad2 of smtPads){let componentId=pad2.pcb_component_id||`standalone_pad_${getPrimaryId(pad2)}`;componentMap.has(componentId)||componentMap.set(componentId,{component_id:componentId,elements:[]}),componentMap.get(componentId).elements.push(pad2)}for(let hole of platedHoles){let componentId=hole.pcb_component_id||`standalone_plated_hole_${getPrimaryId(hole)}`;componentMap.has(componentId)||componentMap.set(componentId,{component_id:componentId,elements:[]}),componentMap.get(componentId).elements.push(hole)}for(let hole of holes){let componentId=hole.pcb_component_id||`standalone_hole_${getPrimaryId(hole)}`;componentMap.has(componentId)||componentMap.set(componentId,{component_id:componentId,elements:[hole]})}for(let courtyard of courtyards){let componentId=courtyard.pcb_component_id;componentMap.has(componentId)||componentMap.set(componentId,{component_id:componentId,elements:[]}),componentMap.get(componentId).elements.push(courtyard)}for(let[componentId,componentData]of componentMap)componentData.elements.length>0&&(componentData.bounds=getBoundsOfPcbElements(componentData.elements));let componentsWithElements=Array.from(componentMap.values());for(let i3=0;i3<componentsWithElements.length;i3++)for(let j4=i3+1;j4<componentsWithElements.length;j4++){let comp1=componentsWithElements[i3],comp2=componentsWithElements[j4];if(!(!comp1.bounds||!comp2.bounds)&&doBoundsOverlap(comp1.bounds,comp2.bounds))for(let elem1 of comp1.elements)for(let elem2 of comp2.elements){let id1=getPrimaryId(elem1),id2=getPrimaryId(elem2);if(!((isCourtyardElement(elem1)||isCourtyardElement(elem2))&&elem1.type!=="pcb_hole"&&elem2.type!=="pcb_hole")&&!(elem1.type==="pcb_smtpad"&&elem2.type==="pcb_smtpad"&&connMap.areIdsConnected(id1,id2))&&doPcbElementsOverlap(elem1,elem2)){let elem1Description=formatOverlapElementDescription(circuitJson,elem1),elem2Description=formatOverlapElementDescription(circuitJson,elem2),error2={type:"pcb_footprint_overlap_error",pcb_error_id:`pcb_footprint_overlap_${id1}_${id2}`,error_type:"pcb_footprint_overlap_error",message:`${elem1.type} ${elem1Description} overlaps with ${elem2.type} ${elem2Description}`};(elem1.type==="pcb_smtpad"||elem2.type==="pcb_smtpad")&&(error2.pcb_smtpad_ids=[],elem1.type==="pcb_smtpad"&&error2.pcb_smtpad_ids.push(id1),elem2.type==="pcb_smtpad"&&error2.pcb_smtpad_ids.push(id2)),(elem1.type==="pcb_plated_hole"||elem2.type==="pcb_plated_hole")&&(error2.pcb_plated_hole_ids=[],elem1.type==="pcb_plated_hole"&&error2.pcb_plated_hole_ids.push(id1),elem2.type==="pcb_plated_hole"&&error2.pcb_plated_hole_ids.push(id2)),(elem1.type==="pcb_hole"||elem2.type==="pcb_hole")&&(error2.pcb_hole_ids=[],elem1.type==="pcb_hole"&&error2.pcb_hole_ids.push(id1),elem2.type==="pcb_hole"&&error2.pcb_hole_ids.push(id2)),errors.push(error2)}}}return errors}var formatMm=value=>{let rounded=Math.round(value*1e3)/1e3;return`${Number(rounded.toFixed(3))}mm`},getPadBounds=pad2=>getBoundsOfPcbElements([pad2]),getPadCenter=pad2=>{let bounds=getPadBounds(pad2);return midpoint({x:bounds.minX,y:bounds.minY},{x:bounds.maxX,y:bounds.maxY})},getPadRadius=pad2=>{let bounds=getPadBounds(pad2);return Math.min(bounds.maxX-bounds.minX,bounds.maxY-bounds.minY)/2},isCircularPad=pad2=>pad2.shape==="circle",getCircleShape=pad2=>{let center2=getPadCenter(pad2);return{kind:"circle",x:center2.x,y:center2.y,radius:getPadRadius(pad2)}},getPolygonShape=pad2=>{let bounds=getPadBounds(pad2);return{kind:"polygon",points:[{x:bounds.minX,y:bounds.minY},{x:bounds.maxX,y:bounds.minY},{x:bounds.maxX,y:bounds.maxY},{x:bounds.minX,y:bounds.maxY}]}},getPadToPadGap=(padA,padB)=>isCircularPad(padA)&&isCircularPad(padB)?distanceBetweenCircleAndCircle(getCircleShape(padA),getCircleShape(padB)):isCircularPad(padA)?distanceBetweenCircleAndPolygon(getCircleShape(padA),getPolygonShape(padB)):isCircularPad(padB)?distanceBetweenCircleAndPolygon(getCircleShape(padB),getPolygonShape(padA)):distanceBetweenPolygonAndPolygon(getPolygonShape(padA),getPolygonShape(padB)),getPads=circuitJson=>[...cju_default(circuitJson).pcb_smtpad.list(),...cju_default(circuitJson).pcb_plated_hole.list()],getTraceSegments=circuitJson=>cju_default(circuitJson).pcb_trace.list().flatMap(pcbTrace=>{let segments=[];for(let i3=0;i3<pcbTrace.route.length-1;i3++){let p12=pcbTrace.route[i3],p22=pcbTrace.route[i3+1];p12.route_type==="wire"&&p22.route_type==="wire"&&p12.layer===p22.layer&&segments.push({type:"pcb_trace_segment",pcb_trace_id:pcbTrace.pcb_trace_id,_pcbTrace:pcbTrace,thickness:"width"in p12?p12.width:"width"in p22?p22.width:DEFAULT_TRACE_THICKNESS,layer:p12.layer,x1:p12.x,y1:p12.y,x2:p22.x,y2:p22.y})}return segments});function checkPadPadClearance(circuitJson,{connMap,minClearance}={}){let pads=getPads(circuitJson);if(pads.length<2)return[];let board=getPcbBoard(circuitJson);minClearance??(minClearance=getBoardDrcValue(board,"min_pad_edge_to_pad_edge_clearance")??jlcMinTolerances.min_pad_edge_to_pad_edge_clearance),connMap??(connMap=getFullConnectivityMapFromCircuitJson(circuitJson));let spatialIndex=new SpatialObjectIndex({objects:pads,getBounds:getPadBounds,getId:pad2=>getPrimaryId(pad2)}),errors=new Map;for(let padA of pads){let padAId=getPrimaryId(padA),nearbyPads=spatialIndex.getObjectsInBounds(getPadBounds(padA),minClearance);for(let padB of nearbyPads){let padBId=getPrimaryId(padB);if(padAId===padBId||!getLayersOfPcbElement(padA).some(layer=>getLayersOfPcbElement(padB).includes(layer))||connMap.areIdsConnected(padAId,padBId))continue;let pairId=[padAId,padBId].sort().join("_"),gap=getPadToPadGap(padA,padB);if(gap+EPSILON2>=minClearance)continue;let centerA=getPadCenter(padA),centerB=getPadCenter(padB),nextError={type:"pcb_pad_pad_clearance_error",pcb_pad_pad_clearance_error_id:`pad_pad_clearance_${pairId}`,error_type:"pcb_pad_pad_clearance_error",message:`Pads ${getReadableNameForElement(circuitJson,padAId)} and ${getReadableNameForElement(circuitJson,padBId)} are too close (clearance: ${formatMm(gap)}, minimum: ${formatMm(minClearance)})`,pcb_pad_ids:[padAId,padBId],minimum_clearance:minClearance,actual_clearance:gap,center:{x:(centerA.x+centerB.x)/2,y:(centerA.y+centerB.y)/2}};errors.has(pairId)||errors.set(pairId,nextError)}}return Array.from(errors.values())}function checkPadTraceClearance(circuitJson,{connMap,minClearance}={}){let pads=getPads(circuitJson),segments=getTraceSegments(circuitJson);if(pads.length===0||segments.length===0)return[];let board=getPcbBoard(circuitJson);minClearance??(minClearance=getBoardDrcValue(board,"min_trace_to_pad_edge_clearance")??jlcMinTolerances.min_trace_to_pad_edge_clearance),connMap??(connMap=getFullConnectivityMapFromCircuitJson(circuitJson));let spatialIndex=new SpatialObjectIndex({objects:pads,getBounds:getPadBounds,getId:pad2=>getPrimaryId(pad2)}),errors=new Map;for(let segment2 of segments){let nearbyPads=spatialIndex.getObjectsInBounds(getCollidableBounds(segment2),minClearance+segment2.thickness/2);for(let pad2 of nearbyPads){let padId=getPrimaryId(pad2);if(!getLayersOfPcbElement(pad2).includes(segment2.layer)||connMap.areIdsConnected(segment2.pcb_trace_id,padId))continue;let center2=getPadCenter(pad2),gap=isCircularPad(pad2)?segmentToCircleMinDistance({x:segment2.x1,y:segment2.y1},{x:segment2.x2,y:segment2.y2},{x:center2.x,y:center2.y,radius:getPadRadius(pad2)})-segment2.thickness/2:segmentToBoundsMinDistance({x:segment2.x1,y:segment2.y1},{x:segment2.x2,y:segment2.y2},getPadBounds(pad2))-segment2.thickness/2;if(gap+EPSILON2>=minClearance)continue;let pairId=`${padId}_${segment2.pcb_trace_id}`,nextError={type:"pcb_pad_trace_clearance_error",pcb_pad_trace_clearance_error_id:`pad_trace_clearance_${pairId}`,error_type:"pcb_pad_trace_clearance_error",message:`Pad ${getReadableNameForElement(circuitJson,padId)} and trace ${getReadableNameForElement(circuitJson,segment2.pcb_trace_id)} are too close (clearance: ${formatMm(gap)}, minimum: ${formatMm(minClearance)})`,pcb_pad_id:padId,pcb_trace_id:segment2.pcb_trace_id,minimum_clearance:minClearance,actual_clearance:gap,center:{x:(center2.x+(segment2.x1+segment2.x2)/2)/2,y:(center2.y+(segment2.y1+segment2.y2)/2)/2}},current3=errors.get(pairId);(!current3||gap<current3.gap)&&errors.set(pairId,{error:nextError,gap})}}return Array.from(errors.values()).map(({error:error2})=>error2)}var getClosestPointOnSegment=(point7,segmentStart,segmentEnd)=>{let dx3=segmentEnd.x-segmentStart.x,dy3=segmentEnd.y-segmentStart.y,lengthSquared=dx3*dx3+dy3*dy3;if(lengthSquared===0)return segmentStart;let t52=Math.max(0,Math.min(1,((point7.x-segmentStart.x)*dx3+(point7.y-segmentStart.y)*dy3)/lengthSquared));return{x:segmentStart.x+t52*dx3,y:segmentStart.y+t52*dy3}};function checkViaTraceClearance(circuitJson,{connMap,minClearance}={}){let vias=circuitJson.filter(el3=>el3.type==="pcb_via"),segments=getTraceSegments(circuitJson);if(vias.length===0||segments.length===0)return[];let board=getPcbBoard(circuitJson);minClearance??(minClearance=getBoardDrcValue(board,"min_trace_to_pad_edge_clearance")??jlcMinTolerances.min_trace_to_pad_edge_clearance),connMap??(connMap=getFullConnectivityMapFromCircuitJson(circuitJson));let errors=new Map;for(let via of vias){let viaRadius=via.outer_diameter/2;for(let segment2 of segments){if(!getLayersOfPcbElement(via).includes(segment2.layer)||connMap.areIdsConnected(segment2.pcb_trace_id,via.pcb_via_id))continue;let gap=segmentToCircleMinDistance({x:segment2.x1,y:segment2.y1},{x:segment2.x2,y:segment2.y2},{x:via.x,y:via.y,radius:viaRadius})-segment2.thickness/2;if(gap+EPSILON2>=minClearance)continue;let closestPoint=getClosestPointOnSegment({x:via.x,y:via.y},{x:segment2.x1,y:segment2.y1},{x:segment2.x2,y:segment2.y2}),pairId=`${via.pcb_via_id}_${segment2.pcb_trace_id}`,nextError={type:"pcb_via_trace_clearance_error",pcb_via_trace_clearance_error_id:`via_trace_clearance_${pairId}`,error_type:"pcb_via_trace_clearance_error",message:`Via ${getReadableNameForElement(circuitJson,via.pcb_via_id)} and trace ${getReadableNameForElement(circuitJson,segment2.pcb_trace_id)} are too close (clearance: ${formatMm(gap)}, minimum: ${formatMm(minClearance)})`,pcb_via_id:via.pcb_via_id,pcb_trace_id:segment2.pcb_trace_id,minimum_clearance:minClearance,actual_clearance:gap,center:{x:(via.x+closestPoint.x)/2,y:(via.y+closestPoint.y)/2}},current3=errors.get(pairId);(!current3||gap<current3.gap)&&errors.set(pairId,{error:nextError,gap})}}return Array.from(errors.values()).map(({error:error2})=>error2)}function checkPinMustBeConnected(circuitJson){let errors=[],sourceComponents=circuitJson.filter(el3=>"source_component_id"in el3&&(el3.type==="source_component"||el3.type.startsWith("source_simple_"))),sourcePorts=circuitJson.filter(el3=>el3.type==="source_port"),sourceTraces=circuitJson.filter(el3=>el3.type==="source_trace"),connectedPortIds=new Set;for(let trace of sourceTraces)for(let portId of trace.connected_source_port_ids??[])connectedPortIds.add(portId);let componentInternalConnections=new Map;for(let component of sourceComponents)"internally_connected_source_port_ids"in component&&component.internally_connected_source_port_ids&&componentInternalConnections.set(component.source_component_id,component.internally_connected_source_port_ids);for(let internalGroups of componentInternalConnections.values())for(let group of internalGroups)if(group.some(portId=>connectedPortIds.has(portId)))for(let portId of group)connectedPortIds.add(portId);for(let port of sourcePorts)if(port.must_be_connected===!0&&!connectedPortIds.has(port.source_port_id)){let componentName=sourceComponents.find(c4=>c4.source_component_id===port.source_component_id)?.name??"Unknown";errors.push({type:"source_pin_must_be_connected_error",source_pin_must_be_connected_error_id:`source_pin_must_be_connected_error_${port.source_port_id}`,error_type:"source_pin_must_be_connected_error",message:`Port ${port.name} on ${componentName} must be connected but is floating`,source_component_id:port.source_component_id??"",source_port_id:port.source_port_id,subcircuit_id:port.subcircuit_id})}return errors}var PIN_ATTRIBUTE_KEYS=["must_be_connected","provides_power","requires_power","provides_ground","requires_ground","provides_voltage","requires_voltage","do_not_connect","include_in_board_pinout","can_use_internal_pullup","is_using_internal_pullup","needs_external_pullup","can_use_internal_pulldown","is_using_internal_pulldown","needs_external_pulldown","can_use_open_drain","is_using_open_drain","can_use_push_pull","is_using_push_pull","should_have_decoupling_capacitor","recommended_decoupling_capacitor_capacitance","is_configured_for_i2c_sda","is_configured_for_i2c_scl","is_configured_for_spi_mosi","is_configured_for_spi_miso","is_configured_for_spi_sck","is_configured_for_spi_cs","is_configured_for_uart_tx","is_configured_for_uart_rx","supports_i2c_sda","supports_i2c_scl","supports_spi_mosi","supports_spi_miso","supports_spi_sck","supports_spi_cs","supports_uart_tx","supports_uart_rx"];function hasAnyPinAttribute(port){return PIN_ATTRIBUTE_KEYS.some(key=>port[key]!==void 0)}function checkAllPinsInComponentAreUnderspecified(circuitJson){let warnings=[],db2=cju_default(circuitJson),sourceComponents=db2.source_component.list(),sourcePorts=db2.source_port.list(),portsByComponent=new Map;for(let port of sourcePorts){if(!port.source_component_id)continue;let existing=portsByComponent.get(port.source_component_id)??[];existing.push(port),portsByComponent.set(port.source_component_id,existing)}for(let component of sourceComponents){if(component.ftype!=="simple_chip")continue;let componentPorts=portsByComponent.get(component.source_component_id)??[];componentPorts.length===0||componentPorts.some(port=>hasAnyPinAttribute(port))||warnings.push({type:"source_component_pins_underspecified_warning",source_component_pins_underspecified_warning_id:`source_component_pins_underspecified_warning_${component.source_component_id}`,warning_type:"source_component_pins_underspecified_warning",message:`All pins on ${component.name} are underspecified (no pinAttributes set)`,source_component_id:component.source_component_id,source_port_ids:componentPorts.map(port=>port.source_port_id),subcircuit_id:componentPorts[0]?.subcircuit_id})}return warnings}function checkNoPowerPinDefined(circuitJson){let warnings=[],db2=cju_default(circuitJson),sourceComponents=db2.source_component.list(),sourcePorts=db2.source_port.list(),portsByComponent=new Map;for(let port of sourcePorts){if(!port.source_component_id)continue;let existing=portsByComponent.get(port.source_component_id)??[];existing.push(port),portsByComponent.set(port.source_component_id,existing)}for(let component of sourceComponents){if(component.ftype!=="simple_chip")continue;let componentPorts=portsByComponent.get(component.source_component_id)??[];componentPorts.length===0||componentPorts.some(port=>port.requires_power===!0)||warnings.push({type:"source_no_power_pin_defined_warning",source_no_power_pin_defined_warning_id:`source_no_power_pin_defined_warning_${component.source_component_id}`,warning_type:"source_no_power_pin_defined_warning",message:`${component.name} has no pin with requires_power=true`,source_component_id:component.source_component_id,source_port_ids:componentPorts.map(port=>port.source_port_id),subcircuit_id:componentPorts[0]?.subcircuit_id})}return warnings}function checkNoGroundPinDefined(circuitJson){let warnings=[],db2=cju_default(circuitJson),sourceComponents=db2.source_component.list(),sourcePorts=db2.source_port.list(),portsByComponent=new Map;for(let port of sourcePorts){if(!port.source_component_id)continue;let existing=portsByComponent.get(port.source_component_id)??[];existing.push(port),portsByComponent.set(port.source_component_id,existing)}for(let component of sourceComponents){if(component.ftype!=="simple_chip")continue;let componentPorts=portsByComponent.get(component.source_component_id)??[];componentPorts.length===0||componentPorts.some(port=>port.requires_ground===!0)||warnings.push({type:"source_no_ground_pin_defined_warning",source_no_ground_pin_defined_warning_id:`source_no_ground_pin_defined_warning_${component.source_component_id}`,warning_type:"source_no_ground_pin_defined_warning",message:`${component.name} has no pin with requires_ground=true`,source_component_id:component.source_component_id,source_port_ids:componentPorts.map(port=>port.source_port_id),subcircuit_id:componentPorts[0]?.subcircuit_id})}return warnings}function getFacingDirectionFromInsertionDirection(component){switch(component.insertion_direction){case"from_left":return"x-";case"from_right":return"x+";case"from_front":return"y+";case"from_back":return"y-";case"from_above":return null;default:return null}}function getFacingDirection(component){if(component.insertion_direction)return getFacingDirectionFromInsertionDirection(component);if(!component.center||!component.cable_insertion_center)return null;let dx3=component.cable_insertion_center.x-component.center.x,dy3=component.cable_insertion_center.y-component.center.y;return Math.abs(dx3)<1e-6&&Math.abs(dy3)<1e-6?null:Math.abs(dx3)>=Math.abs(dy3)?dx3>=0?"x+":"x-":dy3>=0?"y+":"y-"}function getRecommendedFacingDirection(component,bounds){if(!component.center)return null;let distances=[{direction:"x-",distance:component.center.x-bounds.minX},{direction:"x+",distance:bounds.maxX-component.center.x},{direction:"y-",distance:component.center.y-bounds.minY},{direction:"y+",distance:bounds.maxY-component.center.y}];return distances.sort((a3,b3)=>a3.distance-b3.distance),distances[0]?.direction??null}function checkConnectorAccessibleOrientation(circuitJson){let board=circuitJson.find(el3=>el3.type==="pcb_board");if(!board)return[];let bounds=(()=>{try{return getBoardBounds(board)}catch{return null}})();if(!bounds)return[];let warnings=[],components=circuitJson.filter(el3=>el3.type==="pcb_component");for(let component of components){let facingDirection=getFacingDirection(component),recommendedFacingDirection=getRecommendedFacingDirection(component,bounds);if(!facingDirection||!recommendedFacingDirection||facingDirection===recommendedFacingDirection)continue;let componentName=getReadableNameForComponent(circuitJson,component.pcb_component_id);warnings.push({type:"pcb_connector_not_in_accessible_orientation_warning",warning_type:"pcb_connector_not_in_accessible_orientation_warning",pcb_connector_not_in_accessible_orientation_warning_id:`pcb_connector_not_in_accessible_orientation_warning_${component.pcb_component_id}`,message:`${componentName} is facing ${facingDirection} but should face ${recommendedFacingDirection} so the connector is accessible from the board edge`,pcb_component_id:component.pcb_component_id,source_component_id:component.source_component_id,pcb_board_id:board.pcb_board_id,facing_direction:facingDirection,recommended_facing_direction:recommendedFacingDirection,subcircuit_id:component.subcircuit_id})}return warnings}function getCourtyardPolygon(el3){if(el3.type==="pcb_courtyard_rect"){let hw3=el3.width/2,hh3=el3.height/2,corners=[{x:-hw3,y:-hh3},{x:+hw3,y:-hh3},{x:+hw3,y:+hh3},{x:-hw3,y:+hh3}],angle=(el3.ccw_rotation??0)*Math.PI/180,cos6=Math.cos(angle),sin6=Math.sin(angle);return corners.map(({x:x4,y:y4})=>({x:el3.center.x+x4*cos6-y4*sin6,y:el3.center.y+x4*sin6+y4*cos6}))}return el3.type==="pcb_courtyard_circle"?Array.from({length:32},(_4,i3)=>{let a3=2*Math.PI*i3/32;return{x:el3.center.x+el3.radius*Math.cos(a3),y:el3.center.y+el3.radius*Math.sin(a3)}}):el3.outline}function getComponentName2(circuitJson,pcbComponentId){let pcbComponent=circuitJson.find(el3=>el3.type==="pcb_component"&&el3.pcb_component_id===pcbComponentId);if(pcbComponent?.type!=="pcb_component")return pcbComponentId;let sourceComponent=circuitJson.find(el3=>el3.type==="source_component"&&el3.source_component_id===pcbComponent.source_component_id);return sourceComponent?.type==="source_component"&&sourceComponent.name?sourceComponent.name:pcbComponentId}function polygonsOverlap(polyA,polyB){if(polyA.some(p4=>isPointInsidePolygon(p4,polyB))||polyB.some(p4=>isPointInsidePolygon(p4,polyA)))return!0;for(let i3=0;i3<polyA.length;i3++){let a12=polyA[i3],a22=polyA[(i3+1)%polyA.length];for(let j4=0;j4<polyB.length;j4++){let b12=polyB[j4],b22=polyB[(j4+1)%polyB.length];if(doSegmentsIntersect(a12,a22,b12,b22))return!0}}return!1}function checkCourtyardOverlap(circuitJson){let courtyards=circuitJson.filter(el3=>el3.type==="pcb_courtyard_rect"||el3.type==="pcb_courtyard_circle"||el3.type==="pcb_courtyard_outline"),byComponent=new Map;for(let el3 of courtyards){let id2=el3.pcb_component_id;byComponent.has(id2)||byComponent.set(id2,[]),byComponent.get(id2).push(el3)}let componentIds=Array.from(byComponent.keys()),errors=[];for(let i3=0;i3<componentIds.length;i3++)for(let j4=i3+1;j4<componentIds.length;j4++){let idA=componentIds[i3],idB=componentIds[j4],overlapping=!1;outer:for(let a3 of byComponent.get(idA))for(let b3 of byComponent.get(idB)){if("layer"in a3&&"layer"in b3&&a3.layer!==b3.layer)continue;let polyA=getCourtyardPolygon(a3),polyB=getCourtyardPolygon(b3);if(polygonsOverlap(polyA,polyB)){overlapping=!0;break outer}}overlapping&&errors.push({type:"pcb_courtyard_overlap_error",pcb_error_id:`pcb_courtyard_overlap_${idA}_${idB}`,error_type:"pcb_courtyard_overlap_error",message:`Courtyard of ${getComponentName2(circuitJson,idA)} overlaps with courtyard of ${getComponentName2(circuitJson,idB)}`,pcb_component_ids:[idA,idB]})}return errors}function getDistanceBetweenPoints(pointA,pointB){return Math.sqrt((pointB.x-pointA.x)**2+(pointB.y-pointA.y)**2)}var POINT_ON_SEGMENT_TOLERANCE_MM=1e-9;function isPointOnSegment3(point7,segment2){let crossProduct=(point7.y-segment2.start.y)*(segment2.end.x-segment2.start.x)-(point7.x-segment2.start.x)*(segment2.end.y-segment2.start.y);if(Math.abs(crossProduct)>POINT_ON_SEGMENT_TOLERANCE_MM)return!1;let dotProduct=(point7.x-segment2.start.x)*(segment2.end.x-segment2.start.x)+(point7.y-segment2.start.y)*(segment2.end.y-segment2.start.y);if(dotProduct<-POINT_ON_SEGMENT_TOLERANCE_MM)return!1;let squaredLength=(segment2.end.x-segment2.start.x)**2+(segment2.end.y-segment2.start.y)**2;return dotProduct<=squaredLength+POINT_ON_SEGMENT_TOLERANCE_MM}function isPointInPad(point7,pad2){if(pad2.type==="pcb_smtpad"){if(pad2.shape==="circle")return getDistanceBetweenPoints(point7,pad2)<=pad2.radius;if(pad2.shape==="rect"){let halfWidth=pad2.width/2,halfHeight=pad2.height/2;return Math.abs(point7.x-pad2.x)<=halfWidth&&Math.abs(point7.y-pad2.y)<=halfHeight}if(pad2.shape==="rotated_rect"){let dx3=point7.x-pad2.x,dy3=point7.y-pad2.y,angle=-pad2.ccw_rotation,rotatedX=dx3*Math.cos(angle)-dy3*Math.sin(angle),rotatedY=dx3*Math.sin(angle)+dy3*Math.cos(angle);return Math.abs(rotatedX)<=pad2.width/2&&Math.abs(rotatedY)<=pad2.height/2}if(pad2.shape==="pill"){let halfWidth=pad2.width/2,halfHeight=pad2.height/2,radius=pad2.radius;if(Math.abs(point7.x-pad2.x)<=halfWidth-radius&&Math.abs(point7.y-pad2.y)<=halfHeight)return!0;let cornerX=Math.max(Math.abs(point7.x-pad2.x)-(halfWidth-radius),0),cornerY=Math.max(Math.abs(point7.y-pad2.y)-(halfHeight-radius),0);return cornerX*cornerX+cornerY*cornerY<=radius*radius}if(pad2.shape==="polygon"){let inside2=!1;for(let i3=0,j4=pad2.points.length-1;i3<pad2.points.length;j4=i3++){let pi3=pad2.points[i3],pj=pad2.points[j4];if(isPointOnSegment3(point7,{start:pi3,end:pj}))return!0;pi3.y>point7.y!=pj.y>point7.y&&point7.x<(pj.x-pi3.x)*(point7.y-pi3.y)/(pj.y-pi3.y)+pi3.x&&(inside2=!inside2)}return inside2}}if(pad2.type==="pcb_plated_hole"){if(pad2.shape==="circle")return getDistanceBetweenPoints(point7,pad2)<=pad2.outer_diameter/2;if(pad2.shape==="oval"||pad2.shape==="pill")return Math.abs(point7.x-pad2.x)<=pad2.outer_width/2&&Math.abs(point7.y-pad2.y)<=pad2.outer_height/2;if(pad2.shape==="circular_hole_with_rect_pad"||pad2.shape==="pill_hole_with_rect_pad")return Math.abs(point7.x-pad2.x)<=pad2.rect_pad_width/2&&Math.abs(point7.y-pad2.y)<=pad2.rect_pad_height/2}return!1}function getRoutePointCenter(point7){return point7.route_type==="through_pad"?{x:(point7.start.x+point7.end.x)/2,y:(point7.start.y+point7.end.y)/2}:{x:point7.x,y:point7.y}}function routePointConnectsToAnotherExpectedPort(point7,expectedPorts,missingPcbPortId,padMap){return point7.route_type!=="wire"?!1:expectedPorts.some(expectedPort=>!expectedPort.pcb_port_id||expectedPort.pcb_port_id===missingPcbPortId?!1:padMap.get(expectedPort.pcb_port_id)?.some(pad2=>isPointInPad({x:point7.x,y:point7.y},pad2))??!1)}function getMissingConnectionErrorCenter({firstPoint,lastPoint,port,expectedPorts,padMap}){let errorLocation,firstWirePoint=firstPoint.route_type==="wire"?firstPoint:void 0,lastWirePoint=lastPoint.route_type==="wire"?lastPoint:void 0,firstWirePointReferencesPort=getPcbPortIdsConnectedToRoutePoint(firstPoint).includes(port.pcb_port_id),lastWirePointReferencesPort=getPcbPortIdsConnectedToRoutePoint(lastPoint).includes(port.pcb_port_id);firstWirePointReferencesPort&&firstWirePoint?errorLocation=firstWirePoint:lastWirePointReferencesPort&&lastWirePoint||routePointConnectsToAnotherExpectedPort(firstPoint,expectedPorts,port.pcb_port_id,padMap)&&lastWirePoint?errorLocation=lastWirePoint:routePointConnectsToAnotherExpectedPort(lastPoint,expectedPorts,port.pcb_port_id,padMap)&&firstWirePoint?errorLocation=firstWirePoint:firstWirePoint&&lastWirePoint?errorLocation=distance22(firstWirePoint,port)<=distance22(lastWirePoint,port)?firstWirePoint:lastWirePoint:firstWirePoint?errorLocation=firstWirePoint:lastWirePoint&&(errorLocation=lastWirePoint);let firstPointCenter=getRoutePointCenter(firstPoint),lastPointCenter=getRoutePointCenter(lastPoint);return errorLocation?{x:errorLocation.x,y:errorLocation.y}:{x:(firstPointCenter.x+lastPointCenter.x)/2,y:(firstPointCenter.y+lastPointCenter.y)/2}}function checkTracesAreContiguous(circuitJson){let errors=[],pcbPorts=circuitJson.filter(el3=>el3.type==="pcb_port"),pcbTraces=circuitJson.filter(el3=>el3.type==="pcb_trace"),sourceTraces=circuitJson.filter(el3=>el3.type==="source_trace"),pcbSmtPads=circuitJson.filter(el3=>el3.type==="pcb_smtpad"),pcbPlatedHoles=circuitJson.filter(el3=>el3.type==="pcb_plated_hole"),padMap=new Map,pcbConnectivityMap=new PcbConnectivityMap(circuitJson);for(let pad2 of pcbSmtPads)pad2.pcb_port_id&&padMap.set(pad2.pcb_port_id,[...padMap.get(pad2.pcb_port_id)??[],pad2]);for(let hole of pcbPlatedHoles)hole.pcb_port_id&&padMap.set(hole.pcb_port_id,[...padMap.get(hole.pcb_port_id)??[],hole]);for(let trace of pcbTraces){if(trace.route.length===0)continue;let firstPoint=trace.route[0],lastPoint=trace.route[trace.route.length-1],sourceTrace=sourceTraces.find(st3=>st3.source_trace_id===trace.source_trace_id),expectedPorts=sourceTrace?pcbPorts.filter(port=>sourceTrace.connected_source_port_ids?.includes(port.source_port_id)):[];for(let i3=1;i3<trace.route.length-1;i3++){let prevPoint=trace.route[i3-1],currentPoint=trace.route[i3],nextPoint=trace.route[i3+1];if(currentPoint.route_type==="via"){let prevIsWire=prevPoint.route_type==="wire",nextIsWire=nextPoint.route_type==="wire";if(prevIsWire&&nextIsWire){let prevAligned=Math.abs(prevPoint.x-currentPoint.x)<.01&&Math.abs(prevPoint.y-currentPoint.y)<.01,nextAligned=Math.abs(nextPoint.x-currentPoint.x)<.01&&Math.abs(nextPoint.y-currentPoint.y)<.01;if(!prevAligned||!nextAligned){let traceName2=getReadableNameForPcbTrace(circuitJson,trace.pcb_trace_id);errors.push({type:"pcb_trace_error",message:`Via in trace [${traceName2}] is misaligned at position {x: ${currentPoint.x}, y: ${currentPoint.y}}.`,source_trace_id:sourceTrace?.source_trace_id||trace.source_trace_id||`!${trace.pcb_trace_id}`,error_type:"pcb_trace_error",pcb_trace_id:trace.pcb_trace_id,pcb_trace_error_id:`misaligned_via_${trace.pcb_trace_id}_${i3}`,pcb_component_ids:[],pcb_port_ids:[]})}}}}let traceName=getReadableNameForPcbTrace(circuitJson,trace.pcb_trace_id);for(let port of expectedPorts){if(!port.pcb_port_id)continue;let pads=padMap.get(port.pcb_port_id);if(!pads?.length)continue;let isConnectedByRoutedSourceTrace=!1;for(let candidateTrace of pcbConnectivityMap.getAllTracesConnectedToTrace(trace.pcb_trace_id)){if(candidateTrace.pcb_trace_id===trace.pcb_trace_id||!candidateTrace.source_trace_id)continue;let candidateSourceTrace=sourceTraces.find(st3=>st3.source_trace_id===candidateTrace.source_trace_id);if(!(!sourceTrace||candidateTrace.source_trace_id!==sourceTrace.source_trace_id&&!candidateSourceTrace?.connected_source_port_ids.includes(port.source_port_id))&&getPcbPortIdsConnectedToTrace(candidateTrace).includes(port.pcb_port_id)){isConnectedByRoutedSourceTrace=!0;break}}if(isConnectedByRoutedSourceTrace)continue;let isFirstPointConnected=firstPoint.route_type==="wire"&&pads.some(pad2=>isPointInPad({x:firstPoint.x,y:firstPoint.y},pad2)),isLastPointConnected=lastPoint.route_type==="wire"&&pads.some(pad2=>isPointInPad({x:lastPoint.x,y:lastPoint.y},pad2));if(!isFirstPointConnected&&!isLastPointConnected){let portName=getReadableNameForPcbPort(circuitJson,port.pcb_port_id).replace("pcb_port",""),padType=pads[0].type.replace(/pcb_/,""),errorCenter=getMissingConnectionErrorCenter({firstPoint,lastPoint,port,expectedPorts,padMap});errors.push({type:"pcb_trace_error",message:`Trace [${traceName}] is missing a connection to ${padType}${portName}`,source_trace_id:sourceTrace?.source_trace_id||trace.source_trace_id||`!${trace.pcb_trace_id}`,error_type:"pcb_trace_error",pcb_trace_id:trace.pcb_trace_id,pcb_trace_error_id:`missing_connection_${trace.pcb_trace_id}_${port.pcb_port_id}`,center:errorCenter,pcb_component_ids:[],pcb_port_ids:[port.pcb_port_id]})}}if(expectedPorts.length===0){let firstConnectsToAnyPad=!1,lastConnectsToAnyPad=!1,endpointsAreSame=firstPoint.route_type==="wire"&&lastPoint.route_type==="wire"&&Math.abs(firstPoint.x-lastPoint.x)<.01&&Math.abs(firstPoint.y-lastPoint.y)<.01;for(let pads of padMap.values())firstPoint.route_type==="wire"&&pads.some(pad2=>isPointInPad({x:firstPoint.x,y:firstPoint.y},pad2))&&(firstConnectsToAnyPad=!0),lastPoint.route_type==="wire"&&pads.some(pad2=>isPointInPad({x:lastPoint.x,y:lastPoint.y},pad2))&&(lastConnectsToAnyPad=!0);!firstConnectsToAnyPad&&firstPoint.route_type==="wire"&&errors.push({type:"pcb_trace_error",message:`Trace [${traceName}] has disconnected endpoint at (${firstPoint.x.toFixed(2)}, ${firstPoint.y.toFixed(2)})`,source_trace_id:sourceTrace?.source_trace_id||trace.source_trace_id||`!${trace.pcb_trace_id}`,error_type:"pcb_trace_error",pcb_trace_id:trace.pcb_trace_id,pcb_trace_error_id:`disconnected_endpoint_${trace.pcb_trace_id}_start`,center:{x:firstPoint.x,y:firstPoint.y},pcb_component_ids:[],pcb_port_ids:[]}),!lastConnectsToAnyPad&&lastPoint.route_type==="wire"&&!(endpointsAreSame&&!firstConnectsToAnyPad)&&errors.push({type:"pcb_trace_error",message:`Trace [${traceName}] has disconnected endpoint at (${lastPoint.x.toFixed(2)}, ${lastPoint.y.toFixed(2)})`,source_trace_id:sourceTrace?.source_trace_id||trace.source_trace_id||`!${trace.pcb_trace_id}`,error_type:"pcb_trace_error",pcb_trace_id:trace.pcb_trace_id,pcb_trace_error_id:`disconnected_endpoint_${trace.pcb_trace_id}_end`,center:{x:lastPoint.x,y:lastPoint.y},pcb_component_ids:[],pcb_port_ids:[]})}}return errors}async function runAllPlacementChecks(circuitJson){return[...checkViasOffBoard(circuitJson),...checkPcbComponentsOutOfBoard(circuitJson),...checkPcbComponentOverlap(circuitJson),...checkPadPadClearance(circuitJson),...checkPadTraceClearance(circuitJson),...checkCourtyardOverlap(circuitJson),...checkConnectorAccessibleOrientation(circuitJson)]}async function runAllNetlistChecks(circuitJson){return[...checkPinMustBeConnected(circuitJson)]}async function runAllPinSpecificationChecks(circuitJson){return[...checkAllPinsInComponentAreUnderspecified(circuitJson),...checkNoPowerPinDefined(circuitJson),...checkNoGroundPinDefined(circuitJson)]}async function runAllRoutingChecks(circuitJson){return[...checkEachPcbPortConnectedToPcbTraces(circuitJson),...checkSourceTracesHavePcbTraces(circuitJson),...checkEachPcbTraceNonOverlapping(circuitJson),...checkViaTraceClearance(circuitJson),...checkSameNetViaSpacing(circuitJson),...checkDifferentNetViaSpacing(circuitJson),...checkTracesAreContiguous(circuitJson),...checkPcbTracesOutOfBoard(circuitJson)]}init_dist6();var SI_PREFIXES=[{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 formatSiUnit(value){if(value==null)return"";if(value===0)return"0";let absValue=Math.abs(value),prefix=SI_PREFIXES.find(p4=>{let scaled2=absValue/p4.value;return scaled2>=1&&scaled2<1e3})||SI_PREFIXES[SI_PREFIXES.length-1],formatted=(value/prefix.value).toPrecision(3);return formatted.includes(".")&&!/\.0+$/.test(formatted)&&(formatted=formatted.replace(/0+$/,"")),formatted=formatted.replace(/\.0+$/,""),`${formatted}${prefix.symbol}`}init_dist6();init_dist();var FlatQueue=class{constructor(capacity2=1/0,ValuesArray=Float64Array,IdsArray=Uint32Array){let fixed=capacity2!==1/0;this.ids=fixed?new IdsArray(capacity2):[],this.values=fixed?new ValuesArray(capacity2):[],this.capacity=capacity2,this.length=0}clear(){this.length=0}push(item,priority){if(this.length===this.capacity)throw new RangeError("Queue is at capacity.");let pos=this.length++;for(;pos>0;){let parent=pos-1>>1,parentValue=this.values[parent];if(priority>=parentValue)break;this.ids[pos]=this.ids[parent],this.values[pos]=parentValue,pos=parent}this.ids[pos]=item,this.values[pos]=priority}pop(){if(this.length===0)return;let ids=this.ids,values=this.values,top=ids[0],last=--this.length;if(last>0){let id2=ids[last],value=values[last],pos=0,halfLen=last>>1;for(;pos<halfLen;){let left=(pos<<1)+1,right=left+1,child=left+(+(right<last)&+(values[right]<values[left]));if(values[child]>=value)break;ids[pos]=ids[child],values[pos]=values[child],pos=child}ids[pos]=id2,values[pos]=value}return top}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){Array.isArray(this.ids)&&(this.ids.length=this.length),Array.isArray(this.values)&&(this.values.length=this.length)}};var ARRAY_TYPES=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],VERSION=3,Flatbush=class _Flatbush{static from(data,byteOffset=0){if(byteOffset%8!==0)throw new Error("byteOffset must be 8-byte aligned.");if(!data||data.byteLength===void 0||"buffer"in data)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[magic,versionAndType]=new Uint8Array(data,byteOffset+0,2);if(magic!==251)throw new Error("Data does not appear to be in a Flatbush format.");let version2=versionAndType>>4;if(version2!==VERSION)throw new Error(`Got v${version2} data when expected v${VERSION}.`);let ArrayType=ARRAY_TYPES[versionAndType&15];if(!ArrayType)throw new Error("Unrecognized array type.");let[nodeSize]=new Uint16Array(data,byteOffset+2,1),[numItems]=new Uint32Array(data,byteOffset+4,1);return new _Flatbush(numItems,nodeSize,ArrayType,void 0,data,byteOffset)}constructor(numItems,nodeSize=16,ArrayType=Float64Array,ArrayBufferType=ArrayBuffer,data,byteOffset=0){if(numItems===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(numItems)||numItems<=0)throw new Error(`Unexpected numItems value: ${numItems}.`);this.numItems=+numItems,this.nodeSize=Math.min(Math.max(+nodeSize,2),65535),this.byteOffset=byteOffset;let n4=numItems,numNodes=n4;this._levelBounds=[n4*4];do n4=Math.ceil(n4/this.nodeSize),numNodes+=n4,this._levelBounds.push(numNodes*4);while(n4!==1);this.ArrayType=ArrayType,this.IndexArrayType=numNodes<16384?Uint16Array:Uint32Array;let arrayTypeIndex=ARRAY_TYPES.indexOf(ArrayType),nodesByteSize=numNodes*4*ArrayType.BYTES_PER_ELEMENT;if(arrayTypeIndex<0)throw new Error(`Unexpected typed array class: ${ArrayType}.`);let BoxCtor=ArrayType,IdxCtor=this.IndexArrayType;if(data)this.data=data,this._boxes=new BoxCtor(data,byteOffset+8,numNodes*4),this._indices=new IdxCtor(data,byteOffset+8+nodesByteSize,numNodes),this._pos=numNodes*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 data2=this.data=new ArrayBufferType(8+nodesByteSize+numNodes*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new BoxCtor(data2,8,numNodes*4),this._indices=new IdxCtor(data2,8+nodesByteSize,numNodes),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(data2,0,2).set([251,(VERSION<<4)+arrayTypeIndex]),new Uint16Array(data2,2,1)[0]=nodeSize,new Uint32Array(data2,4,1)[0]=numItems}this._queue=new FlatQueue}add(minX,minY,maxX=minX,maxY=minY){let pos=this._pos,index=pos>>2,boxes=this._boxes;return this._indices[index]=index,boxes[pos]=minX,boxes[pos+1]=minY,boxes[pos+2]=maxX,boxes[pos+3]=maxY,this._pos=pos+4,minX<this.minX&&(this.minX=minX),minY<this.minY&&(this.minY=minY),maxX>this.maxX&&(this.maxX=maxX),maxY>this.maxY&&(this.maxY=maxY),index}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let boxes=this._boxes;if(this.numItems<=this.nodeSize){boxes[this._pos++]=this.minX,boxes[this._pos++]=this.minY,boxes[this._pos++]=this.maxX,boxes[this._pos++]=this.maxY;return}let{numItems,minX,minY,nodeSize,_indices:indices,_levelBounds:levelBounds}=this,width=this.maxX-minX||1,height=this.maxY-minY||1,hilbertValues=new Int32Array(numItems),hilbertMax=65535,sx3=hilbertMax/width,sy3=hilbertMax/height;for(let i3=0,pos2=0;i3<numItems;i3++){let itemMinX=boxes[pos2++],itemMinY=boxes[pos2++],itemMaxX=boxes[pos2++],itemMaxY=boxes[pos2++],x4=sx3*((itemMinX+itemMaxX)/2-minX)|0,y4=sy3*((itemMinY+itemMaxY)/2-minY)|0;hilbertValues[i3]=hilbert(x4,y4)}sort(hilbertValues,boxes,indices,0,numItems-1,nodeSize);let pos=numItems*4;for(let i3=0,readPos=0;i3<levelBounds.length-1;i3++){let end=levelBounds[i3];for(;readPos<end;){let nodeIndex=readPos,nodeMinX=boxes[readPos++],nodeMinY=boxes[readPos++],nodeMaxX=boxes[readPos++],nodeMaxY=boxes[readPos++];for(let j4=1;j4<nodeSize&&readPos<end;j4++)nodeMinX=Math.min(nodeMinX,boxes[readPos++]),nodeMinY=Math.min(nodeMinY,boxes[readPos++]),nodeMaxX=Math.max(nodeMaxX,boxes[readPos++]),nodeMaxY=Math.max(nodeMaxY,boxes[readPos++]);indices[pos>>2]=nodeIndex,boxes[pos++]=nodeMinX,boxes[pos++]=nodeMinY,boxes[pos++]=nodeMaxX,boxes[pos++]=nodeMaxY}}this._pos=pos}search(minX,minY,maxX,maxY,filterFn){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let{_boxes:boxes,_levelBounds:levelBounds,_indices:indices,nodeSize}=this,numItems4=this.numItems*4,nodeIndex=boxes.length-4,level=levelBounds.length-1,q4=[],results=[],contained=!1;for(;nodeIndex!==void 0;){let end=Math.min(nodeIndex+nodeSize*4,levelBounds[level]),isNode=nodeIndex>=numItems4;if(contained)this._collectContained(nodeIndex,end,level,numItems4,results,filterFn);else for(let pos=nodeIndex;pos<end;pos+=4){let x02=boxes[pos];if(maxX<x02)continue;let y02=boxes[pos+1];if(maxY<y02)continue;let x12=boxes[pos+2];if(minX>x12)continue;let y12=boxes[pos+3];if(minY>y12)continue;let index=indices[pos>>2]|0;if(isNode){let c4=+(minX<=x02&&minY<=y02&&maxX>=x12&&maxY>=y12);q4.push(index|c4,level-1)}else(filterFn===void 0||filterFn(index,x02,y02,x12,y12))&&results.push(index)}level=q4.pop(),nodeIndex=q4.pop(),nodeIndex!==void 0&&(contained=(nodeIndex&1)===1,nodeIndex&=-2)}return results}_collectContained(nodeIndex,end,level,numItems4,results,filterFn){let boxes=this._boxes,indices=this._indices,pos=nodeIndex;for(let l4=level;l4>0;l4--)pos=indices[pos>>2];let leafEnd=Math.min(pos+(end-nodeIndex)*this.nodeSize**level,numItems4);if(filterFn===void 0)for(;pos<leafEnd;pos+=4)results.push(indices[pos>>2]|0);else for(;pos<leafEnd;pos+=4){let index=indices[pos>>2]|0;filterFn(index,boxes[pos],boxes[pos+1],boxes[pos+2],boxes[pos+3])&&results.push(index)}}neighbors(x4,y4,maxResults=1/0,maxDistance=1/0,filterFn){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let{_boxes:boxes,_levelBounds:levelBounds,_indices:indices,_queue:q4,nodeSize}=this,numItems4=this.numItems*4,nodeSize4=nodeSize*4,results=[],maxDistSquared=maxDistance*maxDistance,trackNearest=maxResults===1,bound=maxDistSquared;for(q4.push(boxes.length-4<<1,0);q4.length;){let top=q4.ids[0];if(top&1){if(q4.pop(),results.push(top>>1),results.length===maxResults)break;continue}q4.pop();let nodeIndex=top>>1,isLeafLevel=nodeIndex<numItems4,end=Math.min(nodeIndex+nodeSize4,upperBound(nodeIndex,levelBounds));for(let pos=nodeIndex;pos<end;pos+=4){let minX=boxes[pos],minY=boxes[pos+1],maxX=boxes[pos+2],maxY=boxes[pos+3],dx3=Math.max(Math.max(minX-x4,x4-maxX),0),dy3=Math.max(Math.max(minY-y4,y4-maxY),0),dist=dx3*dx3+dy3*dy3;if(dist>bound)continue;let childIndex=indices[pos>>2]|0;isLeafLevel?(filterFn===void 0||filterFn(childIndex))&&(q4.push(childIndex<<1|1,dist),trackNearest&&dist<bound&&(bound=dist)):q4.push(childIndex<<1,dist)}}return q4.clear(),results}};function upperBound(value,arr){let i3=0,j4=arr.length-1;for(;i3<j4;){let m4=i3+j4>>1;arr[m4]>value?j4=m4:i3=m4+1}return arr[i3]}function sort(values,boxes,indices,left,right,nodeSize){let stack=[left,right];for(;stack.length;){let r5=stack.pop()||0,l4=stack.pop()||0;if(r5-l4<=nodeSize&&Math.floor(l4/nodeSize)>=Math.floor(r5/nodeSize))continue;let a3=values[l4],b3=values[l4+r5>>1],c4=values[r5],pivot=a3>b3!=a3>c4?a3:b3<a3!=b3<c4?b3:c4,i3=l4-1,j4=r5+1;for(;;){do i3++;while(values[i3]<pivot);do j4--;while(values[j4]>pivot);if(i3>=j4)break;swap(values,boxes,indices,i3,j4)}stack.push(l4,j4,j4+1,r5)}}function swap(values,boxes,indices,i3,j4){let temp=values[i3];values[i3]=values[j4],values[j4]=temp;let k4=4*i3,m4=4*j4,a3=boxes[k4],b3=boxes[k4+1],c4=boxes[k4+2],d4=boxes[k4+3];boxes[k4]=boxes[m4],boxes[k4+1]=boxes[m4+1],boxes[k4+2]=boxes[m4+2],boxes[k4+3]=boxes[m4+3],boxes[m4]=a3,boxes[m4+1]=b3,boxes[m4+2]=c4,boxes[m4+3]=d4;let e5=indices[i3];indices[i3]=indices[j4],indices[j4]=e5}function hilbert(x4,y4){let a3=x4^y4,b3=65535^a3,c4=65535^(x4|y4),d4=x4&(y4^65535),A4=a3|b3>>1,B4=a3>>1^a3,C4=c4^(c4>>1^b3&d4>>1),D4=d4^(a3&c4>>1^d4>>1);return a3=A4&A4>>2^B4&B4>>2,b3=A4&B4>>2^B4&(A4^B4)>>2,c4=C4^(A4&C4>>2^B4&D4>>2),d4=D4^(B4&C4>>2^(A4^B4)&D4>>2),A4=a3&a3>>4^b3&b3>>4,B4=a3&b3>>4^b3&(a3^b3)>>4,C4=c4^(a3&c4>>4^b3&d4>>4),D4=d4^(b3&c4>>4^(a3^b3)&d4>>4),c4=C4^(A4&C4>>8^B4&D4>>8),d4=D4^(B4&C4>>8^(A4^B4)&D4>>8),c4^=c4>>1,d4^=d4>>1,a3=x4^y4,b3=d4|65535^(a3|c4),a3=(a3|a3<<8)&16711935,a3=(a3|a3<<4)&252645135,a3=(a3|a3<<2)&858993459,a3=(a3|a3<<1)&1431655765,b3=(b3|b3<<8)&16711935,b3=(b3|b3<<4)&252645135,b3=(b3|b3<<2)&858993459,b3=(b3|b3<<1)&1431655765,((b3<<1|a3)>>>0)-2147483648}var __create2=Object.create,__defProp3=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__getProtoOf2=Object.getPrototypeOf,__hasOwnProp2=Object.prototype.hasOwnProperty,__commonJS2=(cb3,mod)=>function(){return mod||(0,cb3[__getOwnPropNames2(cb3)[0]])((mod={exports:{}}).exports,mod),mod.exports},__copyProps2=(to3,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames2(from))!__hasOwnProp2.call(to3,key)&&key!==except&&__defProp3(to3,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc2(from,key))||desc.enumerable});return to3},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create2(__getProtoOf2(mod)):{},__copyProps2(isNodeMode||!mod||!mod.__esModule?__defProp3(target,"default",{value:mod,enumerable:!0}):target,mod)),require_is_buffer=__commonJS2({"node_modules/is-buffer/index.js"(exports,module){"use strict";module.exports=function(obj){return obj!=null&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)};function isBuffer(obj){return!!obj.constructor&&typeof obj.constructor.isBuffer=="function"&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return typeof obj.readFloatLE=="function"&&typeof obj.slice=="function"&&isBuffer(obj.slice(0,0))}}}),require_kind_of=__commonJS2({"node_modules/kind-of/index.js"(exports,module){"use strict";var isBuffer=require_is_buffer(),toString3=Object.prototype.toString;module.exports=function(val){if(typeof val>"u")return"undefined";if(val===null)return"null";if(val===!0||val===!1||val instanceof Boolean)return"boolean";if(typeof val=="string"||val instanceof String)return"string";if(typeof val=="number"||val instanceof Number)return"number";if(typeof val=="function"||val instanceof Function)return"function";if(typeof Array.isArray<"u"&&Array.isArray(val))return"array";if(val instanceof RegExp)return"regexp";if(val instanceof Date)return"date";var type=toString3.call(val);return type==="[object RegExp]"?"regexp":type==="[object Date]"?"date":type==="[object Arguments]"?"arguments":type==="[object Error]"?"error":isBuffer(val)?"buffer":type==="[object Set]"?"set":type==="[object WeakSet]"?"weakset":type==="[object Map]"?"map":type==="[object WeakMap]"?"weakmap":type==="[object Symbol]"?"symbol":type==="[object Int8Array]"?"int8array":type==="[object Uint8Array]"?"uint8array":type==="[object Uint8ClampedArray]"?"uint8clampedarray":type==="[object Int16Array]"?"int16array":type==="[object Uint16Array]"?"uint16array":type==="[object Int32Array]"?"int32array":type==="[object Uint32Array]"?"uint32array":type==="[object Float32Array]"?"float32array":type==="[object Float64Array]"?"float64array":"object"}}}),require_rename_keys=__commonJS2({"node_modules/rename-keys/index.js"(exports,module){"use strict";(function(){"use strict";function rename2(obj,fn3){if(typeof fn3!="function")return obj;var res2={};for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(res2[fn3(key,obj[key])||key]=obj[key]);return res2}typeof module<"u"&&module.exports?module.exports=rename2:typeof define=="function"&&define.amd?define([],function(){return rename2}):window.rename=rename2})()}}),require_deep_rename_keys=__commonJS2({"node_modules/deep-rename-keys/index.js"(exports,module){"use strict";var typeOf=require_kind_of(),rename2=require_rename_keys();module.exports=function renameDeep(obj,cb3){var type=typeOf(obj);if(type!=="object"&&type!=="array")throw new Error("expected an object");var res2=[];type==="object"&&(obj=rename2(obj,cb3),res2={});for(var key in obj)if(obj.hasOwnProperty(key)){var val=obj[key];typeOf(val)==="object"||typeOf(val)==="array"?res2[key]=renameDeep(val,cb3):res2[key]=val}return res2}}}),require_eventemitter3=__commonJS2({"node_modules/eventemitter3/index.js"(exports,module){"use strict";var has=Object.prototype.hasOwnProperty,prefix="~";function Events(){}Object.create&&(Events.prototype=Object.create(null),new Events().__proto__||(prefix=!1));function EE3(fn3,context,once){this.fn=fn3,this.context=context,this.once=once||!1}function EventEmitter(){this._events=new Events,this._eventsCount=0}EventEmitter.prototype.eventNames=function(){var names=[],events,name;if(this._eventsCount===0)return names;for(name in events=this._events)has.call(events,name)&&names.push(prefix?name.slice(1):name);return Object.getOwnPropertySymbols?names.concat(Object.getOwnPropertySymbols(events)):names},EventEmitter.prototype.listeners=function(event,exists){var evt=prefix?prefix+event:event,available=this._events[evt];if(exists)return!!available;if(!available)return[];if(available.fn)return[available.fn];for(var i3=0,l4=available.length,ee3=new Array(l4);i3<l4;i3++)ee3[i3]=available[i3].fn;return ee3},EventEmitter.prototype.emit=function(event,a12,a22,a3,a4,a52){var evt=prefix?prefix+event:event;if(!this._events[evt])return!1;var listeners=this._events[evt],len=arguments.length,args,i3;if(listeners.fn){switch(listeners.once&&this.removeListener(event,listeners.fn,void 0,!0),len){case 1:return listeners.fn.call(listeners.context),!0;case 2:return listeners.fn.call(listeners.context,a12),!0;case 3:return listeners.fn.call(listeners.context,a12,a22),!0;case 4:return listeners.fn.call(listeners.context,a12,a22,a3),!0;case 5:return listeners.fn.call(listeners.context,a12,a22,a3,a4),!0;case 6:return listeners.fn.call(listeners.context,a12,a22,a3,a4,a52),!0}for(i3=1,args=new Array(len-1);i3<len;i3++)args[i3-1]=arguments[i3];listeners.fn.apply(listeners.context,args)}else{var length22=listeners.length,j4;for(i3=0;i3<length22;i3++)switch(listeners[i3].once&&this.removeListener(event,listeners[i3].fn,void 0,!0),len){case 1:listeners[i3].fn.call(listeners[i3].context);break;case 2:listeners[i3].fn.call(listeners[i3].context,a12);break;case 3:listeners[i3].fn.call(listeners[i3].context,a12,a22);break;case 4:listeners[i3].fn.call(listeners[i3].context,a12,a22,a3);break;default:if(!args)for(j4=1,args=new Array(len-1);j4<len;j4++)args[j4-1]=arguments[j4];listeners[i3].fn.apply(listeners[i3].context,args)}}return!0},EventEmitter.prototype.on=function(event,fn3,context){var listener=new EE3(fn3,context||this),evt=prefix?prefix+event:event;return this._events[evt]?this._events[evt].fn?this._events[evt]=[this._events[evt],listener]:this._events[evt].push(listener):(this._events[evt]=listener,this._eventsCount++),this},EventEmitter.prototype.once=function(event,fn3,context){var listener=new EE3(fn3,context||this,!0),evt=prefix?prefix+event:event;return this._events[evt]?this._events[evt].fn?this._events[evt]=[this._events[evt],listener]:this._events[evt].push(listener):(this._events[evt]=listener,this._eventsCount++),this},EventEmitter.prototype.removeListener=function(event,fn3,context,once){var evt=prefix?prefix+event:event;if(!this._events[evt])return this;if(!fn3)return--this._eventsCount===0?this._events=new Events:delete this._events[evt],this;var listeners=this._events[evt];if(listeners.fn)listeners.fn===fn3&&(!once||listeners.once)&&(!context||listeners.context===context)&&(--this._eventsCount===0?this._events=new Events:delete this._events[evt]);else{for(var i3=0,events=[],length22=listeners.length;i3<length22;i3++)(listeners[i3].fn!==fn3||once&&!listeners[i3].once||context&&listeners[i3].context!==context)&&events.push(listeners[i3]);events.length?this._events[evt]=events.length===1?events[0]:events:--this._eventsCount===0?this._events=new Events:delete this._events[evt]}return this},EventEmitter.prototype.removeAllListeners=function(event){var evt;return event?(evt=prefix?prefix+event:event,this._events[evt]&&(--this._eventsCount===0?this._events=new Events:delete this._events[evt])):(this._events=new Events,this._eventsCount=0),this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.addListener=EventEmitter.prototype.on,EventEmitter.prototype.setMaxListeners=function(){return this},EventEmitter.prefixed=prefix,EventEmitter.EventEmitter=EventEmitter,typeof module<"u"&&(module.exports=EventEmitter)}}),require_lexer=__commonJS2({"node_modules/xml-lexer/dist/lexer.js"(exports,module){"use strict";function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}var EventEmitter=require_eventemitter3(),noop=function(){},State2={data:"state-data",cdata:"state-cdata",tagBegin:"state-tag-begin",tagName:"state-tag-name",tagEnd:"state-tag-end",attributeNameStart:"state-attribute-name-start",attributeName:"state-attribute-name",attributeNameEnd:"state-attribute-name-end",attributeValueBegin:"state-attribute-value-begin",attributeValue:"state-attribute-value"},Action={lt:"action-lt",gt:"action-gt",space:"action-space",equal:"action-equal",quote:"action-quote",slash:"action-slash",char:"action-char",error:"action-error"},Type={text:"text",openTag:"open-tag",closeTag:"close-tag",attributeName:"attribute-name",attributeValue:"attribute-value"},charToAction={" ":Action.space," ":Action.space,"\n":Action.space,"\r":Action.space,"<":Action.lt,">":Action.gt,'"':Action.quote,"'":Action.quote,"=":Action.equal,"/":Action.slash},getAction=function(char){return charToAction[char]||Action.char},create=function(options){var _State$data,_State$tagBegin,_State$tagName,_State$tagEnd,_State$attributeNameS,_State$attributeName,_State$attributeNameE,_State$attributeValue,_State$attributeValue2,_lexer$stateMachine;options=Object.assign({debug:!1},options);var lexer=new EventEmitter,state2=State2.data,data="",tagName="",attrName="",attrValue="",isClosing="",openingQuote="",emit=function(type,value){if(!(tagName[0]==="?"||tagName[0]==="!")){var event={type,value};options.debug&&console.log("emit:",event),lexer.emit("data",event)}};lexer.stateMachine=(_lexer$stateMachine={},_defineProperty(_lexer$stateMachine,State2.data,(_State$data={},_defineProperty(_State$data,Action.lt,function(){data.trim()&&emit(Type.text,data),tagName="",isClosing=!1,state2=State2.tagBegin}),_defineProperty(_State$data,Action.char,function(char){data+=char}),_State$data)),_defineProperty(_lexer$stateMachine,State2.cdata,_defineProperty({},Action.char,function(char){data+=char,data.substr(-3)==="]]>"&&(emit(Type.text,data.slice(0,-3)),data="",state2=State2.data)})),_defineProperty(_lexer$stateMachine,State2.tagBegin,(_State$tagBegin={},_defineProperty(_State$tagBegin,Action.space,noop),_defineProperty(_State$tagBegin,Action.char,function(char){tagName=char,state2=State2.tagName}),_defineProperty(_State$tagBegin,Action.slash,function(){tagName="",isClosing=!0}),_State$tagBegin)),_defineProperty(_lexer$stateMachine,State2.tagName,(_State$tagName={},_defineProperty(_State$tagName,Action.space,function(){isClosing?state2=State2.tagEnd:(state2=State2.attributeNameStart,emit(Type.openTag,tagName))}),_defineProperty(_State$tagName,Action.gt,function(){emit(isClosing?Type.closeTag:Type.openTag,tagName),data="",state2=State2.data}),_defineProperty(_State$tagName,Action.slash,function(){state2=State2.tagEnd,emit(Type.openTag,tagName)}),_defineProperty(_State$tagName,Action.char,function(char){tagName+=char,tagName==="![CDATA["&&(state2=State2.cdata,data="",tagName="")}),_State$tagName)),_defineProperty(_lexer$stateMachine,State2.tagEnd,(_State$tagEnd={},_defineProperty(_State$tagEnd,Action.gt,function(){emit(Type.closeTag,tagName),data="",state2=State2.data}),_defineProperty(_State$tagEnd,Action.char,noop),_State$tagEnd)),_defineProperty(_lexer$stateMachine,State2.attributeNameStart,(_State$attributeNameS={},_defineProperty(_State$attributeNameS,Action.char,function(char){attrName=char,state2=State2.attributeName}),_defineProperty(_State$attributeNameS,Action.gt,function(){data="",state2=State2.data}),_defineProperty(_State$attributeNameS,Action.space,noop),_defineProperty(_State$attributeNameS,Action.slash,function(){isClosing=!0,state2=State2.tagEnd}),_State$attributeNameS)),_defineProperty(_lexer$stateMachine,State2.attributeName,(_State$attributeName={},_defineProperty(_State$attributeName,Action.space,function(){state2=State2.attributeNameEnd}),_defineProperty(_State$attributeName,Action.equal,function(){emit(Type.attributeName,attrName),state2=State2.attributeValueBegin}),_defineProperty(_State$attributeName,Action.gt,function(){attrValue="",emit(Type.attributeName,attrName),emit(Type.attributeValue,attrValue),data="",state2=State2.data}),_defineProperty(_State$attributeName,Action.slash,function(){isClosing=!0,attrValue="",emit(Type.attributeName,attrName),emit(Type.attributeValue,attrValue),state2=State2.tagEnd}),_defineProperty(_State$attributeName,Action.char,function(char){attrName+=char}),_State$attributeName)),_defineProperty(_lexer$stateMachine,State2.attributeNameEnd,(_State$attributeNameE={},_defineProperty(_State$attributeNameE,Action.space,noop),_defineProperty(_State$attributeNameE,Action.equal,function(){emit(Type.attributeName,attrName),state2=State2.attributeValueBegin}),_defineProperty(_State$attributeNameE,Action.gt,function(){attrValue="",emit(Type.attributeName,attrName),emit(Type.attributeValue,attrValue),data="",state2=State2.data}),_defineProperty(_State$attributeNameE,Action.char,function(char){attrValue="",emit(Type.attributeName,attrName),emit(Type.attributeValue,attrValue),attrName=char,state2=State2.attributeName}),_State$attributeNameE)),_defineProperty(_lexer$stateMachine,State2.attributeValueBegin,(_State$attributeValue={},_defineProperty(_State$attributeValue,Action.space,noop),_defineProperty(_State$attributeValue,Action.quote,function(char){openingQuote=char,attrValue="",state2=State2.attributeValue}),_defineProperty(_State$attributeValue,Action.gt,function(){attrValue="",emit(Type.attributeValue,attrValue),data="",state2=State2.data}),_defineProperty(_State$attributeValue,Action.char,function(char){openingQuote="",attrValue=char,state2=State2.attributeValue}),_State$attributeValue)),_defineProperty(_lexer$stateMachine,State2.attributeValue,(_State$attributeValue2={},_defineProperty(_State$attributeValue2,Action.space,function(char){openingQuote?attrValue+=char:(emit(Type.attributeValue,attrValue),state2=State2.attributeNameStart)}),_defineProperty(_State$attributeValue2,Action.quote,function(char){openingQuote===char?(emit(Type.attributeValue,attrValue),state2=State2.attributeNameStart):attrValue+=char}),_defineProperty(_State$attributeValue2,Action.gt,function(char){openingQuote?attrValue+=char:(emit(Type.attributeValue,attrValue),data="",state2=State2.data)}),_defineProperty(_State$attributeValue2,Action.slash,function(char){openingQuote?attrValue+=char:(emit(Type.attributeValue,attrValue),isClosing=!0,state2=State2.tagEnd)}),_defineProperty(_State$attributeValue2,Action.char,function(char){attrValue+=char}),_State$attributeValue2)),_lexer$stateMachine);var step=function(char){options.debug&&console.log(state2,char);var actions=lexer.stateMachine[state2],action=actions[getAction(char)]||actions[Action.error]||actions[Action.char];action(char)};return lexer.write=function(str){for(var len=str.length,i3=0;i3<len;i3++)step(str[i3])},lexer};module.exports={State:State2,Action,Type,create}}}),require_reader=__commonJS2({"node_modules/xml-reader/dist/reader.js"(exports,module){"use strict";var EventEmitter=require_eventemitter3(),Lexer=require_lexer(),Type=Lexer.Type,NodeType={element:"element",text:"text"},createNode=function(params){return Object.assign({name:"",type:NodeType.element,value:"",parent:null,attributes:{},children:[]},params)},create=function(options){options=Object.assign({stream:!1,parentNodes:!0,doneEvent:"done",tagPrefix:"tag:",emitTopLevelOnly:!1,debug:!1},options);var lexer=void 0,rootNode=void 0,current3=void 0,attrName=void 0,reader=new EventEmitter,handleLexerData=function(data){switch(data.type){case Type.openTag:if(current3===null)current3=rootNode,current3.name=data.value;else{var node=createNode({name:data.value,parent:current3});current3.children.push(node),current3=node}break;case Type.closeTag:var parent=current3.parent;if(options.parentNodes||(current3.parent=null),current3.name!==data.value)break;options.stream&&parent===rootNode&&(rootNode.children=[],current3.parent=null),(!options.emitTopLevelOnly||parent===rootNode)&&(reader.emit(options.tagPrefix+current3.name,current3),reader.emit("tag",current3.name,current3)),current3===rootNode&&(lexer.removeAllListeners("data"),reader.emit(options.doneEvent,current3),rootNode=null),current3=parent;break;case Type.text:current3&¤t3.children.push(createNode({type:NodeType.text,value:data.value,parent:options.parentNodes?current3:null}));break;case Type.attributeName:attrName=data.value,current3.attributes[attrName]="";break;case Type.attributeValue:current3.attributes[attrName]=data.value;break}};return reader.reset=function(){lexer=Lexer.create({debug:options.debug}),lexer.on("data",handleLexerData),rootNode=createNode(),current3=null,attrName="",reader.parse=lexer.write},reader.reset(),reader},parseSync2=function(xml,options){options=Object.assign({},options,{stream:!1,tagPrefix:":"});var reader=create(options),res2=void 0;return reader.on("done",function(ast){res2=ast}),reader.parse(xml),res2};module.exports={parseSync:parseSync2,create,NodeType}}});function computeGridToAffineTransform(params){let{originX,originY,rows,cols,cellSizeMm,width,height}=params,a3,c4;cols>1?(a3=width/((cols-1)*cellSizeMm),c4=originX*(1-a3)-.5*cellSizeMm*a3):(a3=1,c4=originX+width/2-(originX+.5*cellSizeMm));let e5,f3;return rows>1?(e5=height/((rows-1)*cellSizeMm),f3=originY*(1-e5)-.5*cellSizeMm*e5):(e5=1,f3=originY+height/2-(originY+.5*cellSizeMm)),{a:a3,b:0,c:c4,d:0,e:e5,f:f3}}function applyAffineTransformToPoint(t52,p4){return{x:t52.a*p4.x+t52.b*p4.y+t52.c,y:t52.d*p4.x+t52.e*p4.y+t52.f}}var{cos:cos3,sin:sin3,PI:PI3}=Math,{tan:tan3}=Math,import_deep_rename_keys=__toESM2(require_deep_rename_keys()),import_xml_reader=__toESM2(require_reader());var BaseSolver=class{constructor(){__publicField(this,"MAX_ITERATIONS",1e5);__publicField(this,"solved",!1);__publicField(this,"failed",!1);__publicField(this,"iterations",0);__publicField(this,"progress",0);__publicField(this,"error",null);__publicField(this,"activeSubSolver");__publicField(this,"failedSubSolvers");__publicField(this,"timeToSolve");__publicField(this,"stats",{});__publicField(this,"_setupDone",!1)}getSolverName(){return this.constructor.name}setup(){this._setupDone||(this._setup(),this._setupDone=!0)}_setup(){}step(){if(this._setupDone||this.setup(),!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e5){throw this.error=`${this.getSolverName()} error: ${e5}`,this.failed=!0,e5}!this.solved&&this.iterations>=this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>=this.MAX_ITERATIONS&&(this.error=`${this.getSolverName()} ran out of iterations`,this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}getOutput(){return null}solve(){let startTime=Date.now();for(;!this.solved&&!this.failed;)this.step();let endTime=Date.now();this.timeToSolve=endTime-startTime}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function clamp5(value,min,max){return Math.max(min,Math.min(max,value))}function computeMaxIterationsByNodeSizeAndConnectionCount(input2){let states=input2.planeSize*input2.layers,connectionCount=input2.connectionCount,connectionFactor=Math.sqrt(connectionCount),requestedMaxIterations=Math.max(1,input2.maxIterations),baseComputedMaxIterations=clamp5(Math.round(states*(8+1.2*connectionFactor)),15e4,12e6),computedMaxIters=clamp5(Math.round(baseComputedMaxIterations*input2.effort),15e4,12e6),minIterationBudgetIters=clamp5(Math.round(requestedMaxIterations*.2),15e4,2e6),maxIterationsIters=Math.max(1,Math.min(requestedMaxIterations,Math.max(minIterationBudgetIters,computedMaxIters))),baseSearchBudgetIters=clamp5(Math.round(states*(10+.8*connectionFactor)*input2.effort),5e4,4e6);return{maxIterationsIters,baseSearchBudgetIters}}function rippedContains(r5,id2){for(let cur=r5;cur;cur=cur.prev)if(cur.id===id2)return!0;return!1}var MinHeap=class{constructor(){__publicField(this,"f",[]);__publicField(this,"seq",[]);__publicField(this,"id",[]);__publicField(this,"n",0)}push(f3,seq,id2){let i3=this.n++;for(this.f[i3]=f3,this.seq[i3]=seq,this.id[i3]=id2;i3>0;){let p4=i3-1>>1;if(this.less(p4,i3))break;this.swap(i3,p4),i3=p4}}pop(){let out=this.id[0];return this.n--,this.n>0&&(this.f[0]=this.f[this.n],this.seq[0]=this.seq[this.n],this.id[0]=this.id[this.n],this.siftDown(0)),out}get size(){return this.n}clear(){this.n=0}siftDown(i3){for(;;){let l4=i3*2+1,r5=l4+1;if(l4>=this.n)return;let m4=l4;if(r5<this.n&&!this.less(l4,r5)&&(m4=r5),this.less(i3,m4))return;this.swap(i3,m4),i3=m4}}less(i3,j4){let fi3=this.f[i3],fj=this.f[j4];return fi3!==fj?fi3<fj:this.seq[i3]<this.seq[j4]}swap(i3,j4){let tmpF=this.f[i3];this.f[i3]=this.f[j4],this.f[j4]=tmpF;let tmpS=this.seq[i3];this.seq[i3]=this.seq[j4],this.seq[j4]=tmpS;let tmpI=this.id[i3];this.id[i3]=this.id[j4],this.id[j4]=tmpI}};function toRootNetName(connectionName,rootConnectionName){return rootConnectionName??connectionName.replace(/_mst\d+$/,"")}var DIRS_DR=[-1,-1,-1,0,0,1,1,1],DIRS_DC=[-1,0,1,-1,1,-1,0,1],HighDensitySolverA01=class extends BaseSolver{constructor(props){super();__publicField(this,"nodeWithPortPoints");__publicField(this,"cellSizeMm");__publicField(this,"viaDiameter");__publicField(this,"MAX_RIPS");__publicField(this,"maxCellCount");__publicField(this,"traceThickness");__publicField(this,"traceMargin");__publicField(this,"viaMinDistFromBorder");__publicField(this,"showPenaltyMap");__publicField(this,"showUsedCellMap");__publicField(this,"effort");__publicField(this,"stepMultiplier");__publicField(this,"hyperParameters");__publicField(this,"initialPenaltyFn");__publicField(this,"rows");__publicField(this,"cols");__publicField(this,"layers");__publicField(this,"gridOrigin");__publicField(this,"gridToBoundsTransform");__publicField(this,"availableZ");__publicField(this,"zToLayer");__publicField(this,"layerToZ");__publicField(this,"connNameToId");__publicField(this,"connIdToName");__publicField(this,"connIdToRootNet");__publicField(this,"overlapFriendlyRootNets");__publicField(this,"planeSize");__publicField(this,"usedCellsFlat");__publicField(this,"portOwnerFlat");__publicField(this,"usedDiagFlat");__publicField(this,"penalty2d");__publicField(this,"visitedStamp");__publicField(this,"sharedCrossRootPortCells");__publicField(this,"stamp",0);__publicField(this,"viaOffsetsDr");__publicField(this,"viaOffsetsDc");__publicField(this,"viaOffsetsLen");__publicField(this,"minViaRow");__publicField(this,"maxViaRow");__publicField(this,"minViaCol");__publicField(this,"maxViaCol");__publicField(this,"usedIndicesByConn");__publicField(this,"usedDiagIndicesByConn");__publicField(this,"unsolvedSegs");__publicField(this,"solvedRoutes");__publicField(this,"activeConnSeg",null);__publicField(this,"activeConnId",-1);__publicField(this,"crossLayerSearch",!1);__publicField(this,"nodePool");__publicField(this,"heap");__publicField(this,"seqCounter",0);__publicField(this,"_viaOccs",[]);__publicField(this,"ripCount");__publicField(this,"totalRipEvents",0);__publicField(this,"searchIterations",0);__publicField(this,"consecutiveSkips",0);__publicField(this,"penaltyCap");__publicField(this,"baseSearchBudgetIters");__publicField(this,"_moveCost",0);__publicField(this,"_moveRipped",null);this.nodeWithPortPoints=props.nodeWithPortPoints,this.cellSizeMm=props.cellSizeMm,this.viaDiameter=props.viaDiameter,this.maxCellCount=props.maxCellCount,this.traceThickness=props.traceThickness??.1,this.traceMargin=props.traceMargin??.15,this.viaMinDistFromBorder=props.viaMinDistFromBorder??.15,this.showPenaltyMap=props.showPenaltyMap??!1,this.showUsedCellMap=props.showUsedCellMap??!1,this.effort=props.effort??1,this.stepMultiplier=Math.max(1,Math.floor(props.stepMultiplier??1)),this.hyperParameters={shuffleSeed:0,ripCost:10,ripTracePenalty:.5,ripViaPenalty:.75,viaBaseCost:.1,greedyMultiplier:1.5,...props.hyperParameters},this.MAX_ITERATIONS=1e8,this.MAX_RIPS=200,this.initialPenaltyFn=props.initialPenaltyFn}get unsolvedConnections(){return this.unsolvedSegs}get solvedConnectionsMap(){return this.solvedRoutes}get activeConnection(){if(!this.activeConnSeg)return null;let s3=this.activeConnSeg;return{connectionName:this.connIdToName[s3.connId]??"",start:{row:s3.startRow,col:s3.startCol,z:s3.startZ,x:0,y:0},end:{row:s3.endRow,col:s3.endCol,z:s3.endZ,x:0,y:0}}}get openSet(){return{length:this.heap?.size??0}}get gridStats(){return{cells:this.planeSize||0,layers:this.layers||0,states:(this.planeSize||0)*(this.layers||0)}}getConstructorParams(){return[{nodeWithPortPoints:this.nodeWithPortPoints,cellSizeMm:this.cellSizeMm,viaDiameter:this.viaDiameter,maxCellCount:this.maxCellCount,stepMultiplier:this.stepMultiplier,traceThickness:this.traceThickness,traceMargin:this.traceMargin,viaMinDistFromBorder:this.viaMinDistFromBorder,showPenaltyMap:this.showPenaltyMap,showUsedCellMap:this.showUsedCellMap,effort:this.effort,hyperParameters:this.hyperParameters,initialPenaltyFn:this.initialPenaltyFn}]}_setup(){let{nodeWithPortPoints,cellSizeMm}=this,{width,height,center:center2}=nodeWithPortPoints;this.availableZ=nodeWithPortPoints.availableZ??[...new Set(nodeWithPortPoints.portPoints.map(pp3=>pp3.z))].sort((a3,b3)=>a3-b3),this.rows=Math.floor(height/cellSizeMm),this.cols=Math.floor(width/cellSizeMm),this.layers=this.availableZ.length,this.planeSize=this.rows*this.cols;let totalCells=this.layers*this.planeSize;if(this.maxCellCount!==void 0&&totalCells>this.maxCellCount){this.error=`Cell count ${totalCells} exceeds maxCellCount ${this.maxCellCount}`,this.failed=!0;return}let totalDiags=this.layers*Math.max(0,this.rows-1)*Math.max(0,this.cols-1)*2;this.zToLayer=new Map,this.layerToZ=new Map;for(let i3=0;i3<this.availableZ.length;i3++){let z4=this.availableZ[i3];this.zToLayer.set(z4,i3),this.layerToZ.set(i3,z4)}if(this.gridOrigin={x:center2.x-width/2,y:center2.y-height/2},this.gridToBoundsTransform=computeGridToAffineTransform({originX:this.gridOrigin.x,originY:this.gridOrigin.y,rows:this.rows,cols:this.cols,cellSizeMm,width,height}),this.connNameToId=new Map,this.connIdToName=[],this.connIdToRootNet=[],this.overlapFriendlyRootNets=new Set,this.penalty2d=new Float64Array(this.planeSize),this.initialPenaltyFn)for(let row=0;row<this.rows;row++){let rowBase=row*this.cols;for(let col=0;col<this.cols;col++){let x4=this.gridOrigin.x+(col+.5)*cellSizeMm,y4=this.gridOrigin.y+(row+.5)*cellSizeMm,px3=(col+.5)/this.cols,py3=(row+.5)/this.rows;this.penalty2d[rowBase+col]=this.initialPenaltyFn({x:x4,y:y4,px:px3,py:py3,row,col})}}this.usedCellsFlat=new Int32Array(totalCells).fill(-1),this.portOwnerFlat=new Int32Array(totalCells).fill(-1),this.usedDiagFlat=new Int32Array(totalDiags).fill(-1),this.visitedStamp=new Uint32Array(totalCells),this.stamp=0;let viaRadiusCells=Math.ceil(this.viaDiameter/2/cellSizeMm),r22=viaRadiusCells*viaRadiusCells,drList=[],dcList=[];for(let dr3=-viaRadiusCells;dr3<=viaRadiusCells;dr3++)for(let dc3=-viaRadiusCells;dc3<=viaRadiusCells;dc3++)dr3*dr3+dc3*dc3<=r22&&(drList.push(dr3),dcList.push(dc3));if(this.viaOffsetsLen=drList.length,this.viaOffsetsDr=new Int32Array(drList),this.viaOffsetsDc=new Int32Array(dcList),this.viaMinDistFromBorder>0){let borderCells=Math.ceil(this.viaMinDistFromBorder/cellSizeMm);this.minViaRow=borderCells,this.maxViaRow=this.rows-1-borderCells,this.minViaCol=borderCells,this.maxViaCol=this.cols-1-borderCells}else this.minViaRow=0,this.maxViaRow=this.rows-1,this.minViaCol=0,this.maxViaCol=this.cols-1;this.unsolvedSegs=this.buildConnectionSegs(),this.sharedCrossRootPortCells=new Set;let rootByPortFlat=new Map;for(let pp3 of this.nodeWithPortPoints.portPoints){let connId=this.connNameToId.get(pp3.connectionName);if(connId===void 0)continue;let cell=this.pointToCell(pp3),flatIdx=(cell.z*this.rows+cell.row)*this.cols+cell.col,rootNet=this.connIdToRootNet[connId],existingRoot=rootByPortFlat.get(flatIdx);existingRoot===void 0?rootByPortFlat.set(flatIdx,rootNet):existingRoot!==rootNet&&this.sharedCrossRootPortCells.add(flatIdx);let existing=this.portOwnerFlat[flatIdx];existing===-1||existing===connId?this.portOwnerFlat[flatIdx]=connId:this.portOwnerFlat[flatIdx]=-2}this.solvedRoutes=new Map,this.usedIndicesByConn=[],this.usedDiagIndicesByConn=[],this.ripCount=[],this.consecutiveSkips=0,this.penaltyCap=this.hyperParameters.ripCost*.5,this.shuffleConnections();let budget=computeMaxIterationsByNodeSizeAndConnectionCount({planeSize:this.planeSize,layers:this.layers,connectionCount:this.unsolvedSegs.length,effort:this.effort,maxIterations:this.MAX_ITERATIONS});this.baseSearchBudgetIters=budget.baseSearchBudgetIters,this.MAX_ITERATIONS=budget.maxIterationsIters,this.activeConnSeg=null,this.activeConnId=-1,this.nodePool=[],this.heap=new MinHeap,this.seqCounter=0}_step(){for(let i3=0;i3<this.stepMultiplier;i3++){if(this.solved||this.failed)return;this.stepOnce()}}stepOnce(){if(!this.activeConnSeg){if(this.unsolvedSegs.length===0){this.solved=!0;return}let next2=this.unsolvedSegs.shift();this.activeConnSeg=next2,this.activeConnId=next2.connId,this.crossLayerSearch=next2.startZ!==next2.endZ,this.nodePool=[],this.heap.clear(),this.seqCounter=0,this.searchIterations=0,this.nextStamp();let f3=this.computeH(next2.startZ,next2.startRow,next2.startCol,next2.endZ,next2.endRow,next2.endCol)*this.hyperParameters.greedyMultiplier;this.nodePool.push({z:next2.startZ,row:next2.startRow,col:next2.startCol,g:0,f:f3,parentIdx:-1,ripped:null}),this.heap.push(f3,this.seqCounter++,0);return}this.searchIterations++;let connRips=this.ripCount[this.activeConnId]??0,budget=Math.round(this.baseSearchBudgetIters*(1+Math.min(connRips,10)*.25));if(this.searchIterations>budget){let pen=this.penalty2d;for(let i3=0;i3<pen.length;i3++)pen[i3]=pen[i3]*.9;this.unsolvedSegs.push(this.activeConnSeg),this.activeConnSeg=null,this.activeConnId=-1,this.heap.clear(),this.nodePool=[],this.consecutiveSkips++,this.consecutiveSkips>=this.unsolvedSegs.length*3&&(this.error=`Convergence failure: ${this.unsolvedSegs.length} connections stuck`,this.failed=!0);return}if(this.heap.size===0){this.error=`No path found for ${this.connIdToName[this.activeConnId]}`,this.failed=!0;return}let nodeIdx=this.heap.pop(),node=this.nodePool[nodeIdx],{z:z4,row,col,g:g6,ripped}=node,cellIdx=(z4*this.rows+row)*this.cols+col;if(this.visitedStamp[cellIdx]===this.stamp)return;this.visitedStamp[cellIdx]=this.stamp;let seg=this.activeConnSeg;if(z4===seg.endZ&&row===seg.endRow&&col===seg.endCol){this.finalizeRoute(nodeIdx),this.activeConnSeg=null,this.activeConnId=-1;return}let endZ=seg.endZ,endRow=seg.endRow,endCol=seg.endCol,activeConn=this.activeConnId,rows=this.rows,cols=this.cols,cellSizeMm=this.cellSizeMm,visited=this.visitedStamp,stamp=this.stamp;for(let d4=0;d4<8;d4++){let nr3=row+DIRS_DR[d4],nc3=col+DIRS_DC[d4];if(nr3<0||nr3>=rows||nc3<0||nc3>=cols)continue;let nIdx=(z4*rows+nr3)*cols+nc3;if(visited[nIdx]===stamp||(this.computeMoveCostAndRips(activeConn,z4,row,col,z4,nr3,nc3,ripped),this._moveCost<0))continue;let g22=g6+this._moveCost,f22=g22+this.computeH(z4,nr3,nc3,endZ,endRow,endCol)*this.hyperParameters.greedyMultiplier,newNodeIdx=this.nodePool.length;this.nodePool.push({z:z4,row:nr3,col:nc3,g:g22,f:f22,parentIdx:nodeIdx,ripped:this._moveRipped}),this.heap.push(f22,this.seqCounter++,newNodeIdx)}if(row>=this.minViaRow&&row<=this.maxViaRow&&col>=this.minViaCol&&col<=this.maxViaCol)for(let nz2=0;nz2<this.layers;nz2++){if(nz2===z4)continue;let nIdx=(nz2*rows+row)*cols+col;if(visited[nIdx]===stamp||(this.computeMoveCostAndRips(activeConn,z4,row,col,nz2,row,col,ripped),this._moveCost<0))continue;let g22=g6+this._moveCost,f22=g22+this.computeH(nz2,row,col,endZ,endRow,endCol)*this.hyperParameters.greedyMultiplier,newNodeIdx=this.nodePool.length;this.nodePool.push({z:nz2,row,col,g:g22,f:f22,parentIdx:nodeIdx,ripped:this._moveRipped}),this.heap.push(f22,this.seqCounter++,newNodeIdx)}}computeMoveCostAndRips(activeConn,fromZ,fromRow,fromCol,toZ,toRow,toCol,ripped){let cost=0,r5=ripped,cols=this.cols;if(fromZ!==toZ){cost+=this.hyperParameters.viaBaseCost,cost+=Math.min(this.penalty2d[toRow*cols+toCol],this.penaltyCap);let toFlatIdx=(toZ*this.rows+toRow)*cols+toCol,fixedOwner=this.portOwnerFlat[toFlatIdx],allowFixedOverlap=this.connIdToRootNet[fixedOwner]===this.connIdToRootNet[activeConn]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[activeConn]),seg=this.activeConnSeg,isSegEnd=!!seg&&toZ===seg.endZ&&toRow===seg.endRow&&toCol===seg.endCol;if(fixedOwner>=0&&fixedOwner!==activeConn&&!allowFixedOverlap&&!isSegEnd){this._moveCost=-1,this._moveRipped=r5;return}this.fillViaOccupants(toRow,toCol,activeConn);let occs=this._viaOccs;for(let i3=0;i3<occs.length;i3++){let occ=occs[i3];rippedContains(r5,occ)||(cost+=this.hyperParameters.ripCost,r5={id:occ,prev:r5}),cost+=this.hyperParameters.ripViaPenalty}}else{let dr3=fromRow>toRow?fromRow-toRow:toRow-fromRow,dc3=fromCol>toCol?fromCol-toCol:toCol-fromCol;cost+=(dr3+dc3>1?Math.SQRT2:1)*this.cellSizeMm,cost+=Math.min(this.penalty2d[toRow*cols+toCol],this.penaltyCap);let flatIdx=(toZ*this.rows+toRow)*cols+toCol,fixedOwner=this.portOwnerFlat[flatIdx],allowFixedOverlap=this.connIdToRootNet[fixedOwner]===this.connIdToRootNet[activeConn]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[activeConn]),seg=this.activeConnSeg,isSegEnd=!!seg&&toZ===seg.endZ&&toRow===seg.endRow&&toCol===seg.endCol;if(fixedOwner>=0&&fixedOwner!==activeConn&&!allowFixedOverlap&&!isSegEnd){this._moveCost=-1,this._moveRipped=r5;return}let occ=this.usedCellsFlat[flatIdx],allowSameRootOverlap=this.connIdToRootNet[occ]===this.connIdToRootNet[activeConn]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[activeConn]);if(occ!==-1&&occ!==activeConn&&!allowSameRootOverlap&&(rippedContains(r5,occ)||(cost+=this.hyperParameters.ripCost,r5={id:occ,prev:r5}),cost+=this.hyperParameters.ripTracePenalty),dr3===1&&dc3===1){let sqRow=fromRow<toRow?fromRow:toRow,sqCol=fromCol<toCol?fromCol:toCol,crossingSlot=(fromRow<toRow&&fromCol<toCol||fromRow>toRow&&fromCol>toCol?0:1)^1,sqCols=this.cols-1,diagBase=((toZ*(this.rows-1)+sqRow)*sqCols+sqCol)*2,crossingOcc=this.usedDiagFlat[diagBase+crossingSlot],allowCrossingOverlap=this.connIdToRootNet[crossingOcc]===this.connIdToRootNet[activeConn]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[activeConn]);if(crossingOcc!==-1&&crossingOcc!==activeConn&&!allowCrossingOverlap){this._moveCost=-1,this._moveRipped=r5;return}}}this._moveCost=cost,this._moveRipped=r5}fillViaOccupants(row,col,activeConn){let occs=this._viaOccs;occs.length=0;let rows=this.rows,cols=this.cols,offDr=this.viaOffsetsDr,offDc=this.viaOffsetsDc,offLen=this.viaOffsetsLen,used=this.usedCellsFlat;for(let z4=0;z4<this.layers;z4++){let zBase=z4*this.planeSize;for(let i3=0;i3<offLen;i3++){let r5=row+offDr[i3],c4=col+offDc[i3];if(r5<0||c4<0||r5>=rows||c4>=cols)continue;let occ=used[zBase+r5*cols+c4];if(occ===-1||occ===activeConn||this.connIdToRootNet[occ]===this.connIdToRootNet[activeConn]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[activeConn]))continue;let seen=!1;for(let j4=0;j4<occs.length;j4++)if(occs[j4]===occ){seen=!0;break}seen||occs.push(occ)}}}shouldSkipFixedPortHalo(flatIdx,connId){let fixedOwner=this.portOwnerFlat[flatIdx];return fixedOwner===connId?!1:fixedOwner===-2?!0:fixedOwner<0?!1:!(this.connIdToRootNet[fixedOwner]===this.connIdToRootNet[connId]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[connId]))}nextStamp(){this.stamp=this.stamp+1>>>0,this.stamp===0&&(this.visitedStamp.fill(0),this.stamp=1)}computeH(z4,row,col,toZ,toRow,toCol){let dr3=Math.abs(row-toRow),dc3=Math.abs(col-toCol),manhattan=dr3+dc3;if(z4===toZ)return manhattan*this.cellSizeMm;if(!this.crossLayerSearch)return manhattan*this.cellSizeMm+this.hyperParameters.viaBaseCost;let vr1=Math.max(this.minViaRow,Math.min(this.maxViaRow,row)),vc1=Math.max(this.minViaCol,Math.min(this.maxViaCol,col)),vr22=Math.max(this.minViaRow,Math.min(this.maxViaRow,toRow)),vc22=Math.max(this.minViaCol,Math.min(this.maxViaCol,toCol)),via1=Math.abs(row-vr1)+Math.abs(col-vc1)+Math.abs(vr1-toRow)+Math.abs(vc1-toCol),via2=Math.abs(row-vr22)+Math.abs(col-vc22)+Math.abs(vr22-toRow)+Math.abs(vc22-toCol);return Math.max(Math.min(via1,via2),manhattan)*this.cellSizeMm+this.hyperParameters.viaBaseCost}internConn(name,rootNetName){let existing=this.connNameToId.get(name);if(existing!==void 0)return existing;let id2=this.connIdToName.length;return this.connIdToName.push(name),this.connIdToRootNet.push(toRootNetName(name,rootNetName)),this.connNameToId.set(name,id2),id2}buildConnectionSegs(){let byName=new Map;for(let pp3 of this.nodeWithPortPoints.portPoints){let name=pp3.connectionName;byName.has(name)||byName.set(name,{points:[],rootConnectionName:pp3.rootConnectionName}),byName.get(name).points.push(pp3)}let segs=[],seenSegmentKeys=new Set;for(let[name,conn]of byName){let pts=conn.points;if(pts.length<2)continue;let connId=this.internConn(name,conn.rootConnectionName);for(let i3=0;i3<pts.length-1;i3++){let s3=this.pointToCell(pts[i3]),e5=this.pointToCell(pts[i3+1]),endpointA=`${s3.z}:${s3.row}:${s3.col}`,endpointB=`${e5.z}:${e5.row}:${e5.col}`,orderedEndpoints=endpointA<endpointB?`${endpointA}|${endpointB}`:`${endpointB}|${endpointA}`,netName=conn.rootConnectionName??name,segKey=`${netName}|${orderedEndpoints}`;if(seenSegmentKeys.has(segKey)){this.overlapFriendlyRootNets.add(netName);continue}seenSegmentKeys.add(segKey),segs.push({connId,startZ:s3.z,startRow:s3.row,startCol:s3.col,startPoint:pts[i3],endZ:e5.z,endRow:e5.row,endCol:e5.col,endPoint:pts[i3+1]})}}return segs}pointToCell(pt3){let col=Math.max(0,Math.min(this.cols-1,Math.round((pt3.x-this.gridOrigin.x)/this.cellSizeMm-.5))),row=Math.max(0,Math.min(this.rows-1,Math.round((pt3.y-this.gridOrigin.y)/this.cellSizeMm-.5)));return{z:this.zToLayer.get(pt3.z)??0,row,col}}shuffleConnections(){let arr=this.unsolvedSegs,s3=this.hyperParameters.shuffleSeed,rng=()=>(s3=s3*1664525+1013904223&4294967295,(s3>>>0)/4294967295);for(let i3=arr.length-1;i3>0;i3--){let j4=Math.floor(rng()*(i3+1)),tmp=arr[i3];arr[i3]=arr[j4],arr[j4]=tmp}}finalizeRoute(goalNodeIdx){this.consecutiveSkips=Math.max(0,this.consecutiveSkips-1);let cells=[],idx=goalNodeIdx;for(;idx>=0;){let n4=this.nodePool[idx];cells.push({z:n4.z,row:n4.row,col:n4.col}),idx=n4.parentIdx}for(cells.reverse();cells.length>1;){let first=cells[0],firstFlat=(first.z*this.rows+first.row)*this.cols+first.col;if(!this.sharedCrossRootPortCells.has(firstFlat))break;cells.shift()}for(;cells.length>1;){let last=cells[cells.length-1],lastFlat=(last.z*this.rows+last.row)*this.cols+last.col;if(!this.sharedCrossRootPortCells.has(lastFlat))break;cells.pop()}let viaCells=[];for(let i3=1;i3<cells.length;i3++)cells[i3].z!==cells[i3-1].z&&viaCells.push({row:cells[i3].row,col:cells[i3].col});let firstCell=cells[0],lastCell=cells[cells.length-1],connId=this.activeConnId,goalNode=this.nodePool[goalNodeIdx],rippedIds=[];for(let cur=goalNode.ripped;cur;cur=cur.prev)rippedIds.push(cur.id);for(let i3=0;i3<rippedIds.length;i3++)if(this.ripTrace(rippedIds[i3]),this.failed)return;let marginCells=Math.ceil(this.traceMargin/this.cellSizeMm),indices=[],rows=this.rows,cols=this.cols,used=this.usedCellsFlat;for(let ci3=0;ci3<cells.length;ci3++){let cell=cells[ci3];for(let dr3=-marginCells;dr3<=marginCells;dr3++)for(let dc3=-marginCells;dc3<=marginCells;dc3++){let r5=cell.row+dr3,c4=cell.col+dc3;if(r5<0||r5>=rows||c4<0||c4>=cols)continue;let flatIdx=(cell.z*rows+r5)*cols+c4;if((r5!==cell.row||c4!==cell.col)&&this.shouldSkipFixedPortHalo(flatIdx,connId))continue;let existing=used[flatIdx],allowSameRootOverlap=this.connIdToRootNet[existing]===this.connIdToRootNet[connId]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[connId]);existing!==-1&&existing!==connId&&!allowSameRootOverlap||(used[flatIdx]=connId,indices.push(flatIdx))}}let displacedByVias=[],offDr=this.viaOffsetsDr,offDc=this.viaOffsetsDc,offLen=this.viaOffsetsLen;for(let vi3=0;vi3<viaCells.length;vi3++){let via=viaCells[vi3];for(let z4=0;z4<this.layers;z4++){let zBase=z4*this.planeSize;for(let oi3=0;oi3<offLen;oi3++){let r5=via.row+offDr[oi3],c4=via.col+offDc[oi3];if(r5<0||r5>=rows||c4<0||c4>=cols)continue;let flatIdx=zBase+r5*cols+c4;if((r5!==via.row||c4!==via.col)&&this.shouldSkipFixedPortHalo(flatIdx,connId))continue;let existing=used[flatIdx],allowSameRootOverlap=this.connIdToRootNet[existing]===this.connIdToRootNet[connId]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[connId]);if(existing!==-1&&existing!==connId&&!allowSameRootOverlap){let seen=!1;for(let k4=0;k4<displacedByVias.length;k4++)if(displacedByVias[k4]===existing){seen=!0;break}seen||displacedByVias.push(existing)}used[flatIdx]=connId,indices.push(flatIdx)}}}let diagIndices=[],sqCols=this.cols-1;for(let i3=1;i3<cells.length;i3++){let prev=cells[i3-1],curr=cells[i3];if(prev.z!==curr.z)continue;let dr3=prev.row>curr.row?prev.row-curr.row:curr.row-prev.row,dc3=prev.col>curr.col?prev.col-curr.col:curr.col-prev.col;if(dr3!==1||dc3!==1)continue;let sqRow=prev.row<curr.row?prev.row:curr.row,sqCol=prev.col<curr.col?prev.col:curr.col,diagSlot=prev.row<curr.row&&prev.col<curr.col||prev.row>curr.row&&prev.col>curr.col?0:1,crossingSlot=diagSlot^1,diagBase=((prev.z*(this.rows-1)+sqRow)*sqCols+sqCol)*2,crossingIdx=diagBase+crossingSlot,crossingOcc=this.usedDiagFlat[crossingIdx],allowCrossingOverlap=this.connIdToRootNet[crossingOcc]===this.connIdToRootNet[connId]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[connId]);if(crossingOcc!==-1&&crossingOcc!==connId&&!allowCrossingOverlap)continue;let diagIdx=diagBase+diagSlot;this.usedDiagFlat[diagIdx]=connId,diagIndices.push(diagIdx)}for(;this.usedIndicesByConn.length<=connId;)this.usedIndicesByConn.push([]);let usedIndices=this.usedIndicesByConn[connId]??[];for(usedIndices.push(...indices),this.usedIndicesByConn[connId]=usedIndices;this.usedDiagIndicesByConn.length<=connId;)this.usedDiagIndicesByConn.push([]);let usedDiagIndices=this.usedDiagIndicesByConn[connId]??[];usedDiagIndices.push(...diagIndices),this.usedDiagIndicesByConn[connId]=usedDiagIndices;let solvedRoutes=this.solvedRoutes.get(connId)??[];solvedRoutes.push({connId,startZ:firstCell.z,startRow:firstCell.row,startCol:firstCell.col,startPoint:this.activeConnSeg.startPoint,endZ:lastCell.z,endRow:lastCell.row,endCol:lastCell.col,endPoint:this.activeConnSeg.endPoint,cells,viaCells}),this.solvedRoutes.set(connId,solvedRoutes);for(let i3=0;i3<displacedByVias.length;i3++)if(this.ripTrace(displacedByVias[i3]),this.failed)return;if(rippedIds.length>0||displacedByVias.length>0){let pen=this.penalty2d,cap2=this.penaltyCap;if(this.totalRipEvents>50)for(let i3=0;i3<pen.length;i3++)pen[i3]=pen[i3]*.99;else for(let i3=0;i3<pen.length;i3++)pen[i3]>cap2&&(pen[i3]=pen[i3]*.5)}}ripTrace(connId){for(;this.ripCount.length<=connId;)this.ripCount.push(0);if(this.ripCount[connId]++,this.totalRipEvents++,this.totalRipEvents>=this.MAX_RIPS){this.error=`Convergence failure: exceeded MAX_RIPS ${this.MAX_RIPS}`,this.failed=!0;return}let routes=this.solvedRoutes.get(connId)??[];if(routes.length>0){let cols=this.cols;for(let route of routes){for(let i3=0;i3<route.cells.length;i3++){let cell=route.cells[i3],cellIdx=cell.row*cols+cell.col;this.penalty2d[cellIdx]=this.penalty2d[cellIdx]+this.hyperParameters.ripTracePenalty}for(let i3=0;i3<route.viaCells.length;i3++){let via=route.viaCells[i3],viaIdx=via.row*cols+via.col;this.penalty2d[viaIdx]=this.penalty2d[viaIdx]+this.hyperParameters.ripViaPenalty}}}let indices=this.usedIndicesByConn[connId];if(indices){let used=this.usedCellsFlat;for(let i3=0;i3<indices.length;i3++){let flatIdx=indices[i3];used[flatIdx]===connId&&(used[flatIdx]=-1)}this.usedIndicesByConn[connId]=[]}let diagIndices=this.usedDiagIndicesByConn[connId];if(diagIndices){let usedDiag=this.usedDiagFlat;for(let i3=0;i3<diagIndices.length;i3++){let flatIdx=diagIndices[i3];usedDiag[flatIdx]===connId&&(usedDiag[flatIdx]=-1)}this.usedDiagIndicesByConn[connId]=[]}if(routes.length>0){this.solvedRoutes.delete(connId);for(let route of routes)this.unsolvedSegs.push({connId,startZ:route.startZ,startRow:route.startRow,startCol:route.startCol,startPoint:route.startPoint,endZ:route.endZ,endRow:route.endRow,endCol:route.endCol,endPoint:route.endPoint})}}visualize(){let LAYER_COLORS2=["red","blue","orange","green"],points=[],lines=[],circles=[],rects=[],{width,height,center:center2}=this.nodeWithPortPoints;rects.push({center:{x:center2.x,y:center2.y},width,height,stroke:"gray"});let vt3=this.gridToBoundsTransform;if(this.showPenaltyMap&&this.penalty2d){let maxPenalty=0;for(let i3=0;i3<this.penalty2d.length;i3++)this.penalty2d[i3]>maxPenalty&&(maxPenalty=this.penalty2d[i3]);if(maxPenalty>0)for(let row=0;row<this.rows;row++)for(let col=0;col<this.cols;col++){let p4=this.penalty2d[row*this.cols+col];if(p4<=0)continue;let alpha=Math.min(.6,p4/maxPenalty*.6),tc3=applyAffineTransformToPoint(vt3,{x:this.gridOrigin.x+(col+.5)*this.cellSizeMm,y:this.gridOrigin.y+(row+.5)*this.cellSizeMm});rects.push({center:tc3,width:this.cellSizeMm*vt3.a,height:this.cellSizeMm*vt3.e,fill:`rgba(255,165,0,${alpha.toFixed(3)})`})}}if(this.showUsedCellMap&&this.usedCellsFlat)for(let z4=0;z4<this.layers;z4++)for(let row=0;row<this.rows;row++)for(let col=0;col<this.cols;col++){if(this.usedCellsFlat[(z4*this.rows+row)*this.cols+col]===-1)continue;let tc3=applyAffineTransformToPoint(vt3,{x:this.gridOrigin.x+(col+.5)*this.cellSizeMm,y:this.gridOrigin.y+(row+.5)*this.cellSizeMm});rects.push({center:tc3,width:this.cellSizeMm*vt3.a,height:this.cellSizeMm*vt3.e,fill:"rgba(0,0,255,0.5)"})}for(let pp3 of this.nodeWithPortPoints.portPoints)points.push({x:pp3.x,y:pp3.y,color:LAYER_COLORS2[pp3.z]??"gray",label:pp3.connectionName});let TRACE_COLORS3=["rgba(255,0,0,0.75)","rgba(0,0,255,0.75)","rgba(255,165,0,0.75)","rgba(0,128,0,0.75)"],transformedRoutes=this.getOutput();for(let route of transformedRoutes){if(route.route.length<2)continue;let segStart=0;for(let i3=1;i3<route.route.length;i3++){let prev=route.route[i3-1];route.route[i3].z!==prev.z&&(i3-segStart>=2&&lines.push({points:route.route.slice(segStart,i3).map(p4=>({x:p4.x,y:p4.y})),strokeColor:TRACE_COLORS3[prev.z]??"rgba(128,128,128,0.75)",strokeWidth:this.traceThickness}),segStart=i3)}if(route.route.length-segStart>=2){let lastZ=route.route[segStart].z;lines.push({points:route.route.slice(segStart).map(p4=>({x:p4.x,y:p4.y})),strokeColor:TRACE_COLORS3[lastZ]??"rgba(128,128,128,0.75)",strokeWidth:this.traceThickness})}}for(let route of transformedRoutes)for(let via of route.vias)circles.push({center:{x:via.x,y:via.y},radius:this.viaDiameter/2,fill:"rgba(0,0,0,0.3)",stroke:"black"});if(this.activeConnSeg&&this.visitedStamp){let currentStamp=this.stamp;for(let z4=0;z4<this.layers;z4++)for(let row=0;row<this.rows;row++)for(let col=0;col<this.cols;col++){if(this.visitedStamp[(z4*this.rows+row)*this.cols+col]!==currentStamp)continue;let tc3=applyAffineTransformToPoint(vt3,{x:this.gridOrigin.x+(col+.5)*this.cellSizeMm,y:this.gridOrigin.y+(row+.5)*this.cellSizeMm});points.push({x:tc3.x,y:tc3.y,color:"rgba(0,0,255,0.2)"})}}return{points,lines,circles,rects,coordinateSystem:"cartesian",title:`HighDensityA01 [${this.solvedRoutes?.size??0} solved, ${this.unsolvedSegs?.length??0} remaining]`}}getOutput(){let t52=this.gridToBoundsTransform,result=[];for(let[connId,routes]of this.solvedRoutes??[]){let connName=this.connIdToName[connId];for(let route of routes){let points=route.cells.map(cell=>{let rawX=this.gridOrigin.x+(cell.col+.5)*this.cellSizeMm,rawY=this.gridOrigin.y+(cell.row+.5)*this.cellSizeMm,tp3=applyAffineTransformToPoint(t52,{x:rawX,y:rawY});return{x:tp3.x,y:tp3.y,z:this.layerToZ.get(cell.z)??cell.z}});points.length>0&&(points[0]={...route.startPoint},points.length>1&&(points[points.length-1]={...route.endPoint})),result.push({connectionName:connName,rootConnectionName:this.connIdToRootNet[connId],traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,route:points,vias:route.viaCells.map(via=>{let rawX=this.gridOrigin.x+(via.col+.5)*this.cellSizeMm,rawY=this.gridOrigin.y+(via.row+.5)*this.cellSizeMm;return applyAffineTransformToPoint(t52,{x:rawX,y:rawY})})})}}return result}};var REGION_LEFT=0,REGION_TOP=1,REGION_RIGHT=2,REGION_BOTTOM=3,REGION_MIDDLE=4,REGION_NAMES=["left","top","right","bottom","middle"],TypedMinHeap2=class{constructor(){__publicField(this,"f",new Float64Array(1024));__publicField(this,"seq",new Uint32Array(1024));__publicField(this,"id",new Int32Array(1024));__publicField(this,"n",0)}push(f3,seq,id2){this.ensureCapacity(this.n+1);let i3=this.n++;for(this.f[i3]=f3,this.seq[i3]=seq,this.id[i3]=id2;i3>0;){let p4=i3-1>>1;if(this.less(p4,i3))break;this.swap(i3,p4),i3=p4}}pop(){let out=this.id[0];return this.n--,this.n>0&&(this.f[0]=this.f[this.n],this.seq[0]=this.seq[this.n],this.id[0]=this.id[this.n],this.siftDown(0)),out}get size(){return this.n}clear(){this.n=0}ensureCapacity(size3){if(size3<=this.f.length)return;let next2=this.f.length;for(;next2<size3;)next2*=2;let nf3=new Float64Array(next2);nf3.set(this.f),this.f=nf3;let ns3=new Uint32Array(next2);ns3.set(this.seq),this.seq=ns3;let ni3=new Int32Array(next2);ni3.set(this.id),this.id=ni3}siftDown(i3){for(;;){let l4=i3*2+1,r5=l4+1;if(l4>=this.n)return;let m4=l4;if(r5<this.n&&!this.less(l4,r5)&&(m4=r5),this.less(i3,m4))return;this.swap(i3,m4),i3=m4}}less(i3,j4){let fi3=this.f[i3],fj=this.f[j4];return fi3!==fj?fi3<fj:this.seq[i3]<this.seq[j4]}swap(i3,j4){let tf3=this.f[i3];this.f[i3]=this.f[j4],this.f[j4]=tf3;let ts3=this.seq[i3];this.seq[i3]=this.seq[j4],this.seq[j4]=ts3;let ti3=this.id[i3];this.id[i3]=this.id[j4],this.id[j4]=ti3}},TypedNodePool2=class{constructor(){__publicField(this,"z",new Int32Array(1024));__publicField(this,"cellId",new Int32Array(1024));__publicField(this,"g",new Float64Array(1024));__publicField(this,"parent",new Int32Array(1024));__publicField(this,"ripHead",new Int32Array(1024).fill(-1));__publicField(this,"ripCount",new Int32Array(1024));__publicField(this,"length",0)}clear(){this.length=0}push(z4,cellId,g6,parent,ripHead,ripCount){this.ensureCapacity(this.length+1);let idx=this.length++;return this.z[idx]=z4,this.cellId[idx]=cellId,this.g[idx]=g6,this.parent[idx]=parent,this.ripHead[idx]=ripHead,this.ripCount[idx]=ripCount,idx}ensureCapacity(size3){if(size3<=this.z.length)return;let next2=this.z.length;for(;next2<size3;)next2*=2;let nz2=new Int32Array(next2);nz2.set(this.z),this.z=nz2;let nc3=new Int32Array(next2);nc3.set(this.cellId),this.cellId=nc3;let ng3=new Float64Array(next2);ng3.set(this.g),this.g=ng3;let np2=new Int32Array(next2);np2.set(this.parent),this.parent=np2;let nr3=new Int32Array(next2);nr3.fill(-1),nr3.set(this.ripHead.subarray(0,this.length)),this.ripHead=nr3;let nrc=new Int32Array(next2);nrc.set(this.ripCount.subarray(0,this.length)),this.ripCount=nrc}},TypedRipChain2=class{constructor(){__publicField(this,"connId",new Int32Array(1024));__publicField(this,"prev",new Int32Array(1024).fill(-1));__publicField(this,"length",0)}clear(){this.length=0}append(prevHead,connId){this.ensureCapacity(this.length+1);let idx=this.length++;return this.connId[idx]=connId,this.prev[idx]=prevHead,idx}contains(head,connId){for(let cur=head;cur>=0;cur=this.prev[cur])if(this.connId[cur]===connId)return!0;return!1}collect(head,out){out.length=0;for(let cur=head;cur>=0;cur=this.prev[cur])out.push(this.connId[cur])}ensureCapacity(size3){if(size3<=this.connId.length)return;let next2=this.connId.length;for(;next2<size3;)next2*=2;let nc3=new Int32Array(next2);nc3.set(this.connId),this.connId=nc3;let np2=new Int32Array(next2);np2.fill(-1),np2.set(this.prev.subarray(0,this.length)),this.prev=np2}};function toRootNetName3(connectionName,rootConnectionName){return rootConnectionName??connectionName.replace(/_mst\d+$/,"")}function clamp32(value,min,max){return Math.max(min,Math.min(max,value))}function pushUnique2(arr,value){for(let i3=0;i3<arr.length;i3++)if(arr[i3]===value)return;arr.push(value)}function pushUniqueNeighbor2(arr,edge){for(let i3=0;i3<arr.length;i3++)if(arr[i3].cellId===edge.cellId)return;arr.push(edge)}function circleIntersectsRect2(cx3,cy3,r5,minX,minY,maxX,maxY){let qx3=clamp32(cx3,minX,maxX),qy3=clamp32(cy3,minY,maxY),dx3=cx3-qx3,dy3=cy3-qy3;return dx3*dx3+dy3*dy3<=r5*r5}var HighDensitySolverA03=class extends BaseSolver{constructor(props){super();__publicField(this,"nodeWithPortPoints");__publicField(this,"highResolutionCellSize");__publicField(this,"highResolutionCellThickness");__publicField(this,"lowResolutionCellSize");__publicField(this,"viaDiameter");__publicField(this,"MAX_RIPS");__publicField(this,"maxCellCount");__publicField(this,"traceThickness");__publicField(this,"traceMargin");__publicField(this,"viaMinDistFromBorder");__publicField(this,"showPenaltyMap");__publicField(this,"showUsedCellMap");__publicField(this,"effort");__publicField(this,"stepMultiplier");__publicField(this,"hyperParameters");__publicField(this,"initialPenaltyFn");__publicField(this,"boundsMinX");__publicField(this,"boundsMaxX");__publicField(this,"boundsMinY");__publicField(this,"boundsMaxY");__publicField(this,"gridToBoundsTransform");__publicField(this,"availableZ");__publicField(this,"zToLayer");__publicField(this,"layerToZ");__publicField(this,"layers");__publicField(this,"fineRows");__publicField(this,"fineCols");__publicField(this,"lowScale");__publicField(this,"bandRows");__publicField(this,"bandCols");__publicField(this,"regions");__publicField(this,"planeSize");__publicField(this,"cellCenterX");__publicField(this,"cellCenterY");__publicField(this,"cellMinX");__publicField(this,"cellMinY");__publicField(this,"cellMaxX");__publicField(this,"cellMaxY");__publicField(this,"cellWidth");__publicField(this,"cellHeight");__publicField(this,"cellRegion");__publicField(this,"cellRow");__publicField(this,"cellCol");__publicField(this,"viaAllowed");__publicField(this,"neighborOffset");__publicField(this,"neighborIds");__publicField(this,"neighborCosts");__publicField(this,"usedCellsFlat");__publicField(this,"sharedCellsFlat");__publicField(this,"portOwnerFlat");__publicField(this,"penalty2d");__publicField(this,"ripStateBuckets");__publicField(this,"visitedStamp");__publicField(this,"bestGStamp");__publicField(this,"bestGValue");__publicField(this,"visitedFlatStamp");__publicField(this,"sharedCrossRootPortFlat");__publicField(this,"stamp",0);__publicField(this,"connNameToId");__publicField(this,"connIdToName");__publicField(this,"connIdToRootNet");__publicField(this,"overlapFriendlyRootNets");__publicField(this,"usedIndicesByConn");__publicField(this,"unsolvedSegs");__publicField(this,"solvedRoutes");__publicField(this,"activeConnSeg",null);__publicField(this,"activeConnId",-1);__publicField(this,"nodePool");__publicField(this,"heap");__publicField(this,"ripChain");__publicField(this,"seqCounter",0);__publicField(this,"_viaOccs",[]);__publicField(this,"_cellOccs",[]);__publicField(this,"_rippedIds",[]);__publicField(this,"ripCount");__publicField(this,"totalRipEvents",0);__publicField(this,"searchIterations",0);__publicField(this,"consecutiveSkips",0);__publicField(this,"penaltyCap");__publicField(this,"baseSearchBudgetIters");__publicField(this,"_moveCost",0);__publicField(this,"_moveRippedHead",-1);__publicField(this,"_moveRipCount",0);__publicField(this,"traceKeepoutRadius");__publicField(this,"viaKeepoutRadius");this.nodeWithPortPoints=props.nodeWithPortPoints,this.highResolutionCellSize=props.highResolutionCellSize??.1,this.highResolutionCellThickness=Math.max(1,Math.floor(props.highResolutionCellThickness??8)),this.lowResolutionCellSize=props.lowResolutionCellSize??.4,this.viaDiameter=props.viaDiameter,this.maxCellCount=props.maxCellCount,this.traceThickness=props.traceThickness??.1,this.traceMargin=props.traceMargin??.15,this.viaMinDistFromBorder=props.viaMinDistFromBorder??.15,this.showPenaltyMap=props.showPenaltyMap??!1,this.showUsedCellMap=props.showUsedCellMap??!1,this.effort=props.effort??1,this.stepMultiplier=Math.max(1,Math.floor(props.stepMultiplier??1)),this.hyperParameters={shuffleSeed:0,ripCost:8,ripTracePenalty:.5,ripViaPenalty:.75,viaBaseCost:.1,greedyMultiplier:1.5,...props.hyperParameters},this.MAX_ITERATIONS=1e8,this.MAX_RIPS=200,this.initialPenaltyFn=props.initialPenaltyFn}get unsolvedConnections(){return this.unsolvedSegs}get solvedConnectionsMap(){let map=new Map;for(let connId=0;connId<this.solvedRoutes.length;connId++){let route=this.solvedRoutes[connId];route&&map.set(connId,route)}return map}get activeConnection(){if(!this.activeConnSeg)return null;let startCellId=this.activeConnSeg.startCellId,endCellId=this.activeConnSeg.endCellId;return{connectionName:this.connIdToName[this.activeConnSeg.connId]??"",start:{cellId:startCellId,region:REGION_NAMES[this.cellRegion[startCellId]],row:this.cellRow[startCellId],col:this.cellCol[startCellId],x:this.cellCenterX[startCellId],y:this.cellCenterY[startCellId],z:this.activeConnSeg.startZ},end:{cellId:endCellId,region:REGION_NAMES[this.cellRegion[endCellId]],row:this.cellRow[endCellId],col:this.cellCol[endCellId],x:this.cellCenterX[endCellId],y:this.cellCenterY[endCellId],z:this.activeConnSeg.endZ}}}get openSet(){return{length:this.heap?.size??0}}get gridStats(){return{cells:this.planeSize||0,layers:this.layers||0,states:(this.planeSize||0)*(this.layers||0),ripStateBuckets:this.ripStateBuckets||0,neighborEdges:this.neighborIds?.length??0,regionCounts:this.regions?Object.fromEntries(this.regions.map(region=>[region.name,region.rows*region.cols])):{}}}getConstructorParams(){return[{nodeWithPortPoints:this.nodeWithPortPoints,highResolutionCellSize:this.highResolutionCellSize,highResolutionCellThickness:this.highResolutionCellThickness,lowResolutionCellSize:this.lowResolutionCellSize,viaDiameter:this.viaDiameter,maxCellCount:this.maxCellCount,stepMultiplier:this.stepMultiplier,traceThickness:this.traceThickness,traceMargin:this.traceMargin,viaMinDistFromBorder:this.viaMinDistFromBorder,showPenaltyMap:this.showPenaltyMap,showUsedCellMap:this.showUsedCellMap,effort:this.effort,hyperParameters:this.hyperParameters,initialPenaltyFn:this.initialPenaltyFn}]}_setup(){let{nodeWithPortPoints}=this,{width,height,center:center2}=nodeWithPortPoints,rawScale=this.lowResolutionCellSize/this.highResolutionCellSize,roundedScale=Math.round(rawScale);if(!Number.isFinite(rawScale)||rawScale<=0||Math.abs(rawScale-roundedScale)>1e-9){this.error="lowResolutionCellSize must be a positive integer multiple of highResolutionCellSize",this.failed=!0;return}this.lowScale=Math.max(1,roundedScale),this.availableZ=nodeWithPortPoints.availableZ??[...new Set(nodeWithPortPoints.portPoints.map(pp3=>pp3.z))].sort((a3,b3)=>a3-b3),this.layers=this.availableZ.length,this.zToLayer=new Map,this.layerToZ=new Map;for(let i3=0;i3<this.availableZ.length;i3++){let z4=this.availableZ[i3];this.zToLayer.set(z4,i3),this.layerToZ.set(i3,z4)}this.boundsMinX=center2.x-width/2,this.boundsMaxX=center2.x+width/2,this.boundsMinY=center2.y-height/2,this.boundsMaxY=center2.y+height/2,this.traceKeepoutRadius=this.traceMargin+this.traceThickness/2,this.viaKeepoutRadius=this.viaDiameter/2+this.traceKeepoutRadius,this.buildFiveRegionGrid(width,height),this.gridToBoundsTransform=this.computeGridToBoundsTransform();let totalCells=this.layers*this.planeSize;if(this.maxCellCount!==void 0&&totalCells>this.maxCellCount){this.error=`Cell count ${totalCells} exceeds maxCellCount ${this.maxCellCount}`,this.failed=!0;return}this.connNameToId=new Map,this.connIdToName=[],this.connIdToRootNet=[],this.overlapFriendlyRootNets=new Set,this.unsolvedSegs=this.buildConnectionSegs(),this.penalty2d=new Float64Array(this.planeSize);let widthInv=width>0?1/width:0,heightInv=height>0?1/height:0;for(let cellId=0;cellId<this.planeSize;cellId++){let penalty=0;this.initialPenaltyFn&&(penalty+=this.initialPenaltyFn({x:this.cellCenterX[cellId],y:this.cellCenterY[cellId],px:(this.cellCenterX[cellId]-this.boundsMinX)*widthInv,py:(this.cellCenterY[cellId]-this.boundsMinY)*heightInv,cellId,region:REGION_NAMES[this.cellRegion[cellId]],row:this.cellRow[cellId],col:this.cellCol[cellId]})),this.penalty2d[cellId]=penalty}this.usedCellsFlat=new Int32Array(totalCells).fill(-1),this.sharedCellsFlat=Array.from({length:totalCells},()=>{}),this.portOwnerFlat=new Int32Array(totalCells).fill(-1),this.sharedCrossRootPortFlat=new Uint8Array(totalCells),this.ripStateBuckets=1;let searchStateCount=totalCells;this.visitedStamp=new Uint32Array(searchStateCount),this.bestGStamp=new Uint32Array(searchStateCount),this.bestGValue=new Float64Array(searchStateCount),this.visitedFlatStamp=new Uint32Array(totalCells),this.stamp=0;let rootByPortFlat=new Map;for(let pp3 of this.nodeWithPortPoints.portPoints){let connId=this.connNameToId.get(pp3.connectionName);if(connId===void 0)continue;let cell=this.pointToCell(pp3),flatIdx=cell.z*this.planeSize+cell.cellId,rootNet=this.connIdToRootNet[connId],existingRoot=rootByPortFlat.get(flatIdx);existingRoot===void 0?rootByPortFlat.set(flatIdx,rootNet):existingRoot!==rootNet&&(this.sharedCrossRootPortFlat[flatIdx]=1);let existing=this.portOwnerFlat[flatIdx];existing===-1||existing===connId?this.portOwnerFlat[flatIdx]=connId:this.portOwnerFlat[flatIdx]=-2}this.solvedRoutes=[],this.usedIndicesByConn=[],this.ripCount=[],this.consecutiveSkips=0,this.penaltyCap=this.hyperParameters.ripCost*.5,this.shuffleConnections();let budget=computeMaxIterationsByNodeSizeAndConnectionCount({planeSize:this.planeSize,layers:this.layers,connectionCount:this.unsolvedSegs.length,effort:this.effort,maxIterations:this.MAX_ITERATIONS});this.baseSearchBudgetIters=budget.baseSearchBudgetIters,this.MAX_ITERATIONS=budget.maxIterationsIters,this.activeConnSeg=null,this.activeConnId=-1,this.nodePool=new TypedNodePool2,this.heap=new TypedMinHeap2,this.ripChain=new TypedRipChain2,this.seqCounter=0}_step(){for(let i3=0;i3<this.stepMultiplier;i3++){if(this.solved||this.failed)return;this.stepOnce()}}buildFiveRegionGrid(width,height){this.fineCols=Math.max(1,Math.ceil(width/this.highResolutionCellSize)),this.fineRows=Math.max(1,Math.ceil(height/this.highResolutionCellSize)),this.bandCols=Math.min(this.highResolutionCellThickness,Math.floor(this.fineCols/2)),this.bandRows=Math.min(this.highResolutionCellThickness,Math.floor(this.fineRows/2));let middleFineCols=Math.max(0,this.fineCols-this.bandCols*2),middleFineRows=Math.max(0,this.fineRows-this.bandRows*2),topFineCols=middleFineCols,bottomFineCols=middleFineCols;this.regions=[{id:REGION_LEFT,name:"left",fineOriginRow:0,fineOriginCol:0,fineRows:this.fineRows,fineCols:this.bandCols,cellScale:1,rows:this.fineRows,cols:this.bandCols,offset:0},{id:REGION_TOP,name:"top",fineOriginRow:0,fineOriginCol:this.bandCols,fineRows:this.bandRows,fineCols:topFineCols,cellScale:1,rows:this.bandRows,cols:topFineCols,offset:0},{id:REGION_RIGHT,name:"right",fineOriginRow:0,fineOriginCol:this.fineCols-this.bandCols,fineRows:this.fineRows,fineCols:this.bandCols,cellScale:1,rows:this.fineRows,cols:this.bandCols,offset:0},{id:REGION_BOTTOM,name:"bottom",fineOriginRow:this.fineRows-this.bandRows,fineOriginCol:this.bandCols,fineRows:this.bandRows,fineCols:bottomFineCols,cellScale:1,rows:this.bandRows,cols:bottomFineCols,offset:0},{id:REGION_MIDDLE,name:"middle",fineOriginRow:this.bandRows,fineOriginCol:this.bandCols,fineRows:middleFineRows,fineCols:middleFineCols,cellScale:this.lowScale,rows:middleFineRows>0?Math.ceil(middleFineRows/this.lowScale):0,cols:middleFineCols>0?Math.ceil(middleFineCols/this.lowScale):0,offset:0}];let offset=0;for(let i3=0;i3<this.regions.length;i3++)this.regions[i3].offset=offset,offset+=this.regions[i3].rows*this.regions[i3].cols;this.planeSize=offset,this.cellCenterX=new Float64Array(this.planeSize),this.cellCenterY=new Float64Array(this.planeSize),this.cellMinX=new Float64Array(this.planeSize),this.cellMinY=new Float64Array(this.planeSize),this.cellMaxX=new Float64Array(this.planeSize),this.cellMaxY=new Float64Array(this.planeSize),this.cellWidth=new Float64Array(this.planeSize),this.cellHeight=new Float64Array(this.planeSize),this.cellRegion=new Uint8Array(this.planeSize),this.cellRow=new Int32Array(this.planeSize),this.cellCol=new Int32Array(this.planeSize),this.viaAllowed=new Uint8Array(this.planeSize);for(let regionIdx=0;regionIdx<this.regions.length;regionIdx++){let region=this.regions[regionIdx];for(let row=0;row<region.rows;row++){let fineRow0=region.fineOriginRow+row*region.cellScale,fineRow1=Math.min(region.fineOriginRow+region.fineRows,fineRow0+region.cellScale),minY=this.boundsMinY+fineRow0*this.highResolutionCellSize,maxY=Math.min(this.boundsMaxY,this.boundsMinY+fineRow1*this.highResolutionCellSize);for(let col=0;col<region.cols;col++){let fineCol0=region.fineOriginCol+col*region.cellScale,fineCol1=Math.min(region.fineOriginCol+region.fineCols,fineCol0+region.cellScale),minX=this.boundsMinX+fineCol0*this.highResolutionCellSize,maxX=Math.min(this.boundsMaxX,this.boundsMinX+fineCol1*this.highResolutionCellSize),cellId=this.cellIdFor(region.id,row,col);this.cellCenterX[cellId]=(minX+maxX)/2,this.cellCenterY[cellId]=(minY+maxY)/2,this.cellMinX[cellId]=minX,this.cellMinY[cellId]=minY,this.cellMaxX[cellId]=maxX,this.cellMaxY[cellId]=maxY,this.cellWidth[cellId]=maxX-minX,this.cellHeight[cellId]=maxY-minY,this.cellRegion[cellId]=region.id,this.cellRow[cellId]=row,this.cellCol[cellId]=col;let minBorderDist=Math.min(this.cellCenterX[cellId]-this.boundsMinX,this.boundsMaxX-this.cellCenterX[cellId],this.cellCenterY[cellId]-this.boundsMinY,this.boundsMaxY-this.cellCenterY[cellId]);this.viaAllowed[cellId]=minBorderDist>=this.viaMinDistFromBorder?1:0}}}let neighbors=Array.from({length:this.planeSize},()=>[]),addBidirectionalEdge=(a3,b3)=>{if(a3===b3||a3<0||b3<0)return;let dx3=this.cellCenterX[a3]-this.cellCenterX[b3],dy3=this.cellCenterY[a3]-this.cellCenterY[b3],cost=Math.hypot(dx3,dy3);pushUniqueNeighbor2(neighbors[a3],{cellId:b3,cost}),pushUniqueNeighbor2(neighbors[b3],{cellId:a3,cost})};for(let regionIdx=0;regionIdx<this.regions.length;regionIdx++){let region=this.regions[regionIdx];for(let row=0;row<region.rows;row++)for(let col=0;col<region.cols;col++){let cellId=this.cellIdFor(region.id,row,col);row+1<region.rows&&addBidirectionalEdge(cellId,this.cellIdFor(region.id,row+1,col)),col+1<region.cols&&addBidirectionalEdge(cellId,this.cellIdFor(region.id,row,col+1))}}let left=this.regions[REGION_LEFT],top=this.regions[REGION_TOP],right=this.regions[REGION_RIGHT],bottom=this.regions[REGION_BOTTOM],middle=this.regions[REGION_MIDDLE],hasLeft=left.rows>0&&left.cols>0,hasTop=top.rows>0&&top.cols>0,hasRight=right.rows>0&&right.cols>0,hasBottom=bottom.rows>0&&bottom.cols>0,hasMiddle=middle.rows>0&&middle.cols>0;if(hasLeft&&hasTop)for(let globalRow=0;globalRow<this.bandRows;globalRow++)addBidirectionalEdge(this.cellIdFor(REGION_LEFT,globalRow,left.cols-1),this.cellIdFor(REGION_TOP,globalRow,0));if(hasTop&&hasRight)for(let globalRow=0;globalRow<this.bandRows;globalRow++)addBidirectionalEdge(this.cellIdFor(REGION_TOP,globalRow,top.cols-1),this.cellIdFor(REGION_RIGHT,globalRow,0));if(hasLeft&&hasBottom)for(let globalRow=this.fineRows-this.bandRows;globalRow<this.fineRows;globalRow++)addBidirectionalEdge(this.cellIdFor(REGION_LEFT,globalRow,left.cols-1),this.cellIdFor(REGION_BOTTOM,globalRow-(this.fineRows-this.bandRows),0));if(hasBottom&&hasRight)for(let globalRow=this.fineRows-this.bandRows;globalRow<this.fineRows;globalRow++)addBidirectionalEdge(this.cellIdFor(REGION_BOTTOM,globalRow-(this.fineRows-this.bandRows),bottom.cols-1),this.cellIdFor(REGION_RIGHT,globalRow,0));if(hasLeft&&hasMiddle)for(let globalRow=this.bandRows;globalRow<this.fineRows-this.bandRows;globalRow++)addBidirectionalEdge(this.cellIdFor(REGION_LEFT,globalRow,left.cols-1),this.cellIdFor(REGION_MIDDLE,Math.floor((globalRow-this.bandRows)/this.lowScale),0));if(hasRight&&hasMiddle)for(let globalRow=this.bandRows;globalRow<this.fineRows-this.bandRows;globalRow++)addBidirectionalEdge(this.cellIdFor(REGION_MIDDLE,Math.floor((globalRow-this.bandRows)/this.lowScale),middle.cols-1),this.cellIdFor(REGION_RIGHT,globalRow,0));if(hasTop&&hasMiddle)for(let globalCol=this.bandCols;globalCol<this.fineCols-this.bandCols;globalCol++)addBidirectionalEdge(this.cellIdFor(REGION_TOP,top.rows-1,globalCol-this.bandCols),this.cellIdFor(REGION_MIDDLE,0,Math.floor((globalCol-this.bandCols)/this.lowScale)));if(hasBottom&&hasMiddle)for(let globalCol=this.bandCols;globalCol<this.fineCols-this.bandCols;globalCol++)addBidirectionalEdge(this.cellIdFor(REGION_MIDDLE,middle.rows-1,Math.floor((globalCol-this.bandCols)/this.lowScale)),this.cellIdFor(REGION_BOTTOM,0,globalCol-this.bandCols));if(!hasMiddle&&!hasTop&&!hasBottom&&hasLeft&&hasRight)for(let row=0;row<Math.min(left.rows,right.rows);row++)addBidirectionalEdge(this.cellIdFor(REGION_LEFT,row,left.cols-1),this.cellIdFor(REGION_RIGHT,row,0));if(!hasMiddle&&!hasLeft&&!hasRight&&hasTop&&hasBottom)for(let col=0;col<Math.min(top.cols,bottom.cols);col++)addBidirectionalEdge(this.cellIdFor(REGION_TOP,top.rows-1,col),this.cellIdFor(REGION_BOTTOM,0,col));let flattened=this.flattenNeighborLists(neighbors);this.neighborOffset=flattened.offset,this.neighborIds=flattened.ids,this.neighborCosts=flattened.costs}cellIdFor(regionId,row,col){let region=this.regions[regionId];return region.offset+row*region.cols+col}stepOnce(){if(!this.activeConnSeg){if(this.unsolvedSegs.length===0){this.solved=!0;return}let next2=this.unsolvedSegs.shift();this.activeConnSeg=next2,this.activeConnId=next2.connId,this.nodePool.clear(),this.ripChain.clear(),this.heap.clear(),this.seqCounter=0,this.searchIterations=0,this.nextStamp();let f3=this.computeH(next2.startZ,next2.startCellId,next2.endZ,next2.endCellId)*this.hyperParameters.greedyMultiplier,startIdx=this.nodePool.push(next2.startZ,next2.startCellId,0,-1,-1,0),startFlatIdx=next2.startZ*this.planeSize+next2.startCellId,startStateIdx=this.getSearchStateIdx(startFlatIdx,0);this.bestGStamp[startStateIdx]=this.stamp,this.bestGValue[startStateIdx]=0,this.heap.push(f3,this.seqCounter++,startIdx);return}this.searchIterations++;let connRips=this.ripCount[this.activeConnId]??0,budget=Math.round(this.baseSearchBudgetIters*(1+Math.min(connRips,10)*.25));if(this.searchIterations>budget){let pen=this.penalty2d;for(let i3=0;i3<pen.length;i3++)pen[i3]=pen[i3]*.9;this.unsolvedSegs.push(this.activeConnSeg),this.activeConnSeg=null,this.activeConnId=-1,this.heap.clear(),this.nodePool.clear(),this.consecutiveSkips++,this.consecutiveSkips>=Math.max(3,this.unsolvedSegs.length*3)&&(this.error=`Convergence failure: ${this.unsolvedSegs.length} connections stuck`,this.failed=!0);return}if(this.heap.size===0){this.error=`No path found for ${this.connIdToName[this.activeConnId]}`,this.failed=!0;return}let nodeIdx=this.heap.pop(),z4=this.nodePool.z[nodeIdx],cellId=this.nodePool.cellId[nodeIdx],g6=this.nodePool.g[nodeIdx],rippedHead=this.nodePool.ripHead[nodeIdx],ripCount=this.nodePool.ripCount[nodeIdx],flatIdx=z4*this.planeSize+cellId,searchStateIdx=this.getSearchStateIdx(flatIdx,ripCount);if(this.visitedStamp[searchStateIdx]===this.stamp)return;this.visitedStamp[searchStateIdx]=this.stamp,this.visitedFlatStamp[flatIdx]=this.stamp;let seg=this.activeConnSeg;if(z4===seg.endZ&&cellId===seg.endCellId){this.finalizeRoute(nodeIdx),this.activeConnSeg=null,this.activeConnId=-1;return}let visited=this.visitedStamp,stamp=this.stamp,activeConn=this.activeConnId,endZ=seg.endZ,endCellId=seg.endCellId,neighborStart=this.neighborOffset[cellId],neighborEnd=this.neighborOffset[cellId+1];for(let i3=neighborStart;i3<neighborEnd;i3++){let neighborCellId=this.neighborIds[i3],nextFlatIdx=z4*this.planeSize+neighborCellId;if(this.computeMoveCostAndRips(activeConn,z4,neighborCellId,!1,rippedHead,ripCount,this.neighborCosts[i3]),this._moveCost<0)continue;let nextStateIdx=this.getSearchStateIdx(nextFlatIdx,this._moveRipCount);if(visited[nextStateIdx]===stamp)continue;let g22=g6+this._moveCost;if(this.bestGStamp[nextStateIdx]===stamp&&g22>=this.bestGValue[nextStateIdx])continue;this.bestGStamp[nextStateIdx]=stamp,this.bestGValue[nextStateIdx]=g22;let f22=g22+this.computeH(z4,neighborCellId,endZ,endCellId)*this.hyperParameters.greedyMultiplier,newNodeIdx=this.nodePool.push(z4,neighborCellId,g22,nodeIdx,this._moveRippedHead,this._moveRipCount);this.heap.push(f22,this.seqCounter++,newNodeIdx)}if(this.viaAllowed[cellId])for(let nz2=0;nz2<this.layers;nz2++){if(nz2===z4)continue;let nextFlatIdx=nz2*this.planeSize+cellId;if(this.computeMoveCostAndRips(activeConn,nz2,cellId,!0,rippedHead,ripCount,0),this._moveCost<0)continue;let nextStateIdx=this.getSearchStateIdx(nextFlatIdx,this._moveRipCount);if(visited[nextStateIdx]===stamp)continue;let g22=g6+this._moveCost;if(this.bestGStamp[nextStateIdx]===stamp&&g22>=this.bestGValue[nextStateIdx])continue;this.bestGStamp[nextStateIdx]=stamp,this.bestGValue[nextStateIdx]=g22;let f22=g22+this.computeH(nz2,cellId,endZ,endCellId)*this.hyperParameters.greedyMultiplier,newNodeIdx=this.nodePool.push(nz2,cellId,g22,nodeIdx,this._moveRippedHead,this._moveRipCount);this.heap.push(f22,this.seqCounter++,newNodeIdx)}}computeMoveCostAndRips(activeConn,toZ,toCellId,isVia,rippedHead,currentRipCount,lateralCost){let cost=0,head=rippedHead,ripCount=currentRipCount,toFlatIdx=toZ*this.planeSize+toCellId;if(isVia){cost+=this.hyperParameters.viaBaseCost,cost+=Math.min(this.penalty2d[toCellId],this.penaltyCap);let fixedOwner=this.portOwnerFlat[toFlatIdx],allowFixedOverlap=this.allowSharedUse(activeConn,fixedOwner),seg=this.activeConnSeg,isSegEnd=!!seg&&toZ===seg.endZ&&toCellId===seg.endCellId;if(fixedOwner>=0&&fixedOwner!==activeConn&&!allowFixedOverlap&&!isSegEnd){this._moveCost=-1,this._moveRippedHead=head;return}this.fillViaOccupants(toCellId,activeConn);let occs=this._viaOccs;for(let i3=0;i3<occs.length;i3++){let occ=occs[i3];this.ripChain.contains(head,occ)||(cost+=this.hyperParameters.ripCost,head=this.ripChain.append(head,occ),ripCount++),cost+=this.hyperParameters.ripViaPenalty}}else{cost+=lateralCost,cost+=Math.min(this.penalty2d[toCellId],this.penaltyCap);let fixedOwner=this.portOwnerFlat[toFlatIdx],allowFixedOverlap=this.allowSharedUse(activeConn,fixedOwner),seg=this.activeConnSeg,isSegEnd=!!seg&&toZ===seg.endZ&&toCellId===seg.endCellId;if(fixedOwner>=0&&fixedOwner!==activeConn&&!allowFixedOverlap&&!isSegEnd){this._moveCost=-1,this._moveRippedHead=head;return}this.fillTraceOccupants(toFlatIdx,activeConn,this._cellOccs);for(let i3=0;i3<this._cellOccs.length;i3++){let occ=this._cellOccs[i3];this.ripChain.contains(head,occ)||(cost+=this.hyperParameters.ripCost,head=this.ripChain.append(head,occ),ripCount++),cost+=this.hyperParameters.ripTracePenalty}}this._moveCost=cost,this._moveRippedHead=head,this._moveRipCount=ripCount}fillViaOccupants(cellId,activeConn){let occs=this._viaOccs;occs.length=0;let cx3=this.cellCenterX[cellId],cy3=this.cellCenterY[cellId];this.forEachCellNearCircle(cx3,cy3,this.viaKeepoutRadius,occCellId=>{if(circleIntersectsRect2(cx3,cy3,this.viaKeepoutRadius,this.cellMinX[occCellId],this.cellMinY[occCellId],this.cellMaxX[occCellId],this.cellMaxY[occCellId]))for(let z4=0;z4<this.layers;z4++)this.pushFlatOccupants(z4*this.planeSize+occCellId,activeConn,occs)})}fillTraceOccupants(flatIdx,activeConn,out){out.length=0,this.pushFlatOccupants(flatIdx,activeConn,out)}pushFlatOccupants(flatIdx,activeConn,out){let primaryOcc=this.usedCellsFlat[flatIdx];primaryOcc!==-1&&primaryOcc!==activeConn&&!this.allowSharedUse(activeConn,primaryOcc)&&pushUnique2(out,primaryOcc);let sharedOccs=this.sharedCellsFlat[flatIdx];if(sharedOccs)for(let i3=0;i3<sharedOccs.length;i3++){let occ=sharedOccs[i3];occ!==activeConn&&(this.allowSharedUse(activeConn,occ)||pushUnique2(out,occ))}}addSharedOccupant(flatIdx,connId){if(this.usedCellsFlat[flatIdx]===connId)return;let sharedOccs=this.sharedCellsFlat[flatIdx];sharedOccs||(sharedOccs=[],this.sharedCellsFlat[flatIdx]=sharedOccs),pushUnique2(sharedOccs,connId)}replaceOccupants(flatIdx,connId){this.usedCellsFlat[flatIdx]=connId,this.sharedCellsFlat[flatIdx]=void 0}removeOccupant(flatIdx,connId){let sharedOccs=this.sharedCellsFlat[flatIdx];if(this.usedCellsFlat[flatIdx]===connId){sharedOccs&&sharedOccs.length>0?(this.usedCellsFlat[flatIdx]=sharedOccs.pop(),sharedOccs.length===0&&(this.sharedCellsFlat[flatIdx]=void 0)):this.usedCellsFlat[flatIdx]=-1;return}if(!sharedOccs)return;let idx=sharedOccs.indexOf(connId);idx!==-1&&(sharedOccs.splice(idx,1),sharedOccs.length===0&&(this.sharedCellsFlat[flatIdx]=void 0))}allowSharedUse(activeConn,existingConn){return existingConn<0?!1:this.connIdToRootNet[existingConn]===this.connIdToRootNet[activeConn]}shouldSkipFixedPortHalo(flatIdx,connId){let fixedOwner=this.portOwnerFlat[flatIdx];return fixedOwner===connId?!1:fixedOwner===-2?!0:fixedOwner<0?!1:!this.allowSharedUse(connId,fixedOwner)}nextStamp(){this.stamp=this.stamp+1>>>0,this.stamp===0&&(this.visitedStamp.fill(0),this.bestGStamp.fill(0),this.visitedFlatStamp.fill(0),this.stamp=1)}getSearchStateIdx(flatIdx,ripCount){return flatIdx}computeH(z4,cellId,toZ,toCellId){let dist=Math.hypot(this.cellCenterX[cellId]-this.cellCenterX[toCellId],this.cellCenterY[cellId]-this.cellCenterY[toCellId]);return z4===toZ?dist:dist+this.hyperParameters.viaBaseCost}internConn(name,rootNetName){let existing=this.connNameToId.get(name);if(existing!==void 0)return existing;let id2=this.connIdToName.length;return this.connIdToName.push(name),this.connIdToRootNet.push(toRootNetName3(name,rootNetName)),this.connNameToId.set(name,id2),id2}buildConnectionSegs(){let byName=new Map;for(let pp3 of this.nodeWithPortPoints.portPoints){let name=pp3.connectionName;byName.has(name)||byName.set(name,{points:[],rootConnectionName:pp3.rootConnectionName}),byName.get(name).points.push(pp3)}let segs=[],seenSegmentKeys=new Set;for(let[name,conn]of byName){let pts=conn.points;if(pts.length<2)continue;let connId=this.internConn(name,conn.rootConnectionName);for(let i3=0;i3<pts.length-1;i3++){let s3=this.pointToCell(pts[i3]),e5=this.pointToCell(pts[i3+1]),endpointA=`${s3.z}:${s3.cellId}`,endpointB=`${e5.z}:${e5.cellId}`,orderedEndpoints=endpointA<endpointB?`${endpointA}|${endpointB}`:`${endpointB}|${endpointA}`,netName=conn.rootConnectionName??name,segKey=`${netName}|${orderedEndpoints}`;if(seenSegmentKeys.has(segKey)){this.overlapFriendlyRootNets.add(netName);continue}seenSegmentKeys.add(segKey),segs.push({connId,startZ:s3.z,startCellId:s3.cellId,startPoint:pts[i3],endZ:e5.z,endCellId:e5.cellId,endPoint:pts[i3+1]})}}return segs}pointToCell(pt3){let fineCol=clamp32(Math.floor((pt3.x-this.boundsMinX)/this.highResolutionCellSize),0,this.fineCols-1),fineRow=clamp32(Math.floor((pt3.y-this.boundsMinY)/this.highResolutionCellSize),0,this.fineRows-1),regionId=REGION_MIDDLE;fineCol<this.bandCols?regionId=REGION_LEFT:fineCol>=this.fineCols-this.bandCols?regionId=REGION_RIGHT:fineRow<this.bandRows?regionId=REGION_TOP:fineRow>=this.fineRows-this.bandRows&&(regionId=REGION_BOTTOM);let region=this.regions[regionId],localFineRow=fineRow-region.fineOriginRow,localFineCol=fineCol-region.fineOriginCol,row=clamp32(Math.floor(localFineRow/region.cellScale),0,Math.max(0,region.rows-1)),col=clamp32(Math.floor(localFineCol/region.cellScale),0,Math.max(0,region.cols-1));return{z:this.zToLayer.get(pt3.z)??0,cellId:this.cellIdFor(regionId,row,col)}}shuffleConnections(){let arr=this.unsolvedSegs,s3=this.hyperParameters.shuffleSeed>>>0,rng=()=>(s3=Math.imul(s3,1664525)+1013904223>>>0,s3/4294967295);for(let i3=arr.length-1;i3>0;i3--){let j4=Math.floor(rng()*(i3+1)),tmp=arr[i3];arr[i3]=arr[j4],arr[j4]=tmp}}finalizeRoute(goalNodeIdx){this.consecutiveSkips=Math.max(0,this.consecutiveSkips-1);let states=[],idx=goalNodeIdx;for(;idx>=0;){let z4=this.nodePool.z[idx],cellId=this.nodePool.cellId[idx];states.push(z4*this.planeSize+cellId),idx=this.nodePool.parent[idx]}for(states.reverse();states.length>1&&this.sharedCrossRootPortFlat[states[0]];)states.shift();for(;states.length>1&&this.sharedCrossRootPortFlat[states[states.length-1]];)states.pop();let viaCellIds=this.extractViaCellIds(states),connId=this.activeConnId;this.ripChain.collect(this.nodePool.ripHead[goalNodeIdx],this._rippedIds);for(let i3=0;i3<this._rippedIds.length;i3++)if(this.ripTrace(this._rippedIds[i3]),this.failed)return;let indices=[];for(let i3=0;i3<states.length;i3++){let state2=states[i3],z4=Math.floor(state2/this.planeSize),cellId=state2-z4*this.planeSize;this.markTraceFootprint(connId,z4,cellId,indices)}let displacedByVias=[];for(let i3=0;i3<viaCellIds.length;i3++)this.markViaFootprint(connId,viaCellIds[i3],indices,displacedByVias);for(;this.usedIndicesByConn.length<=connId;)this.usedIndicesByConn.push(void 0);for(this.usedIndicesByConn[connId]=indices;this.solvedRoutes.length<=connId;)this.solvedRoutes.push(void 0);this.solvedRoutes[connId]={connId,states:Int32Array.from(states),viaCellIds:Int32Array.from(viaCellIds),startPoint:this.activeConnSeg.startPoint,endPoint:this.activeConnSeg.endPoint};for(let i3=0;i3<displacedByVias.length;i3++)if(this.ripTrace(displacedByVias[i3]),this.failed)return;if(this._rippedIds.length>0||displacedByVias.length>0){let pen=this.penalty2d,cap2=this.penaltyCap;if(this.totalRipEvents>50)for(let i3=0;i3<pen.length;i3++)pen[i3]=pen[i3]*.99;else for(let i3=0;i3<pen.length;i3++)pen[i3]>cap2&&(pen[i3]=pen[i3]*.5)}}extractViaCellIds(states){let viaCellIds=[];for(let i3=1;i3<states.length;i3++){let prevState=states[i3-1],nextState=states[i3],prevZ=Math.floor(prevState/this.planeSize),nextZ=Math.floor(nextState/this.planeSize);prevZ!==nextZ&&viaCellIds.push(nextState-nextZ*this.planeSize)}return viaCellIds}markTraceFootprint(connId,z4,sourceCellId,indices){let cx3=this.cellCenterX[sourceCellId],cy3=this.cellCenterY[sourceCellId];this.forEachCellNearCircle(cx3,cy3,this.traceKeepoutRadius,cellId=>{if(!circleIntersectsRect2(cx3,cy3,this.traceKeepoutRadius,this.cellMinX[cellId],this.cellMinY[cellId],this.cellMaxX[cellId],this.cellMaxY[cellId]))return;let flatIdx=z4*this.planeSize+cellId;if(cellId!==sourceCellId&&this.shouldSkipFixedPortHalo(flatIdx,connId))return;let existing=this.usedCellsFlat[flatIdx],allowSameRootOverlap=this.allowSharedUse(connId,existing);existing!==-1&&existing!==connId&&!allowSameRootOverlap||(existing!==-1&&existing!==connId?this.addSharedOccupant(flatIdx,connId):this.usedCellsFlat[flatIdx]=connId,indices.push(flatIdx))})}markViaFootprint(connId,sourceCellId,indices,displacedByVias){let cx3=this.cellCenterX[sourceCellId],cy3=this.cellCenterY[sourceCellId];this.forEachCellNearCircle(cx3,cy3,this.viaKeepoutRadius,cellId=>{if(circleIntersectsRect2(cx3,cy3,this.viaKeepoutRadius,this.cellMinX[cellId],this.cellMinY[cellId],this.cellMaxX[cellId],this.cellMaxY[cellId]))for(let z4=0;z4<this.layers;z4++){let flatIdx=z4*this.planeSize+cellId;if(cellId!==sourceCellId&&this.shouldSkipFixedPortHalo(flatIdx,connId))continue;if(this.fillTraceOccupants(flatIdx,connId,this._cellOccs),this._cellOccs.length>0){for(let i3=0;i3<this._cellOccs.length;i3++)pushUnique2(displacedByVias,this._cellOccs[i3]);this.replaceOccupants(flatIdx,connId),indices.push(flatIdx);continue}let existing=this.usedCellsFlat[flatIdx];existing!==-1&&existing!==connId?this.addSharedOccupant(flatIdx,connId):this.usedCellsFlat[flatIdx]=connId,indices.push(flatIdx)}})}forEachCellNearCircle(cx3,cy3,radius,visitor){let minFineCol=clamp32(Math.floor((cx3-radius-this.boundsMinX)/this.highResolutionCellSize),0,this.fineCols-1),maxFineCol=clamp32(Math.floor((cx3+radius-this.boundsMinX)/this.highResolutionCellSize),0,this.fineCols-1),minFineRow=clamp32(Math.floor((cy3-radius-this.boundsMinY)/this.highResolutionCellSize),0,this.fineRows-1),maxFineRow=clamp32(Math.floor((cy3+radius-this.boundsMinY)/this.highResolutionCellSize),0,this.fineRows-1);for(let regionIdx=0;regionIdx<this.regions.length;regionIdx++){let region=this.regions[regionIdx];if(region.rows===0||region.cols===0)continue;let regionFineRowMin=Math.max(minFineRow,region.fineOriginRow),regionFineRowMax=Math.min(maxFineRow,region.fineOriginRow+region.fineRows-1),regionFineColMin=Math.max(minFineCol,region.fineOriginCol),regionFineColMax=Math.min(maxFineCol,region.fineOriginCol+region.fineCols-1);if(regionFineRowMin>regionFineRowMax||regionFineColMin>regionFineColMax)continue;let localRowMin=Math.floor((regionFineRowMin-region.fineOriginRow)/region.cellScale),localRowMax=Math.floor((regionFineRowMax-region.fineOriginRow)/region.cellScale),localColMin=Math.floor((regionFineColMin-region.fineOriginCol)/region.cellScale),localColMax=Math.floor((regionFineColMax-region.fineOriginCol)/region.cellScale);for(let row=localRowMin;row<=localRowMax;row++)for(let col=localColMin;col<=localColMax;col++)visitor(this.cellIdFor(region.id,row,col))}}ripTrace(connId){for(;this.ripCount.length<=connId;)this.ripCount.push(0);if(this.ripCount[connId]++,this.totalRipEvents++,this.totalRipEvents>=this.MAX_RIPS){this.error=`Convergence failure: exceeded MAX_RIPS ${this.MAX_RIPS}`,this.failed=!0;return}let route=this.solvedRoutes[connId];if(route){for(let i3=0;i3<route.states.length;i3++){let cellId=route.states[i3]%this.planeSize;this.penalty2d[cellId]=this.penalty2d[cellId]+this.hyperParameters.ripTracePenalty}for(let i3=0;i3<route.viaCellIds.length;i3++){let cellId=route.viaCellIds[i3];this.penalty2d[cellId]=this.penalty2d[cellId]+this.hyperParameters.ripViaPenalty}}let indices=this.usedIndicesByConn[connId];if(indices){for(let i3=0;i3<indices.length;i3++)this.removeOccupant(indices[i3],connId);this.usedIndicesByConn[connId]=void 0}if(route){this.solvedRoutes[connId]=void 0;let first=route.states[0],last=route.states[route.states.length-1],startZ=Math.floor(first/this.planeSize),endZ=Math.floor(last/this.planeSize);this.unsolvedSegs.push({connId,startZ,startCellId:first-startZ*this.planeSize,startPoint:route.startPoint,endZ,endCellId:last-endZ*this.planeSize,endPoint:route.endPoint})}}flattenNeighborLists(neighbors){let offset=new Int32Array(neighbors.length+1),total=0;for(let i3=0;i3<neighbors.length;i3++)offset[i3]=total,total+=neighbors[i3].length;offset[neighbors.length]=total;let ids=new Int32Array(total),costs=new Float32Array(total),cursor=0;for(let i3=0;i3<neighbors.length;i3++){let edges=neighbors[i3];for(let j4=0;j4<edges.length;j4++){let edge=edges[j4];ids[cursor]=edge.cellId,costs[cursor]=edge.cost,cursor++}}return{offset,ids,costs}}visualize(){let LAYER_COLORS2=["red","blue","orange","green"],vt3=this.gridToBoundsTransform,points=[],lines=[],circles=[],rects=[];if(rects.push({center:{x:this.nodeWithPortPoints.center.x,y:this.nodeWithPortPoints.center.y},width:this.nodeWithPortPoints.width,height:this.nodeWithPortPoints.height,stroke:"gray"}),this.showPenaltyMap&&this.penalty2d){let maxPenalty=0;for(let i3=0;i3<this.penalty2d.length;i3++)this.penalty2d[i3]>maxPenalty&&(maxPenalty=this.penalty2d[i3]);if(maxPenalty>0)for(let cellId=0;cellId<this.planeSize;cellId++){let penalty=this.penalty2d[cellId];if(penalty<=0)continue;let tc3=applyAffineTransformToPoint(vt3,{x:this.cellCenterX[cellId],y:this.cellCenterY[cellId]}),alpha=Math.min(.6,penalty/maxPenalty*.6);rects.push({center:tc3,width:this.cellWidth[cellId]*vt3.a,height:this.cellHeight[cellId]*vt3.e,fill:`rgba(255,165,0,${alpha.toFixed(3)})`})}}if(this.showUsedCellMap&&this.usedCellsFlat)for(let z4=0;z4<this.layers;z4++){let zBase=z4*this.planeSize;for(let cellId=0;cellId<this.planeSize;cellId++){if(this.usedCellsFlat[zBase+cellId]===-1)continue;let tc3=applyAffineTransformToPoint(vt3,{x:this.cellCenterX[cellId],y:this.cellCenterY[cellId]});rects.push({center:tc3,width:this.cellWidth[cellId]*vt3.a,height:this.cellHeight[cellId]*vt3.e,fill:"rgba(0,0,255,0.5)"})}}for(let pp3 of this.nodeWithPortPoints.portPoints)points.push({x:pp3.x,y:pp3.y,color:LAYER_COLORS2[pp3.z]??"gray",label:pp3.connectionName});let TRACE_COLORS3=["rgba(255,0,0,0.75)","rgba(0,0,255,0.75)","rgba(255,165,0,0.75)","rgba(0,128,0,0.75)"],transformedRoutes=this.getOutput();for(let route of transformedRoutes){if(route.route.length<2)continue;let segStart=0;for(let i3=1;i3<route.route.length;i3++){let prev=route.route[i3-1];route.route[i3].z!==prev.z&&(i3-segStart>=2&&lines.push({points:route.route.slice(segStart,i3).map(p4=>({x:p4.x,y:p4.y})),strokeColor:TRACE_COLORS3[prev.z]??"rgba(128,128,128,0.75)",strokeWidth:this.traceThickness}),segStart=i3)}if(route.route.length-segStart>=2){let lastZ=route.route[segStart].z;lines.push({points:route.route.slice(segStart).map(p4=>({x:p4.x,y:p4.y})),strokeColor:TRACE_COLORS3[lastZ]??"rgba(128,128,128,0.75)",strokeWidth:this.traceThickness})}}for(let route of transformedRoutes)for(let via of route.vias)circles.push({center:{x:via.x,y:via.y},radius:this.viaDiameter/2,fill:"rgba(0,0,0,0.3)",stroke:"black"});if(this.activeConnSeg&&this.visitedFlatStamp){let currentStamp=this.stamp;for(let z4=0;z4<this.layers;z4++){let zBase=z4*this.planeSize;for(let cellId=0;cellId<this.planeSize;cellId++){if(this.visitedFlatStamp[zBase+cellId]!==currentStamp)continue;let tc3=applyAffineTransformToPoint(vt3,{x:this.cellCenterX[cellId],y:this.cellCenterY[cellId]});points.push({x:tc3.x,y:tc3.y,color:"rgba(0,0,255,0.2)"})}}}return{points,lines,circles,rects,coordinateSystem:"cartesian",title:`HighDensityA03 [${this.getSolvedRouteCount()} solved, ${this.unsolvedSegs?.length??0} remaining]`}}getOutput(){let t52=this.gridToBoundsTransform,result=[];for(let connId=0;connId<this.solvedRoutes.length;connId++){let route=this.solvedRoutes[connId];if(!route)continue;let connName=this.connIdToName[connId],points=Array.from(route.states,state2=>{let z4=Math.floor(state2/this.planeSize),cellId=state2-z4*this.planeSize,tp3=applyAffineTransformToPoint(t52,{x:this.cellCenterX[cellId],y:this.cellCenterY[cellId]});return{x:tp3.x,y:tp3.y,z:this.layerToZ.get(z4)??z4}});points.length>0&&(points[0]={...route.startPoint},points.length>1&&(points[points.length-1]={...route.endPoint})),result.push({connectionName:connName,traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,route:points,vias:Array.from(route.viaCellIds,cellId=>applyAffineTransformToPoint(t52,{x:this.cellCenterX[cellId],y:this.cellCenterY[cellId]}))})}return result}getSolvedRouteCount(){let count=0;for(let i3=0;i3<this.solvedRoutes.length;i3++)this.solvedRoutes[i3]&&count++;return count}computeGridToBoundsTransform(){let minCenterX=1/0,maxCenterX=-1/0,minCenterY=1/0,maxCenterY=-1/0;for(let cellId=0;cellId<this.planeSize;cellId++){let centerX=this.cellCenterX[cellId],centerY=this.cellCenterY[cellId];centerX<minCenterX&&(minCenterX=centerX),centerX>maxCenterX&&(maxCenterX=centerX),centerY<minCenterY&&(minCenterY=centerY),centerY>maxCenterY&&(maxCenterY=centerY)}let xSpan=maxCenterX-minCenterX,ySpan=maxCenterY-minCenterY,width=this.boundsMaxX-this.boundsMinX,height=this.boundsMaxY-this.boundsMinY,a3=xSpan>0?width/xSpan:1,e5=ySpan>0?height/ySpan:1,c4=xSpan>0?this.boundsMinX-a3*minCenterX:(this.boundsMinX+this.boundsMaxX)/2-minCenterX,f3=ySpan>0?this.boundsMinY-e5*minCenterY:(this.boundsMinY+this.boundsMaxY)/2-minCenterY;return{a:a3,b:0,c:c4,d:0,e:e5,f:f3}}};var ROUNDING_PRECISION=1e3;var BOUNDARY_INSET=1/ROUNDING_PRECISION;var VIA_BORDER_EXTRA_CLEARANCE=.15,VIA_SEGMENT_TARGET_CLEARANCE=.4;var VIA_BORDER_TARGET_CLEARANCE=VIA_SEGMENT_TARGET_CLEARANCE+VIA_BORDER_EXTRA_CLEARANCE+.1,VIA_BORDER_FALLOFF_DISTANCE=VIA_BORDER_TARGET_CLEARANCE+.05;var defaultParams={cellSizeMm:.1,traceMargin:.15,traceThickness:.1,viaDiameter:.3,viaMinDistFromBorder:.15},defaultA03Params={highResolutionCellSize:.1,highResolutionCellThickness:8,lowResolutionCellSize:.4,traceMargin:.15,traceThickness:.1,viaDiameter:.3,viaMinDistFromBorder:.15},defaultA08Params={...defaultParams,stepMultiplier:1,showPenaltyMap:!1,showUsedCellMap:!1,effort:1,initialRectMarginMm:.2,rectShrinkStepMm:.1,breakoutTraceMarginMm:.1,breakoutSegmentCount:2,breakoutMaxIterationsPerRect:60,breakoutForceStepSize:.2,breakoutRepulsionStrength:1.8,breakoutSmoothingStrength:.16,breakoutAttractionStrength:.06,innerPortSpreadFactor:1},defaultA09Params={...defaultA03Params,effort:1,boundaryBonus:.18,boundaryBonusSigma:.22,portShadowStrength:.55,portShadowTangentSigma:.18,portShadowDepthSigma:.5,fullOrderSearchConnectionCountLimit:6,priorityHeadSize:4,maxCandidateOrders:720};var import_object_hash=__toESM(require_object_hash(),1),import_object_hash2=__toESM(require_object_hash(),1),import_object_hash3=__toESM(require_object_hash(),1);var t3=Object.create,e4=Object.defineProperty,n3=Object.getOwnPropertyDescriptor,o3=Object.getOwnPropertyNames,i2=Object.getPrototypeOf,s2=Object.prototype.hasOwnProperty,r4=(t52,e5)=>function(){return e5||(0,t52[o3(t52)[0]])((e5={exports:{}}).exports,e5),e5.exports},a2=(t52,n4)=>{for(var o4 in n4)e4(t52,o4,{get:n4[o4],enumerable:!0})},c3=(r5,a3,c4)=>(c4=r5!=null?t3(i2(r5)):{},((t52,i3,r6,a4)=>{if(i3&&typeof i3=="object"||typeof i3=="function")for(let c5 of o3(i3))s2.call(t52,c5)||c5===r6||e4(t52,c5,{get:()=>i3[c5],enumerable:!(a4=n3(i3,c5))||a4.enumerable});return t52})(!a3&&r5&&r5.__esModule?c4:e4(c4,"default",{value:r5,enumerable:!0}),r5)),l3=r4({"node_modules/is-buffer/index.js"(t52,e5){function n4(t53){return!!t53.constructor&&typeof t53.constructor.isBuffer=="function"&&t53.constructor.isBuffer(t53)}e5.exports=function(t53){return t53!=null&&(n4(t53)||(function(t54){return typeof t54.readFloatLE=="function"&&typeof t54.slice=="function"&&n4(t54.slice(0,0))})(t53)||!!t53._isBuffer)}}}),h4=r4({"node_modules/kind-of/index.js"(t52,e5){var n4=l3(),o4=Object.prototype.toString;e5.exports=function(t53){if(t53===void 0)return"undefined";if(t53===null)return"null";if(t53===!0||t53===!1||t53 instanceof Boolean)return"boolean";if(typeof t53=="string"||t53 instanceof String)return"string";if(typeof t53=="number"||t53 instanceof Number)return"number";if(typeof t53=="function"||t53 instanceof Function)return"function";if(Array.isArray!==void 0&&Array.isArray(t53))return"array";if(t53 instanceof RegExp)return"regexp";if(t53 instanceof Date)return"date";var e6=o4.call(t53);return e6==="[object RegExp]"?"regexp":e6==="[object Date]"?"date":e6==="[object Arguments]"?"arguments":e6==="[object Error]"?"error":n4(t53)?"buffer":e6==="[object Set]"?"set":e6==="[object WeakSet]"?"weakset":e6==="[object Map]"?"map":e6==="[object WeakMap]"?"weakmap":e6==="[object Symbol]"?"symbol":e6==="[object Int8Array]"?"int8array":e6==="[object Uint8Array]"?"uint8array":e6==="[object Uint8ClampedArray]"?"uint8clampedarray":e6==="[object Int16Array]"?"int16array":e6==="[object Uint16Array]"?"uint16array":e6==="[object Int32Array]"?"int32array":e6==="[object Uint32Array]"?"uint32array":e6==="[object Float32Array]"?"float32array":e6==="[object Float64Array]"?"float64array":"object"}}}),d3=r4({"node_modules/rename-keys/index.js"(t52,e5){(function(){function t53(t54,e6){if(typeof e6!="function")return t54;var n4={};for(var o4 in t54)Object.prototype.hasOwnProperty.call(t54,o4)&&(n4[e6(o4,t54[o4])||o4]=t54[o4]);return n4}e5!==void 0&&e5.exports?e5.exports=t53:typeof define=="function"&&define.amd?define([],function(){return t53}):window.rename=t53})()}}),u4=r4({"node_modules/deep-rename-keys/index.js"(t52,e5){var n4=h4(),o4=d3();e5.exports=function t53(e6,i3){var s3=n4(e6);if(s3!=="object"&&s3!=="array")throw new Error("expected an object");var r5=[];for(var a3 in s3==="object"&&(e6=o4(e6,i3),r5={}),e6)if(e6.hasOwnProperty(a3)){var c4=e6[a3];n4(c4)==="object"||n4(c4)==="array"?r5[a3]=t53(c4,i3):r5[a3]=c4}return r5}}}),p3=r4({"node_modules/xml-reader/node_modules/eventemitter3/index.js"(t52,e5){var n4=Object.prototype.hasOwnProperty,o4="~";function i3(){}function s3(t53,e6,n5){this.fn=t53,this.context=e6,this.once=n5||!1}function r5(){this._events=new i3,this._eventsCount=0}Object.create&&(i3.prototype=Object.create(null),new i3().__proto__||(o4=!1)),r5.prototype.eventNames=function(){var t53,e6,i4=[];if(this._eventsCount===0)return i4;for(e6 in t53=this._events)n4.call(t53,e6)&&i4.push(o4?e6.slice(1):e6);return Object.getOwnPropertySymbols?i4.concat(Object.getOwnPropertySymbols(t53)):i4},r5.prototype.listeners=function(t53,e6){var n5=o4?o4+t53:t53,i4=this._events[n5];if(e6)return!!i4;if(!i4)return[];if(i4.fn)return[i4.fn];for(var s4=0,r6=i4.length,a3=new Array(r6);s4<r6;s4++)a3[s4]=i4[s4].fn;return a3},r5.prototype.emit=function(t53,e6,n5,i4,s4,r6){var a3=o4?o4+t53:t53;if(!this._events[a3])return!1;var c4,l4,h6=this._events[a3],d4=arguments.length;if(h6.fn){switch(h6.once&&this.removeListener(t53,h6.fn,void 0,!0),d4){case 1:return h6.fn.call(h6.context),!0;case 2:return h6.fn.call(h6.context,e6),!0;case 3:return h6.fn.call(h6.context,e6,n5),!0;case 4:return h6.fn.call(h6.context,e6,n5,i4),!0;case 5:return h6.fn.call(h6.context,e6,n5,i4,s4),!0;case 6:return h6.fn.call(h6.context,e6,n5,i4,s4,r6),!0}for(l4=1,c4=new Array(d4-1);l4<d4;l4++)c4[l4-1]=arguments[l4];h6.fn.apply(h6.context,c4)}else{var u5,p4=h6.length;for(l4=0;l4<p4;l4++)switch(h6[l4].once&&this.removeListener(t53,h6[l4].fn,void 0,!0),d4){case 1:h6[l4].fn.call(h6[l4].context);break;case 2:h6[l4].fn.call(h6[l4].context,e6);break;case 3:h6[l4].fn.call(h6[l4].context,e6,n5);break;case 4:h6[l4].fn.call(h6[l4].context,e6,n5,i4);break;default:if(!c4)for(u5=1,c4=new Array(d4-1);u5<d4;u5++)c4[u5-1]=arguments[u5];h6[l4].fn.apply(h6[l4].context,c4)}}return!0},r5.prototype.on=function(t53,e6,n5){var i4=new s3(e6,n5||this),r6=o4?o4+t53:t53;return this._events[r6]?this._events[r6].fn?this._events[r6]=[this._events[r6],i4]:this._events[r6].push(i4):(this._events[r6]=i4,this._eventsCount++),this},r5.prototype.once=function(t53,e6,n5){var i4=new s3(e6,n5||this,!0),r6=o4?o4+t53:t53;return this._events[r6]?this._events[r6].fn?this._events[r6]=[this._events[r6],i4]:this._events[r6].push(i4):(this._events[r6]=i4,this._eventsCount++),this},r5.prototype.removeListener=function(t53,e6,n5,s4){var r6=o4?o4+t53:t53;if(!this._events[r6])return this;if(!e6)return--this._eventsCount===0?this._events=new i3:delete this._events[r6],this;var a3=this._events[r6];if(a3.fn)a3.fn!==e6||s4&&!a3.once||n5&&a3.context!==n5||(--this._eventsCount===0?this._events=new i3:delete this._events[r6]);else{for(var c4=0,l4=[],h6=a3.length;c4<h6;c4++)(a3[c4].fn!==e6||s4&&!a3[c4].once||n5&&a3[c4].context!==n5)&&l4.push(a3[c4]);l4.length?this._events[r6]=l4.length===1?l4[0]:l4:--this._eventsCount===0?this._events=new i3:delete this._events[r6]}return this},r5.prototype.removeAllListeners=function(t53){var e6;return t53?(e6=o4?o4+t53:t53,this._events[e6]&&(--this._eventsCount===0?this._events=new i3:delete this._events[e6])):(this._events=new i3,this._eventsCount=0),this},r5.prototype.off=r5.prototype.removeListener,r5.prototype.addListener=r5.prototype.on,r5.prototype.setMaxListeners=function(){return this},r5.prefixed=o4,r5.EventEmitter=r5,e5!==void 0&&(e5.exports=r5)}}),m3=r4({"node_modules/xml-lexer/node_modules/eventemitter3/index.js"(t52,e5){var n4=Object.prototype.hasOwnProperty,o4="~";function i3(){}function s3(t53,e6,n5){this.fn=t53,this.context=e6,this.once=n5||!1}function r5(){this._events=new i3,this._eventsCount=0}Object.create&&(i3.prototype=Object.create(null),new i3().__proto__||(o4=!1)),r5.prototype.eventNames=function(){var t53,e6,i4=[];if(this._eventsCount===0)return i4;for(e6 in t53=this._events)n4.call(t53,e6)&&i4.push(o4?e6.slice(1):e6);return Object.getOwnPropertySymbols?i4.concat(Object.getOwnPropertySymbols(t53)):i4},r5.prototype.listeners=function(t53,e6){var n5=o4?o4+t53:t53,i4=this._events[n5];if(e6)return!!i4;if(!i4)return[];if(i4.fn)return[i4.fn];for(var s4=0,r6=i4.length,a3=new Array(r6);s4<r6;s4++)a3[s4]=i4[s4].fn;return a3},r5.prototype.emit=function(t53,e6,n5,i4,s4,r6){var a3=o4?o4+t53:t53;if(!this._events[a3])return!1;var c4,l4,h6=this._events[a3],d4=arguments.length;if(h6.fn){switch(h6.once&&this.removeListener(t53,h6.fn,void 0,!0),d4){case 1:return h6.fn.call(h6.context),!0;case 2:return h6.fn.call(h6.context,e6),!0;case 3:return h6.fn.call(h6.context,e6,n5),!0;case 4:return h6.fn.call(h6.context,e6,n5,i4),!0;case 5:return h6.fn.call(h6.context,e6,n5,i4,s4),!0;case 6:return h6.fn.call(h6.context,e6,n5,i4,s4,r6),!0}for(l4=1,c4=new Array(d4-1);l4<d4;l4++)c4[l4-1]=arguments[l4];h6.fn.apply(h6.context,c4)}else{var u5,p4=h6.length;for(l4=0;l4<p4;l4++)switch(h6[l4].once&&this.removeListener(t53,h6[l4].fn,void 0,!0),d4){case 1:h6[l4].fn.call(h6[l4].context);break;case 2:h6[l4].fn.call(h6[l4].context,e6);break;case 3:h6[l4].fn.call(h6[l4].context,e6,n5);break;case 4:h6[l4].fn.call(h6[l4].context,e6,n5,i4);break;default:if(!c4)for(u5=1,c4=new Array(d4-1);u5<d4;u5++)c4[u5-1]=arguments[u5];h6[l4].fn.apply(h6[l4].context,c4)}}return!0},r5.prototype.on=function(t53,e6,n5){var i4=new s3(e6,n5||this),r6=o4?o4+t53:t53;return this._events[r6]?this._events[r6].fn?this._events[r6]=[this._events[r6],i4]:this._events[r6].push(i4):(this._events[r6]=i4,this._eventsCount++),this},r5.prototype.once=function(t53,e6,n5){var i4=new s3(e6,n5||this,!0),r6=o4?o4+t53:t53;return this._events[r6]?this._events[r6].fn?this._events[r6]=[this._events[r6],i4]:this._events[r6].push(i4):(this._events[r6]=i4,this._eventsCount++),this},r5.prototype.removeListener=function(t53,e6,n5,s4){var r6=o4?o4+t53:t53;if(!this._events[r6])return this;if(!e6)return--this._eventsCount===0?this._events=new i3:delete this._events[r6],this;var a3=this._events[r6];if(a3.fn)a3.fn!==e6||s4&&!a3.once||n5&&a3.context!==n5||(--this._eventsCount===0?this._events=new i3:delete this._events[r6]);else{for(var c4=0,l4=[],h6=a3.length;c4<h6;c4++)(a3[c4].fn!==e6||s4&&!a3[c4].once||n5&&a3[c4].context!==n5)&&l4.push(a3[c4]);l4.length?this._events[r6]=l4.length===1?l4[0]:l4:--this._eventsCount===0?this._events=new i3:delete this._events[r6]}return this},r5.prototype.removeAllListeners=function(t53){var e6;return t53?(e6=o4?o4+t53:t53,this._events[e6]&&(--this._eventsCount===0?this._events=new i3:delete this._events[e6])):(this._events=new i3,this._eventsCount=0),this},r5.prototype.off=r5.prototype.removeListener,r5.prototype.addListener=r5.prototype.on,r5.prototype.setMaxListeners=function(){return this},r5.prefixed=o4,r5.EventEmitter=r5,e5!==void 0&&(e5.exports=r5)}}),g4=r4({"node_modules/xml-lexer/dist/lexer.js"(t52,e5){function n4(t53,e6,n5){return e6 in t53?Object.defineProperty(t53,e6,{value:n5,enumerable:!0,configurable:!0,writable:!0}):t53[e6]=n5,t53}var o4=m3(),i3=function(){},s3={data:"state-data",cdata:"state-cdata",tagBegin:"state-tag-begin",tagName:"state-tag-name",tagEnd:"state-tag-end",attributeNameStart:"state-attribute-name-start",attributeName:"state-attribute-name",attributeNameEnd:"state-attribute-name-end",attributeValueBegin:"state-attribute-value-begin",attributeValue:"state-attribute-value"},r5={lt:"action-lt",gt:"action-gt",space:"action-space",equal:"action-equal",quote:"action-quote",slash:"action-slash",char:"action-char",error:"action-error"},a3={text:"text",openTag:"open-tag",closeTag:"close-tag",attributeName:"attribute-name",attributeValue:"attribute-value"},c4={" ":r5.space," ":r5.space,"\n":r5.space,"\r":r5.space,"<":r5.lt,">":r5.gt,'"':r5.quote,"'":r5.quote,"=":r5.equal,"/":r5.slash};e5.exports={State:s3,Action:r5,Type:a3,create:function(t53){var e6,l4,h6,d4,u5,p4,m4,g6,f3,_4;t53=Object.assign({debug:!1},t53);var y4=new o4,b3=s3.data,x4="",v4="",S3="",I4="",P4="",M4="",N4=function(e7,n5){if(v4[0]!=="?"&&v4[0]!=="!"){var o6={type:e7,value:n5};t53.debug&&console.log("emit:",o6),y4.emit("data",o6)}};y4.stateMachine=(n4(_4={},s3.data,(n4(e6={},r5.lt,function(){x4.trim()&&N4(a3.text,x4),v4="",P4=!1,b3=s3.tagBegin}),n4(e6,r5.char,function(t54){x4+=t54}),e6)),n4(_4,s3.cdata,n4({},r5.char,function(t54){(x4+=t54).substr(-3)==="]]>"&&(N4(a3.text,x4.slice(0,-3)),x4="",b3=s3.data)})),n4(_4,s3.tagBegin,(n4(l4={},r5.space,i3),n4(l4,r5.char,function(t54){v4=t54,b3=s3.tagName}),n4(l4,r5.slash,function(){v4="",P4=!0}),l4)),n4(_4,s3.tagName,(n4(h6={},r5.space,function(){P4?b3=s3.tagEnd:(b3=s3.attributeNameStart,N4(a3.openTag,v4))}),n4(h6,r5.gt,function(){N4(P4?a3.closeTag:a3.openTag,v4),x4="",b3=s3.data}),n4(h6,r5.slash,function(){b3=s3.tagEnd,N4(a3.openTag,v4)}),n4(h6,r5.char,function(t54){(v4+=t54)==="![CDATA["&&(b3=s3.cdata,x4="",v4="")}),h6)),n4(_4,s3.tagEnd,(n4(d4={},r5.gt,function(){N4(a3.closeTag,v4),x4="",b3=s3.data}),n4(d4,r5.char,i3),d4)),n4(_4,s3.attributeNameStart,(n4(u5={},r5.char,function(t54){S3=t54,b3=s3.attributeName}),n4(u5,r5.gt,function(){x4="",b3=s3.data}),n4(u5,r5.space,i3),n4(u5,r5.slash,function(){P4=!0,b3=s3.tagEnd}),u5)),n4(_4,s3.attributeName,(n4(p4={},r5.space,function(){b3=s3.attributeNameEnd}),n4(p4,r5.equal,function(){N4(a3.attributeName,S3),b3=s3.attributeValueBegin}),n4(p4,r5.gt,function(){I4="",N4(a3.attributeName,S3),N4(a3.attributeValue,I4),x4="",b3=s3.data}),n4(p4,r5.slash,function(){P4=!0,I4="",N4(a3.attributeName,S3),N4(a3.attributeValue,I4),b3=s3.tagEnd}),n4(p4,r5.char,function(t54){S3+=t54}),p4)),n4(_4,s3.attributeNameEnd,(n4(m4={},r5.space,i3),n4(m4,r5.equal,function(){N4(a3.attributeName,S3),b3=s3.attributeValueBegin}),n4(m4,r5.gt,function(){I4="",N4(a3.attributeName,S3),N4(a3.attributeValue,I4),x4="",b3=s3.data}),n4(m4,r5.char,function(t54){I4="",N4(a3.attributeName,S3),N4(a3.attributeValue,I4),S3=t54,b3=s3.attributeName}),m4)),n4(_4,s3.attributeValueBegin,(n4(g6={},r5.space,i3),n4(g6,r5.quote,function(t54){M4=t54,I4="",b3=s3.attributeValue}),n4(g6,r5.gt,function(){N4(a3.attributeValue,I4=""),x4="",b3=s3.data}),n4(g6,r5.char,function(t54){M4="",I4=t54,b3=s3.attributeValue}),g6)),n4(_4,s3.attributeValue,(n4(f3={},r5.space,function(t54){M4?I4+=t54:(N4(a3.attributeValue,I4),b3=s3.attributeNameStart)}),n4(f3,r5.quote,function(t54){M4===t54?(N4(a3.attributeValue,I4),b3=s3.attributeNameStart):I4+=t54}),n4(f3,r5.gt,function(t54){M4?I4+=t54:(N4(a3.attributeValue,I4),x4="",b3=s3.data)}),n4(f3,r5.slash,function(t54){M4?I4+=t54:(N4(a3.attributeValue,I4),P4=!0,b3=s3.tagEnd)}),n4(f3,r5.char,function(t54){I4+=t54}),f3)),_4);var C4=function(e7){t53.debug&&console.log(b3,e7);var n5=y4.stateMachine[b3],o6=n5[(function(t54){return c4[t54]||r5.char})(e7)]||n5[r5.error]||n5[r5.char];o6(e7)};return y4.write=function(t54){for(var e7=t54.length,n5=0;n5<e7;n5++)C4(t54[n5])},y4}}}}),f2=r4({"node_modules/xml-reader/dist/reader.js"(t52,e5){var n4=p3(),o4=g4(),i3=o4.Type,s3={element:"element",text:"text"},r5=function(t53){return Object.assign({name:"",type:s3.element,value:"",parent:null,attributes:{},children:[]},t53)},a3=function(t53){t53=Object.assign({stream:!1,parentNodes:!0,doneEvent:"done",tagPrefix:"tag:",emitTopLevelOnly:!1,debug:!1},t53);var e6=void 0,a4=void 0,c4=void 0,l4=void 0,h6=new n4,d4=function(n5){switch(n5.type){case i3.openTag:if(c4===null)(c4=a4).name=n5.value;else{var o6=r5({name:n5.value,parent:c4});c4.children.push(o6),c4=o6}break;case i3.closeTag:var d5=c4.parent;if(t53.parentNodes||(c4.parent=null),c4.name!==n5.value)break;t53.stream&&d5===a4&&(a4.children=[],c4.parent=null),t53.emitTopLevelOnly&&d5!==a4||(h6.emit(t53.tagPrefix+c4.name,c4),h6.emit("tag",c4.name,c4)),c4===a4&&(e6.removeAllListeners("data"),h6.emit(t53.doneEvent,c4),a4=null),c4=d5;break;case i3.text:c4&&c4.children.push(r5({type:s3.text,value:n5.value,parent:t53.parentNodes?c4:null}));break;case i3.attributeName:l4=n5.value,c4.attributes[l4]="";break;case i3.attributeValue:c4.attributes[l4]=n5.value}};return h6.reset=function(){(e6=o4.create({debug:t53.debug})).on("data",d4),a4=r5(),c4=null,l4="",h6.parse=e6.write},h6.reset(),h6};e5.exports={parseSync:function(t53,e6){e6=Object.assign({},e6,{stream:!1,tagPrefix:":"});var n5=a3(e6),o6=void 0;return n5.on("done",function(t54){o6=t54}),n5.parse(t53),o6},create:a3,NodeType:s3}}}),_3=r4({"node_modules/binary-search-bounds/search-bounds.js"(t52,e5){function n4(t53,e6,n5,o6,i4){for(var s4=i4+1;o6<=i4;){var r6=o6+i4>>>1,a4=t53[r6];(n5!==void 0?n5(a4,e6):a4-e6)>=0?(s4=r6,i4=r6-1):o6=r6+1}return s4}function o4(t53,e6,n5,o6,i4){for(var s4=i4+1;o6<=i4;){var r6=o6+i4>>>1,a4=t53[r6];(n5!==void 0?n5(a4,e6):a4-e6)>0?(s4=r6,i4=r6-1):o6=r6+1}return s4}function i3(t53,e6,n5,o6,i4){for(var s4=o6-1;o6<=i4;){var r6=o6+i4>>>1,a4=t53[r6];(n5!==void 0?n5(a4,e6):a4-e6)<0?(s4=r6,o6=r6+1):i4=r6-1}return s4}function s3(t53,e6,n5,o6,i4){for(var s4=o6-1;o6<=i4;){var r6=o6+i4>>>1,a4=t53[r6];(n5!==void 0?n5(a4,e6):a4-e6)<=0?(s4=r6,o6=r6+1):i4=r6-1}return s4}function r5(t53,e6,n5,o6,i4){for(;o6<=i4;){var s4=o6+i4>>>1,r6=t53[s4],a4=n5!==void 0?n5(r6,e6):r6-e6;if(a4===0)return s4;a4<=0?o6=s4+1:i4=s4-1}return-1}function a3(t53,e6,n5,o6,i4,s4){return typeof n5=="function"?s4(t53,e6,n5,o6===void 0?0:0|o6,i4===void 0?t53.length-1:0|i4):s4(t53,e6,void 0,n5===void 0?0:0|n5,o6===void 0?t53.length-1:0|o6)}e5.exports={ge:function(t53,e6,o6,i4,s4){return a3(t53,e6,o6,i4,s4,n4)},gt:function(t53,e6,n5,i4,s4){return a3(t53,e6,n5,i4,s4,o4)},lt:function(t53,e6,n5,o6,s4){return a3(t53,e6,n5,o6,s4,i3)},le:function(t53,e6,n5,o6,i4){return a3(t53,e6,n5,o6,i4,s3)},eq:function(t53,e6,n5,o6,i4){return a3(t53,e6,n5,o6,i4,r5)}}}}),y=r4({"node_modules/two-product/two-product.js"(t52,e5){e5.exports=function(t53,e6,o4){var i3=t53*e6,s3=n4*t53,r5=s3-(s3-t53),a3=t53-r5,c4=n4*e6,l4=c4-(c4-e6),h6=e6-l4,d4=a3*h6-(i3-r5*l4-a3*l4-r5*h6);return o4?(o4[0]=d4,o4[1]=i3,o4):[d4,i3]};var n4=+(Math.pow(2,27)+1)}}),b=r4({"node_modules/robust-sum/robust-sum.js"(t52,e5){e5.exports=function(t53,e6){var n4=0|t53.length,o4=0|e6.length;if(n4===1&&o4===1)return(function(t54,e7){var n5=t54+e7,o6=n5-t54,i4=n5-o6,s4=e7-o6,r6=t54-i4,a4=r6+s4;return a4?[a4,n5]:[n5]})(t53[0],e6[0]);var i3,s3,r5=new Array(n4+o4),a3=0,c4=0,l4=0,h6=Math.abs,d4=t53[c4],u5=h6(d4),p4=e6[l4],m4=h6(p4);u5<m4?(s3=d4,(c4+=1)<n4&&(u5=h6(d4=t53[c4]))):(s3=p4,(l4+=1)<o4&&(m4=h6(p4=e6[l4]))),c4<n4&&u5<m4||l4>=o4?(i3=d4,(c4+=1)<n4&&(u5=h6(d4=t53[c4]))):(i3=p4,(l4+=1)<o4&&(m4=h6(p4=e6[l4])));for(var g6,f3,_4=i3+s3,y4=_4-i3,b3=s3-y4,x4=b3,v4=_4;c4<n4&&l4<o4;)u5<m4?(i3=d4,(c4+=1)<n4&&(u5=h6(d4=t53[c4]))):(i3=p4,(l4+=1)<o4&&(m4=h6(p4=e6[l4]))),(b3=(s3=x4)-(y4=(_4=i3+s3)-i3))&&(r5[a3++]=b3),x4=v4-((g6=v4+_4)-(f3=g6-v4))+(_4-f3),v4=g6;for(;c4<n4;)(b3=(s3=x4)-(y4=(_4=(i3=d4)+s3)-i3))&&(r5[a3++]=b3),x4=v4-((g6=v4+_4)-(f3=g6-v4))+(_4-f3),v4=g6,(c4+=1)<n4&&(d4=t53[c4]);for(;l4<o4;)(b3=(s3=x4)-(y4=(_4=(i3=p4)+s3)-i3))&&(r5[a3++]=b3),x4=v4-((g6=v4+_4)-(f3=g6-v4))+(_4-f3),v4=g6,(l4+=1)<o4&&(p4=e6[l4]);return x4&&(r5[a3++]=x4),v4&&(r5[a3++]=v4),a3||(r5[a3++]=0),r5.length=a3,r5}}}),x3=r4({"node_modules/two-sum/two-sum.js"(t52,e5){e5.exports=function(t53,e6,n4){var o4=t53+e6,i3=o4-t53,s3=e6-i3,r5=t53-(o4-i3);return n4?(n4[0]=r5+s3,n4[1]=o4,n4):[r5+s3,o4]}}}),v3=r4({"node_modules/robust-scale/robust-scale.js"(t52,e5){var n4=y(),o4=x3();e5.exports=function(t53,e6){var i3=t53.length;if(i3===1){var s3=n4(t53[0],e6);return s3[0]?s3:[s3[1]]}var r5=new Array(2*i3),a3=[.1,.1],c4=[.1,.1],l4=0;n4(t53[0],e6,a3),a3[0]&&(r5[l4++]=a3[0]);for(var h6=1;h6<i3;++h6){n4(t53[h6],e6,c4);var d4=a3[1];o4(d4,c4[0],a3),a3[0]&&(r5[l4++]=a3[0]);var u5=c4[1],p4=a3[1],m4=u5+p4,g6=p4-(m4-u5);a3[1]=m4,g6&&(r5[l4++]=g6)}return a3[1]&&(r5[l4++]=a3[1]),l4===0&&(r5[l4++]=0),r5.length=l4,r5}}}),S2=r4({"node_modules/robust-subtract/robust-diff.js"(t52,e5){e5.exports=function(t53,e6){var n4=0|t53.length,o4=0|e6.length;if(n4===1&&o4===1)return(function(t54,e7){var n5=t54+e7,o6=n5-t54,i4=n5-o6,s4=e7-o6,r6=t54-i4,a4=r6+s4;return a4?[a4,n5]:[n5]})(t53[0],-e6[0]);var i3,s3,r5=new Array(n4+o4),a3=0,c4=0,l4=0,h6=Math.abs,d4=t53[c4],u5=h6(d4),p4=-e6[l4],m4=h6(p4);u5<m4?(s3=d4,(c4+=1)<n4&&(u5=h6(d4=t53[c4]))):(s3=p4,(l4+=1)<o4&&(m4=h6(p4=-e6[l4]))),c4<n4&&u5<m4||l4>=o4?(i3=d4,(c4+=1)<n4&&(u5=h6(d4=t53[c4]))):(i3=p4,(l4+=1)<o4&&(m4=h6(p4=-e6[l4])));for(var g6,f3,_4=i3+s3,y4=_4-i3,b3=s3-y4,x4=b3,v4=_4;c4<n4&&l4<o4;)u5<m4?(i3=d4,(c4+=1)<n4&&(u5=h6(d4=t53[c4]))):(i3=p4,(l4+=1)<o4&&(m4=h6(p4=-e6[l4]))),(b3=(s3=x4)-(y4=(_4=i3+s3)-i3))&&(r5[a3++]=b3),x4=v4-((g6=v4+_4)-(f3=g6-v4))+(_4-f3),v4=g6;for(;c4<n4;)(b3=(s3=x4)-(y4=(_4=(i3=d4)+s3)-i3))&&(r5[a3++]=b3),x4=v4-((g6=v4+_4)-(f3=g6-v4))+(_4-f3),v4=g6,(c4+=1)<n4&&(d4=t53[c4]);for(;l4<o4;)(b3=(s3=x4)-(y4=(_4=(i3=p4)+s3)-i3))&&(r5[a3++]=b3),x4=v4-((g6=v4+_4)-(f3=g6-v4))+(_4-f3),v4=g6,(l4+=1)<o4&&(p4=-e6[l4]);return x4&&(r5[a3++]=x4),v4&&(r5[a3++]=v4),a3||(r5[a3++]=0),r5.length=a3,r5}}}),I3=r4({"node_modules/robust-orientation/orientation.js"(t52,e5){var n4=y(),o4=b(),i3=v3(),s3=S2();function r5(t53,e6,n5,o6){return function(n6,i4,s4){var r6=t53(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),t53(e6(n6[1],i4[0]),e6(-i4[1],n6[0]))),a4=t53(e6(n6[1],s4[0]),e6(-s4[1],n6[0])),c5=o6(r6,a4);return c5[c5.length-1]}}function a3(t53,e6,n5,o6){return function(i4,s4,r6,a4){var c5=t53(t53(n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),s4[2]),t53(n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),-r6[2]),n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),a4[2]))),t53(n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),a4[2])))),l5=t53(t53(n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),i4[2]),t53(n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),-r6[2]),n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),a4[2]))),t53(n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),r6[2])))),h7=o6(c5,l5);return h7[h7.length-1]}}function c4(t53,e6,n5,o6){return function(i4,s4,r6,a4,c5){var l5=t53(t53(t53(n5(t53(n5(t53(e6(a4[1],c5[0]),e6(-c5[1],a4[0])),r6[2]),t53(n5(t53(e6(r6[1],c5[0]),e6(-c5[1],r6[0])),-a4[2]),n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),c5[2]))),s4[3]),t53(n5(t53(n5(t53(e6(a4[1],c5[0]),e6(-c5[1],a4[0])),s4[2]),t53(n5(t53(e6(s4[1],c5[0]),e6(-c5[1],s4[0])),-a4[2]),n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),c5[2]))),-r6[3]),n5(t53(n5(t53(e6(r6[1],c5[0]),e6(-c5[1],r6[0])),s4[2]),t53(n5(t53(e6(s4[1],c5[0]),e6(-c5[1],s4[0])),-r6[2]),n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),c5[2]))),a4[3]))),t53(n5(t53(n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),s4[2]),t53(n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),-r6[2]),n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),a4[2]))),-c5[3]),t53(n5(t53(n5(t53(e6(a4[1],c5[0]),e6(-c5[1],a4[0])),s4[2]),t53(n5(t53(e6(s4[1],c5[0]),e6(-c5[1],s4[0])),-a4[2]),n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),c5[2]))),i4[3]),n5(t53(n5(t53(e6(a4[1],c5[0]),e6(-c5[1],a4[0])),i4[2]),t53(n5(t53(e6(i4[1],c5[0]),e6(-c5[1],i4[0])),-a4[2]),n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),c5[2]))),-s4[3])))),t53(t53(n5(t53(n5(t53(e6(s4[1],c5[0]),e6(-c5[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],c5[0]),e6(-c5[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),c5[2]))),a4[3]),t53(n5(t53(n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),a4[2]))),-c5[3]),n5(t53(n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),s4[2]),t53(n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),-r6[2]),n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),a4[2]))),i4[3]))),t53(n5(t53(n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),i4[2]),t53(n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),-r6[2]),n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),a4[2]))),-s4[3]),t53(n5(t53(n5(t53(e6(s4[1],a4[0]),e6(-a4[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),a4[2]))),r6[3]),n5(t53(n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),r6[2]))),-a4[3]))))),h7=t53(t53(t53(n5(t53(n5(t53(e6(a4[1],c5[0]),e6(-c5[1],a4[0])),r6[2]),t53(n5(t53(e6(r6[1],c5[0]),e6(-c5[1],r6[0])),-a4[2]),n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),c5[2]))),i4[3]),n5(t53(n5(t53(e6(a4[1],c5[0]),e6(-c5[1],a4[0])),i4[2]),t53(n5(t53(e6(i4[1],c5[0]),e6(-c5[1],i4[0])),-a4[2]),n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),c5[2]))),-r6[3])),t53(n5(t53(n5(t53(e6(r6[1],c5[0]),e6(-c5[1],r6[0])),i4[2]),t53(n5(t53(e6(i4[1],c5[0]),e6(-c5[1],i4[0])),-r6[2]),n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),c5[2]))),a4[3]),n5(t53(n5(t53(e6(r6[1],a4[0]),e6(-a4[1],r6[0])),i4[2]),t53(n5(t53(e6(i4[1],a4[0]),e6(-a4[1],i4[0])),-r6[2]),n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),a4[2]))),-c5[3]))),t53(t53(n5(t53(n5(t53(e6(r6[1],c5[0]),e6(-c5[1],r6[0])),s4[2]),t53(n5(t53(e6(s4[1],c5[0]),e6(-c5[1],s4[0])),-r6[2]),n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),c5[2]))),i4[3]),n5(t53(n5(t53(e6(r6[1],c5[0]),e6(-c5[1],r6[0])),i4[2]),t53(n5(t53(e6(i4[1],c5[0]),e6(-c5[1],i4[0])),-r6[2]),n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),c5[2]))),-s4[3])),t53(n5(t53(n5(t53(e6(s4[1],c5[0]),e6(-c5[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],c5[0]),e6(-c5[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),c5[2]))),r6[3]),n5(t53(n5(t53(e6(s4[1],r6[0]),e6(-r6[1],s4[0])),i4[2]),t53(n5(t53(e6(i4[1],r6[0]),e6(-r6[1],i4[0])),-s4[2]),n5(t53(e6(i4[1],s4[0]),e6(-s4[1],i4[0])),r6[2]))),-c5[3])))),d5=o6(l5,h7);return d5[d5.length-1]}}function l4(t53){return(t53===3?r5:t53===4?a3:c4)(o4,n4,i3,s3)}var h6=l4(3),d4=l4(4),u5=[function(){return 0},function(){return 0},function(t53,e6){return e6[0]-t53[0]},function(t53,e6,n5){var o6,i4=(t53[1]-n5[1])*(e6[0]-n5[0]),s4=(t53[0]-n5[0])*(e6[1]-n5[1]),r6=i4-s4;if(i4>0){if(s4<=0)return r6;o6=i4+s4}else{if(!(i4<0)||s4>=0)return r6;o6=-(i4+s4)}var a4=33306690738754716e-32*o6;return r6>=a4||r6<=-a4?r6:h6(t53,e6,n5)},function(t53,e6,n5,o6){var i4=t53[0]-o6[0],s4=e6[0]-o6[0],r6=n5[0]-o6[0],a4=t53[1]-o6[1],c5=e6[1]-o6[1],l5=n5[1]-o6[1],h7=t53[2]-o6[2],u6=e6[2]-o6[2],p5=n5[2]-o6[2],m6=s4*l5,g6=r6*c5,f3=r6*a4,_4=i4*l5,y4=i4*c5,b3=s4*a4,x4=h7*(m6-g6)+u6*(f3-_4)+p5*(y4-b3),v4=7771561172376103e-31*((Math.abs(m6)+Math.abs(g6))*Math.abs(h7)+(Math.abs(f3)+Math.abs(_4))*Math.abs(u6)+(Math.abs(y4)+Math.abs(b3))*Math.abs(p5));return x4>v4||-x4>v4?x4:d4(t53,e6,n5,o6)}];function p4(t53){var e6=u5[t53.length];return e6||(e6=u5[t53.length]=l4(t53.length)),e6.apply(void 0,t53)}function m4(t53,e6,n5,o6,i4,s4,r6){return function(e7,n6,a4,c5,l5){switch(arguments.length){case 0:case 1:return 0;case 2:return o6(e7,n6);case 3:return i4(e7,n6,a4);case 4:return s4(e7,n6,a4,c5);case 5:return r6(e7,n6,a4,c5,l5)}for(var h7=new Array(arguments.length),d5=0;d5<arguments.length;++d5)h7[d5]=arguments[d5];return t53(h7)}}(function(){for(;u5.length<=5;)u5.push(l4(u5.length));e5.exports=m4.apply(void 0,[p4].concat(u5));for(var t53=0;t53<=5;++t53)e5.exports[t53]=u5[t53]})()}}),P2=r4({"node_modules/cdt2d/lib/monotone.js"(t52,e5){var n4=_3(),o4=I3()[3];function i3(t53,e6,n5,o6,i4){this.a=t53,this.b=e6,this.idx=n5,this.lowerIds=o6,this.upperIds=i4}function s3(t53,e6,n5,o6){this.a=t53,this.b=e6,this.type=n5,this.idx=o6}function r5(t53,e6){var n5=t53.a[0]-e6.a[0]||t53.a[1]-e6.a[1]||t53.type-e6.type;return n5||(t53.type!==0&&(n5=o4(t53.a,t53.b,e6.b))?n5:t53.idx-e6.idx)}function a3(t53,e6){return o4(t53.a,t53.b,e6)}function c4(t53,e6,i4,s4,r6){for(var c5=n4.lt(e6,s4,a3),l5=n4.gt(e6,s4,a3),h7=c5;h7<l5;++h7){for(var d5=e6[h7],u5=d5.lowerIds,p4=u5.length;p4>1&&o4(i4[u5[p4-2]],i4[u5[p4-1]],s4)>0;)t53.push([u5[p4-1],u5[p4-2],r6]),p4-=1;u5.length=p4,u5.push(r6);var m4=d5.upperIds;for(p4=m4.length;p4>1&&o4(i4[m4[p4-2]],i4[m4[p4-1]],s4)<0;)t53.push([m4[p4-2],m4[p4-1],r6]),p4-=1;m4.length=p4,m4.push(r6)}}function l4(t53,e6){var n5;return(n5=t53.a[0]<e6.a[0]?o4(t53.a,t53.b,e6.a):o4(e6.b,e6.a,t53.a))?n5:(n5=e6.b[0]<t53.b[0]?o4(t53.a,t53.b,e6.b):o4(e6.b,e6.a,t53.b))||t53.idx-e6.idx}function h6(t53,e6,o6){var s4=n4.le(t53,o6,l4),r6=t53[s4],a4=r6.upperIds,c5=a4[a4.length-1];r6.upperIds=[c5],t53.splice(s4+1,0,new i3(o6.a,o6.b,o6.idx,[c5],a4))}function d4(t53,e6,o6){var i4=o6.a;o6.a=o6.b,o6.b=i4;var s4=n4.eq(t53,o6,l4),r6=t53[s4];t53[s4-1].upperIds=r6.upperIds,t53.splice(s4,1)}e5.exports=function(t53,e6){for(var n5=t53.length,o6=e6.length,a4=[],l5=0;l5<n5;++l5)a4.push(new s3(t53[l5],null,0,l5));for(l5=0;l5<o6;++l5){var u5=e6[l5],p4=t53[u5[0]],m4=t53[u5[1]];p4[0]<m4[0]?a4.push(new s3(p4,m4,2,l5),new s3(m4,p4,1,l5)):p4[0]>m4[0]&&a4.push(new s3(m4,p4,2,l5),new s3(p4,m4,1,l5))}a4.sort(r5);for(var g6=a4[0].a[0]-(1+Math.abs(a4[0].a[0]))*Math.pow(2,-52),f3=[new i3([g6,1],[g6,0],-1,[],[],[],[])],_4=[],y4=(l5=0,a4.length);l5<y4;++l5){var b3=a4[l5],x4=b3.type;x4===0?c4(_4,f3,t53,b3.a,b3.idx):x4===2?h6(f3,t53,b3):d4(f3,t53,b3)}return _4}}}),M3=r4({"node_modules/cdt2d/lib/triangulation.js"(t52,e5){var n4=_3();function o4(t53,e6){this.stars=t53,this.edges=e6}e5.exports=function(t53,e6){for(var n5=new Array(t53),i4=0;i4<t53;++i4)n5[i4]=[];return new o4(n5,e6)};var i3=o4.prototype;function s3(t53,e6,n5){for(var o6=1,i4=t53.length;o6<i4;o6+=2)if(t53[o6-1]===e6&&t53[o6]===n5)return t53[o6-1]=t53[i4-2],t53[o6]=t53[i4-1],void(t53.length=i4-2)}i3.isConstraint=(function(){var t53=[0,0];function e6(t54,e7){return t54[0]-e7[0]||t54[1]-e7[1]}return function(o6,i4){return t53[0]=Math.min(o6,i4),t53[1]=Math.max(o6,i4),n4.eq(this.edges,t53,e6)>=0}})(),i3.removeTriangle=function(t53,e6,n5){var o6=this.stars;s3(o6[t53],e6,n5),s3(o6[e6],n5,t53),s3(o6[n5],t53,e6)},i3.addTriangle=function(t53,e6,n5){var o6=this.stars;o6[t53].push(e6,n5),o6[e6].push(n5,t53),o6[n5].push(t53,e6)},i3.opposite=function(t53,e6){for(var n5=this.stars[e6],o6=1,i4=n5.length;o6<i4;o6+=2)if(n5[o6]===t53)return n5[o6-1];return-1},i3.flip=function(t53,e6){var n5=this.opposite(t53,e6),o6=this.opposite(e6,t53);this.removeTriangle(t53,e6,n5),this.removeTriangle(e6,t53,o6),this.addTriangle(t53,o6,n5),this.addTriangle(e6,n5,o6)},i3.edges=function(){for(var t53=this.stars,e6=[],n5=0,o6=t53.length;n5<o6;++n5)for(var i4=t53[n5],s4=0,r5=i4.length;s4<r5;s4+=2)e6.push([i4[s4],i4[s4+1]]);return e6},i3.cells=function(){for(var t53=this.stars,e6=[],n5=0,o6=t53.length;n5<o6;++n5)for(var i4=t53[n5],s4=0,r5=i4.length;s4<r5;s4+=2){var a3=i4[s4],c4=i4[s4+1];n5<Math.min(a3,c4)&&e6.push([n5,a3,c4])}return e6}}}),N3=r4({"node_modules/robust-in-sphere/in-sphere.js"(t52,e5){var n4=y(),o4=b(),i3=S2(),s3=v3();function r5(t53){return(t53===3?a3:t53===4?c4:t53===5?l4:h6)(o4,i3,n4,s3)}function a3(t53,e6,n5,o6){return function(i4,s4,r6){var a4=n5(i4[0],i4[0]),c5=o6(a4,s4[0]),l5=o6(a4,r6[0]),h7=n5(s4[0],s4[0]),d5=o6(h7,i4[0]),u6=o6(h7,r6[0]),p5=n5(r6[0],r6[0]),m4=o6(p5,i4[0]),g6=o6(p5,s4[0]),f3=t53(e6(g6,u6),e6(d5,c5)),_4=e6(m4,l5),y4=e6(f3,_4);return y4[y4.length-1]}}function c4(t53,e6,n5,o6){return function(i4,s4,r6,a4){var c5=t53(n5(i4[0],i4[0]),n5(i4[1],i4[1])),l5=o6(c5,s4[0]),h7=o6(c5,r6[0]),d5=o6(c5,a4[0]),u6=t53(n5(s4[0],s4[0]),n5(s4[1],s4[1])),p5=o6(u6,i4[0]),m4=o6(u6,r6[0]),g6=o6(u6,a4[0]),f3=t53(n5(r6[0],r6[0]),n5(r6[1],r6[1])),_4=o6(f3,i4[0]),y4=o6(f3,s4[0]),b3=o6(f3,a4[0]),x4=t53(n5(a4[0],a4[0]),n5(a4[1],a4[1])),v4=o6(x4,i4[0]),S3=o6(x4,s4[0]),I4=o6(x4,r6[0]),P4=t53(t53(o6(e6(I4,b3),s4[1]),t53(o6(e6(S3,g6),-r6[1]),o6(e6(y4,m4),a4[1]))),t53(o6(e6(S3,g6),i4[1]),t53(o6(e6(v4,d5),-s4[1]),o6(e6(p5,l5),a4[1])))),M4=t53(t53(o6(e6(I4,b3),i4[1]),t53(o6(e6(v4,d5),-r6[1]),o6(e6(_4,h7),a4[1]))),t53(o6(e6(y4,m4),i4[1]),t53(o6(e6(_4,h7),-s4[1]),o6(e6(p5,l5),r6[1])))),N4=e6(P4,M4);return N4[N4.length-1]}}function l4(t53,e6,n5,o6){return function(i4,s4,r6,a4,c5){var l5=t53(n5(i4[0],i4[0]),t53(n5(i4[1],i4[1]),n5(i4[2],i4[2]))),h7=o6(l5,s4[0]),d5=o6(l5,r6[0]),u6=o6(l5,a4[0]),p5=o6(l5,c5[0]),m4=t53(n5(s4[0],s4[0]),t53(n5(s4[1],s4[1]),n5(s4[2],s4[2]))),g6=o6(m4,i4[0]),f3=o6(m4,r6[0]),_4=o6(m4,a4[0]),y4=o6(m4,c5[0]),b3=t53(n5(r6[0],r6[0]),t53(n5(r6[1],r6[1]),n5(r6[2],r6[2]))),x4=o6(b3,i4[0]),v4=o6(b3,s4[0]),S3=o6(b3,a4[0]),I4=o6(b3,c5[0]),P4=t53(n5(a4[0],a4[0]),t53(n5(a4[1],a4[1]),n5(a4[2],a4[2]))),M4=o6(P4,i4[0]),N4=o6(P4,s4[0]),C4=o6(P4,r6[0]),T4=o6(P4,c5[0]),w4=t53(n5(c5[0],c5[0]),t53(n5(c5[1],c5[1]),n5(c5[2],c5[2]))),R3=o6(w4,i4[0]),E3=o6(w4,s4[0]),A4=o6(w4,r6[0]),O3=o6(w4,a4[0]),L3=t53(t53(t53(o6(t53(o6(e6(O3,T4),r6[1]),t53(o6(e6(A4,I4),-a4[1]),o6(e6(C4,S3),c5[1]))),s4[2]),t53(o6(t53(o6(e6(O3,T4),s4[1]),t53(o6(e6(E3,y4),-a4[1]),o6(e6(N4,_4),c5[1]))),-r6[2]),o6(t53(o6(e6(A4,I4),s4[1]),t53(o6(e6(E3,y4),-r6[1]),o6(e6(v4,f3),c5[1]))),a4[2]))),t53(o6(t53(o6(e6(C4,S3),s4[1]),t53(o6(e6(N4,_4),-r6[1]),o6(e6(v4,f3),a4[1]))),-c5[2]),t53(o6(t53(o6(e6(O3,T4),s4[1]),t53(o6(e6(E3,y4),-a4[1]),o6(e6(N4,_4),c5[1]))),i4[2]),o6(t53(o6(e6(O3,T4),i4[1]),t53(o6(e6(R3,p5),-a4[1]),o6(e6(M4,u6),c5[1]))),-s4[2])))),t53(t53(o6(t53(o6(e6(E3,y4),i4[1]),t53(o6(e6(R3,p5),-s4[1]),o6(e6(g6,h7),c5[1]))),a4[2]),t53(o6(t53(o6(e6(N4,_4),i4[1]),t53(o6(e6(M4,u6),-s4[1]),o6(e6(g6,h7),a4[1]))),-c5[2]),o6(t53(o6(e6(C4,S3),s4[1]),t53(o6(e6(N4,_4),-r6[1]),o6(e6(v4,f3),a4[1]))),i4[2]))),t53(o6(t53(o6(e6(C4,S3),i4[1]),t53(o6(e6(M4,u6),-r6[1]),o6(e6(x4,d5),a4[1]))),-s4[2]),t53(o6(t53(o6(e6(N4,_4),i4[1]),t53(o6(e6(M4,u6),-s4[1]),o6(e6(g6,h7),a4[1]))),r6[2]),o6(t53(o6(e6(v4,f3),i4[1]),t53(o6(e6(x4,d5),-s4[1]),o6(e6(g6,h7),r6[1]))),-a4[2]))))),D4=t53(t53(t53(o6(t53(o6(e6(O3,T4),r6[1]),t53(o6(e6(A4,I4),-a4[1]),o6(e6(C4,S3),c5[1]))),i4[2]),o6(t53(o6(e6(O3,T4),i4[1]),t53(o6(e6(R3,p5),-a4[1]),o6(e6(M4,u6),c5[1]))),-r6[2])),t53(o6(t53(o6(e6(A4,I4),i4[1]),t53(o6(e6(R3,p5),-r6[1]),o6(e6(x4,d5),c5[1]))),a4[2]),o6(t53(o6(e6(C4,S3),i4[1]),t53(o6(e6(M4,u6),-r6[1]),o6(e6(x4,d5),a4[1]))),-c5[2]))),t53(t53(o6(t53(o6(e6(A4,I4),s4[1]),t53(o6(e6(E3,y4),-r6[1]),o6(e6(v4,f3),c5[1]))),i4[2]),o6(t53(o6(e6(A4,I4),i4[1]),t53(o6(e6(R3,p5),-r6[1]),o6(e6(x4,d5),c5[1]))),-s4[2])),t53(o6(t53(o6(e6(E3,y4),i4[1]),t53(o6(e6(R3,p5),-s4[1]),o6(e6(g6,h7),c5[1]))),r6[2]),o6(t53(o6(e6(v4,f3),i4[1]),t53(o6(e6(x4,d5),-s4[1]),o6(e6(g6,h7),r6[1]))),-c5[2])))),k4=e6(L3,D4);return k4[k4.length-1]}}function h6(t53,e6,n5,o6){return function(i4,s4,r6,a4,c5,l5){var h7=t53(t53(n5(i4[0],i4[0]),n5(i4[1],i4[1])),t53(n5(i4[2],i4[2]),n5(i4[3],i4[3]))),d5=o6(h7,s4[0]),u6=o6(h7,r6[0]),p5=o6(h7,a4[0]),m4=o6(h7,c5[0]),g6=o6(h7,l5[0]),f3=t53(t53(n5(s4[0],s4[0]),n5(s4[1],s4[1])),t53(n5(s4[2],s4[2]),n5(s4[3],s4[3]))),_4=o6(f3,i4[0]),y4=o6(f3,r6[0]),b3=o6(f3,a4[0]),x4=o6(f3,c5[0]),v4=o6(f3,l5[0]),S3=t53(t53(n5(r6[0],r6[0]),n5(r6[1],r6[1])),t53(n5(r6[2],r6[2]),n5(r6[3],r6[3]))),I4=o6(S3,i4[0]),P4=o6(S3,s4[0]),M4=o6(S3,a4[0]),N4=o6(S3,c5[0]),C4=o6(S3,l5[0]),T4=t53(t53(n5(a4[0],a4[0]),n5(a4[1],a4[1])),t53(n5(a4[2],a4[2]),n5(a4[3],a4[3]))),w4=o6(T4,i4[0]),R3=o6(T4,s4[0]),E3=o6(T4,r6[0]),A4=o6(T4,c5[0]),O3=o6(T4,l5[0]),L3=t53(t53(n5(c5[0],c5[0]),n5(c5[1],c5[1])),t53(n5(c5[2],c5[2]),n5(c5[3],c5[3]))),D4=o6(L3,i4[0]),k4=o6(L3,s4[0]),z4=o6(L3,r6[0]),j4=o6(L3,a4[0]),F4=o6(L3,l5[0]),$5=t53(t53(n5(l5[0],l5[0]),n5(l5[1],l5[1])),t53(n5(l5[2],l5[2]),n5(l5[3],l5[3]))),B4=o6($5,i4[0]),Y4=o6($5,s4[0]),X4=o6($5,r6[0]),H4=o6($5,a4[0]),W5=o6($5,c5[0]),V4=t53(t53(t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),a4[1]),t53(o6(e6(H4,O3),-c5[1]),o6(e6(j4,A4),l5[1]))),r6[2]),o6(t53(o6(e6(W5,F4),r6[1]),t53(o6(e6(X4,C4),-c5[1]),o6(e6(z4,N4),l5[1]))),-a4[2])),t53(o6(t53(o6(e6(H4,O3),r6[1]),t53(o6(e6(X4,C4),-a4[1]),o6(e6(E3,M4),l5[1]))),c5[2]),o6(t53(o6(e6(j4,A4),r6[1]),t53(o6(e6(z4,N4),-a4[1]),o6(e6(E3,M4),c5[1]))),-l5[2]))),s4[3]),t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),a4[1]),t53(o6(e6(H4,O3),-c5[1]),o6(e6(j4,A4),l5[1]))),s4[2]),o6(t53(o6(e6(W5,F4),s4[1]),t53(o6(e6(Y4,v4),-c5[1]),o6(e6(k4,x4),l5[1]))),-a4[2])),t53(o6(t53(o6(e6(H4,O3),s4[1]),t53(o6(e6(Y4,v4),-a4[1]),o6(e6(R3,b3),l5[1]))),c5[2]),o6(t53(o6(e6(j4,A4),s4[1]),t53(o6(e6(k4,x4),-a4[1]),o6(e6(R3,b3),c5[1]))),-l5[2]))),-r6[3]),o6(t53(t53(o6(t53(o6(e6(W5,F4),r6[1]),t53(o6(e6(X4,C4),-c5[1]),o6(e6(z4,N4),l5[1]))),s4[2]),o6(t53(o6(e6(W5,F4),s4[1]),t53(o6(e6(Y4,v4),-c5[1]),o6(e6(k4,x4),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),s4[1]),t53(o6(e6(Y4,v4),-r6[1]),o6(e6(P4,y4),l5[1]))),c5[2]),o6(t53(o6(e6(z4,N4),s4[1]),t53(o6(e6(k4,x4),-r6[1]),o6(e6(P4,y4),c5[1]))),-l5[2]))),a4[3]))),t53(t53(o6(t53(t53(o6(t53(o6(e6(H4,O3),r6[1]),t53(o6(e6(X4,C4),-a4[1]),o6(e6(E3,M4),l5[1]))),s4[2]),o6(t53(o6(e6(H4,O3),s4[1]),t53(o6(e6(Y4,v4),-a4[1]),o6(e6(R3,b3),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),s4[1]),t53(o6(e6(Y4,v4),-r6[1]),o6(e6(P4,y4),l5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),s4[1]),t53(o6(e6(R3,b3),-r6[1]),o6(e6(P4,y4),a4[1]))),-l5[2]))),-c5[3]),o6(t53(t53(o6(t53(o6(e6(j4,A4),r6[1]),t53(o6(e6(z4,N4),-a4[1]),o6(e6(E3,M4),c5[1]))),s4[2]),o6(t53(o6(e6(j4,A4),s4[1]),t53(o6(e6(k4,x4),-a4[1]),o6(e6(R3,b3),c5[1]))),-r6[2])),t53(o6(t53(o6(e6(z4,N4),s4[1]),t53(o6(e6(k4,x4),-r6[1]),o6(e6(P4,y4),c5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),s4[1]),t53(o6(e6(R3,b3),-r6[1]),o6(e6(P4,y4),a4[1]))),-c5[2]))),l5[3])),t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),a4[1]),t53(o6(e6(H4,O3),-c5[1]),o6(e6(j4,A4),l5[1]))),s4[2]),o6(t53(o6(e6(W5,F4),s4[1]),t53(o6(e6(Y4,v4),-c5[1]),o6(e6(k4,x4),l5[1]))),-a4[2])),t53(o6(t53(o6(e6(H4,O3),s4[1]),t53(o6(e6(Y4,v4),-a4[1]),o6(e6(R3,b3),l5[1]))),c5[2]),o6(t53(o6(e6(j4,A4),s4[1]),t53(o6(e6(k4,x4),-a4[1]),o6(e6(R3,b3),c5[1]))),-l5[2]))),i4[3]),o6(t53(t53(o6(t53(o6(e6(W5,F4),a4[1]),t53(o6(e6(H4,O3),-c5[1]),o6(e6(j4,A4),l5[1]))),i4[2]),o6(t53(o6(e6(W5,F4),i4[1]),t53(o6(e6(B4,g6),-c5[1]),o6(e6(D4,m4),l5[1]))),-a4[2])),t53(o6(t53(o6(e6(H4,O3),i4[1]),t53(o6(e6(B4,g6),-a4[1]),o6(e6(w4,p5),l5[1]))),c5[2]),o6(t53(o6(e6(j4,A4),i4[1]),t53(o6(e6(D4,m4),-a4[1]),o6(e6(w4,p5),c5[1]))),-l5[2]))),-s4[3])))),t53(t53(t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),s4[1]),t53(o6(e6(Y4,v4),-c5[1]),o6(e6(k4,x4),l5[1]))),i4[2]),o6(t53(o6(e6(W5,F4),i4[1]),t53(o6(e6(B4,g6),-c5[1]),o6(e6(D4,m4),l5[1]))),-s4[2])),t53(o6(t53(o6(e6(Y4,v4),i4[1]),t53(o6(e6(B4,g6),-s4[1]),o6(e6(_4,d5),l5[1]))),c5[2]),o6(t53(o6(e6(k4,x4),i4[1]),t53(o6(e6(D4,m4),-s4[1]),o6(e6(_4,d5),c5[1]))),-l5[2]))),a4[3]),o6(t53(t53(o6(t53(o6(e6(H4,O3),s4[1]),t53(o6(e6(Y4,v4),-a4[1]),o6(e6(R3,b3),l5[1]))),i4[2]),o6(t53(o6(e6(H4,O3),i4[1]),t53(o6(e6(B4,g6),-a4[1]),o6(e6(w4,p5),l5[1]))),-s4[2])),t53(o6(t53(o6(e6(Y4,v4),i4[1]),t53(o6(e6(B4,g6),-s4[1]),o6(e6(_4,d5),l5[1]))),a4[2]),o6(t53(o6(e6(R3,b3),i4[1]),t53(o6(e6(w4,p5),-s4[1]),o6(e6(_4,d5),a4[1]))),-l5[2]))),-c5[3])),t53(o6(t53(t53(o6(t53(o6(e6(j4,A4),s4[1]),t53(o6(e6(k4,x4),-a4[1]),o6(e6(R3,b3),c5[1]))),i4[2]),o6(t53(o6(e6(j4,A4),i4[1]),t53(o6(e6(D4,m4),-a4[1]),o6(e6(w4,p5),c5[1]))),-s4[2])),t53(o6(t53(o6(e6(k4,x4),i4[1]),t53(o6(e6(D4,m4),-s4[1]),o6(e6(_4,d5),c5[1]))),a4[2]),o6(t53(o6(e6(R3,b3),i4[1]),t53(o6(e6(w4,p5),-s4[1]),o6(e6(_4,d5),a4[1]))),-c5[2]))),l5[3]),o6(t53(t53(o6(t53(o6(e6(H4,O3),r6[1]),t53(o6(e6(X4,C4),-a4[1]),o6(e6(E3,M4),l5[1]))),s4[2]),o6(t53(o6(e6(H4,O3),s4[1]),t53(o6(e6(Y4,v4),-a4[1]),o6(e6(R3,b3),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),s4[1]),t53(o6(e6(Y4,v4),-r6[1]),o6(e6(P4,y4),l5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),s4[1]),t53(o6(e6(R3,b3),-r6[1]),o6(e6(P4,y4),a4[1]))),-l5[2]))),i4[3]))),t53(t53(o6(t53(t53(o6(t53(o6(e6(H4,O3),r6[1]),t53(o6(e6(X4,C4),-a4[1]),o6(e6(E3,M4),l5[1]))),i4[2]),o6(t53(o6(e6(H4,O3),i4[1]),t53(o6(e6(B4,g6),-a4[1]),o6(e6(w4,p5),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),i4[1]),t53(o6(e6(B4,g6),-r6[1]),o6(e6(I4,u6),l5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),i4[1]),t53(o6(e6(w4,p5),-r6[1]),o6(e6(I4,u6),a4[1]))),-l5[2]))),-s4[3]),o6(t53(t53(o6(t53(o6(e6(H4,O3),s4[1]),t53(o6(e6(Y4,v4),-a4[1]),o6(e6(R3,b3),l5[1]))),i4[2]),o6(t53(o6(e6(H4,O3),i4[1]),t53(o6(e6(B4,g6),-a4[1]),o6(e6(w4,p5),l5[1]))),-s4[2])),t53(o6(t53(o6(e6(Y4,v4),i4[1]),t53(o6(e6(B4,g6),-s4[1]),o6(e6(_4,d5),l5[1]))),a4[2]),o6(t53(o6(e6(R3,b3),i4[1]),t53(o6(e6(w4,p5),-s4[1]),o6(e6(_4,d5),a4[1]))),-l5[2]))),r6[3])),t53(o6(t53(t53(o6(t53(o6(e6(X4,C4),s4[1]),t53(o6(e6(Y4,v4),-r6[1]),o6(e6(P4,y4),l5[1]))),i4[2]),o6(t53(o6(e6(X4,C4),i4[1]),t53(o6(e6(B4,g6),-r6[1]),o6(e6(I4,u6),l5[1]))),-s4[2])),t53(o6(t53(o6(e6(Y4,v4),i4[1]),t53(o6(e6(B4,g6),-s4[1]),o6(e6(_4,d5),l5[1]))),r6[2]),o6(t53(o6(e6(P4,y4),i4[1]),t53(o6(e6(I4,u6),-s4[1]),o6(e6(_4,d5),r6[1]))),-l5[2]))),-a4[3]),o6(t53(t53(o6(t53(o6(e6(E3,M4),s4[1]),t53(o6(e6(R3,b3),-r6[1]),o6(e6(P4,y4),a4[1]))),i4[2]),o6(t53(o6(e6(E3,M4),i4[1]),t53(o6(e6(w4,p5),-r6[1]),o6(e6(I4,u6),a4[1]))),-s4[2])),t53(o6(t53(o6(e6(R3,b3),i4[1]),t53(o6(e6(w4,p5),-s4[1]),o6(e6(_4,d5),a4[1]))),r6[2]),o6(t53(o6(e6(P4,y4),i4[1]),t53(o6(e6(I4,u6),-s4[1]),o6(e6(_4,d5),r6[1]))),-a4[2]))),l5[3]))))),U3=t53(t53(t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),a4[1]),t53(o6(e6(H4,O3),-c5[1]),o6(e6(j4,A4),l5[1]))),r6[2]),o6(t53(o6(e6(W5,F4),r6[1]),t53(o6(e6(X4,C4),-c5[1]),o6(e6(z4,N4),l5[1]))),-a4[2])),t53(o6(t53(o6(e6(H4,O3),r6[1]),t53(o6(e6(X4,C4),-a4[1]),o6(e6(E3,M4),l5[1]))),c5[2]),o6(t53(o6(e6(j4,A4),r6[1]),t53(o6(e6(z4,N4),-a4[1]),o6(e6(E3,M4),c5[1]))),-l5[2]))),i4[3]),t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),a4[1]),t53(o6(e6(H4,O3),-c5[1]),o6(e6(j4,A4),l5[1]))),i4[2]),o6(t53(o6(e6(W5,F4),i4[1]),t53(o6(e6(B4,g6),-c5[1]),o6(e6(D4,m4),l5[1]))),-a4[2])),t53(o6(t53(o6(e6(H4,O3),i4[1]),t53(o6(e6(B4,g6),-a4[1]),o6(e6(w4,p5),l5[1]))),c5[2]),o6(t53(o6(e6(j4,A4),i4[1]),t53(o6(e6(D4,m4),-a4[1]),o6(e6(w4,p5),c5[1]))),-l5[2]))),-r6[3]),o6(t53(t53(o6(t53(o6(e6(W5,F4),r6[1]),t53(o6(e6(X4,C4),-c5[1]),o6(e6(z4,N4),l5[1]))),i4[2]),o6(t53(o6(e6(W5,F4),i4[1]),t53(o6(e6(B4,g6),-c5[1]),o6(e6(D4,m4),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),i4[1]),t53(o6(e6(B4,g6),-r6[1]),o6(e6(I4,u6),l5[1]))),c5[2]),o6(t53(o6(e6(z4,N4),i4[1]),t53(o6(e6(D4,m4),-r6[1]),o6(e6(I4,u6),c5[1]))),-l5[2]))),a4[3]))),t53(t53(o6(t53(t53(o6(t53(o6(e6(H4,O3),r6[1]),t53(o6(e6(X4,C4),-a4[1]),o6(e6(E3,M4),l5[1]))),i4[2]),o6(t53(o6(e6(H4,O3),i4[1]),t53(o6(e6(B4,g6),-a4[1]),o6(e6(w4,p5),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),i4[1]),t53(o6(e6(B4,g6),-r6[1]),o6(e6(I4,u6),l5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),i4[1]),t53(o6(e6(w4,p5),-r6[1]),o6(e6(I4,u6),a4[1]))),-l5[2]))),-c5[3]),o6(t53(t53(o6(t53(o6(e6(j4,A4),r6[1]),t53(o6(e6(z4,N4),-a4[1]),o6(e6(E3,M4),c5[1]))),i4[2]),o6(t53(o6(e6(j4,A4),i4[1]),t53(o6(e6(D4,m4),-a4[1]),o6(e6(w4,p5),c5[1]))),-r6[2])),t53(o6(t53(o6(e6(z4,N4),i4[1]),t53(o6(e6(D4,m4),-r6[1]),o6(e6(I4,u6),c5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),i4[1]),t53(o6(e6(w4,p5),-r6[1]),o6(e6(I4,u6),a4[1]))),-c5[2]))),l5[3])),t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),r6[1]),t53(o6(e6(X4,C4),-c5[1]),o6(e6(z4,N4),l5[1]))),s4[2]),o6(t53(o6(e6(W5,F4),s4[1]),t53(o6(e6(Y4,v4),-c5[1]),o6(e6(k4,x4),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),s4[1]),t53(o6(e6(Y4,v4),-r6[1]),o6(e6(P4,y4),l5[1]))),c5[2]),o6(t53(o6(e6(z4,N4),s4[1]),t53(o6(e6(k4,x4),-r6[1]),o6(e6(P4,y4),c5[1]))),-l5[2]))),i4[3]),o6(t53(t53(o6(t53(o6(e6(W5,F4),r6[1]),t53(o6(e6(X4,C4),-c5[1]),o6(e6(z4,N4),l5[1]))),i4[2]),o6(t53(o6(e6(W5,F4),i4[1]),t53(o6(e6(B4,g6),-c5[1]),o6(e6(D4,m4),l5[1]))),-r6[2])),t53(o6(t53(o6(e6(X4,C4),i4[1]),t53(o6(e6(B4,g6),-r6[1]),o6(e6(I4,u6),l5[1]))),c5[2]),o6(t53(o6(e6(z4,N4),i4[1]),t53(o6(e6(D4,m4),-r6[1]),o6(e6(I4,u6),c5[1]))),-l5[2]))),-s4[3])))),t53(t53(t53(o6(t53(t53(o6(t53(o6(e6(W5,F4),s4[1]),t53(o6(e6(Y4,v4),-c5[1]),o6(e6(k4,x4),l5[1]))),i4[2]),o6(t53(o6(e6(W5,F4),i4[1]),t53(o6(e6(B4,g6),-c5[1]),o6(e6(D4,m4),l5[1]))),-s4[2])),t53(o6(t53(o6(e6(Y4,v4),i4[1]),t53(o6(e6(B4,g6),-s4[1]),o6(e6(_4,d5),l5[1]))),c5[2]),o6(t53(o6(e6(k4,x4),i4[1]),t53(o6(e6(D4,m4),-s4[1]),o6(e6(_4,d5),c5[1]))),-l5[2]))),r6[3]),o6(t53(t53(o6(t53(o6(e6(X4,C4),s4[1]),t53(o6(e6(Y4,v4),-r6[1]),o6(e6(P4,y4),l5[1]))),i4[2]),o6(t53(o6(e6(X4,C4),i4[1]),t53(o6(e6(B4,g6),-r6[1]),o6(e6(I4,u6),l5[1]))),-s4[2])),t53(o6(t53(o6(e6(Y4,v4),i4[1]),t53(o6(e6(B4,g6),-s4[1]),o6(e6(_4,d5),l5[1]))),r6[2]),o6(t53(o6(e6(P4,y4),i4[1]),t53(o6(e6(I4,u6),-s4[1]),o6(e6(_4,d5),r6[1]))),-l5[2]))),-c5[3])),t53(o6(t53(t53(o6(t53(o6(e6(z4,N4),s4[1]),t53(o6(e6(k4,x4),-r6[1]),o6(e6(P4,y4),c5[1]))),i4[2]),o6(t53(o6(e6(z4,N4),i4[1]),t53(o6(e6(D4,m4),-r6[1]),o6(e6(I4,u6),c5[1]))),-s4[2])),t53(o6(t53(o6(e6(k4,x4),i4[1]),t53(o6(e6(D4,m4),-s4[1]),o6(e6(_4,d5),c5[1]))),r6[2]),o6(t53(o6(e6(P4,y4),i4[1]),t53(o6(e6(I4,u6),-s4[1]),o6(e6(_4,d5),r6[1]))),-c5[2]))),l5[3]),o6(t53(t53(o6(t53(o6(e6(j4,A4),r6[1]),t53(o6(e6(z4,N4),-a4[1]),o6(e6(E3,M4),c5[1]))),s4[2]),o6(t53(o6(e6(j4,A4),s4[1]),t53(o6(e6(k4,x4),-a4[1]),o6(e6(R3,b3),c5[1]))),-r6[2])),t53(o6(t53(o6(e6(z4,N4),s4[1]),t53(o6(e6(k4,x4),-r6[1]),o6(e6(P4,y4),c5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),s4[1]),t53(o6(e6(R3,b3),-r6[1]),o6(e6(P4,y4),a4[1]))),-c5[2]))),i4[3]))),t53(t53(o6(t53(t53(o6(t53(o6(e6(j4,A4),r6[1]),t53(o6(e6(z4,N4),-a4[1]),o6(e6(E3,M4),c5[1]))),i4[2]),o6(t53(o6(e6(j4,A4),i4[1]),t53(o6(e6(D4,m4),-a4[1]),o6(e6(w4,p5),c5[1]))),-r6[2])),t53(o6(t53(o6(e6(z4,N4),i4[1]),t53(o6(e6(D4,m4),-r6[1]),o6(e6(I4,u6),c5[1]))),a4[2]),o6(t53(o6(e6(E3,M4),i4[1]),t53(o6(e6(w4,p5),-r6[1]),o6(e6(I4,u6),a4[1]))),-c5[2]))),-s4[3]),o6(t53(t53(o6(t53(o6(e6(j4,A4),s4[1]),t53(o6(e6(k4,x4),-a4[1]),o6(e6(R3,b3),c5[1]))),i4[2]),o6(t53(o6(e6(j4,A4),i4[1]),t53(o6(e6(D4,m4),-a4[1]),o6(e6(w4,p5),c5[1]))),-s4[2])),t53(o6(t53(o6(e6(k4,x4),i4[1]),t53(o6(e6(D4,m4),-s4[1]),o6(e6(_4,d5),c5[1]))),a4[2]),o6(t53(o6(e6(R3,b3),i4[1]),t53(o6(e6(w4,p5),-s4[1]),o6(e6(_4,d5),a4[1]))),-c5[2]))),r6[3])),t53(o6(t53(t53(o6(t53(o6(e6(z4,N4),s4[1]),t53(o6(e6(k4,x4),-r6[1]),o6(e6(P4,y4),c5[1]))),i4[2]),o6(t53(o6(e6(z4,N4),i4[1]),t53(o6(e6(D4,m4),-r6[1]),o6(e6(I4,u6),c5[1]))),-s4[2])),t53(o6(t53(o6(e6(k4,x4),i4[1]),t53(o6(e6(D4,m4),-s4[1]),o6(e6(_4,d5),c5[1]))),r6[2]),o6(t53(o6(e6(P4,y4),i4[1]),t53(o6(e6(I4,u6),-s4[1]),o6(e6(_4,d5),r6[1]))),-c5[2]))),-a4[3]),o6(t53(t53(o6(t53(o6(e6(E3,M4),s4[1]),t53(o6(e6(R3,b3),-r6[1]),o6(e6(P4,y4),a4[1]))),i4[2]),o6(t53(o6(e6(E3,M4),i4[1]),t53(o6(e6(w4,p5),-r6[1]),o6(e6(I4,u6),a4[1]))),-s4[2])),t53(o6(t53(o6(e6(R3,b3),i4[1]),t53(o6(e6(w4,p5),-s4[1]),o6(e6(_4,d5),a4[1]))),r6[2]),o6(t53(o6(e6(P4,y4),i4[1]),t53(o6(e6(I4,u6),-s4[1]),o6(e6(_4,d5),r6[1]))),-a4[2]))),c5[3]))))),Z3=e6(V4,U3);return Z3[Z3.length-1]}}var d4=[function(){return 0},function(){return 0},function(){return 0}];function u5(t53){var e6=d4[t53.length];return e6||(e6=d4[t53.length]=r5(t53.length)),e6.apply(void 0,t53)}function p4(t53,e6,n5,o6,i4,s4,r6,a4){return function(e7,n6,c5,l5,h7,d5){switch(arguments.length){case 0:case 1:return 0;case 2:return o6(e7,n6);case 3:return i4(e7,n6,c5);case 4:return s4(e7,n6,c5,l5);case 5:return r6(e7,n6,c5,l5,h7);case 6:return a4(e7,n6,c5,l5,h7,d5)}for(var u6=new Array(arguments.length),p5=0;p5<arguments.length;++p5)u6[p5]=arguments[p5];return t53(u6)}}(function(){for(;d4.length<=6;)d4.push(r5(d4.length));e5.exports=p4.apply(void 0,[u5].concat(d4));for(var t53=0;t53<=6;++t53)e5.exports[t53]=d4[t53]})()}}),C3=r4({"node_modules/cdt2d/lib/delaunay.js"(t52,e5){var n4=N3()[4];_3();function o4(t53,e6,o6,i3,s3,r5){var a3=e6.opposite(i3,s3);if(!(a3<0)){if(s3<i3){var c4=i3;i3=s3,s3=c4,c4=r5,r5=a3,a3=c4}e6.isConstraint(i3,s3)||n4(t53[i3],t53[s3],t53[r5],t53[a3])<0&&o6.push(i3,s3)}}e5.exports=function(t53,e6){for(var i3=[],s3=t53.length,r5=e6.stars,a3=0;a3<s3;++a3)for(var c4=r5[a3],l4=1;l4<c4.length;l4+=2)if(!((p4=c4[l4])<a3)&&!e6.isConstraint(a3,p4)){for(var h6=c4[l4-1],d4=-1,u5=1;u5<c4.length;u5+=2)if(c4[u5-1]===p4){d4=c4[u5];break}d4<0||n4(t53[a3],t53[p4],t53[h6],t53[d4])<0&&i3.push(a3,p4)}for(;i3.length>0;){for(var p4=i3.pop(),m4=(h6=-1,d4=-1,c4=r5[a3=i3.pop()],1);m4<c4.length;m4+=2){var g6=c4[m4-1],f3=c4[m4];g6===p4?d4=f3:f3===p4&&(h6=g6)}h6<0||d4<0||n4(t53[a3],t53[p4],t53[h6],t53[d4])>=0||(e6.flip(a3,p4),o4(t53,e6,i3,h6,a3,d4),o4(t53,e6,i3,a3,d4,h6),o4(t53,e6,i3,d4,p4,h6),o4(t53,e6,i3,p4,h6,d4))}}}}),T3=r4({"node_modules/cdt2d/lib/filter.js"(t52,e5){var n4=_3();function o4(t53,e6,n5,o6,i4,s3,r5){this.cells=t53,this.neighbor=e6,this.flags=o6,this.constraint=n5,this.active=i4,this.next=s3,this.boundary=r5}function i3(t53,e6){return t53[0]-e6[0]||t53[1]-e6[1]||t53[2]-e6[2]}e5.exports=function(t53,e6,n5){var s3=(function(t54,e7){for(var n6=t54.cells(),s4=n6.length,r6=0;r6<s4;++r6){var a4=(_5=n6[r6])[0],c5=_5[1],l5=_5[2];c5<l5?c5<a4&&(_5[0]=c5,_5[1]=l5,_5[2]=a4):l5<a4&&(_5[0]=l5,_5[1]=a4,_5[2]=c5)}n6.sort(i3);var h7=new Array(s4);for(r6=0;r6<h7.length;++r6)h7[r6]=0;var d5=[],u6=[],p5=new Array(3*s4),m6=new Array(3*s4),g7=null;e7&&(g7=[]);var f4=new o4(n6,p5,m6,h7,d5,u6,g7);for(r6=0;r6<s4;++r6)for(var _5=n6[r6],y4=0;y4<3;++y4){a4=_5[y4],c5=_5[(y4+1)%3];var b3=p5[3*r6+y4]=f4.locate(c5,a4,t54.opposite(c5,a4)),x4=m6[3*r6+y4]=t54.isConstraint(a4,c5);b3<0&&(x4?u6.push(r6):(d5.push(r6),h7[r6]=1),e7&&g7.push([c5,a4,-1]))}return f4})(t53,n5);if(e6===0)return n5?s3.cells.concat(s3.boundary):s3.cells;for(var r5=1,a3=s3.active,c4=s3.next,l4=s3.flags,h6=s3.cells,d4=s3.constraint,u5=s3.neighbor;a3.length>0||c4.length>0;){for(;a3.length>0;){var p4=a3.pop();if(l4[p4]!==-r5){l4[p4]=r5,h6[p4];for(var m4=0;m4<3;++m4){var g6=u5[3*p4+m4];g6>=0&&l4[g6]===0&&(d4[3*p4+m4]?c4.push(g6):(a3.push(g6),l4[g6]=r5))}}}var f3=c4;c4=a3,a3=f3,c4.length=0,r5=-r5}var _4=(function(t54,e7,n6){for(var o6=0,i4=0;i4<t54.length;++i4)e7[i4]===n6&&(t54[o6++]=t54[i4]);return t54.length=o6,t54})(h6,l4,e6);return n5?_4.concat(s3.boundary):_4},o4.prototype.locate=(function(){var t53=[0,0,0];return function(e6,o6,s3){var r5=e6,a3=o6,c4=s3;return o6<s3?o6<e6&&(r5=o6,a3=s3,c4=e6):s3<e6&&(r5=s3,a3=e6,c4=o6),r5<0?-1:(t53[0]=r5,t53[1]=a3,t53[2]=c4,n4.eq(this.cells,t53,i3))}})()}}),w3=r4({"node_modules/cdt2d/cdt2d.js"(t52,e5){var n4=P2(),o4=M3(),i3=C3(),s3=T3();function r5(t53){return[Math.min(t53[0],t53[1]),Math.max(t53[0],t53[1])]}function a3(t53,e6){return t53[0]-e6[0]||t53[1]-e6[1]}function c4(t53,e6,n5){return e6 in t53?t53[e6]:n5}e5.exports=function(t53,e6,l4){Array.isArray(e6)?(l4=l4||{},e6=e6||[]):(l4=e6||{},e6=[]);var h6=!!c4(l4,"delaunay",!0),d4=!!c4(l4,"interior",!0),u5=!!c4(l4,"exterior",!0),p4=!!c4(l4,"infinity",!1);if(!d4&&!u5||t53.length===0)return[];var m4=n4(t53,e6);if(h6||d4!==u5||p4){for(var g6=o4(t53.length,(function(t54){return t54.map(r5).sort(a3)})(e6)),f3=0;f3<m4.length;++f3){var _4=m4[f3];g6.addTriangle(_4[0],_4[1],_4[2])}return h6&&i3(t53,g6),u5?d4?p4?s3(g6,0,p4):g6.cells():s3(g6,1,p4):s3(g6,-1)}return m4}}}),R2={0:"M0.301025 0.257813 L0.206593 0.283385 L0.122042 0.361307 L0.075923 0.474441 L0.064942 0.642221 L0.091296 0.78289 L0.159376 0.899463 L0.257104 0.961214 L0.344948 0.961214 L0.442678 0.899463 L0.510757 0.78289 L0.537111 0.642221 L0.526131 0.474441 L0.480012 0.361307 L0.39546 0.283385 L0.301025 0.257813",1:"M0.220426 0.40845 L0.381626 0.270996 L0.381626 0.948966",2:"M0.110409 0.39212 L0.125621 0.342293 L0.170571 0.295823 L0.244237 0.26431 L0.291518 0.257813 L0.373319 0.263799 L0.434683 0.290705 L0.468239 0.331966 L0.480292 0.379913 L0.479492 0.411806 L0.465088 0.465192 L0.402571 0.568988 L0.245134 0.766438 L0.07959 0.948045 L0.522462 0.948045",3:"M0.081606 0.345073 L0.119154 0.315633 L0.178996 0.284091 L0.255265 0.257813 L0.349133 0.263062 L0.43127 0.289348 L0.48994 0.336662 L0.525141 0.394491 L0.513407 0.457577 L0.466472 0.504892 L0.384334 0.541692 L0.290464 0.56272 L0.20833 0.573235 L0.290464 0.583749 L0.384334 0.610035 L0.466472 0.652092 L0.519274 0.709922 L0.531007 0.773007 L0.50754 0.841351 L0.454738 0.899179 L0.3726 0.946494 L0.310412 0.961214 L0.209503 0.959111 L0.127367 0.946494 L0.071046 0.929671",4:"M0.418494 0.270996 L0.048828 0.724199 L0.553224 0.724199 M0.414181 0.578167 L0.414181 0.94897",5:"M0.074951 0.270996 L0.074951 0.614701 L0.267655 0.5695 L0.405247 0.586502 L0.460002 0.617189 L0.498028 0.660731 L0.527101 0.779401 L0.513352 0.841049 L0.477274 0.889568 L0.406378 0.93463 L0.324445 0.958337 L0.247399 0.962139 L0.182516 0.949767 L0.130068 0.925508 L0.074951 0.875607 M0.074951 0.270996 L0.527101 0.270996",6:"M0.428549 0.257813 L0.341433 0.285053 L0.26073 0.312099 L0.192188 0.360182 L0.138902 0.410969 L0.098219 0.500422 L0.070249 0.584267 L0.067264 0.670716 L0.065164 0.756863 L0.087163 0.820973 L0.108168 0.861042 L0.157916 0.913131 L0.210981 0.948192 L0.29279 0.961214 L0.384548 0.956206 L0.456409 0.924151 L0.507262 0.881077 L0.5349 0.821975 L0.537111 0.771889 L0.521634 0.718798 L0.498418 0.67372 L0.463042 0.636657 L0.414398 0.613617 L0.34696 0.598591 L0.28284 0.595587 L0.215403 0.605604 L0.145756 0.641665 L0.109274 0.678729 L0.064942 0.724006",7:"M0.071534 0.270996 L0.530519 0.270996 L0.495935 0.291702 L0.477752 0.305407 L0.435186 0.346112 L0.412067 0.374136 L0.388565 0.40796 L0.365315 0.448098 L0.342943 0.495062 L0.322081 0.549366 L0.303364 0.611524 L0.287416 0.68205 L0.270077 0.80465 L0.26253 0.94897",8:"M0.286761 0.257813 L0.210684 0.27162 L0.1414 0.305622 L0.092494 0.382125 L0.111513 0.450128 L0.16857 0.502193 L0.228345 0.539382 L0.377781 0.594635 L0.470161 0.645637 L0.52586 0.706203 L0.538087 0.792269 L0.506841 0.87621 L0.438915 0.927212 L0.339743 0.961214 L0.263666 0.959089 L0.174004 0.929337 L0.102003 0.881523 L0.063965 0.811395 L0.066682 0.741266 L0.102003 0.671139 L0.180797 0.608448 L0.259591 0.580822 L0.358762 0.548945 L0.456576 0.49688 L0.486463 0.446941 L0.487822 0.362999 L0.453859 0.302434 L0.384574 0.265245 L0.286761 0.257813",9:"M0.511026 0.437812 L0.491026 0.347812 L0.451026 0.297812 L0.391026 0.267812 L0.311026 0.257813 L0.231026 0.267812 L0.161026 0.297812 L0.111026 0.347812 L0.091026 0.417812 L0.111026 0.487812 L0.161026 0.537812 L0.231026 0.567812 L0.311026 0.577812 L0.391026 0.557812 L0.451026 0.517812 L0.491026 0.477812 L0.511026 0.437812 M0.510026 0.438812 L0.434026 0.636812 L0.381026 0.777812 L0.337026 0.879812 L0.301026 0.957812","!":"M0.301026 0.270996 L0.301026 0.749566 M0.251466 0.94897 L0.350587 0.94897",'"':"M0.16504 0.270996 L0.16504 0.523022 M0.437013 0.270996 L0.437013 0.523022","#":"M0.20958 0.282227 L0.146515 0.949754 M0.461844 0.282227 L0.398779 0.949754 M0.032999 0.526969 L0.600587 0.452796 M0.001465 0.82366 L0.569055 0.749486",$:"M0.307121 0.240234 L0.307121 1.083502 M0.490031 0.415915 L0.404676 0.328075 L0.23396 0.310507 L0.136407 0.398347 L0.099828 0.521324 L0.124213 0.591596 L0.197379 0.644299 L0.429061 0.697003 L0.502224 0.749708 L0.526613 0.837547 L0.477836 0.960526 L0.355897 1.013228 L0.197379 0.99566 L0.112021 0.942957 L0.07544 0.837547","'":"M0.301026 0.270996 L0.301026 0.523022","(":"M0.413087 0.241211 L0.372337 0.28347 L0.331589 0.334184 L0.290838 0.393349 L0.25009 0.460965 L0.219528 0.528584 L0.199153 0.5962 L0.188966 0.655364 L0.199153 0.714529 L0.219528 0.782146 L0.25009 0.849764 L0.290838 0.91738 L0.331589 0.976544 L0.372337 1.027258 L0.413087 1.069491",")":"M0.188966 0.241211 L0.229716 0.28347 L0.270466 0.334184 L0.311213 0.393349 L0.351964 0.460965 L0.382526 0.528584 L0.4029 0.5962 L0.413087 0.655364 L0.4029 0.714529 L0.382526 0.782146 L0.351964 0.849764 L0.311213 0.91738 L0.270466 0.976544 L0.229716 1.027258 L0.188966 1.069491","*":"M0.301026 0.458702 L0.301026 0.681942 M0.301026 0.458702 L0.520997 0.536834 M0.301026 0.458702 L0.439954 0.257813 M0.301026 0.458702 L0.162098 0.257813 M0.301026 0.458702 L0.081055 0.536834","+":"M0.042969 0.66845 L0.559083 0.66845 M0.301023 0.428223 L0.301023 0.908661",",":"M0.38672 0.852051 L0.215333 1.030661 L0.301025 1.119971","-":"M0.173829 0.686035 L0.428224 0.686035",".":"M0.362549 0.851074 L0.239503 0.851074","/":"M0.062501 1.035249 L0.539551 0.270996","<":"M0.559083 0.441895 L0.042969 0.66939 L0.042969 0.66939 L0.559083 0.896902","=":"M0.042969 0.545898 L0.559083 0.545898 M0.042969 0.80837 L0.559083 0.80837",">":"M0.042969 0.441895 L0.559083 0.66939 L0.559083 0.66939 L0.042969 0.896902",A:"M0.018067 0.94897 L0.290179 0.270996 L0.583986 0.94897 M0.155303 0.684521 L0.433548 0.684521",B:"M0.063965 0.94897 L0.063965 0.278953 L0.209356 0.270996 L0.342486 0.294394 L0.432179 0.37292 L0.418224 0.48773 L0.312686 0.549166 L0.084728 0.575531 L0.306377 0.589434 L0.468877 0.647456 L0.538087 0.736658 L0.5324 0.85202 L0.501247 0.902983 L0.42355 0.944398 L0.063965 0.94897",C:"M0.529054 0.419847 L0.498425 0.345196 L0.442238 0.292341 L0.33583 0.257813 L0.257199 0.268357 L0.187906 0.303748 L0.120243 0.385432 L0.072998 0.599844 L0.110073 0.815385 L0.165381 0.902183 L0.222883 0.942801 L0.334904 0.961214 L0.43253 0.937679 L0.504816 0.868999 L0.529054 0.772065",D:"M0.064454 0.94897 L0.071838 0.285078 L0.171217 0.270996 L0.247348 0.272633 L0.37101 0.306078 L0.462461 0.378304 L0.514748 0.475555 L0.535591 0.576392 L0.537599 0.652313 L0.528065 0.717381 L0.508562 0.772419 L0.445948 0.855695 L0.362356 0.90871 L0.225203 0.945862 L0.064454 0.94897",E:"M0.080078 0.270996 L0.080078 0.94897 M0.080078 0.270996 L0.521974 0.270996 M0.080078 0.609981 L0.389405 0.609981 M0.080078 0.94897 L0.521974 0.94897",F:"M0.086426 0.270996 L0.086426 0.94897 M0.091304 0.275607 L0.515626 0.275607 M0.091304 0.607677 L0.447344 0.607677",G:"M0.498034 0.284943 L0.374621 0.257813 L0.244219 0.268648 L0.160577 0.311997 L0.094556 0.398116 L0.056397 0.58404 L0.076752 0.785532 L0.120865 0.858197 L0.188947 0.916734 L0.271008 0.953591 L0.357069 0.961214 L0.43715 0.932047 L0.501262 0.858539 L0.545656 0.648611 L0.329595 0.648131",H:"M0.066895 0.270996 L0.066895 0.94897 M0.066895 0.595658 L0.530009 0.595658 M0.535157 0.270996 L0.535157 0.94897",I:"M0.301026 0.270996 L0.301026 0.94897",J:"M0.506839 0.270996 L0.507814 0.782193 L0.498468 0.846168 L0.480733 0.880789 L0.455864 0.90832 L0.426095 0.929408 L0.360746 0.954812 L0.302508 0.962139 L0.223573 0.953638 L0.16538 0.930312 L0.137072 0.907715 L0.116428 0.880312 L0.102822 0.848819 L0.095633 0.813947 L0.094239 0.776413",K:"M0.035401 0.270996 L0.035401 0.94897 M0.502258 0.316194 L0.035401 0.687823 M0.212484 0.582361 L0.566652 0.933903",L:"M0.07544 0.270996 L0.07544 0.94897 L0.526613 0.94897",M:"M0.042481 0.94897 L0.042481 0.270996 L0.301027 0.712492 L0.559571 0.270996 L0.559571 0.94897",N:"M0.067871 0.94897 L0.067871 0.270996 L0.534181 0.94897 L0.525031 0.270996",O:"M0.287293 0.961214 L0.19843 0.933567 L0.1172 0.849451 L0.057129 0.563945 L0.114348 0.350255 L0.18455 0.289392 L0.306101 0.257813 L0.42054 0.29572 L0.487543 0.365003 L0.544923 0.625294 L0.516366 0.789624 L0.465476 0.884596 L0.375084 0.949287 L0.287293 0.961214",P:"M0.070557 0.94897 L0.070557 0.28379 L0.20704 0.270996 L0.329134 0.278993 L0.408525 0.300514 L0.444022 0.317908 L0.500637 0.368929 L0.525796 0.423728 L0.531496 0.50384 L0.508934 0.554205 L0.473724 0.582043 L0.417577 0.604365 L0.336375 0.620372 L0.226014 0.629268 L0.082368 0.630258",Q:"M0.282435 1.050813 L0.195447 1.019646 L0.115933 0.924817 L0.057129 0.602943 L0.113139 0.362034 L0.18186 0.293418 L0.300844 0.257813 L0.412868 0.300553 L0.478457 0.37866 L0.534625 0.672103 L0.506671 0.857367 L0.456855 0.964437 L0.368371 1.037368 L0.282435 1.050813 M0.341225 0.815559 L0.544923 1.070653",R:"M0.034912 0.944112 L0.034912 0.288556 L0.227127 0.270996 L0.362038 0.276867 L0.443423 0.294907 L0.477644 0.309614 L0.505809 0.328757 L0.526616 0.352817 L0.544963 0.418061 L0.543241 0.475921 L0.524463 0.517817 L0.49076 0.546518 L0.444265 0.564799 L0.355195 0.578739 L0.047653 0.589627 M0.303054 0.617306 L0.56714 0.94897",S:"M0.483037 0.364333 L0.407613 0.267477 L0.22883 0.257813 L0.128623 0.327565 L0.087712 0.455539 L0.104656 0.518727 L0.168054 0.573307 L0.41928 0.617318 L0.503796 0.669342 L0.535157 0.759324 L0.493846 0.900055 L0.367668 0.961214 L0.205436 0.956661 L0.116711 0.907038 L0.066895 0.790334",T:"M0.022949 0.270996 L0.579103 0.270996 M0.309284 0.270996 L0.309284 0.94897",U:"M0.072022 0.270996 L0.07308 0.648875 L0.080372 0.75167 L0.099024 0.827813 L0.134786 0.885729 L0.181571 0.924023 L0.251464 0.95168 L0.339655 0.962139 L0.401553 0.951668 L0.45232 0.924086 L0.482701 0.891771 L0.495745 0.870529 L0.515699 0.81637 L0.525014 0.744626 L0.530031 0.272017",V:"M0.027832 0.270996 L0.320083 0.94897 L0.57422 0.270996",W:"M0 0.270996 L0.079799 0.940377 L0.285198 0.472884 L0.505255 0.94897 L0.602052 0.270996",X:"M0.009034 0.270996 L0.586805 0.94897 M0.593019 0.270996 L0.015246 0.94897",Y:"M0.018067 0.270996 L0.293132 0.574135 M0.583986 0.271959 L0.294954 0.57606 L0.305277 0.94897",Z:"M0.053711 0.270996 L0.548341 0.270996 L0.053711 0.94897 L0.548341 0.94897","[":"M0.404542 0.240234 L0.197511 0.240234 L0.197511 1.069424 L0.404542 1.069424","\\":"M0.062501 0.270996 L0.539551 1.035249","]":"M0.19751 0.240234 L0.404542 0.240234 L0.404542 1.069424 L0.19751 1.069424","^":"M0.035156 0.523931 L0.301024 0.270996 L0.566896 0.523931",_:"M0 1.160601 L0.602052 1.160601",a:"M0.527101 0.439941 L0.527101 0.973965 M0.527101 0.553824 L0.451366 0.477535 L0.376759 0.439941 L0.263722 0.439941 L0.187989 0.477535 L0.112255 0.553824 L0.074951 0.66881 L0.074951 0.745099 L0.112255 0.85898 L0.187989 0.93527 L0.263722 0.973965 L0.376759 0.973965 L0.451366 0.93527 L0.527101 0.85898",b:"M0.07666 0.240234 L0.07666 0.959985 M0.07666 0.582737 L0.151822 0.514237 L0.225865 0.480483 L0.338045 0.480483 L0.413211 0.514237 L0.488374 0.582737 L0.525392 0.685983 L0.525392 0.754485 L0.488374 0.856739 L0.413211 0.92524 L0.338045 0.959985 L0.225865 0.959985 L0.151822 0.92524 L0.07666 0.856739",c:"M0.512452 0.553823 L0.441624 0.477535 L0.371854 0.439941 L0.26614 0.439941 L0.195312 0.477535 L0.124486 0.553823 L0.0896 0.668808 L0.0896 0.745099 L0.124486 0.858979 L0.195312 0.93527 L0.26614 0.973965 L0.371854 0.973965 L0.441624 0.93527 L0.512452 0.858979",d:"M0.525392 0.240234 L0.525392 0.959985 M0.525392 0.582737 L0.450232 0.514237 L0.376189 0.480483 L0.264006 0.480483 L0.188844 0.514237 L0.11368 0.582737 L0.076661 0.685983 L0.076661 0.754485 L0.11368 0.856739 L0.188844 0.92524 L0.264006 0.959985 L0.376189 0.959985 L0.450232 0.92524 L0.525392 0.856739",e:"M0.059571 0.668808 L0.542482 0.668808 M0.542482 0.592521 L0.502641 0.516231 L0.461594 0.477535 L0.381914 0.439941 L0.261186 0.439941 L0.180299 0.477535 L0.099412 0.553823 L0.059571 0.668808 L0.059571 0.745099 L0.099412 0.858979 L0.180299 0.93527 L0.261186 0.973965 L0.381914 0.973965 L0.461594 0.93527 L0.542482 0.858979",f:"M0.512941 0.240234 L0.406984 0.240234 L0.301026 0.274346 L0.248047 0.374731 L0.248047 0.946817 M0.089112 0.476088 L0.459965 0.476088",g:"M0.525392 0.439941 L0.525392 0.989395 L0.488373 1.091918 L0.45023 1.126757 L0.376189 1.160601 L0.264004 1.160601 L0.188844 1.126757 L0.113681 1.058075 L0.076661 0.954555 M0.525392 0.542467 L0.45023 0.473786 L0.376189 0.439941 L0.264004 0.439941 L0.188844 0.473786 L0.113681 0.542467 L0.076661 0.645988 L0.076661 0.714669 L0.113681 0.817193 L0.188844 0.885875 L0.264004 0.920713 L0.376189 0.920713 L0.45023 0.885875 L0.525392 0.817193",h:"M0.092041 0.240234 L0.092041 0.946817 M0.092041 0.61058 L0.205937 0.509225 L0.282214 0.476086 L0.396109 0.476086 L0.47187 0.509225 L0.510011 0.61058 L0.510011 0.946817",i:"M0.261026 0.240234 L0.341026 0.240234 M0.300978 0.476089 L0.300978 0.946817",j:"M0.3853 0.240234 L0.447023 0.240234 M0.416159 0.465708 L0.416159 1.011689 L0.383887 1.108586 L0.252832 1.140264 L0.15503 1.108586",k:"M0.065186 0.240234 L0.065186 0.946817 M0.493824 0.476086 L0.065186 0.812323 M0.236758 0.677829 L0.536867 0.946817",l:"M0.301026 0.234863 L0.301026 0.946441",m:"M0.050538 0.439941 L0.050538 0.960796 M0.050538 0.588758 L0.114405 0.476607 L0.157178 0.439941 L0.236864 0.439941 L0.279637 0.476607 L0.32241 0.588758 L0.32241 0.960796 M0.32241 0.588758 L0.386281 0.476607 L0.428467 0.439941 L0.50874 0.439941 L0.551515 0.476607 L0.551515 0.960796",n:"M0.092041 0.439941 L0.092041 0.960796 M0.092041 0.588758 L0.205936 0.476607 L0.282216 0.439941 L0.396113 0.439941 L0.471871 0.476607 L0.510011 0.588758 L0.510011 0.960796",o:"M0.247175 0.439941 L0.175178 0.477535 L0.103186 0.553823 L0.066895 0.668808 L0.066895 0.745099 L0.103186 0.858979 L0.175178 0.93527 L0.247175 0.973965 L0.354874 0.973965 L0.426872 0.93527 L0.498866 0.858979 L0.535157 0.745099 L0.535157 0.668808 L0.498866 0.553823 L0.426872 0.477535 L0.354874 0.439941 L0.247175 0.439941",p:"M0.076904 0.439941 L0.076904 1.154244 M0.076904 0.541563 L0.151986 0.473487 L0.225944 0.439941 L0.338005 0.439941 L0.413087 0.473487 L0.488166 0.541563 L0.525148 0.644169 L0.525148 0.712246 L0.488166 0.813866 L0.413087 0.881942 L0.338005 0.916471 L0.225944 0.916471 L0.151986 0.881942 L0.076904 0.813866",q:"M0.525148 0.441895 L0.525148 1.156195 M0.525148 0.5435 L0.450067 0.47544 L0.376106 0.441895 L0.264042 0.441895 L0.188966 0.47544 L0.113885 0.5435 L0.076905 0.646108 L0.076905 0.714187 L0.113885 0.815809 L0.188966 0.883886 L0.264042 0.918418 L0.376106 0.918418 L0.450067 0.883886 L0.525148 0.815809",r:"M0.107422 0.439941 L0.107422 0.960796 M0.107422 0.663164 L0.155824 0.551014 L0.252626 0.476607 L0.349428 0.439941 L0.49463 0.439941",s:"M0.475556 0.477535 L0.400757 0.439941 L0.276092 0.439941 L0.176361 0.477535 L0.101563 0.553823 L0.101563 0.630112 L0.176361 0.668808 L0.301024 0.668808 L0.425688 0.745099 L0.50049 0.821387 L0.50049 0.897677 L0.425688 0.93527 L0.325956 0.973965 L0.201295 0.973965 L0.126496 0.93527 L0.101563 0.858979",t:"M0.246032 0.297852 L0.246032 0.826549 L0.301023 0.919323 L0.411011 0.950848 L0.520997 0.950848 M0.081055 0.515799 L0.466004 0.515799",u:"M0.092041 0.454102 L0.092041 0.826134 L0.13018 0.937211 L0.205936 0.974954 L0.319832 0.974954 L0.396113 0.937211 L0.510011 0.826134 M0.510011 0.454102 L0.510011 0.974954",v:"M0.048828 0.453125 L0.301026 0.961719 M0.553224 0.453125 L0.301026 0.961719",w:"M0 0.453125 L0.150512 0.961719 M0.301024 0.453125 L0.150512 0.961719 M0.301024 0.453125 L0.451539 0.961719 M0.602052 0.453125 L0.451539 0.961719",x:"M0.03711 0.453125 L0.564943 0.961719 M0.564943 0.453125 L0.03711 0.961719",y:"M0.084618 0.453125 L0.320232 0.921476 M0.55713 0.453125 L0.320232 0.921476 L0.242119 1.055289 L0.163369 1.122196 L0.084618 1.155166 L0.044922 1.155166",z:"M0.505373 0.452148 L0.09668 0.961651 M0.09668 0.452148 L0.505373 0.452148 M0.09668 0.961651 L0.505373 0.961651"},E2={};for(let t52 in R2){E2[t52]=[];let e5=R2[t52].split("M").slice(1).map(t53=>t53.split("L").map(t54=>t54.trim().split(" ").map(parseFloat)));for(let n4 of e5)for(let e6=0;e6<n4.length-1;e6++)E2[t52].push({x1:n4[e6][0],y1:1-n4[e6][1],x2:n4[e6+1][0],y2:1-n4[e6+1][1]})}new TextEncoder,(()=>{let t52=new Uint8Array(4);new Uint32Array(t52.buffer)[0]=1,t52[0]})(),globalThis.Int8Array,globalThis.Uint8Array,globalThis.Int16Array,globalThis.Uint16Array,globalThis.Int32Array,globalThis.Uint32Array,globalThis.BigUint64Array,globalThis.BigInt64Array,globalThis.Float32Array,globalThis.Float64Array;var A3=[];for(let t52=0;t52<256;t52++){let e5=t52;for(let t53=0;t53<8;t53++)1&e5?e5=3988292384^e5>>>1:e5>>>=1;A3[t52]=e5}var O2=new Uint16Array([255]),L2=(new Uint8Array(O2.buffer)[0],new Uint16Array([255]));new Uint8Array(L2.buffer)[0],new Uint8Array(0),Uint8Array.of(137,80,78,71,13,10,26,10),new TextDecoder("latin1");function D3(){return D3=Object.assign?Object.assign.bind():function(t52){for(var e5=1;e5<arguments.length;e5++){var n4=arguments[e5];for(var o4 in n4)({}).hasOwnProperty.call(n4,o4)&&(t52[o4]=n4[o4])}return t52},D3.apply(null,arguments)}function k3(t52,e5){return(k3=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t53,e6){return t53.__proto__=e6,t53})(t52,e5)}function z3(t52){return(z3=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t53){return t53.__proto__||Object.getPrototypeOf(t53)})(t52)}function j2(){try{var t52=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(j2=function(){return!!t52})()}function F3(t52){var e5=typeof Map=="function"?new Map:void 0;return F3=function(t53){if(t53===null||!(function(t54){try{return Function.toString.call(t54).indexOf("[native code]")!==-1}catch{return typeof t54=="function"}})(t53))return t53;if(typeof t53!="function")throw new TypeError("Super expression must either be null or a function");if(e5!==void 0){if(e5.has(t53))return e5.get(t53);e5.set(t53,n4)}function n4(){return(function(t54,e6,n5){if(j2())return Reflect.construct.apply(null,arguments);var o4=[null];o4.push.apply(o4,e6);var i3=new(t54.bind.apply(t54,o4));return n5&&k3(i3,n5.prototype),i3})(t53,arguments,z3(this).constructor)}return n4.prototype=Object.create(t53.prototype,{constructor:{value:n4,enumerable:!1,writable:!0,configurable:!0}}),k3(n4,t53)},F3(t52)}var $4={1:`Passed invalid arguments to hsl, please pass multiple numbers e.g. hsl(360, 0.75, 0.4) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75 }).
|
|
338
338
|
|
|
339
339
|
`,2:`Passed invalid arguments to hsla, please pass multiple numbers e.g. hsla(360, 0.75, 0.4, 0.7) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75, alpha: 0.7 }).
|
|
340
340
|
|
|
@@ -646,8 +646,8 @@ ${childDivs.join(`
|
|
|
646
646
|
`)}
|
|
647
647
|
</div>`},CssGrid_visualize=grid4=>{let layout=grid4.layout(),go3={title:"CssGrid",coordinateSystem:"screen",lines:[],circles:[],points:[],rects:[],texts:[]},{cells}=layout;for(let cell of cells){let{x:x4,y:y4,width,height,key}=cell;go3.rects.push({center:{x:x4+width/2,y:y4+height/2},width,height,fill:getColor(key),label:key})}return go3};function expandRepeat(templateStr){return templateStr.replace(/repeat\((\d+),\s*([^)]+)\)/g,(_4,count,val)=>Array(Number(count)).fill(val.trim()).join(" "))}function tokenize(templateStr){return templateStr.trim().split(/\s+/).filter(Boolean)}function countTracks(tpl){return tpl?tokenize(expandRepeat(tpl)).length:0}function pxFromToken(token,containerSize){if(token==="auto")return{fr:1};if(token.endsWith("%")){let n22=parseFloat(token);return containerSize!=null?containerSize*n22/100:0}if(token.endsWith("px"))return parseFloat(token);if(token.endsWith("em"))return parseFloat(token)*16;if(token.endsWith("fr"))return{fr:parseFloat(token)};let n4=parseFloat(token);return Number.isNaN(n4)?0:n4}function resolveNegativeLine(idx,trackCnt){return idx>0?idx:trackCnt+2+idx}var CssGrid_layout=grid4=>{let opts=grid4.opts,children=opts.children,rowsTpl,colsTpl;if("gridTemplate"in opts&&typeof opts.gridTemplate=="string"){let[rows,cols]=opts.gridTemplate.split("/");rowsTpl=rows?.trim(),colsTpl=cols?.trim()}else rowsTpl=typeof opts.gridTemplateRows=="string"?opts.gridTemplateRows:void 0,colsTpl=typeof opts.gridTemplateColumns=="string"?opts.gridTemplateColumns:void 0;let columnTrackCountDeclared=countTracks(colsTpl),rowTrackCountDeclared=countTracks(rowsTpl);function calculateMinimumContainerSize(tpl,children2,isWidth,gap){if(!tpl)return 0;let expanded=expandRepeat(tpl),tokens=tokenize(expanded),trackCount=tokens.length,minContentSize=0,hasFlexibleTracks=!1;for(let i3=0;i3<tokens.length;i3++){let token=tokens[i3];if(token.endsWith("px"))minContentSize+=parseFloat(token);else if(token.endsWith("em"))minContentSize+=parseFloat(token)*16;else if(token.endsWith("fr")||token==="auto"){hasFlexibleTracks=!0;let maxContentInTrack=0;for(let child of children2){let childStart=isWidth?child.columnStart||child.column:child.rowStart||child.row,childSpan=isWidth?child.columnSpan||1:child.rowSpan||1,contentSize=isWidth?child.contentWidth:child.contentHeight,startIdx=(typeof childStart=="number"?childStart:parseInt(childStart||"1"))-1,span=typeof childSpan=="number"?childSpan:parseInt(childSpan.toString());if(startIdx<=i3&&i3<startIdx+span&&contentSize){let size3=typeof contentSize=="string"&&contentSize.endsWith("px")?parseFloat(contentSize):typeof contentSize=="number"?contentSize:0;maxContentInTrack=Math.max(maxContentInTrack,size3/span)}}minContentSize+=maxContentInTrack}}let totalGaps=gap*(trackCount-1);return minContentSize+totalGaps}function buildTrackSizes(tpl,containerSize,gap,isWidth=!0,crossTrackCount=1){if(!tpl)return[];if(containerSize==null){let expanded2=expandRepeat(tpl),tokens2=tokenize(expanded2),trackCnt=tokens2.length,toPx=v4=>v4===void 0?0:typeof v4=="number"?v4:(v4.endsWith("px"),parseFloat(v4)),sizes2=new Array(trackCnt).fill(0),autoCursor=0;for(let child of children){let span=isWidth?typeof child.columnSpan=="number"?child.columnSpan:child.columnSpan?parseInt(child.columnSpan.toString()):1:typeof child.rowSpan=="number"?child.rowSpan:child.rowSpan?parseInt(child.rowSpan.toString()):1,rawSize=isWidth?child.contentWidth:child.contentHeight,sizePerTrack=toPx(rawSize)/span,startIdx;isWidth?(child.columnStart!==void 0||child.column!==void 0)&&(startIdx=parseInt(child.columnStart??child.column)-1):(child.rowStart!==void 0||child.row!==void 0)&&(startIdx=parseInt(child.rowStart??child.row)-1),(startIdx===void 0||Number.isNaN(startIdx))&&(isWidth?startIdx=autoCursor%trackCnt:startIdx=Math.floor(autoCursor/crossTrackCount),autoCursor+=span);for(let i3=0;i3<span&&startIdx+i3<trackCnt;i3++)sizes2[startIdx+i3]=Math.max(sizes2[startIdx+i3],sizePerTrack)}return tokens2.forEach((tok,idx)=>{let px3=pxFromToken(tok,void 0);typeof px3=="number"&&(sizes2[idx]=px3)}),sizes2}let expanded=expandRepeat(tpl),tokens=tokenize(expanded),trackCount=tokens.length,effectiveContainerSize=containerSize;effectiveContainerSize==null&&(effectiveContainerSize=calculateMinimumContainerSize(tpl,children,isWidth,gap));let sizeForTracks=effectiveContainerSize-gap*(trackCount-1),sumFixed=0,totalFr=0,frTokens=[],sizes=[];tokens.forEach((token,i3)=>{let px3=pxFromToken(token,sizeForTracks);typeof px3=="number"?(sizes.push(px3),sumFixed+=px3):px3&&typeof px3=="object"&&"fr"in px3?(sizes.push(px3),totalFr+=px3.fr,frTokens.push({idx:i3,fr:px3.fr})):(sizes.push(0),sumFixed+=0)});let free=Math.max(sizeForTracks-sumFixed,0);return sizes.map(v4=>typeof v4=="number"?v4:totalFr>0?free/totalFr*v4.fr:0)}let rowGap=typeof opts.gap=="number"?opts.gap:Array.isArray(opts.gap)?opts.gap[0]:0,columnGap=typeof opts.gap=="number"?opts.gap:Array.isArray(opts.gap)?opts.gap[1]:0,rowSizes=buildTrackSizes(rowsTpl,opts.containerHeight,rowGap,!1,columnTrackCountDeclared||1),columnSizes=buildTrackSizes(colsTpl,opts.containerWidth,columnGap,!0,rowTrackCountDeclared||1),rowCount=rowSizes.length,colCount=columnSizes.length;colCount===0&&children.length>0&&(colCount=1);let cells=[],nextAutoCell=0;for(let child of children){let rowStart=child.rowStart!==void 0?child.rowStart:child.row,colStart=child.columnStart!==void 0?child.columnStart:child.column,rowSpan=child.rowSpan!==void 0?typeof child.rowSpan=="string"?parseInt(child.rowSpan):child.rowSpan:1,colSpan=child.columnSpan!==void 0?typeof child.columnSpan=="string"?parseInt(child.columnSpan):child.columnSpan:1;if(child.rowEnd!==void 0){let end=typeof child.rowEnd=="string"?parseInt(child.rowEnd):child.rowEnd;rowStart!==void 0?rowSpan=end-(typeof rowStart=="string"?parseInt(rowStart):rowStart):rowStart=end-rowSpan}if(child.columnEnd!==void 0){let end=typeof child.columnEnd=="string"?parseInt(child.columnEnd):child.columnEnd;colStart!==void 0?colSpan=end-(typeof colStart=="string"?parseInt(colStart):colStart):colStart=end-colSpan}if(typeof rowStart=="string"&&(rowStart=parseInt(rowStart)),typeof colStart=="string"&&(colStart=parseInt(colStart)),typeof rowStart=="number"&&rowStart<0&&(rowStart=resolveNegativeLine(rowStart,rowCount)),typeof colStart=="number"&&colStart<0&&(colStart=resolveNegativeLine(colStart,colCount)),rowStart===void 0&&colStart!==void 0)rowStart=1;else if(colStart===void 0&&rowStart!==void 0)colStart=1;else if(rowStart===void 0&&colStart===void 0){let idx=nextAutoCell;rowStart=Math.floor(idx/colCount)+1,colStart=idx%colCount+1}let row=rowStart-1,column=colStart-1;rowSpan=Math.max(1,rowSpan),colSpan=Math.max(1,colSpan),cells.push({key:child.key,row,column,rowSpan,columnSpan:colSpan,x:0,y:0,width:0,height:0}),nextAutoCell+=colSpan}let maxRow=rowSizes.length,maxCol=columnSizes.length;for(let cell of cells)cell.row+cell.rowSpan>maxRow&&(maxRow=cell.row+cell.rowSpan),cell.column+cell.columnSpan>maxCol&&(maxCol=cell.column+cell.columnSpan);if(rowSizes.length===0&&maxRow>0&&opts.containerHeight){let implicitRowCount=maxRow,implicitRowHeight=(opts.containerHeight-rowGap*(implicitRowCount-1))/implicitRowCount;for(let i3=0;i3<implicitRowCount;i3++)rowSizes.push(implicitRowHeight)}else for(;rowSizes.length<maxRow;)rowSizes.push(0);if(columnSizes.length===0&&maxCol>0&&opts.containerWidth){let implicitColCount=maxCol,implicitColWidth=(opts.containerWidth-columnGap*(implicitColCount-1))/implicitColCount;for(let i3=0;i3<implicitColCount;i3++)columnSizes.push(implicitColWidth)}else if(columnSizes.length===0&&children.length>0&&opts.containerWidth)columnSizes.push(opts.containerWidth);else for(;columnSizes.length<maxCol;)columnSizes.push(0);let getPositionFromTracks=(trackIndex,trackSizes,gap)=>{let position4=0;for(let i3=0;i3<trackIndex;i3++)position4+=trackSizes[i3]||0,position4+=gap;return position4},getSizeFromSpan=(trackIndex,span,trackSizes,gap)=>{let size3=0;for(let i3=trackIndex;i3<trackIndex+span;i3++)size3+=trackSizes[i3]||0,i3>trackIndex&&(size3+=gap);return size3},itemCoordinates={};for(let cell of cells){let child=children.find(c4=>c4.key===cell.key),cellX=getPositionFromTracks(cell.column,columnSizes,columnGap),cellY=getPositionFromTracks(cell.row,rowSizes,rowGap),cellWidth=getSizeFromSpan(cell.column,cell.columnSpan,columnSizes,columnGap),cellHeight=getSizeFromSpan(cell.row,cell.rowSpan,rowSizes,rowGap),getContentDimension=value=>value===void 0?0:typeof value=="string"?value.endsWith("px")?parseFloat(value):value.endsWith("%")?0:parseFloat(value):value,contentWidth=getContentDimension(child?.contentWidth),contentHeight=getContentDimension(child?.contentHeight),itemWidth=cellWidth,itemHeight=cellHeight,itemX=cellX,itemY=cellY;if(contentWidth>0)switch(itemWidth=contentWidth,opts.justifyItems||"stretch"){case"start":itemX=cellX;break;case"end":itemX=cellX+cellWidth-itemWidth;break;case"center":itemX=cellX+(cellWidth-itemWidth)/2;break;case"stretch":itemWidth=cellWidth,itemX=cellX;break}if(contentHeight>0)switch(itemHeight=contentHeight,opts.alignItems||"stretch"){case"start":itemY=cellY;break;case"end":itemY=cellY+cellHeight-itemHeight;break;case"center":itemY=cellY+(cellHeight-itemHeight)/2;break;case"stretch":itemHeight=cellHeight,itemY=cellY;break}cell.x=itemX,cell.y=itemY,cell.width=itemWidth,cell.height=itemHeight,itemCoordinates[cell.key]={x:itemX,y:itemY,width:itemWidth,height:itemHeight}}return{cells,rowSizes,columnSizes,rowGap,columnGap,itemCoordinates}},CssGrid=class{constructor(opts){__publicField(this,"opts");this.opts=opts}layout(){return CssGrid_layout(this)}convertToHtml(){return CssGrid_convertToHtml(this)}visualize(){return CssGrid_visualize(this)}};init_dist();var import_debug12=__toESM(require_browser(),1);init_dist6();init_dist6();init_dist();init_dist();init_dist6();init_dist6();init_dist6();var __defProp4=Object.defineProperty,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp3=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp2=(obj,key,value)=>key in obj?__defProp4(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a3,b3)=>{for(var prop in b3||(b3={}))__hasOwnProp3.call(b3,prop)&&__defNormalProp2(a3,prop,b3[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b3))__propIsEnum.call(b3,prop)&&__defNormalProp2(a3,prop,b3[prop]);return a3},getUnitVecFromAnchorSide=anchorSide=>{switch(anchorSide){case"left":return{x:-1,y:0};case"right":return{x:1,y:0};case"top":return{x:0,y:1};case"bottom":return{x:0,y:-1}}},getReadableIdMap=circuitJson=>{var _a497,_b3;let schComps=cju_default(circuitJson).schematic_component.list(),schLabels=cju_default(circuitJson).schematic_net_label.list(),schPorts=cju_default(circuitJson).schematic_port.list(),readableIdMap={};for(let schComp of schComps){let srcComp=cju_default(circuitJson).source_component.get(schComp.source_component_id);readableIdMap[schComp.schematic_component_id]=srcComp?.name}for(let schLabel of schLabels){let srcNet=cju_default(circuitJson).source_net.get(schLabel.source_net_id);if(!srcNet?.name)continue;let index=0;for(;Object.values(readableIdMap).includes(`NL_${srcNet.name}${index}`);)index++;readableIdMap[schLabel.schematic_net_label_id]=`NL_${srcNet.name}${index}`}for(let schPort of schPorts){let srcPort=cju_default(circuitJson).source_port.get(schPort.source_port_id);if(!srcPort)continue;let srcComp=cju_default(circuitJson).source_component.get(srcPort.source_component_id);if(!srcComp?.name)continue;let readableName=`${srcComp.name}_${(_b3=(_a497=srcPort?.name)!=null?_a497:srcPort?.pin_number)!=null?_b3:""}`;readableIdMap[schPort.schematic_port_id]=readableName}return readableIdMap},generateImplicitNetLabels=circuitJson=>{var _a497;let db2=cju_default(circuitJson),existingLabels=new Set(db2.schematic_net_label.list().map(nl3=>{var _a2100,_b3,_c3,_d3;return`${(_b3=(_a2100=nl3.anchor_position)==null?void 0:_a2100.x)!=null?_b3:nl3.center.x},${(_d3=(_c3=nl3.anchor_position)==null?void 0:_c3.y)!=null?_d3:nl3.center.y}`})),newLabels=[];for(let sp3 of db2.schematic_port.list()){let key=`${sp3.center.x},${sp3.center.y}`;if(existingLabels.has(key))continue;let srcPort=db2.source_port.get(sp3.source_port_id);if(!srcPort)continue;let srcNet=db2.source_net.getWhere({subcircuit_connectivity_map_key:srcPort.subcircuit_connectivity_map_key});if(!srcNet)continue;let srcTrace=db2.source_trace.list().find(st3=>{var _a2100;return(_a2100=st3.connected_source_port_ids)==null?void 0:_a2100.includes(sp3.source_port_id)}),schTrace=db2.schematic_trace.getWhere({source_trace_id:srcTrace?.source_trace_id}),schematic_net_label3={type:"schematic_net_label",schematic_net_label_id:`netlabel_for_${sp3.schematic_port_id}`,schematic_port_id:sp3.schematic_port_id,text:srcNet.name,source_net_id:srcNet.source_net_id,source_trace_id:srcTrace?.source_trace_id,schematic_trace_id:schTrace?.schematic_trace_id,anchor_position:__spreadValues({},sp3.center),center:__spreadValues({},sp3.center),anchor_side:oppositeSide((_a497=sp3.facing_direction)!=null?_a497:"right")};newLabels.push(schematic_net_label3)}return newLabels},convertCircuitJsonToBpc=(circuitJson,opts={})=>{let g6={boxes:[],pins:[]},schComps=cju_default(circuitJson).schematic_component.list(),schLabels=cju_default(circuitJson).schematic_net_label.list();opts.inferNetLabels&&(schLabels=schLabels.concat(generateImplicitNetLabels(circuitJson)));let readableIdMap=opts.useReadableIds?getReadableIdMap(circuitJson):{},maybeMakeIdReadable=id2=>opts.useReadableIds&&readableIdMap[id2]?readableIdMap[id2]:id2,disconnectedCounter=0;for(let schComp of schComps){let box2={boxId:maybeMakeIdReadable(schComp.schematic_component_id),kind:"floating",center:schComp.center};g6.boxes.push(box2);let centerPin={pinId:`${maybeMakeIdReadable(schComp.schematic_component_id)}_center`,color:"component_center",networkId:`center_${schComp.schematic_component_id}`,offset:{x:0,y:0},boxId:maybeMakeIdReadable(schComp.schematic_component_id)};g6.pins.push(centerPin);let schPorts=cju_default(circuitJson).schematic_port.list({schematic_component_id:schComp.schematic_component_id});for(let schPort of schPorts){let srcPort=cju_default(circuitJson).source_port.get(schPort.source_port_id),networkId=srcPort?.subcircuit_connectivity_map_key,color="normal";if(networkId){let srcNet=cju_default(circuitJson).source_net.getWhere({subcircuit_connectivity_map_key:srcPort?.subcircuit_connectivity_map_key});srcNet&&(srcNet.is_power||srcNet.name.startsWith("V"))&&(color="vcc"),srcNet&&(srcNet.is_ground||srcNet.name.startsWith("GND"))&&(color="gnd")}else networkId=`disconnected-${disconnectedCounter++}`,color="not_connected";let pin={pinId:maybeMakeIdReadable(schPort.schematic_port_id),color,networkId,offset:{x:schPort.center.x-box2.center.x,y:schPort.center.y-box2.center.y},boxId:maybeMakeIdReadable(schComp.schematic_component_id)};g6.pins.push(pin)}}for(let schLabel of schLabels){let srcNet=cju_default(circuitJson).source_net.get(schLabel.source_net_id),networkId=srcNet?.subcircuit_connectivity_map_key,color="normal";networkId?(srcNet&&(srcNet.is_power||srcNet.name.startsWith("V"))&&(color="vcc"),srcNet&&(srcNet.is_ground||srcNet.name.startsWith("GND"))&&(color="gnd")):(networkId=`disconnected-${disconnectedCounter++}`,color="not_connected");let netLabelDir=getUnitVecFromAnchorSide(schLabel.anchor_side),netLabelCenter={x:schLabel.anchor_position.x-netLabelDir.x*schLabel.text.length*.18*.5,y:schLabel.anchor_position.y-netLabelDir.y*.18},offset={x:0,y:0};schLabel.anchor_position&&(offset={x:schLabel.anchor_position.x-netLabelCenter.x,y:schLabel.anchor_position.y-netLabelCenter.y});let box2={boxId:maybeMakeIdReadable(schLabel.schematic_net_label_id),kind:"fixed",center:netLabelCenter,boxAttributes:{is_net_label:!0,source_net_id:schLabel.source_net_id,source_trace_id:schLabel.source_trace_id}};g6.boxes.push(box2);let pin={pinId:`${maybeMakeIdReadable(schLabel.schematic_net_label_id)}_pin`,boxId:maybeMakeIdReadable(schLabel.schematic_net_label_id),networkId,color,offset};g6.pins.push(pin),g6.pins.push({pinId:`${maybeMakeIdReadable(schLabel.schematic_net_label_id)}_center`,boxId:maybeMakeIdReadable(schLabel.schematic_net_label_id),networkId:`${maybeMakeIdReadable(schLabel.schematic_net_label_id)}_center`,color:"netlabel_center",offset:{x:0,y:0}})}return g6};init_dist7();var encoder=new TextEncoder;var defaultByteLength=1024*8,hostBigEndian=(()=>{let array2=new Uint8Array(4),view=new Uint32Array(array2.buffer);return!((view[0]=1)&array2[0])})(),typedArrays={int8:globalThis.Int8Array,uint8:globalThis.Uint8Array,int16:globalThis.Int16Array,uint16:globalThis.Uint16Array,int32:globalThis.Int32Array,uint32:globalThis.Uint32Array,uint64:globalThis.BigUint64Array,int64:globalThis.BigInt64Array,float32:globalThis.Float32Array,float64:globalThis.Float64Array};var crcTable=[];for(let n4=0;n4<256;n4++){let c4=n4;for(let k4=0;k4<8;k4++)c4&1?c4=3988292384^c4>>>1:c4=c4>>>1;crcTable[n4]=c4}var uint16=new Uint16Array([255]),uint8=new Uint8Array(uint16.buffer),osIsLittleEndian=uint8[0]===255;var uint162=new Uint16Array([255]),uint82=new Uint8Array(uint162.buffer),osIsLittleEndian2=uint82[0]===255,empty=new Uint8Array(0);var pngSignature=Uint8Array.of(137,80,78,71,13,10,26,10);var latin1Decoder=new TextDecoder("latin1");init_src();var FONT_SIZE_WIDTH_RATIO=.6,FONT_SIZE_HEIGHT_RATIO=1;init_src();var getRectRotationRadians=rect=>(rect.ccwRotationDegrees??0)*Math.PI/180;var rotatePoint3=(point7,angleRadians)=>{let cos6=Math.cos(angleRadians),sin6=Math.sin(angleRadians);return{x:point7.x*cos6-point7.y*sin6,y:point7.x*sin6+point7.y*cos6}},getRectCorners=rect=>getRectCornersWithAngle(rect,getRectRotationRadians(rect));var getRectCornersWithAngle=(rect,angleRadians)=>{let halfWidth=rect.width/2,halfHeight=rect.height/2;return[{x:-halfWidth,y:-halfHeight},{x:halfWidth,y:-halfHeight},{x:halfWidth,y:halfHeight},{x:-halfWidth,y:halfHeight}].map(corner=>{let rotatedCorner=rotatePoint3(corner,angleRadians);return{x:rect.center.x+rotatedCorner.x,y:rect.center.y+rotatedCorner.y}})};var DEFAULT_ARROW_SHAFT_WIDTH=2,DEFAULT_ARROW_HEAD_WIDTH=12,DEFAULT_ARROW_HEAD_LENGTH=12,createDegenerateHead=point7=>({tip:{...point7},base:{...point7},leftWing:{...point7},rightWing:{...point7}}),createHead=(tip,base,headWidth)=>{let dirX=tip.x-base.x,dirY=tip.y-base.y,length4=Math.hypot(dirX,dirY);if(length4===0)return createDegenerateHead(tip);let dirUnitX=dirX/length4,perpX=-(dirY/length4)*(headWidth/2),perpY=dirUnitX*(headWidth/2);return{tip:{...tip},base:{...base},leftWing:{x:base.x+perpX,y:base.y+perpY},rightWing:{x:base.x-perpX,y:base.y-perpY}}};function getArrowGeometry(arrow){let{start,end}=arrow,vx3=end.x-start.x,vy3=end.y-start.y,length4=Math.hypot(vx3,vy3),shaftWidth=DEFAULT_ARROW_SHAFT_WIDTH,headWidth=DEFAULT_ARROW_HEAD_WIDTH;if(length4===0){let heads2=arrow.doubleSided?[createDegenerateHead(start),createDegenerateHead(start)]:[createDegenerateHead(start)];return{shaftStart:{...start},shaftEnd:{...start},heads:heads2,shaftWidth,headLength:0,headWidth,length:length4}}let ux3=vx3/length4,uy3=vy3/length4,baseHeadLength=Math.min(DEFAULT_ARROW_HEAD_LENGTH,length4*.5),desiredHeadLength=Math.max(baseHeadLength,shaftWidth*2),maxHeadLength=arrow.doubleSided?length4/2:length4,headLength=Math.min(desiredHeadLength,maxHeadLength),endHeadBase={x:end.x-ux3*headLength,y:end.y-uy3*headLength},heads=[createHead(end,endHeadBase,headWidth)],shaftStart={...start},shaftEnd={...endHeadBase};if(arrow.doubleSided){let startHeadBase={x:start.x+ux3*headLength,y:start.y+uy3*headLength};heads.unshift(createHead(start,startHeadBase,headWidth)),shaftStart=startHeadBase}return{shaftStart,shaftEnd,heads,shaftWidth,headLength,headWidth,length:length4}}function getArrowBoundingBox(arrow){let geometry=getArrowGeometry(arrow);return[geometry.shaftStart,geometry.shaftEnd,...geometry.heads.flatMap(head=>[head.tip,head.base,head.leftWing,head.rightWing])].reduce((acc,point7)=>({minX:Math.min(acc.minX,point7.x),maxX:Math.max(acc.maxX,point7.x),minY:Math.min(acc.minY,point7.y),maxY:Math.max(acc.maxY,point7.y)}),{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0})}init_src();function getBounds(graphics){let points=[...graphics.points||[],...(graphics.lines||[]).flatMap(line2=>line2.points),...(graphics.polygons||[]).flatMap(polygon2=>polygon2.points),...(graphics.rects||[]).flatMap(rect=>getRectCorners(rect)),...(graphics.circles||[]).flatMap(circle2=>[{x:circle2.center.x-circle2.radius,y:circle2.center.y},{x:circle2.center.x+circle2.radius,y:circle2.center.y},{x:circle2.center.x,y:circle2.center.y-circle2.radius},{x:circle2.center.x,y:circle2.center.y+circle2.radius}]),...(graphics.arrows||[]).flatMap(arrow=>{let bounds=getArrowBoundingBox(arrow);return[{x:bounds.minX,y:bounds.minY},{x:bounds.maxX,y:bounds.maxY}]}),...(graphics.texts||[]).flatMap(text=>{let fontSize=text.fontSize??12,width=text.text.length*fontSize*FONT_SIZE_WIDTH_RATIO,height=fontSize*FONT_SIZE_HEIGHT_RATIO,anchor=text.anchorSide??"center",offsetMap={top_left:{dx:0,dy:0},top_center:{dx:-width/2,dy:0},top_right:{dx:-width,dy:0},center_left:{dx:0,dy:-height/2},center:{dx:-width/2,dy:-height/2},center_right:{dx:-width,dy:-height/2},bottom_left:{dx:0,dy:-height},bottom_center:{dx:-width/2,dy:-height},bottom_right:{dx:-width,dy:-height}},{dx:dx3,dy:dy3}=offsetMap[anchor],x02=text.x+dx3,y02=text.y+dy3;return[{x:x02,y:y02},{x:x02+width,y:y02+height}]})];return points.length===0?{minX:-1,maxX:1,minY:-1,maxY:1}:points.reduce((bounds,point7)=>({minX:Math.min(bounds.minX,point7.x),maxX:Math.max(bounds.maxX,point7.x),minY:Math.min(bounds.minY,point7.y),maxY:Math.max(bounds.maxY,point7.y)}),{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0})}init_src();var import_svgson=__toESM(require_svgson_umd(),1);init_src();function translateGraphics(graphics,dx3,dy3){return{...graphics,points:graphics.points?.map(p4=>({...p4,x:p4.x+dx3,y:p4.y+dy3})),lines:graphics.lines?.map(line2=>({...line2,points:line2.points.map(pt3=>({x:pt3.x+dx3,y:pt3.y+dy3}))})),infiniteLines:graphics.infiniteLines?.map(line2=>({...line2,origin:{x:line2.origin.x+dx3,y:line2.origin.y+dy3}})),polygons:graphics.polygons?.map(polygon2=>({...polygon2,points:polygon2.points.map(pt3=>({x:pt3.x+dx3,y:pt3.y+dy3}))})),rects:graphics.rects?.map(rect=>({...rect,center:{x:rect.center.x+dx3,y:rect.center.y+dy3}})),circles:graphics.circles?.map(circle2=>({...circle2,center:{x:circle2.center.x+dx3,y:circle2.center.y+dy3}})),arrows:graphics.arrows?.map(arrow=>({...arrow,start:{x:arrow.start.x+dx3,y:arrow.start.y+dy3},end:{x:arrow.end.x+dx3,y:arrow.end.y+dy3}})),texts:graphics.texts?.map(text=>({...text,x:text.x+dx3,y:text.y+dy3}))}}var mergeGraphics=(graphics1,graphics2)=>({...graphics1,rects:[...graphics1.rects??[],...graphics2.rects??[]],points:[...graphics1.points??[],...graphics2.points??[]],lines:[...graphics1.lines??[],...graphics2.lines??[]],infiniteLines:[...graphics1.infiniteLines??[],...graphics2.infiniteLines??[]],polygons:[...graphics1.polygons??[],...graphics2.polygons??[]],circles:[...graphics1.circles??[],...graphics2.circles??[]],arrows:[...graphics1.arrows??[],...graphics2.arrows??[]],texts:[...graphics1.texts??[],...graphics2.texts??[]]});function stackGraphicsHorizontally(graphicsList,opts={}){if(graphicsList.length===0)return{};let giantG=graphicsList[0],prevBounds=getBounds(giantG),baseMinY=prevBounds.minY,boundsList=[prevBounds];for(let i3=1;i3<graphicsList.length;i3++){let newG=graphicsList[i3],bounds=getBounds(newG),prevWidth=prevBounds.maxX-prevBounds.minX,width=bounds.maxX-bounds.minX,padding=(prevWidth+width)/8,dx3=prevBounds.maxX+padding-bounds.minX,dy3=baseMinY-bounds.minY,shifted=translateGraphics(newG,dx3,dy3);giantG=mergeGraphics(giantG,shifted),prevBounds=getBounds(shifted),boundsList.push(prevBounds)}if(opts.titles&&opts.titles.length>0){let overall=getBounds(giantG),fontSize=(overall.maxX-overall.minX)*.025,texts=opts.titles.slice(0,boundsList.length).map((title,idx)=>{let b3=boundsList[idx];return{x:(b3.minX+b3.maxX)/2,y:b3.maxY+fontSize,text:title,fontSize,anchorSide:"bottom_center"}});giantG=mergeGraphics(giantG,{texts})}return giantG}function stackGraphicsVertically(graphicsList,opts={}){if(graphicsList.length===0)return{};let result=graphicsList[0],prevBounds=getBounds(result),baseMinX=prevBounds.minX,boundsList=[prevBounds];for(let i3=1;i3<graphicsList.length;i3++){let g6=graphicsList[i3],bounds=getBounds(g6),prevHeight=prevBounds.maxY-prevBounds.minY,height=bounds.maxY-bounds.minY,padding=(prevHeight+height)/8,dx3=baseMinX-bounds.minX,dy3=prevBounds.minY-padding-bounds.maxY,shifted=translateGraphics(g6,dx3,dy3);result=mergeGraphics(result,shifted),prevBounds=getBounds(shifted),boundsList.push(prevBounds)}if(opts.titles&&opts.titles.length>0){let overall=getBounds(result),fontSize=(overall.maxY-overall.minY)*.025,texts=opts.titles.slice(0,boundsList.length).map((title,idx)=>{let b3=boundsList[idx];return{x:b3.minX-fontSize,y:b3.maxY,text:title,fontSize,anchorSide:"top_right"}});result=mergeGraphics(result,{texts})}return result}function setStepOfAllObjects(graphics,step){if(graphics.points)for(let p4 of graphics.points)p4.step=step;if(graphics.lines)for(let line2 of graphics.lines)line2.step=step;if(graphics.infiniteLines)for(let infiniteLine of graphics.infiniteLines)infiniteLine.step=step;if(graphics.polygons)for(let polygon2 of graphics.polygons)polygon2.step=step;if(graphics.rects)for(let rect of graphics.rects)rect.step=step;if(graphics.circles)for(let circle2 of graphics.circles)circle2.step=step;if(graphics.texts)for(let text of graphics.texts)text.step=step;return graphics}var import_debug4=__toESM(require_browser(),1);var center=obj=>obj?"x"in obj&&"y"in obj?obj:"center"in obj?obj.center:{x:(obj.minX+obj.maxX)/2,y:(obj.minY+obj.maxY)/2}:{x:0,y:0},getBoundsOfBpcBox=(graph,boxId)=>{let box2=graph.boxes.find(b3=>b3.boxId===boxId),pins=graph.pins.filter(p4=>p4.boxId===boxId);if(!box2)throw new Error(`Box "${boxId}" not found`);let boxCenter=box2.center??{x:0,y:0},minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0;for(let pin of pins)minX=Math.min(minX,pin.offset.x+boxCenter.x),minY=Math.min(minY,pin.offset.y+boxCenter.y),maxX=Math.max(maxX,pin.offset.x+boxCenter.x),maxY=Math.max(maxY,pin.offset.y+boxCenter.y);return{minX,minY,maxX,maxY}},getColorByIndex=(index,total,opacity)=>`hsl(${index*360/total}, 100%, 50%, ${opacity??1})`;var getGraphNetworkIds=g6=>{let networkIds=new Set;for(let pin of g6.pins)networkIds.add(pin.networkId);return Array.from(networkIds)},COLOR_MAPPINGS={not_connected:"rgba(0, 0, 0, 0.2)",normal:"blue",vcc:"orange",gnd:"purple",component_center:"gray"},COMMON_COLORS=["red","green","blue","yellow","purple","orange","brown","gray","black","white"];function hashString(str){let hash=0;for(let i3=0;i3<str.length;i3++)hash=(hash<<5)-hash+str.charCodeAt(i3);return hash}var translateColor=color=>color.startsWith("rgb")||color.startsWith("hsl")||color.startsWith("#")||COMMON_COLORS.includes(color)?color:color in COLOR_MAPPINGS?COLOR_MAPPINGS[color]:getColorByIndex(hashString(color)%50,50),getGraphicsForBpcGraph=(g6,opts)=>{let graphics={points:[],lines:[],rects:[],circles:[],texts:[],coordinateSystem:"cartesian",title:"BPC Graph Graphics"},pinPositions=new Map,positionGroups=new Map;for(let box2 of g6.boxes){let bounds2=getBoundsOfBpcBox(g6,box2.boxId),boundsCenter=center(bounds2);graphics.rects.push({label:box2.boxId,center:boundsCenter,width:bounds2.maxX-bounds2.minX+.1,height:bounds2.maxY-bounds2.minY+.1,fill:"rgba(0, 0, 0, 0.2)"});let boxPins=g6.pins.filter(p4=>p4.boxId===box2.boxId),boxCenter=box2.center??{x:0,y:0};for(let pin of boxPins){let pinPosition={x:pin.offset.x+boxCenter.x,y:pin.offset.y+boxCenter.y},positionKey=`${pinPosition.x.toFixed(6)},${pinPosition.y.toFixed(6)}`;positionGroups.has(positionKey)||positionGroups.set(positionKey,[]),positionGroups.get(positionKey).push({box:box2,pin}),pinPositions.set(`${box2.boxId}.${pin.pinId}`,pinPosition)}}for(let[positionKey,items]of positionGroups){let coordinates=positionKey.split(",").map(Number),baseX=coordinates[0],baseY=coordinates[1];for(let i3=0;i3<items.length;i3++){let item=items[i3],{box:box2,pin}=item,adjustedPosition={x:baseX,y:baseY};if(items.length>1){let boxCenter=box2.center??{x:0,y:0},directionX=boxCenter.x-baseX,directionY=boxCenter.y-baseY,distance8=Math.sqrt(directionX*directionX+directionY*directionY),unitX=0,unitY=0;if(distance8>0)unitX=directionX/distance8,unitY=directionY/distance8;else{let offsetAngle=i3*2*Math.PI/items.length;unitX=Math.cos(offsetAngle),unitY=Math.sin(offsetAngle)}adjustedPosition={x:baseX+.01*unitX,y:baseY+.01*unitY}}pinPositions.set(`${box2.boxId}.${pin.pinId}`,adjustedPosition),graphics.points.push({...adjustedPosition,label:[pin.pinId,pin.color,pin.networkId].join(`
|
|
648
648
|
`),color:translateColor(pin.color)})}}let networks=getGraphNetworkIds(g6);for(let ni3=0;ni3<networks.length;ni3++){let networkId=networks[ni3],networkColor=getColorByIndex(ni3,networks.length,.5),pinsInNetworkWithPosition=g6.pins.filter(p4=>p4.networkId===networkId).map(pin=>({pin,position:pinPositions.get(`${pin.boxId}.${pin.pinId}`)}));for(let i3=0;i3<pinsInNetworkWithPosition.length;i3++){let{position:pos1}=pinsInNetworkWithPosition[i3];for(let j4=i3+1;j4<pinsInNetworkWithPosition.length;j4++){let{position:pos2}=pinsInNetworkWithPosition[j4];graphics.lines.push({points:[pos1,pos2],strokeColor:opts?.grayNetworks?"rgba(0, 0, 0, 0.05)":networkColor})}}}let bounds=getBounds(graphics);return opts?.title&&(graphics.title=opts.title,graphics.texts.push({text:opts.title,x:bounds.minX,y:bounds.maxY,fontSize:(bounds.maxY-bounds.minY)*.05,anchorSide:"bottom_left"})),opts?.caption&&graphics.texts.push({text:opts.caption,x:bounds.minX,y:bounds.minY,fontSize:(bounds.maxY-bounds.minY)*.05,anchorSide:"top_left"}),graphics},getPinPosition=(g6,boxId,pinId)=>{let pin=g6.pins.find(p4=>p4.pinId===pinId&&p4.boxId===boxId);if(!pin)throw new Error(`Pin "${pinId}" not found`);let box2=g6.boxes.find(b3=>b3.boxId===pin.boxId);if(!box2)throw new Error(`Box "${pin.boxId}" not found`);let boxCenter=box2.center??{x:0,y:0};return{x:pin.offset.x+boxCenter.x,y:pin.offset.y+boxCenter.y}},getPinDirectionOrThrow=(g6,boxIdOrBox,pinIdOrPin)=>{let pin=typeof pinIdOrPin=="string"?g6.pins.find(p4=>p4.pinId===pinIdOrPin&&p4.boxId===boxIdOrBox):pinIdOrPin;if(!pin)throw new Error(`Pin not found "${pinIdOrPin}"`);if(!(typeof boxIdOrBox=="string"?g6.boxes.find(b3=>b3.boxId===boxIdOrBox):boxIdOrBox))throw new Error(`Box not found for pin "${pinIdOrPin}" (looked for "${pin.boxId}")`);let bounds=getBoundsOfBpcBox(g6,pin.boxId),pinPosition=getPinPosition(g6,pin.boxId,pin.pinId),width=bounds.maxX-bounds.minX,height=bounds.maxY-bounds.minY;if(width===0&&height===0)return Math.abs(pin.offset.x)>Math.abs(pin.offset.y)?pin.offset.x>0?"x+":"x-":pin.offset.y>0?"y+":"y-";if(width===0){if(Math.abs(pinPosition.y-bounds.minY)<1e-4)return"y-";if(Math.abs(pinPosition.y-bounds.maxY)<1e-4)return"y+"}if(height===0){if(Math.abs(pinPosition.x-bounds.minX)<1e-4)return"x-";if(Math.abs(pinPosition.x-bounds.maxX)<1e-4)return"x+"}let onLeftEdge=Math.abs(pinPosition.x-bounds.minX)<1e-4,onRightEdge=Math.abs(pinPosition.x-bounds.maxX)<1e-4,onBottomEdge=Math.abs(pinPosition.y-bounds.minY)<1e-4,onTopEdge=Math.abs(pinPosition.y-bounds.maxY)<1e-4;if((onLeftEdge||onRightEdge)&&(onBottomEdge||onTopEdge))return pin.offset.x>0?"x+":"x-";if(onLeftEdge)return"x-";if(onRightEdge)return"x+";if(onBottomEdge)return"y-";if(onTopEdge)return"y+";throw new Error(`Pin "${pin.pinId}" not on the edge of the box "${pin.boxId}" so we couldn't determine the direction`)},getPinDirection=(g6,boxIdOrBox,pinIdOrPin)=>{try{return getPinDirectionOrThrow(g6,boxIdOrBox,pinIdOrPin)}catch{return null}};var getAdjacencyMatrixFromFlatBpcGraph=flatBpcGraph=>{let nodeIdToIndex=new Map,indexMapping=[];flatBpcGraph.nodes.forEach((node,idx)=>{nodeIdToIndex.set(node.id,idx),indexMapping.push(node.id)});let N4=flatBpcGraph.nodes.length,matrix2=Array.from({length:N4},()=>Array.from({length:N4},()=>0));for(let[id1,id2]of flatBpcGraph.undirectedEdges){let i3=nodeIdToIndex.get(id1),j4=nodeIdToIndex.get(id2);i3!==void 0&&j4!==void 0&&i3!==j4&&(matrix2[i3][j4]=1,matrix2[j4][i3]=1)}for(let i3=0;i3<N4;++i3)matrix2[i3][i3]=1;return{matrix:matrix2,mapping:nodeIdToIndex,indexMapping}};var convertToFlatBpcGraph=mixed=>{var _a497;let nodes=[],undirectedEdges=[],boxCenterMap=new Map;for(let box2 of mixed.boxes)box2.kind,boxCenterMap.set(box2.boxId,box2.center),nodes.push({id:box2.boxId,boxId:box2.boxId,color:"box",x:box2.center?.x,y:box2.center?.y});let pinsByNetwork={};for(let pin of mixed.pins){let nodeId=`${pin.boxId}-${pin.pinId}`,bCenter=boxCenterMap.get(pin.boxId);nodes.push({id:nodeId,boxId:pin.boxId,pinId:pin.pinId,color:pin.color,x:bCenter?bCenter.x+pin.offset.x:void 0,y:bCenter?bCenter.y+pin.offset.y:void 0}),pinsByNetwork[_a497=pin.networkId]??(pinsByNetwork[_a497]=[]),pinsByNetwork[pin.networkId].push(nodeId)}for(let nodeIds of Object.values(pinsByNetwork))for(let i3=0;i3<nodeIds.length;i3++)for(let j4=i3+1;j4<nodeIds.length;j4++)undirectedEdges.push([nodeIds[i3],nodeIds[j4]]);for(let box2 of mixed.boxes)for(let pin of mixed.pins)pin.boxId===box2.boxId&&undirectedEdges.push([box2.boxId,`${box2.boxId}-${pin.pinId}`]);return{nodes,undirectedEdges}},wlFeatureVec=(adjMatrix,K3,opts={})=>{let n4=adjMatrix.length;if(adjMatrix.some(row=>row.length!==n4))throw new Error("adjMatrix must be square");let colors=(opts.nodeInitialColors??Array.from({length:n4},()=>"_")).slice(),getCounts=cols=>{let counts={};for(let c4 of cols)counts[c4]=(counts[c4]??0)+1;return counts},countsArr=[];countsArr.push(getCounts(colors));for(let step=0;step<K3;step++){let next2=Array(n4);for(let v4=0;v4<n4;v4++){let neigh=[];for(let u5=0;u5<n4;u5++)adjMatrix[v4][u5]&&neigh.push(colors[u5]);neigh.sort(),next2[v4]=`${colors[v4]}|${neigh.join(",")}`}colors=next2,countsArr.push(getCounts(colors))}return countsArr},wlVecWeightedJaccardSimilarity=(wlFeatureVec1,wlFeatureVec2)=>{let total=0,len=Math.min(wlFeatureVec1.length,wlFeatureVec2.length);for(let i3=0;i3<len;i3++){let rec1=wlFeatureVec1[i3],rec2=wlFeatureVec2[i3],allKeys=new Set([...Object.keys(rec1),...Object.keys(rec2)]),sumMin=0,sumMax=0;for(let k4 of allKeys){let v12=rec1[k4]??0,v22=rec2[k4]??0;sumMin+=Math.min(v12,v22),sumMax+=Math.max(v12,v22)}total+=sumMax===0?0:sumMin/sumMax}return total};var getWlDotProduct=wlVecWeightedJaccardSimilarity,DEFAULT_WL_DEGREES=2,getWlFeatureVecs=(g6,wlDegrees=DEFAULT_WL_DEGREES)=>{let flatBpc=convertToFlatBpcGraph(g6),{matrix:matrix2,indexMapping}=getAdjacencyMatrixFromFlatBpcGraph(flatBpc);return wlFeatureVec(matrix2,wlDegrees,{nodeInitialColors:indexMapping.map(id2=>flatBpc.nodes.find(n4=>n4.id===id2)?.color??"_")})},getBpcGraphWlDistance=(g12,g22,{wlDegrees=DEFAULT_WL_DEGREES}={})=>{let wlVec1=getWlFeatureVecs(g12,wlDegrees),wlVec2=getWlFeatureVecs(g22,wlDegrees);return(DEFAULT_WL_DEGREES+1-getWlDotProduct(wlVec1,wlVec2))/(DEFAULT_WL_DEGREES+1)},hashStringToNumber=str=>{let hash=0;for(let i3=0;i3<str.length;i3++)hash=(hash<<5)-hash+str.charCodeAt(i3);return Math.abs(hash)},convertFlatBpcToGraphics=(flat,opts={})=>{let gfx={points:[],lines:[],rects:[],circles:[],texts:[],coordinateSystem:"cartesian",title:"Flat-BPC Graphics"},pos=new Map;for(let n4 of flat.nodes){if(n4.x===void 0||n4.y===void 0)continue;let p4={x:n4.x,y:n4.y};pos.set(n4.id,p4),gfx.points.push({...p4,color:translateColor(n4.color),label:n4.id})}for(let[a3,b3]of flat.undirectedEdges){let pa3=pos.get(a3),pb2=pos.get(b3);pa3&&pb2&&gfx.lines.push({points:[pa3,pb2],strokeColor:"rgba(0,0,0,0.3)"})}let bounds=getBounds(gfx);return opts.title&&gfx.texts.push({text:opts.title,x:bounds.minX,y:bounds.maxY,fontSize:(bounds.maxY-bounds.minY)*.05,anchorSide:"bottom_left"}),opts.caption&&gfx.texts.push({text:opts.caption,x:bounds.minX,y:bounds.minY,fontSize:(bounds.maxY-bounds.minY)*.05,anchorSide:"top_left"}),gfx};var getTotalNetworkLength=g6=>{let networkPins=new Map;for(let pin of g6.pins){let box2=g6.boxes.find(b3=>b3.boxId===pin.boxId);if(!box2||!box2.center)throw new Error(`Expected fixed graph \u2013 box "${pin.boxId}" missing or has no center`);let pos={x:box2.center.x+pin.offset.x,y:box2.center.y+pin.offset.y};networkPins.has(pin.networkId)||networkPins.set(pin.networkId,[]),networkPins.get(pin.networkId).push(pos)}let networkLengths=new Map,totalNetworkLength=0;for(let[netId,positions]of networkPins){if(positions.length===0){networkLengths.set(netId,0);continue}let centre=positions.reduce((acc,p4)=>({x:acc.x+p4.x,y:acc.y+p4.y}),{x:0,y:0});centre.x/=positions.length,centre.y/=positions.length;let len=positions.reduce((sum,p4)=>{let dx3=p4.x-centre.x,dy3=p4.y-centre.y;return sum+Math.sqrt(dx3*dx3+dy3*dy3)},0);networkLengths.set(netId,len),totalNetworkLength+=len}return{totalNetworkLength,networkLengths}},computeBagOfAnglesForNetwork=(g6,networkId)=>{let pins=g6.pins.filter(p4=>p4.networkId===networkId),angles=[];for(let pin of pins){let pinAngle=Math.atan2(pin.offset.y,pin.offset.x);angles.push(pinAngle)}return angles},computeGraphNetworkBagOfAnglesMap=g6=>{let map=new Map,networks=Array.from(new Set(g6.pins.map(p4=>p4.networkId)));for(let networkId of networks){let angles=computeBagOfAnglesForNetwork(g6,networkId);map.set(networkId,angles)}return map},circularDistance=(a3,b3)=>{let TAU=2*Math.PI,normA=(a3%TAU+TAU)%TAU,normB=(b3%TAU+TAU)%TAU,diff=Math.abs(normA-normB);return Math.min(diff,TAU-diff)},computeBagOfAnglesDistance=(bag1,bag2)=>{if(bag1.length===0&&bag2.length===0)return 0;if(bag1.length===0||bag2.length===0)return Math.PI;let avgNearest=(src,tgt)=>{let sum=0;for(let a3 of src){let best=1/0;for(let b3 of tgt){let d4=circularDistance(a3,b3);d4<best&&(best=d4)}sum+=best}return sum/src.length};return(avgNearest(bag1,bag2)+avgNearest(bag2,bag1))/2},computeNetworkMappingFromBagsOfAngles=(bag1,bag2)=>{let networkMapping=new Map,bag1Entries=Array.from(bag1.entries()),bag2Entries=Array.from(bag2.entries()),n12=bag1Entries.length,n22=bag2Entries.length,distanceMatrix=Array.from({length:n12},()=>new Array(n22).fill(0));for(let i3=0;i3<n12;i3++){let[,angles1]=bag1Entries[i3];for(let j4=0;j4<n22;j4++){let[,angles2]=bag2Entries[j4];distanceMatrix[i3][j4]=computeBagOfAnglesDistance(angles1,angles2)}}let unmapped1=new Set(Array.from({length:n12},(_4,i3)=>i3)),unmapped2=new Set(Array.from({length:n22},(_4,i3)=>i3)),totalDistance=0;for(;unmapped1.size&&unmapped2.size;){let bestI=-1,bestJ=-1,bestD=1/0;for(let i3 of unmapped1)for(let j4 of unmapped2){let d4=distanceMatrix[i3][j4];d4<bestD&&(bestD=d4,bestI=i3,bestJ=j4)}let[net1]=bag1Entries[bestI],[net2]=bag2Entries[bestJ];networkMapping.set(net1,net2),totalDistance+=bestD,unmapped1.delete(bestI),unmapped2.delete(bestJ)}let UNMATCHED_PENALTY=Math.PI;return totalDistance+=(unmapped1.size+unmapped2.size)*UNMATCHED_PENALTY,{networkMapping,distance:totalDistance}},getBoundsOfPinList=pins=>{let minX=Math.min(...pins.map(p4=>p4.offset.x)),maxX=Math.max(...pins.map(p4=>p4.offset.x)),minY=Math.min(...pins.map(p4=>p4.offset.y)),maxY=Math.max(...pins.map(p4=>p4.offset.y));return{minX,maxX,minY,maxY}},getNormalizedPerimeterDistance=(A4,B4)=>{let posToScalar=p4=>{switch(p4.side){case"x+":return p4.cwDistanceFromCorner;case"y-":return 1+p4.cwDistanceFromCorner;case"x-":return 2+p4.cwDistanceFromCorner;case"y+":return 3+p4.cwDistanceFromCorner}},a3=posToScalar(A4)%4,b3=posToScalar(B4)%4,cwDistance=(b3-a3+4)%4,ccwDistance=(a3-b3+4)%4,minDistance=Math.min(cwDistance,ccwDistance);return{cwDistance,ccwDistance,minDistance}},EPS=1e-6,getNormalizedPerimeterPosition=(bounds,position4)=>{let{minX,minY,maxX,maxY}=bounds,near=(a3,b3)=>Math.abs(a3-b3)<EPS,side,cwDistanceFromCorner;if(near(position4.x,maxX)&&position4.y>=minY-EPS&&position4.y<=maxY+EPS)side="x+",cwDistanceFromCorner=(maxY-position4.y)/(maxY-minY);else if(near(position4.y,maxY)&&position4.x<=maxX+EPS&&position4.x>=minX-EPS)side="y+",cwDistanceFromCorner=(position4.x-minX)/(maxX-minX);else if(near(position4.x,minX)&&position4.y<=maxY+EPS&&position4.y>=minY-EPS)side="x-",cwDistanceFromCorner=(position4.y-minY)/(maxY-minY);else if(near(position4.y,minY)&&position4.x>=minX-EPS&&position4.x<=maxX+EPS)side="y-",cwDistanceFromCorner=(maxX-position4.x)/(maxX-minX);else return null;return cwDistanceFromCorner=Math.min(1,Math.max(0,cwDistanceFromCorner)),{side,cwDistanceFromCorner}},matchPins=(pinList1,pinList2)=>{let matchedPins=[],unmatchedPin1Ids=new Set,unmatchedPin2Ids=new Set,matchedPin1Ids=new Set,matchedPin2Ids=new Set,bounds1=getBoundsOfPinList(pinList1),bounds2=getBoundsOfPinList(pinList2);for(let pin1 of pinList1){let matchingPinsByColor=pinList2.filter(p22=>p22.color===pin1.color).filter(p22=>!matchedPin2Ids.has(p22.pinId));if(matchingPinsByColor.length===0){unmatchedPin1Ids.add(pin1.pinId);continue}let normalizedPerimeterPosition1=getNormalizedPerimeterPosition(bounds1,pin1.offset);if(normalizedPerimeterPosition1===null){unmatchedPin1Ids.add(pin1.pinId);continue}let bestPerimeterDistance=1/0,bestMatchingPin2=matchingPinsByColor[0];for(let pin2 of matchingPinsByColor){let normalizedPerimeterPosition2=getNormalizedPerimeterPosition(bounds2,pin2.offset);if(normalizedPerimeterPosition2===null)continue;let{minDistance}=getNormalizedPerimeterDistance(normalizedPerimeterPosition1,normalizedPerimeterPosition2);minDistance<bestPerimeterDistance&&(bestPerimeterDistance=minDistance,bestMatchingPin2=pin2)}matchedPins.push([pin1,bestMatchingPin2]),matchedPin1Ids.add(pin1.pinId),matchedPin2Ids.add(bestMatchingPin2.pinId)}for(let pin2 of pinList2)matchedPin2Ids.has(pin2.pinId)||unmatchedPin2Ids.add(pin2.pinId);return{matchedPins,unmatchedPin1Ids,unmatchedPin2Ids}},AssignmentSolver2=class{constructor(floatingGraph,fixedGraph){__publicField(this,"wipGraph");__publicField(this,"iterations",0);__publicField(this,"solved",!1);__publicField(this,"acceptedFloatingBoxIds",new Set);__publicField(this,"rejectedFloatingBoxIds",new Set);__publicField(this,"acceptedFixedBoxIds",new Set);__publicField(this,"assignment",new Map);__publicField(this,"lastAcceptedEvaluation",null);__publicField(this,"fixedToFloatingNetworkMap");__publicField(this,"floatingToFixedNetworkMap");__publicField(this,"lastComputedEvaluations",[]);this.floatingGraph=floatingGraph,this.fixedGraph=fixedGraph,this.wipGraph={pins:[],boxes:[]},this.fixedToFloatingNetworkMap=this.computeFixedToFloatingNetworkMap(),this.floatingToFixedNetworkMap=new Map(Array.from(this.fixedToFloatingNetworkMap.entries()).map(([k4,v4])=>[v4,k4]))}computeFixedToFloatingNetworkMap(){let floatingBagOfAnglesMap=computeGraphNetworkBagOfAnglesMap(this.floatingGraph),fixedBagOfAnglesMap=computeGraphNetworkBagOfAnglesMap(this.fixedGraph),{networkMapping}=computeNetworkMappingFromBagsOfAngles(fixedBagOfAnglesMap,floatingBagOfAnglesMap);return networkMapping}getNextFloatingBoxId(){let remainingFloatingBoxIds=this.floatingGraph.boxes.map(b3=>b3.boxId).filter(b3=>!this.acceptedFloatingBoxIds.has(b3)&&!this.rejectedFloatingBoxIds.has(b3));if(!remainingFloatingBoxIds.length)throw new Error("No remaining floating box ids");let bestFloatingBoxId=remainingFloatingBoxIds[0],bestFloatingBoxPinCount=0;for(let floatingBoxId of remainingFloatingBoxIds){let floatingBoxPins=this.floatingGraph.pins.filter(p4=>p4.boxId===floatingBoxId);floatingBoxPins.length>bestFloatingBoxPinCount&&(bestFloatingBoxId=floatingBoxId,bestFloatingBoxPinCount=floatingBoxPins.length)}return bestFloatingBoxId}getRemainingFloatingBoxIds(){return this.floatingGraph.boxes.map(b3=>b3.boxId).filter(b3=>!this.acceptedFloatingBoxIds.has(b3)&&!this.rejectedFloatingBoxIds.has(b3))}getPartialFloatingGraph(nextFloatingBoxId){let g6={pins:[],boxes:[]};for(let box2 of this.floatingGraph.boxes)(this.acceptedFloatingBoxIds.has(box2.boxId)||box2.boxId===nextFloatingBoxId)&&(g6.boxes.push(box2),g6.pins.push(...this.floatingGraph.pins.filter(p4=>p4.boxId===box2.boxId)));return g6}evaluateFloatingBoxAssignment(nextFloatingBoxId){let partialFloatingGraph=this.getPartialFloatingGraph(nextFloatingBoxId),currentWlDist=getBpcGraphWlDistance(partialFloatingGraph,this.wipGraph),bestFixedBoxId=null,bestNewWipGraph=null,dEval={floatingBoxId:nextFloatingBoxId,originalWipGraph:this.wipGraph,partialFloatingGraph,currentWlDist,networkLengths:new Map,wlDistances:new Map,wlVecs:new Map,wipGraphsWithAddedFixedBoxId:new Map},bestDist=currentWlDist,bestWlDist=currentWlDist,bestTotalNetworkLength=1/0,floatingBoxWlVec=getWlFeatureVecs(partialFloatingGraph);for(let fixedBoxId of this.fixedGraph.boxes.map(b3=>b3.boxId)){if(this.acceptedFixedBoxIds.has(fixedBoxId))continue;let wipGraphWithAddedFixedBoxId=this.getWipGraphWithAddedFixedBoxIdForFloatingAssignment(fixedBoxId,nextFloatingBoxId),wlDist=getBpcGraphWlDistance(partialFloatingGraph,wipGraphWithAddedFixedBoxId),debug_wlVec=getWlFeatureVecs(wipGraphWithAddedFixedBoxId),{totalNetworkLength}=getTotalNetworkLength(wipGraphWithAddedFixedBoxId);dEval.wipGraphsWithAddedFixedBoxId.set(fixedBoxId,wipGraphWithAddedFixedBoxId),dEval.wlVecs.set(fixedBoxId,debug_wlVec),dEval.wlDistances.set(fixedBoxId,wlDist),dEval.networkLengths.set(fixedBoxId,totalNetworkLength);let dist=wlDist+totalNetworkLength/100;dist<bestDist&&(bestDist=dist,bestWlDist=wlDist,bestTotalNetworkLength=totalNetworkLength,bestNewWipGraph=wipGraphWithAddedFixedBoxId,bestFixedBoxId=fixedBoxId)}return{bestFixedBoxId,bestNewWipGraph,bestDist,bestWlDist,bestTotalNetworkLength,lastDistanceEvaluation:dEval,nextFloatingBoxId,partialFloatingGraph,floatingBoxWlVec}}getPinAssignment(){let pinAssignment={},fixedToFloatingBoxAssignment={};for(let[floatingBoxId,fixedBoxId]of this.assignment)pinAssignment[floatingBoxId]={},fixedToFloatingBoxAssignment[fixedBoxId]=floatingBoxId;for(let pin of this.wipGraph.pins){let fixedBoxId=pin.boxId,floatingBoxId=fixedToFloatingBoxAssignment[fixedBoxId],floatingPinId=pin._floatingPinId,fixedPinId=pin._fixedPinId;pinAssignment[floatingBoxId][floatingPinId]=fixedPinId}return pinAssignment}step(){if(this.solved)return;if(this.iterations>1e3)throw new Error("Too many iterations");if(this.iterations++,this.iterations===1){let nextFloatingBoxId=this.getNextFloatingBoxId(),evalResult=this.evaluateFloatingBoxAssignment(nextFloatingBoxId);this.lastComputedEvaluations=[evalResult],this.acceptEvaluationResult(evalResult);return}let remainingFloatingBoxIds=this.getRemainingFloatingBoxIds();if(remainingFloatingBoxIds.length===0){this.solved=!0;return}let bestEvalDist=1/0,bestEvalResult=null;this.lastComputedEvaluations=[];for(let floatingBoxId of remainingFloatingBoxIds){let evalResult=this.evaluateFloatingBoxAssignment(floatingBoxId);this.lastComputedEvaluations.push(evalResult),evalResult.bestDist<bestEvalDist&&(bestEvalDist=evalResult.bestDist,bestEvalResult=evalResult)}bestEvalResult&&this.acceptEvaluationResult(bestEvalResult)}acceptEvaluationResult(evalResult){let{bestFixedBoxId,bestNewWipGraph,nextFloatingBoxId}=evalResult;if(bestFixedBoxId===null){this.rejectedFloatingBoxIds.add(nextFloatingBoxId);return}this.acceptedFloatingBoxIds.add(nextFloatingBoxId),this.assignment.set(nextFloatingBoxId,bestFixedBoxId),this.acceptedFixedBoxIds.add(bestFixedBoxId),this.wipGraph=bestNewWipGraph,this.lastAcceptedEvaluation=evalResult.lastDistanceEvaluation}getWipGraphWithAddedFixedBoxIdForFloatingAssignment(fixedBoxId,floatingBoxId){let g6=structuredClone(this.wipGraph),boxToAdd=this.fixedGraph.boxes.find(b3=>b3.boxId===fixedBoxId);g6.boxes.push(boxToAdd);let floatingBoxPins=this.floatingGraph.pins.filter(p4=>p4.boxId===floatingBoxId),fixedBoxPins=this.fixedGraph.pins.filter(p4=>p4.boxId===fixedBoxId),{matchedPins}=matchPins(floatingBoxPins,fixedBoxPins);return g6.pins.push(...matchedPins.map(p4=>{let[floatingPin,fixedPin]=p4;return{...fixedPin,networkId:this.floatingToFixedNetworkMap.get(floatingPin.networkId),_floatingPinId:floatingPin.pinId,_fixedPinId:fixedPin.pinId}})),g6}visualize(){let floatingGraphics=getGraphicsForBpcGraph(this.floatingGraph,{title:"Floating"}),wipGraphics=getGraphicsForBpcGraph(this.wipGraph,{title:"WIP"}),fixedGraphics=getGraphicsForBpcGraph(this.fixedGraph,{title:"Fixed"}),floatingPartialGraphics=getGraphicsForBpcGraph(this.getPartialFloatingGraph(),{title:"Partial Floating"}),colorByFloatingId=new Map,fixedToFloating=new Map;for(let[floatId,fixedId]of this.assignment){let colour=getColorByIndex(hashStringToNumber(floatId)*47%100,100,.5);colorByFloatingId.set(floatId,colour),fixedToFloating.set(fixedId,floatId)}function decorateRect(rect,floatId,fixedId){let colour=colorByFloatingId.get(floatId);rect.fill=colour,rect.label=`${floatId}\u2192${fixedId}`}for(let rect of floatingGraphics.rects??[]){let floatId=rect.label;if(!floatId)continue;let fixedId=this.assignment.get(floatId);fixedId&&decorateRect(rect,floatId,fixedId)}for(let rect of floatingPartialGraphics.rects??[]){let floatId=rect.label;if(!floatId)continue;let fixedId=this.assignment.get(floatId);fixedId&&decorateRect(rect,floatId,fixedId)}let targetGraphics=[wipGraphics,fixedGraphics];for(let g6 of targetGraphics)for(let rect of g6.rects??[]){let fixedId=rect.label;if(!fixedId)continue;let floatId=fixedToFloating.get(fixedId);floatId&&decorateRect(rect,floatId,fixedId)}let floatingFlatG=convertToFlatBpcGraph(this.floatingGraph),wipFlatG=convertToFlatBpcGraph(this.wipGraph),fixedFlatG=convertToFlatBpcGraph(this.fixedGraph),floatingFlatGraphics=convertFlatBpcToGraphics(floatingFlatG,{title:"Floating Flat"}),wipFlatGraphics=convertFlatBpcToGraphics(wipFlatG,{title:"WIP Flat"}),fixedFlatGraphics=convertFlatBpcToGraphics(fixedFlatG,{title:"Fixed Flat"});return stackGraphicsHorizontally([stackGraphicsVertically([floatingGraphics,floatingFlatGraphics,floatingPartialGraphics]),stackGraphicsVertically([wipGraphics,wipFlatGraphics]),stackGraphicsVertically([fixedGraphics,fixedFlatGraphics])])}},getApproximateAssignments2=(floatingGraph,fixedGraph)=>{let solver=new AssignmentSolver2(floatingGraph,fixedGraph);for(;!solver.solved&&solver.iterations<1e3;)solver.step();let boxAssignment={};for(let[floatingBoxId,fixedBoxId]of solver.assignment.entries())boxAssignment[floatingBoxId]=fixedBoxId;let networkAssignment={};for(let[floatingNetId,fixedNetId]of solver.floatingToFixedNetworkMap.entries())networkAssignment[floatingNetId]=fixedNetId;let pinAssignment=solver.getPinAssignment();return{floatingToFixedBoxAssignment:boxAssignment,floatingToFixedNetworkAssignment:networkAssignment,floatingToFixedPinAssignment:pinAssignment}};var mergeBoxSideSubgraphs=(graphs,{renetworkedNetworkIdMap}={})=>{if(renetworkedNetworkIdMap??(renetworkedNetworkIdMap={}),graphs.length===1)return graphs[0];let merged={boxes:[],pins:[]},boxMap=new Map,pinMap=new Map,partitionedBoxIds=Object.entries(graphs.flatMap(g6=>Array.from(new Set(g6.boxes.map(b3=>b3.boxId)))).reduce((acc,str)=>(acc[str]=(acc[str]||0)+1,acc),{})).filter(([_4,count])=>count===graphs.length).map(([str])=>str);if(partitionedBoxIds.length>1)throw new Error(`Expected at most one shared box across all partitions, the following box ids are shared across all graphs: ${partitionedBoxIds.join(", ")}`);let partitionedBoxId=partitionedBoxIds[0];for(let g6 of graphs){let offset=g6.boxes.find(b3=>b3.boxId===partitionedBoxId)?.center;for(let box2 of g6.boxes){if(boxMap.has(box2.boxId))continue;let modifiedBox=structuredClone(box2);modifiedBox.center&&offset&&(modifiedBox.center={x:modifiedBox.center.x-offset.x,y:modifiedBox.center.y-offset.y}),boxMap.set(box2.boxId,modifiedBox)}for(let pin of g6.pins)pinMap.has(`${pin.boxId}-${pin.pinId}`)||pinMap.set(`${pin.boxId}-${pin.pinId}`,structuredClone(pin))}return merged.boxes=Array.from(boxMap.values()),merged.pins=Array.from(pinMap.values()),merged};var reflectGraph=({graph,axis,centerBoxId})=>{let newGraph=structuredClone(graph),centreBox=newGraph.boxes.find(b3=>b3.boxId===centerBoxId);if(!centreBox||!centreBox.center)throw new Error(`Center box "${centerBoxId}" not found or has no center`);let{x:cx3,y:cy3}=centreBox.center;for(let box2 of newGraph.boxes)box2.center&&(axis==="x"?box2.center.x=2*cx3-box2.center.x:box2.center.y=2*cy3-box2.center.y);for(let pin of newGraph.pins)axis==="x"?pin.offset.x=-pin.offset.x:pin.offset.y=-pin.offset.y;return newGraph},getCanonicalRightFacingGraph=g6=>{let largestLeftRightBox=null,largestLeftRightBoxPins=-1/0;for(let box2 of g6.boxes){let lrPins2=g6.pins.filter(p4=>p4.boxId===box2.boxId).filter(p4=>["x-","x+"].includes(getPinDirection(g6,box2,p4)??"none"));lrPins2.length>largestLeftRightBoxPins&&lrPins2.length>1&&(largestLeftRightBox=box2,largestLeftRightBoxPins=lrPins2.length)}if(!largestLeftRightBox)return{g:g6,reflected:!1,centerBoxId:null};let largestBoxLRPinDirections=g6.pins.filter(p4=>p4.boxId===largestLeftRightBox.boxId).map(p4=>getPinDirection(g6,largestLeftRightBox,p4)),dirCounts={"x+":0,"x-":0,"y+":0,"y-":0};for(let dir2 of largestBoxLRPinDirections)dir2&&dirCounts[dir2]++;return dirCounts["x+"]>=dirCounts["x-"]?{g:g6,reflected:!1,centerBoxId:largestLeftRightBox.boxId}:{g:reflectGraph({graph:g6,axis:"x",centerBoxId:largestLeftRightBox.boxId}),reflected:!0,centerBoxId:largestLeftRightBox.boxId}},debug4=(0,import_debug4.default)("schematic-partition-processor"),SchematicPartitionProcessor=class{constructor(initialGraph,opts={}){__publicField(this,"lastGraph");__publicField(this,"lastExploredPin");__publicField(this,"solved",!1);__publicField(this,"iteration",0);__publicField(this,"wipPartitions");__publicField(this,"unexploredPins",[]);__publicField(this,"boxSingletonKeys");__publicField(this,"exploredPins");__publicField(this,"addedPins");__publicField(this,"allAcceptedPins",new Set);__publicField(this,"pinConnectionCount");__publicField(this,"networkSize");__publicField(this,"pinNetworkSize");__publicField(this,"splitBoxIds");__publicField(this,"acceptedBoxPartitionMap",new Map);__publicField(this,"singletonKeys");__publicField(this,"centerPinColors");this.initialGraph=initialGraph,this.lastGraph=initialGraph,this.singletonKeys=opts.singletonKeys??[],this.centerPinColors=opts.centerPinColors??[];let partitionInit=this.initializeWipPartitions();this.wipPartitions=partitionInit.wipPartitions,this.splitBoxIds=partitionInit.splitBoxIds,this.addedPins=partitionInit.addedPins,this.exploredPins=new Set,this.unexploredPins=this.wipPartitions.flatMap(part=>part.pins.map(p4=>({...p4,partitionId:part.partitionId}))),this.boxSingletonKeys=this.initializeBoxSingletonKeys(),this.pinConnectionCount=(()=>{let counts={};for(let pin of this.initialGraph.pins)counts[`${pin.boxId}:${pin.pinId}`]=this.getNeighbors(pin).length;return counts})();let netCounts={};for(let p4 of this.initialGraph.pins)netCounts[p4.networkId]=(netCounts[p4.networkId]??0)+1;this.networkSize=netCounts;let pNetSize={};for(let p4 of this.initialGraph.pins)pNetSize[`${p4.boxId}:${p4.pinId}`]=netCounts[p4.networkId];this.pinNetworkSize=pNetSize}initializeBoxSingletonKeys(){let boxSingletonKeys={};for(let box2 of this.initialGraph.boxes){let boxPins=this.initialGraph.pins.filter(p4=>p4.boxId===box2.boxId),boxPinCount=boxPins.length,singletonKeysForBox=boxPins.map(p4=>`${p4.color}/${boxPinCount}`).filter(k4=>this.singletonKeys.includes(k4));boxSingletonKeys[box2.boxId]=new Set(singletonKeysForBox)}return boxSingletonKeys}initializeWipPartitions(){let wipPartitions=[],addedPins=new Set,splitBoxIds=new Set,partitionId=0;for(let box2 of this.initialGraph.boxes){let pins=this.initialGraph.pins.filter(p4=>p4.boxId===box2.boxId).filter(p4=>getPinDirection(this.initialGraph,box2,p4)).filter(p4=>!this.centerPinColors.includes(p4.color));if(pins.length<4)continue;let uniqueDirections=new Set(pins.map(p4=>getPinDirection(this.initialGraph,box2,p4)));uniqueDirections.size>1&&splitBoxIds.add(box2.boxId);for(let direction2 of uniqueDirections){let partition={partitionId:`partition${partitionId++}`,filledSingletonSlots:new Set,pins:[]};for(let pin of pins)getPinDirection(this.initialGraph,box2,pin)===direction2&&(partition.pins.push({boxId:box2.boxId,pinId:pin.pinId}),addedPins.add(`${box2.boxId}:${pin.pinId}`));wipPartitions.push(partition)}}return wipPartitions.length===0&&(wipPartitions.push(this.createWipPartitionFromEntireGraph()),this.solved=!0),debug4(`splitBoxIds = ${Array.from(splitBoxIds).join(", ")}`),debug4(`wipPartitions = ${wipPartitions.map(p4=>p4.partitionId).join(", ")}`),{wipPartitions,splitBoxIds,addedPins}}createWipPartitionFromEntireGraph(){return{partitionId:"entire-graph",filledSingletonSlots:new Set,pins:this.initialGraph.pins.map(p4=>({boxId:p4.boxId,pinId:p4.pinId}))}}step(){if(this.solved)return;if(this.iteration++,debug4(`
|
|
649
|
-
\u2500\u2500 Iteration ${this.iteration} \u2500\u2500 unexplored=${this.unexploredPins.length} explored=${this.exploredPins.size}`),this.unexploredPins.sort((a3,b3)=>{let aKey=`${a3.boxId}:${a3.pinId}`,bKey=`${b3.boxId}:${b3.pinId}`,netDiff=this.pinNetworkSize[aKey]-this.pinNetworkSize[bKey];return netDiff!==0?netDiff:this.pinConnectionCount[aKey]-this.pinConnectionCount[bKey]}),this.unexploredPins.length===0){this.solved=!0;return}let current3=this.unexploredPins.shift(),currentPinKey=`${current3.boxId}:${current3.pinId}`;debug4(`Exploring pin ${current3.boxId}:${current3.pinId} for partition "${current3.partitionId}"`),this.lastExploredPin={...current3,partitionId:current3.partitionId};let currentPinPartitionKey=`${current3.partitionId}[${currentPinKey}]`,currentPin=this.initialGraph.pins.find(p4=>p4.boxId===current3.boxId&&p4.pinId===current3.pinId);if(!currentPin||this.exploredPins.has(currentPinPartitionKey))return;let currentPartition=this.wipPartitions.find(p4=>p4.partitionId===current3.partitionId);if(!currentPartition)return;let pinAlreadyAcceptedIntoPartitionId=this.acceptedBoxPartitionMap.get(current3.boxId);if(pinAlreadyAcceptedIntoPartitionId&&pinAlreadyAcceptedIntoPartitionId!==current3.partitionId&&!this.splitBoxIds.has(current3.boxId)){debug4(` \u21B3 rejected (box ${current3.boxId} for partition ${current3.partitionId} already in partition ${this.acceptedBoxPartitionMap.get(current3.boxId)})`),this.exploredPins.add(currentPinPartitionKey);return}let singletonKeysForBox=this.boxSingletonKeys[current3.boxId];if(Array.from(singletonKeysForBox).some(k4=>currentPartition.filledSingletonSlots.has(k4))){debug4(` \u21B3 rejected (singleton already in partition "${current3.partitionId}")`),this.exploredPins.add(currentPinPartitionKey);return}for(let k4 of singletonKeysForBox)currentPartition.filledSingletonSlots.add(k4);currentPartition.pins.push({boxId:current3.boxId,pinId:current3.pinId}),this.allAcceptedPins.add(currentPinKey),this.addedPins.add(currentPinKey),this.splitBoxIds.has(current3.boxId)||this.acceptedBoxPartitionMap.set(current3.boxId,current3.partitionId),this.exploredPins.add(currentPinPartitionKey),debug4(` \u21B3 accepted \u2192 pins in partition now = ${currentPartition.pins.length}`);let neighbors=this.getNeighbors(currentPin);for(let neighbor of neighbors){let neighborPinKey=`${neighbor.boxId}:${neighbor.pinId}`;this.addedPins.has(neighborPinKey)||this.centerPinColors.includes(neighbor.color)||this.exploredPins.has(`${current3.partitionId}[${neighborPinKey}]`)||this.unexploredPins.push({boxId:neighbor.boxId,pinId:neighbor.pinId,partitionId:current3.partitionId})}this.unexploredPins.length===0&&(this.solved=!0),this.solved&&debug4(`Solver finished in ${this.iteration} iterations, partitions=${this.getPartitions().length}`)}getNeighbors(pin){let neighbors=[];for(let pinInNetwork of this.initialGraph.pins)pinInNetwork.networkId===pin.networkId&&(pin.boxId===pinInNetwork.boxId&&pinInNetwork.pinId===pin.pinId||neighbors.push(pinInNetwork));for(let pinInBox of this.initialGraph.pins)pinInBox.boxId===pin.boxId&&neighbors.push(pinInBox);return neighbors}solve(){for(;!this.solved&&this.iteration<1e3;)this.step()}getPartitions(){if(!this.solved)throw new Error("Graph not solved");let partitions=[];for(let part of this.wipPartitions){if(part.pins.length===0)continue;let partBoxIds=new Set(part.pins.map(p4=>p4.boxId)),partBoxes=this.initialGraph.boxes.filter(b3=>partBoxIds.has(b3.boxId));partitions.push({boxes:partBoxes,pins:this.initialGraph.pins.filter(p4=>part.pins.some(pp3=>pp3.pinId===p4.pinId&&pp3.boxId===p4.boxId)||this.centerPinColors.includes(p4.color)&&partBoxIds.has(p4.boxId))})}return partitions}getGraphicsForLastGraph(){let graphics=getGraphicsForBpcGraph(this.lastGraph,{title:`Iteration ${this.iteration}`}),total=this.wipPartitions.length,PIN_RECT_SIZE=.4;if(this.wipPartitions.forEach((part,idx)=>{if(part.pins.length===0)return;let fill=getColorByIndex(idx,total,.25);for(let{boxId,pinId}of part.pins){let{x:x4,y:y4}=getPinPosition(this.lastGraph,boxId,pinId);graphics.rects.push({center:{x:x4,y:y4},width:PIN_RECT_SIZE,height:PIN_RECT_SIZE,fill})}}),this.lastExploredPin){let{boxId,pinId,color}=this.lastExploredPin,pos=getPinPosition(this.lastGraph,boxId,pinId),size3=.25;graphics.rects.push({center:{x:pos.x,y:pos.y},width:size3,height:size3,fill:this.lastExploredPin.partitionId?getColorByIndex(this.wipPartitions.findIndex(p4=>p4.partitionId===this.lastExploredPin.partitionId),this.wipPartitions.length,1):"black"}),graphics.texts.push({x:pos.x,y:pos.y,text:`${boxId}:${pinId}-${Array.from(this.boxSingletonKeys[boxId]??[]).join(",")}`,fontSize:.1})}let unexploredRectBaseSize=PIN_RECT_SIZE;for(let pin of this.unexploredPins){let{boxId,pinId,partitionId}=pin,partitionIdx=this.wipPartitions.findIndex(p4=>p4.partitionId===partitionId);if(partitionIdx===-1)continue;let stroke=getColorByIndex(partitionIdx,this.wipPartitions.length,1),{x:x4,y:y4}=getPinPosition(this.lastGraph,boxId,pinId),scale5=1+.1*partitionIdx;graphics.rects.push({center:{x:x4,y:y4},width:unexploredRectBaseSize*scale5,height:unexploredRectBaseSize*scale5,fill:"none",stroke})}return graphics}},matchGraph=(g6,corpus,opts={})=>{opts.similarityMethod??(opts.similarityMethod="wl-distance");let distanceFn=getBpcGraphWlDistance,corpusScores=Object.fromEntries(Object.entries(corpus).map(([k4,v4])=>[k4,distanceFn(g6,v4)])),bestMatch=Object.entries(corpusScores).reduce((best,[k4,d4])=>d4<best[1]?[k4,d4]:best);return{graphName:bestMatch[0],graph:corpus[bestMatch[0]],distance:bestMatch[1],corpusScores}},getDirectionFromVec2=vec2=>vec2.x>0?"x+":vec2.x<0?"x-":vec2.y>0?"y+":vec2.y<0?"y-":null,getDirectionVec2=direction2=>{switch(direction2){case"x+":return{x:1,y:0};case"x-":return{x:-1,y:0};case"y+":return{x:0,y:1};case"y-":return{x:0,y:-1}}},getDominantPinSide=(g6,boxId)=>{let box2=g6.boxes.find(b3=>b3.boxId===boxId);if(!box2)throw new Error(`Box ${boxId} not found`);let pinDirections=g6.pins.filter(p4=>p4.boxId===boxId).map(p4=>getPinDirection(g6,box2,p4)),sideCounts={"x-":0,"x+":0,"y-":0,"y+":0};for(let dir2 of pinDirections)dir2&&sideCounts[dir2]++;let maxSideCount=Math.max(...Object.values(sideCounts));for(let key of Object.keys(sideCounts))if(sideCounts[key]===maxSideCount)return key;return null},pushFloatingBoxesAdjustingForFixedSizeDelta=(adaptedFloatingBpcGraph,fixedGraph,{floatingToFixedBoxAssignment,floatingBoxIdsWithMutablePinOffsets})=>{for(let floatingBox of adaptedFloatingBpcGraph.boxes){let fixedBoxId=floatingToFixedBoxAssignment[floatingBox.boxId];if(!fixedBoxId||!floatingBox.center||floatingBoxIdsWithMutablePinOffsets?.has(floatingBox.boxId))continue;let fixedBoxBounds=getBoundsOfBpcBox(fixedGraph,fixedBoxId),floatingBoxBounds=getBoundsOfBpcBox(adaptedFloatingBpcGraph,floatingBox.boxId),fixedDominantPinSide=getDominantPinSide(fixedGraph,fixedBoxId),floatingDominantPinSide=getDominantPinSide(adaptedFloatingBpcGraph,floatingBox.boxId);if(fixedDominantPinSide===null||floatingDominantPinSide===null||fixedDominantPinSide!==floatingDominantPinSide)continue;let shiftVec=getDirectionVec2(fixedDominantPinSide),fixedWidth=fixedBoxBounds.maxX-fixedBoxBounds.minX,floatingWidth=floatingBoxBounds.maxX-floatingBoxBounds.minX,fixedHeight=fixedBoxBounds.maxY-fixedBoxBounds.minY,floatingHeight=floatingBoxBounds.maxY-floatingBoxBounds.minY,deltaWidth=floatingWidth-fixedWidth,deltaHeight=floatingHeight-fixedHeight;if(!(deltaWidth<.001&&deltaHeight<.001))for(let otherBox of adaptedFloatingBpcGraph.boxes){if(otherBox.boxId===floatingBox.boxId||!otherBox.center)continue;let deltaPos={x:otherBox.center.x-floatingBox.center.x,y:otherBox.center.y-floatingBox.center.y};getDirectionFromVec2({x:deltaPos.x*Math.abs(shiftVec.x),y:deltaPos.y*Math.abs(shiftVec.y)})===fixedDominantPinSide&&(otherBox.center.x+=shiftVec.x*deltaWidth,otherBox.center.y+=shiftVec.y*deltaHeight)}}},netAdaptBpcGraph2=(floatingGraph,fixedGraph,opts={})=>{let{floatingBoxIdsWithMutablePinOffsets=new Set}=opts,{floatingToFixedBoxAssignment,floatingToFixedPinAssignment}=getApproximateAssignments2(floatingGraph,fixedGraph),adaptedBpcGraph=structuredClone(floatingGraph);for(let floatingPin of adaptedBpcGraph.pins)if(floatingBoxIdsWithMutablePinOffsets.has(floatingPin.boxId)&&floatingToFixedPinAssignment[floatingPin.boxId]?.[floatingPin.pinId]){let fixedPinId=floatingToFixedPinAssignment[floatingPin.boxId]?.[floatingPin.pinId],fixedBoxId=floatingToFixedBoxAssignment[floatingPin.boxId],fixedPin=fixedGraph.pins.find(p4=>p4.boxId===fixedBoxId&&p4.pinId===fixedPinId);fixedPin&&(floatingPin.offset=fixedPin.offset)}for(let box2 of adaptedBpcGraph.boxes)if(floatingToFixedBoxAssignment[box2.boxId]){let fixedBoxId=floatingToFixedBoxAssignment[box2.boxId],fixedBox=fixedGraph.boxes.find(b3=>b3.boxId===fixedBoxId);fixedBox&&(box2.center=fixedBox.center,box2.kind="fixed")}return opts.pushBoxesAsBoxesChangeSize&&pushFloatingBoxesAdjustingForFixedSizeDelta(adaptedBpcGraph,fixedGraph,{floatingToFixedBoxAssignment,floatingBoxIdsWithMutablePinOffsets}),adaptedBpcGraph},layoutSchematicGraph=(g6,{corpus,singletonKeys,centerPinColors,floatingBoxIdsWithMutablePinOffsets})=>{let processor=new SchematicPartitionProcessor(g6,{singletonKeys,centerPinColors});for(;!processor.solved&&processor.iteration<1e3;)processor.step();let adaptedGraphs=processor.getPartitions().map(getCanonicalRightFacingGraph).map(part=>{let{graph:corpusSource,distance:distance8}=matchGraph(part.g,corpus);return{adaptedBpcGraph:netAdaptBpcGraph2(structuredClone(part.g),corpusSource,{floatingBoxIdsWithMutablePinOffsets,pushBoxesAsBoxesChangeSize:!0}),reflected:part.reflected,centerBoxId:part.centerBoxId,distance:distance8}}),adaptedUnreflectedGraphs=adaptedGraphs.map(({adaptedBpcGraph,reflected,centerBoxId})=>reflected?reflectGraph({graph:adaptedBpcGraph,axis:"x",centerBoxId}):adaptedBpcGraph),remergedGraph=mergeBoxSideSubgraphs(adaptedUnreflectedGraphs),totalDistance=adaptedGraphs.reduce((sum,ag2)=>sum+(ag2.distance||0),0);return{fixedGraph:remergedGraph,distance:totalDistance}},layoutSchematicGraphVariants=(variants,{corpus,singletonKeys,centerPinColors,floatingBoxIdsWithMutablePinOffsets})=>{let variantResults=[],bestVariant=null;for(let variant of variants){let{fixedGraph,distance:distance8}=layoutSchematicGraph(variant.floatingGraph,{corpus,singletonKeys,centerPinColors,floatingBoxIdsWithMutablePinOffsets});variantResults.push({variantName:variant.variantName,distance:distance8}),(!bestVariant||distance8<bestVariant.distance)&&(bestVariant={variantName:variant.variantName,result:fixedGraph,distance:distance8})}return{result:bestVariant.result,selectedVariantName:bestVariant.variantName,variantResults}};var import_debug13=__toESM(require_browser(),1);init_dist6();init_dist6();init_dist6();var BaseSolver4=class{constructor(){__publicField(this,"MAX_ITERATIONS",1e5);__publicField(this,"solved",!1);__publicField(this,"failed",!1);__publicField(this,"iterations",0);__publicField(this,"progress",0);__publicField(this,"error",null);__publicField(this,"activeSubSolver");__publicField(this,"failedSubSolvers");__publicField(this,"timeToSolve");__publicField(this,"stats",{})}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e5){throw this.error=`${this.constructor.name} error: ${e5}`,this.failed=!0,e5}!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 startTime=Date.now();for(;!this.solved&&!this.failed;)this.step();let endTime=Date.now();this.timeToSolve=endTime-startTime}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function rotatePoint4(point7,angleDegrees){let angleRad=angleDegrees*Math.PI/180,cos6=Math.cos(angleRad),sin6=Math.sin(angleRad);return{x:point7.x*cos6-point7.y*sin6,y:point7.x*sin6+point7.y*cos6}}function getRotatedDimensions(width,height,rotation5){let normalizedRotation=(rotation5%360+360)%360;return Math.round((normalizedRotation+90)%180)===0?{width:height,height:width}:{width,height}}function getChipLabelFontSize(width,height){let smallerDimension=Math.min(width,height);return Math.min(.35,Math.max(.08,smallerDimension*.22))}function visualizeInputProblem(inputProblem,basicLayout){let inputViz={points:[],rects:[],lines:[],circles:[],texts:[]},pinToNetMap={};for(let conn of Object.keys(inputProblem.netConnMap)){let[pinId,netId]=conn.split("-");pinToNetMap[pinId]=netId}for(let[chipId,chip]of Object.entries(inputProblem.chipMap)){let chipPins=chip.pins.map(p4=>inputProblem.chipPinMap[p4]),placement=basicLayout.chipPlacements[chipId];if(!placement)continue;let width,height;if(chip.size&&Number.isFinite(chip.size.x)&&Number.isFinite(chip.size.y))width=chip.size.x,height=chip.size.y;else{let xs3=chipPins.map(p4=>p4.offset.x),ys3=chipPins.map(p4=>p4.offset.y),minX=xs3.length?Math.min(...xs3):-5,maxX=xs3.length?Math.max(...xs3):5,minY=ys3.length?Math.min(...ys3):-5,maxY=ys3.length?Math.max(...ys3):5;width=Math.max(10,maxX-minX+6),height=Math.max(10,maxY-minY+6)}let chipCenterX=placement.x,chipCenterY=placement.y,rotatedDims=getRotatedDimensions(width,height,placement.ccwRotationDegrees);inputViz.rects.push({center:{x:chipCenterX,y:chipCenterY},width:rotatedDims.width,height:rotatedDims.height,label:chipId,fill:"rgba(59, 130, 246, 0.12)",stroke:"none"}),inputViz.texts.push({x:chipCenterX,y:chipCenterY,text:chipId,fontSize:getChipLabelFontSize(rotatedDims.width,rotatedDims.height)});for(let pin of chipPins){let rotatedOffset=rotatePoint4(pin.offset,placement.ccwRotationDegrees),pinAbsX=placement.x+rotatedOffset.x,pinAbsY=placement.y+rotatedOffset.y,netId=pinToNetMap[pin.pinId],label=netId?`${pin.pinId} (${netId})`:pin.pinId;inputViz.points.push({x:pinAbsX,y:pinAbsY,label})}}let netToPins={};for(let[pinId,netId]of Object.entries(pinToNetMap))netToPins[netId]||(netToPins[netId]=[]),netToPins[netId].push(pinId);for(let[,pinIds]of Object.entries(netToPins)){let pinPositions=pinIds.map(pinId=>{let chipPin=inputProblem.chipPinMap[pinId];if(chipPin){for(let[chipId,chip]of Object.entries(inputProblem.chipMap))if(chip.pins.includes(pinId)){let placement=basicLayout.chipPlacements[chipId];if(placement){let rotatedOffset=rotatePoint4(chipPin.offset,placement.ccwRotationDegrees);return{x:placement.x+rotatedOffset.x,y:placement.y+rotatedOffset.y}}}return chipPin.offset}return null}).filter(Boolean);for(let i3=0;i3<pinPositions.length;i3++)for(let j4=i3+1;j4<pinPositions.length;j4++)inputViz.lines.push({points:[pinPositions[i3],pinPositions[j4]],strokeColor:"rgba(0,0,0,0.1)"})}let getAbsolutePositionForPin=pinId=>{let chipPin=inputProblem.chipPinMap[pinId];if(chipPin){for(let[chipId,chip]of Object.entries(inputProblem.chipMap))if(chip.pins.includes(pinId)){let placement=basicLayout.chipPlacements[chipId];if(placement){let rotatedOffset=rotatePoint4(chipPin.offset,placement.ccwRotationDegrees);return{x:placement.x+rotatedOffset.x,y:placement.y+rotatedOffset.y}}}return chipPin.offset}return null},seenStrongConn=new Set;for(let[connKey,connected]of Object.entries(inputProblem.pinStrongConnMap)){if(!connected)continue;let[pinA,pinB]=connKey.split("-"),uniqueKey=pinA<pinB?`${pinA}-${pinB}`:`${pinB}-${pinA}`;if(seenStrongConn.has(uniqueKey))continue;seenStrongConn.add(uniqueKey);let p12=getAbsolutePositionForPin(pinA),p22=getAbsolutePositionForPin(pinB);!p12||!p22||inputViz.lines.push({points:[p12,p22]})}return inputViz}var hashInputProblem=inputProblem=>JSON.stringify(inputProblem),cachedProblems=new Map;function doBasicInputProblemLayout(inputProblem){let problemHash=hashInputProblem(inputProblem);if(cachedProblems.has(problemHash))return structuredClone(cachedProblems.get(problemHash));let components=Object.entries(inputProblem.chipMap).map(([chipId,chip])=>{let pads=chip.pins.map(pinId=>inputProblem.chipPinMap[pinId]).map(pin=>{let networkId=pin.pinId;for(let[connKey,connected]of Object.entries(inputProblem.pinStrongConnMap))if(connected&&connKey.includes(pin.pinId)){let[pin1Id,pin2Id]=connKey.split("-");if(pin1Id===pin.pinId||pin2Id===pin.pinId){networkId=[pin1Id,pin2Id].sort().join("_");break}}return{padId:pin.pinId,networkId,type:"rect",offset:pin.offset,size:{x:.001,y:.001}}});return pads.push({padId:`${chipId}-body`,networkId:chipId,type:"rect",offset:{x:0,y:0},size:{x:chip.size.x,y:chip.size.y}}),{componentId:chipId,pads}}),packResult=pack({components,minGap:.4,packOrderStrategy:"largest_to_smallest",packPlacementStrategy:"shortest_connection_along_outline"}),chipPlacements={};for(let component of packResult.components)chipPlacements[component.componentId]={x:component.center.x,y:component.center.y,ccwRotationDegrees:component.ccwRotationOffset};let outputLayout={chipPlacements,groupPlacements:{}};return cachedProblems.set(problemHash,outputLayout),structuredClone(outputLayout)}var ChipPartitionsSolver=class extends BaseSolver4{constructor({inputProblem,decouplingCapGroups}){super();__publicField(this,"inputProblem");__publicField(this,"partitions",[]);__publicField(this,"decouplingCapGroups");this.inputProblem=inputProblem,this.decouplingCapGroups=decouplingCapGroups}_step(){this.partitions=this.createPartitions(this.inputProblem),this.solved=!0}createPartitions(inputProblem){let chipIds=Object.keys(inputProblem.chipMap),decapChipIdSet=new Set,decapGroupPartitions=[];if(this.decouplingCapGroups&&this.decouplingCapGroups.length>0)for(let group of this.decouplingCapGroups){let capsOnly=[];for(let capId of group.decouplingCapChipIds)inputProblem.chipMap[capId]&&capsOnly.push(capId);if(capsOnly.length>=2){decapGroupPartitions.push(capsOnly);for(let capId of capsOnly)decapChipIdSet.add(capId)}}let nonDecapChipIds=chipIds.filter(id2=>!decapChipIdSet.has(id2)),adjacencyMap=new Map;for(let chipId of nonDecapChipIds)adjacencyMap.set(chipId,new Set);for(let[connKey,isConnected]of Object.entries(inputProblem.pinStrongConnMap)){if(!isConnected)continue;let[pin1Id,pin2Id]=connKey.split("-"),owner1=this.findPinOwner(pin1Id,inputProblem),owner2=this.findPinOwner(pin2Id,inputProblem);owner1&&owner2&&owner1!==owner2&&!decapChipIdSet.has(owner1)&&!decapChipIdSet.has(owner2)&&(adjacencyMap.get(owner1).add(owner2),adjacencyMap.get(owner2).add(owner1))}let visited=new Set,nonDecapPartitions=[];for(let componentId of nonDecapChipIds)if(!visited.has(componentId)){let partition=this.dfs(componentId,adjacencyMap,visited);partition.length>0&&nonDecapPartitions.push(partition)}return[...decapGroupPartitions.map(partition=>this.createInputProblemFromPartition(partition,inputProblem,{partitionType:"decoupling_caps"})),...nonDecapPartitions.map(partition=>this.createInputProblemFromPartition(partition,inputProblem))]}findPinOwner(pinId,inputProblem){if(inputProblem.chipPinMap[pinId]){for(let[chipId,chip]of Object.entries(inputProblem.chipMap))if(chip.pins.includes(pinId))return chipId}return null}dfs(startId,adjacencyMap,visited){let partition=[],stack=[startId];for(;stack.length>0;){let currentId=stack.pop();if(visited.has(currentId))continue;visited.add(currentId),partition.push(currentId);let neighbors=adjacencyMap.get(currentId)||new Set;for(let neighborId of neighbors)visited.has(neighborId)||stack.push(neighborId)}return partition}createInputProblemFromPartition(partition,originalProblem,opts){let chipIds=partition,relevantPinIds=new Set;for(let chipId of chipIds){let chip=originalProblem.chipMap[chipId];for(let pinId of chip.pins)relevantPinIds.add(pinId)}let chipMap={},chipPinMap={},netMap={},pinStrongConnMap={},netConnMap={};for(let chipId of chipIds)chipMap[chipId]=originalProblem.chipMap[chipId];for(let pinId of relevantPinIds)originalProblem.chipPinMap[pinId]&&(chipPinMap[pinId]=originalProblem.chipPinMap[pinId]);for(let[connKey,isConnected]of Object.entries(originalProblem.pinStrongConnMap)){let[pin1Id,pin2Id]=connKey.split("-");relevantPinIds.has(pin1Id)&&relevantPinIds.has(pin2Id)&&(pinStrongConnMap[connKey]=isConnected)}let relevantNetIds=new Set;for(let[connKey,isConnected]of Object.entries(originalProblem.netConnMap)){if(!isConnected)continue;let[pinId,netId]=connKey.split("-");relevantPinIds.has(pinId)&&(relevantNetIds.add(netId),netConnMap[connKey]=isConnected)}for(let netId of relevantNetIds)originalProblem.netMap[netId]&&(netMap[netId]=originalProblem.netMap[netId]);return{...originalProblem,chipMap,chipPinMap,netMap,pinStrongConnMap,netConnMap,isPartition:!0,partitionType:opts?.partitionType}}visualize(){if(this.partitions.length===0)return super.visualize();let partitionVisualizations=this.partitions.map(partition=>{let layout=doBasicInputProblemLayout(partition);return visualizeInputProblem(partition,layout)}),titles=this.partitions.map((_4,index)=>`partition${index}`);return stackGraphicsHorizontally(partitionVisualizations,{titles})}},getColorFromString=(string,alpha=1)=>{let hash=0;for(let i3=0;i3<string.length;i3++){let char=string.charCodeAt(i3);hash=(hash<<5)-hash+char,hash=hash&hash}return`hsl(${Math.abs(hash)%360}, 70%, 50%, ${alpha})`},IdentifyDecouplingCapsSolver=class extends BaseSolver4{constructor(inputProblem){super();__publicField(this,"inputProblem");__publicField(this,"queuedChips");__publicField(this,"outputDecouplingCapGroups",[]);__publicField(this,"groupsByMainChipId",new Map);__publicField(this,"lastChip",null);this.inputProblem=inputProblem,this.queuedChips=Object.values(inputProblem.chipMap)}isTwoPinRestrictedRotation(chip){if(chip.pins.length!==2||!chip.availableRotations)return!1;let allowed=new Set([0,180]);return chip.availableRotations.length>0&&chip.availableRotations.every(r5=>allowed.has(r5))}pinsOnOppositeYSides(chip){if(chip.pins.length!==2)return!1;let[p12,p22]=chip.pins,cp1=this.inputProblem.chipPinMap[p12],cp2=this.inputProblem.chipPinMap[p22];if(!cp1||!cp2)return!1;let sides=new Set([cp1.side,cp2.side]);return sides.has("y+")&&sides.has("y-")}getStronglyConnectedNeighborChips(pinId){let neighbors=new Set;for(let[connKey,connected]of Object.entries(this.inputProblem.pinStrongConnMap)){if(!connected)continue;let[a3,b3]=connKey.split("-");if(a3===pinId){let otherChipId=b3.split(".")[0];neighbors.add(otherChipId)}else if(b3===pinId){let otherChipId=a3.split(".")[0];neighbors.add(otherChipId)}}return neighbors}findMainChipIdForCap(capChip){let strongNeighbors=new Map;for(let pinId of capChip.pins){let neighbors=this.getStronglyConnectedNeighborChips(pinId);for(let n4 of neighbors)n4!==capChip.chipId&&strongNeighbors.set(n4,(strongNeighbors.get(n4)||0)+1)}if(strongNeighbors.size===0)return null;let best=null;for(let[id2,score]of strongNeighbors.entries())(!best||score>best.score||score===best.score&&id2<best.id)&&(best={id:id2,score});return best?best.id:null}getNetIdsForPin(pinId){let nets=new Set;for(let[connKey,connected]of Object.entries(this.inputProblem.netConnMap)){if(!connected)continue;let[p4,n4]=connKey.split("-");p4===pinId&&nets.add(n4)}return nets}getNormalizedNetPair(capChip){if(capChip.pins.length!==2)return null;let nets=new Set;for(let pinId of capChip.pins){let pinNets=this.getNetIdsForPin(pinId);for(let n4 of pinNets)nets.add(n4)}if(nets.size!==2)return null;let[a3,b3]=Array.from(nets).sort();return[a3,b3]}addToGroup(mainChipId,netPair,capChipId){let[n12,n22]=netPair,groupKey=`${mainChipId}__${n12}__${n22}`,group=this.groupsByMainChipId.get(groupKey);group||(group={decouplingCapGroupId:`decap_group_${mainChipId}__${n12}__${n22}`,mainChipId,netPair:[n12,n22],decouplingCapChipIds:[]},this.groupsByMainChipId.set(groupKey,group),this.outputDecouplingCapGroups.push(group)),group.decouplingCapChipIds.includes(capChipId)||group.decouplingCapChipIds.push(capChipId)}_step(){let currentChip=this.queuedChips.shift();if(this.lastChip=currentChip??null,!currentChip){this.solved=!0;return}if(!(this.isTwoPinRestrictedRotation(currentChip)&&this.pinsOnOppositeYSides(currentChip)))return;let mainChipId=this.findMainChipIdForCap(currentChip);if(!mainChipId)return;let netPair=this.getNormalizedNetPair(currentChip);if(!netPair)return;let[n12,n22]=netPair,net1=this.inputProblem.netMap[n12],net2=this.inputProblem.netMap[n22];(net1?.isGround&&net2?.isPositiveVoltageSource||net2?.isGround&&net1?.isPositiveVoltageSource)&&this.addToGroup(mainChipId,netPair,currentChip.chipId)}visualize(){let basicLayout=doBasicInputProblemLayout(this.inputProblem),graphics=visualizeInputProblem(this.inputProblem,basicLayout),chipDecapGroupMap=new Map;for(let group of this.outputDecouplingCapGroups){chipDecapGroupMap.set(group.mainChipId,group);for(let capChipId of group.decouplingCapChipIds)chipDecapGroupMap.set(capChipId,group)}for(let rect of graphics.rects||[])rect.label!==this.lastChip?.chipId&&(rect.fill="rgba(0,0,0,0.5)");for(let rect of graphics.rects||[]){let chipId=rect.label,group=chipDecapGroupMap.get(chipId);group&&(rect.label=`${rect.label}
|
|
650
|
-
${group.decouplingCapGroupId}`,rect.fill=getColorFromString(group.decouplingCapGroupId,.8))}return graphics}getConstructorParams(){return[this.inputProblem]}computeProgress(){let total=Object.keys(this.inputProblem.chipMap).length||1,processed=total-this.queuedChips.length;return Math.min(1,Math.max(0,processed/total))}};function createFilteredNetworkMapping(params){let{inputProblem,pinIdToStronglyConnectedPins}=params,pinToNetworkMap=new Map,filteredPins=new Set,hasStrongConnections=!1,strongConnectedChipSides=new Map;for(let[connKey,connected]of Object.entries(inputProblem.pinStrongConnMap)){if(!connected)continue;hasStrongConnections=!0;let pins=connKey.split("-");if(pins.length===2&&pins[0]&&pins[1]){let pin1=inputProblem.chipPinMap[pins[0]],pin2=inputProblem.chipPinMap[pins[1]];if(pin1&&pin2){let chip1Id=pins[0].split(".")[0],chip2Id=pins[1].split(".")[0];if(chip1Id&&chip2Id&&chip1Id!==chip2Id){let key1=`${chip1Id}-${chip2Id}`,key2=`${chip2Id}-${chip1Id}`;strongConnectedChipSides.has(key1)||strongConnectedChipSides.set(key1,new Set),strongConnectedChipSides.has(key2)||strongConnectedChipSides.set(key2,new Set),strongConnectedChipSides.get(key1).add(pin1.side),strongConnectedChipSides.get(key2).add(pin2.side)}}}}if(hasStrongConnections)for(let[connKey,connected]of Object.entries(inputProblem.netConnMap)){if(!connected)continue;let[pinId,netId]=connKey.split("-");pinId&&netId&&filteredPins.add(pinId)}else for(let[connKey,connected]of Object.entries(inputProblem.netConnMap)){if(!connected)continue;let[pinId,netId]=connKey.split("-");if(pinId&&netId){if(!inputProblem.chipPinMap[pinId])continue;let chipId=pinId.split(".")[0],shouldIncludeInNetwork=!0;for(let[strongKey,strongSides]of strongConnectedChipSides.entries()){let[fromChip,toChip]=strongKey.split("-");if(fromChip===chipId)for(let[otherConnKey,otherConnected]of Object.entries(inputProblem.netConnMap)){if(!otherConnected)continue;let[otherPinId,otherNetId]=otherConnKey.split("-");if(otherNetId===netId&&otherPinId&&otherPinId!==pinId){let otherPin=inputProblem.chipPinMap[otherPinId];if(!otherPin)continue;if(otherPinId.split(".")[0]===toChip&&!strongSides.has(otherPin.side)){shouldIncludeInNetwork=!1;break}}}}if(shouldIncludeInNetwork)pinToNetworkMap.set(pinId,netId);else{let disconnectedNetworkId=`${pinId}_opposite-strong-side-disconnected`;pinToNetworkMap.set(pinId,disconnectedNetworkId),filteredPins.add(pinId)}}}for(let[connKey,connected]of Object.entries(inputProblem.pinStrongConnMap)){if(!connected)continue;let pins=connKey.split("-");if(pins.length===2&&pins[0]&&pins[1]){let existingNet=pinToNetworkMap.get(pins[0])||pinToNetworkMap.get(pins[1]);existingNet?(pinToNetworkMap.set(pins[0],existingNet),pinToNetworkMap.set(pins[1],existingNet)):(pinToNetworkMap.set(pins[0],connKey),pinToNetworkMap.set(pins[1],connKey))}}return{pinToNetworkMap,filteredPins}}var getPadsBoundingBox=pads=>{let xs3=pads.flatMap(p4=>[p4.offset.x-p4.size.x/2,p4.offset.x+p4.size.x/2]),ys3=pads.flatMap(p4=>[p4.offset.y-p4.size.y/2,p4.offset.y+p4.size.y/2]),minX=xs3.length?Math.min(...xs3):0,maxX=xs3.length?Math.max(...xs3):0,minY=ys3.length?Math.min(...ys3):0,maxY=ys3.length?Math.max(...ys3):0;return{minX,maxX,minY,maxY}},PIN_SIZE=.1,SingleInnerPartitionPackingSolver=class extends BaseSolver4{constructor(params){super();__publicField(this,"partitionInputProblem");__publicField(this,"layout",null);__publicField(this,"pinIdToStronglyConnectedPins");this.partitionInputProblem=params.partitionInputProblem,this.pinIdToStronglyConnectedPins=params.pinIdToStronglyConnectedPins}_step(){if(!this.activeSubSolver){let pinToNetworkMap=createFilteredNetworkMapping({inputProblem:this.partitionInputProblem,pinIdToStronglyConnectedPins:this.pinIdToStronglyConnectedPins}).pinToNetworkMap,packInput=this.createPackInput(pinToNetworkMap);this.activeSubSolver=new PackSolver2(packInput)}if(this.activeSubSolver.step(),this.activeSubSolver.failed){this.failed=!0,this.error=`PackSolver2 failed: ${this.activeSubSolver.error}`;return}this.activeSubSolver.solved&&(this.layout=this.createLayoutFromPackingResult(this.activeSubSolver.packedComponents),this.solved=!0,this.activeSubSolver=null)}createPackInput(pinToNetworkMap){let packComponents=Object.entries(this.partitionInputProblem.chipMap).map(([chipId,chip])=>{let pads=[];for(let pinId of chip.pins){let pin=this.partitionInputProblem.chipPinMap[pinId];if(!pin)continue;let networkId=pinToNetworkMap.get(pinId)||`${pinId}_isolated`;pads.push({padId:pinId,networkId,type:"rect",offset:{x:pin.offset.x,y:pin.offset.y},size:{x:PIN_SIZE,y:PIN_SIZE}})}let padsBoundingBox=getPadsBoundingBox(pads),padsBoundingBoxSize={x:padsBoundingBox.maxX-padsBoundingBox.minX,y:padsBoundingBox.maxY-padsBoundingBox.minY};pads.push({padId:`${chipId}_body`,networkId:`${chipId}_body_disconnected`,type:"rect",offset:{x:0,y:0},size:{x:Math.max(padsBoundingBoxSize.x,chip.size.x),y:Math.max(padsBoundingBoxSize.y,chip.size.y)}});let fixedRotation=chip.availableRotations?.[0]??0;return{componentId:chipId,pads,availableRotationDegrees:chip.availableRotations??[0,90,180,270],...chip.fixedPosition&&{isStatic:!0,center:chip.fixedPosition,ccwRotationOffset:fixedRotation}}}),minGap=this.partitionInputProblem.chipGap;return this.partitionInputProblem.partitionType==="decoupling_caps"&&(minGap=this.partitionInputProblem.decouplingCapsGap??minGap),{components:packComponents,minGap,packOrderStrategy:"largest_to_smallest",packPlacementStrategy:"minimum_closest_sum_squared_distance"}}createLayoutFromPackingResult(packedComponents){let chipPlacements={};for(let packedComponent of packedComponents){let chipId=packedComponent.componentId;chipPlacements[chipId]={x:packedComponent.center.x,y:packedComponent.center.y,ccwRotationDegrees:packedComponent.ccwRotationDegrees??packedComponent.ccwRotationOffset??0}}return{chipPlacements,groupPlacements:{}}}visualize(){if(this.activeSubSolver&&!this.solved)return this.activeSubSolver.visualize();if(!this.layout){let basicLayout=doBasicInputProblemLayout(this.partitionInputProblem);return visualizeInputProblem(this.partitionInputProblem,basicLayout)}return visualizeInputProblem(this.partitionInputProblem,this.layout)}getConstructorParams(){return[this.partitionInputProblem]}},PackInnerPartitionsSolver=class extends BaseSolver4{constructor(params){super();__publicField(this,"partitions");__publicField(this,"packedPartitions",[]);__publicField(this,"completedSolvers",[]);__publicField(this,"activeSolver",null);__publicField(this,"currentPartitionIndex",0);__publicField(this,"pinIdToStronglyConnectedPins");this.partitions=params.partitions,this.pinIdToStronglyConnectedPins=params.pinIdToStronglyConnectedPins}_step(){if(this.currentPartitionIndex>=this.partitions.length){this.solved=!0;return}if(!this.activeSolver){let currentPartition=this.partitions[this.currentPartitionIndex];this.activeSolver=new SingleInnerPartitionPackingSolver({partitionInputProblem:currentPartition,pinIdToStronglyConnectedPins:this.pinIdToStronglyConnectedPins}),this.activeSubSolver=this.activeSolver}if(this.activeSolver.step(),this.activeSolver.failed){this.failed=!0,this.error=`Partition ${this.currentPartitionIndex} failed: ${this.activeSolver.error}`;return}if(this.activeSolver.solved){if(this.completedSolvers.push(this.activeSolver),this.activeSolver.layout)this.packedPartitions.push({inputProblem:this.partitions[this.currentPartitionIndex],layout:this.activeSolver.layout});else{this.failed=!0,this.error=`Partition ${this.currentPartitionIndex} completed but has no layout`;return}this.activeSolver=null,this.activeSubSolver=null,this.currentPartitionIndex++}}visualize(){if(this.activeSolver)return this.activeSolver.visualize();if(this.completedSolvers.length===0)return super.visualize();let partitionVisualizations=this.completedSolvers.map(solver=>solver.visualize()),titles=this.completedSolvers.map((_4,index)=>`packed_partition_${index}`);return stackGraphicsHorizontally(partitionVisualizations,{titles})}getConstructorParams(){return[this.partitions]}},PartitionPackingSolver=class extends BaseSolver4{constructor(input2){super();__publicField(this,"packedPartitions");__publicField(this,"inputProblem");__publicField(this,"finalLayout",null);__publicField(this,"packSolver2",null);this.packedPartitions=input2.packedPartitions,this.inputProblem=input2.inputProblem}partitionHasFixedChip(partitionIndex){let packedPartition=this.packedPartitions[partitionIndex];return packedPartition?Object.values(packedPartition.inputProblem.chipMap).some(chip=>chip.fixedPosition!==void 0):!1}_step(){try{if(this.packedPartitions.length===0){this.finalLayout={chipPlacements:{},groupPlacements:{}},this.solved=!0;return}if(this.packedPartitions.length===1){this.finalLayout=this.packedPartitions[0].layout,this.solved=!0;return}let partitionGroups=this.organizePackedPartitions();if(!this.packSolver2){let packInput=this.createPackInput(partitionGroups);this.packSolver2=new PackSolver2(packInput),this.activeSubSolver=this.packSolver2}if(this.packSolver2.step(),this.packSolver2.failed){this.failed=!0,this.error=`PackSolver2 failed: ${this.packSolver2.error}`;return}if(this.packSolver2.solved){let packedLayout=this.applyPackingResult(this.packSolver2.packedComponents,partitionGroups);this.finalLayout=packedLayout,this.solved=!0,this.activeSubSolver=null}}catch(error2){this.failed=!0,this.error=`Failed to pack partitions: ${error2}`}}buildConnectivityMap(){let pinToNetworkMap=new Map;for(let packedPartition of this.packedPartitions){for(let[connKey,connected]of Object.entries(packedPartition.inputProblem.netConnMap)){if(!connected)continue;let[pinId,netId]=connKey.split("-");pinId&&netId&&pinToNetworkMap.set(pinId,netId)}for(let[connKey,connected]of Object.entries(packedPartition.inputProblem.pinStrongConnMap)){if(!connected)continue;let pins=connKey.split("-");if(pins.length===2&&pins[0]&&pins[1]){let existingNet=pinToNetworkMap.get(pins[0])||pinToNetworkMap.get(pins[1]);existingNet?(pinToNetworkMap.set(pins[0],existingNet),pinToNetworkMap.set(pins[1],existingNet)):(pinToNetworkMap.set(pins[0],connKey),pinToNetworkMap.set(pins[1],connKey))}}}return pinToNetworkMap}organizePackedPartitions(){let partitionGroups=[];for(let i3=0;i3<this.packedPartitions.length;i3++){let packedPartition=this.packedPartitions[i3],partitionChipIds=Object.keys(packedPartition.layout.chipPlacements);if(partitionChipIds.length>0){let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(let chipId of partitionChipIds){let placement=packedPartition.layout.chipPlacements[chipId],chip=packedPartition.inputProblem.chipMap[chipId],chipWidth=chip.size.x,chipHeight=chip.size.y;(placement.ccwRotationDegrees===90||placement.ccwRotationDegrees===270)&&([chipWidth,chipHeight]=[chipHeight,chipWidth]);let chipMinX=placement.x-chipWidth/2,chipMaxX=placement.x+chipWidth/2,chipMinY=placement.y-chipHeight/2,chipMaxY=placement.y+chipHeight/2;minX=Math.min(minX,chipMinX),maxX=Math.max(maxX,chipMaxX),minY=Math.min(minY,chipMinY),maxY=Math.max(maxY,chipMaxY)}partitionGroups.push({partitionIndex:i3,chipIds:partitionChipIds,bounds:{minX,maxX,minY,maxY}})}}return partitionGroups}createPackInput(groups){let pinToNetworkMap=this.buildConnectivityMap();return{components:groups.map(group=>{let packedPartition=this.packedPartitions[group.partitionIndex],isFixed=this.partitionHasFixedChip(group.partitionIndex),partitionWidth=group.bounds.maxX-group.bounds.minX,partitionHeight=group.bounds.maxY-group.bounds.minY,centerX=(group.bounds.minX+group.bounds.maxX)/2,centerY=(group.bounds.minY+group.bounds.maxY)/2,pads=[{padId:`partition_${group.partitionIndex}_body`,networkId:`partition_${group.partitionIndex}_disconnected`,type:"rect",offset:{x:0,y:0},size:{x:Math.max(partitionWidth,.1),y:Math.max(partitionHeight,.1)}}],addedNetworks=new Set;for(let chipId of group.chipIds){let chipPlacement=packedPartition.layout.chipPlacements[chipId],chip=packedPartition.inputProblem.chipMap[chipId];for(let pinId of chip.pins){let chipPin=packedPartition.inputProblem.chipPinMap[pinId];if(!chipPin)continue;let rotatedPinOffset={x:chipPin.offset.x,y:chipPin.offset.y},chipRotationDeg=chipPlacement.ccwRotationDegrees??0;chipRotationDeg===90?rotatedPinOffset={x:-chipPin.offset.y,y:chipPin.offset.x}:chipRotationDeg===180?rotatedPinOffset={x:-chipPin.offset.x,y:-chipPin.offset.y}:chipRotationDeg===270&&(rotatedPinOffset={x:chipPin.offset.y,y:-chipPin.offset.x});let absolutePinX=chipPlacement.x+rotatedPinOffset.x,absolutePinY=chipPlacement.y+rotatedPinOffset.y,networkId=pinToNetworkMap.get(pinId)??`${pinId}_disconnected`;addedNetworks.has(networkId)||(addedNetworks.add(networkId),pads.push({padId:`${group.partitionIndex}_pin_${pinId}`,networkId,type:"rect",offset:{x:absolutePinX-centerX,y:absolutePinY-centerY},size:{x:.01,y:.01}}))}}return{componentId:`partition_${group.partitionIndex}`,pads,availableRotationDegrees:[0],...isFixed&&{isStatic:!0,center:{x:centerX,y:centerY},ccwRotationOffset:0}}}),minGap:this.inputProblem.partitionGap,packOrderStrategy:"largest_to_smallest",packPlacementStrategy:"minimum_sum_squared_distance_to_network"}}applyPackingResult(packedComponents,partitionGroups){let newChipPlacements={};for(let packedComponent of packedComponents){let partitionIndex=parseInt(packedComponent.componentId.replace("partition_","")),group=partitionGroups.find(g6=>g6.partitionIndex===partitionIndex),packedPartition=this.packedPartitions[partitionIndex];if(group&&packedPartition){let currentCenterX=(group.bounds.minX+group.bounds.maxX)/2,currentCenterY=(group.bounds.minY+group.bounds.maxY)/2,newCenterX=packedComponent.center.x,newCenterY=packedComponent.center.y,offsetX=newCenterX-currentCenterX,offsetY=newCenterY-currentCenterY;for(let chipId of group.chipIds){let originalPlacement=packedPartition.layout.chipPlacements[chipId];newChipPlacements[chipId]={x:originalPlacement.x+offsetX,y:originalPlacement.y+offsetY,ccwRotationDegrees:originalPlacement.ccwRotationDegrees}}}}return{chipPlacements:newChipPlacements,groupPlacements:{}}}visualize(){if(this.packSolver2&&!this.solved)return this.packSolver2.visualize();if(!this.finalLayout)return super.visualize();let combinedProblem={chipMap:{},chipPinMap:{},pinStrongConnMap:{},netMap:{},netConnMap:{},chipGap:this.inputProblem.chipGap,partitionGap:this.inputProblem.partitionGap};for(let packedPartition of this.packedPartitions)Object.assign(combinedProblem.chipMap,packedPartition.inputProblem.chipMap),Object.assign(combinedProblem.chipPinMap,packedPartition.inputProblem.chipPinMap),Object.assign(combinedProblem.pinStrongConnMap,packedPartition.inputProblem.pinStrongConnMap),Object.assign(combinedProblem.netMap,packedPartition.inputProblem.netMap),Object.assign(combinedProblem.netConnMap,packedPartition.inputProblem.netConnMap);return visualizeInputProblem(combinedProblem,this.finalLayout)}getConstructorParams(){return{packedPartitions:this.packedPartitions,inputProblem:this.inputProblem}}},getPinIdToStronglyConnectedPinsObj=inputProblem=>{let pinIdToStronglyConnectedPins={},pinIds=Object.keys(inputProblem.chipPinMap);for(let i3=0;i3<pinIds.length;i3++)for(let j4=i3+1;j4<pinIds.length;j4++){let pinId1=pinIds[i3],pinId2=pinIds[j4];(inputProblem.pinStrongConnMap[`${pinId1}-${pinId2}`]||inputProblem.pinStrongConnMap[`${pinId2}-${pinId1}`])&&(pinIdToStronglyConnectedPins[pinId1]??(pinIdToStronglyConnectedPins[pinId1]=[]),pinIdToStronglyConnectedPins[pinId2]??(pinIdToStronglyConnectedPins[pinId2]=[]),pinIdToStronglyConnectedPins[pinId1].push(inputProblem.chipPinMap[pinId2]),pinIdToStronglyConnectedPins[pinId2].push(inputProblem.chipPinMap[pinId1]))}return pinIdToStronglyConnectedPins};function definePipelineStep(solverName,solverClass,getConstructorParams,opts={}){return{solverName,solverClass,getConstructorParams,onSolved:opts.onSolved}}var LayoutPipelineSolver=class extends BaseSolver4{constructor(inputProblem){super();__publicField(this,"identifyDecouplingCapsSolver");__publicField(this,"chipPartitionsSolver");__publicField(this,"packInnerPartitionsSolver");__publicField(this,"partitionPackingSolver");__publicField(this,"startTimeOfPhase");__publicField(this,"endTimeOfPhase");__publicField(this,"timeSpentOnPhase");__publicField(this,"firstIterationOfPhase");__publicField(this,"pinIdToStronglyConnectedPins");__publicField(this,"inputProblem");__publicField(this,"chipPartitions");__publicField(this,"packedPartitions");__publicField(this,"pipelineDef",[definePipelineStep("identifyDecouplingCapsSolver",IdentifyDecouplingCapsSolver,()=>[this.inputProblem],{onSolved:_layoutSolver=>{}}),definePipelineStep("chipPartitionsSolver",ChipPartitionsSolver,()=>[{inputProblem:this.inputProblem,decouplingCapGroups:this.identifyDecouplingCapsSolver?.outputDecouplingCapGroups}],{onSolved:_layoutSolver=>{this.chipPartitions=this.chipPartitionsSolver.partitions}}),definePipelineStep("packInnerPartitionsSolver",PackInnerPartitionsSolver,()=>[{partitions:this.chipPartitions,pinIdToStronglyConnectedPins:this.pinIdToStronglyConnectedPins}],{onSolved:_solver=>{this.packedPartitions=this.packInnerPartitionsSolver.packedPartitions}}),definePipelineStep("partitionPackingSolver",PartitionPackingSolver,()=>[{packedPartitions:this.packedPartitions||[],inputProblem:this.inputProblem}],{onSolved:_solver=>{}})]);__publicField(this,"currentPipelineStepIndex",0);this.inputProblem=inputProblem,this.MAX_ITERATIONS=1e6,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={},this.firstIterationOfPhase={},this.pinIdToStronglyConnectedPins=getPinIdToStronglyConnectedPinsObj(inputProblem)}_step(){let pipelineStepDef=this.pipelineDef[this.currentPipelineStepIndex];if(!pipelineStepDef){this.solved=!0;return}if(this.activeSubSolver){this.activeSubSolver.step(),this.activeSubSolver.solved?(this.endTimeOfPhase[pipelineStepDef.solverName]=performance.now(),this.timeSpentOnPhase[pipelineStepDef.solverName]=this.endTimeOfPhase[pipelineStepDef.solverName]-this.startTimeOfPhase[pipelineStepDef.solverName],pipelineStepDef.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++):this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let constructorParams=pipelineStepDef.getConstructorParams(this);this.activeSubSolver=new pipelineStepDef.solverClass(...constructorParams),this[pipelineStepDef.solverName]=this.activeSubSolver,this.timeSpentOnPhase[pipelineStepDef.solverName]=0,this.startTimeOfPhase[pipelineStepDef.solverName]=performance.now(),this.firstIterationOfPhase[pipelineStepDef.solverName]=this.iterations}solveUntilPhase(phase){for(;this.getCurrentPhase()!==phase;)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();if(this.solved&&this.partitionPackingSolver?.solved)return this.partitionPackingSolver.visualize();let identifyDecouplingCapsViz=this.identifyDecouplingCapsSolver?.visualize(),chipPartitionsViz=this.chipPartitionsSolver?.visualize(),packInnerPartitionsViz=this.packInnerPartitionsSolver?.visualize(),partitionPackingViz=this.partitionPackingSolver?.visualize(),basicLayout=doBasicInputProblemLayout(this.inputProblem),visualizations=[visualizeInputProblem(this.inputProblem,basicLayout),identifyDecouplingCapsViz,chipPartitionsViz,packInnerPartitionsViz,partitionPackingViz].filter(Boolean).map((viz,stepIndex)=>{for(let rect of viz.rects??[])rect.step=stepIndex;for(let point7 of viz.points??[])point7.step=stepIndex;for(let circle2 of viz.circles??[])circle2.step=stepIndex;for(let text of viz.texts??[])text.step=stepIndex;for(let line2 of viz.lines??[])line2.step=stepIndex;return viz});return visualizations.length===1?visualizations[0]:{points:visualizations.flatMap(v4=>v4.points||[]),rects:visualizations.flatMap(v4=>v4.rects||[]),lines:visualizations.flatMap(v4=>v4.lines||[]),circles:visualizations.flatMap(v4=>v4.circles||[]),texts:visualizations.flatMap(v4=>v4.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():this.partitionPackingSolver?.solved?this.partitionPackingSolver.visualize():this.packInnerPartitionsSolver?.solved?this.packInnerPartitionsSolver.visualize():this.chipPartitionsSolver?.solved?this.chipPartitionsSolver.visualize():this.identifyDecouplingCapsSolver?.solved?this.identifyDecouplingCapsSolver.visualize():super.preview()}checkForOverlaps(layout){let overlaps=[],chipIds=Object.keys(layout.chipPlacements);for(let i3=0;i3<chipIds.length;i3++)for(let j4=i3+1;j4<chipIds.length;j4++){let chip1Id=chipIds[i3],chip2Id=chipIds[j4],placement1=layout.chipPlacements[chip1Id],placement2=layout.chipPlacements[chip2Id],chip1=this.inputProblem.chipMap[chip1Id],chip2=this.inputProblem.chipMap[chip2Id];if(!chip1||!chip2)continue;let bounds1=this.getRotatedBounds(placement1,chip1.size),bounds2=this.getRotatedBounds(placement2,chip2.size),overlapArea=this.calculateOverlapArea(bounds1,bounds2);overlapArea>0&&overlaps.push({chip1:chip1Id,chip2:chip2Id,overlapArea})}return overlaps}getRotatedBounds(placement,size3){let halfWidth=size3.x/2,halfHeight=size3.y/2,angleRad=placement.ccwRotationDegrees*Math.PI/180,cos6=Math.abs(Math.cos(angleRad)),sin6=Math.abs(Math.sin(angleRad)),rotatedWidth=halfWidth*cos6+halfHeight*sin6,rotatedHeight=halfWidth*sin6+halfHeight*cos6;return{minX:placement.x-rotatedWidth,maxX:placement.x+rotatedWidth,minY:placement.y-rotatedHeight,maxY:placement.y+rotatedHeight}}calculateOverlapArea(bounds1,bounds2){if(bounds1.maxX<=bounds2.minX||bounds1.minX>=bounds2.maxX||bounds1.maxY<=bounds2.minY||bounds1.minY>=bounds2.maxY)return 0;let overlapWidth=Math.min(bounds1.maxX,bounds2.maxX)-Math.max(bounds1.minX,bounds2.minX),overlapHeight=Math.min(bounds1.maxY,bounds2.maxY)-Math.max(bounds1.minY,bounds2.minY);return overlapWidth*overlapHeight}getOutputLayout(){if(!this.solved)throw new Error("Pipeline not solved yet. Call solve() or step() until solved.");let finalLayout;if(this.partitionPackingSolver?.solved&&this.partitionPackingSolver.finalLayout)finalLayout=this.partitionPackingSolver.finalLayout;else throw new Error("No layout available. Pipeline may have failed or not progressed far enough.");let overlaps=this.checkForOverlaps(finalLayout);if(overlaps.length>0){let overlapDetails=overlaps.map(overlap=>`${overlap.chip1} overlaps ${overlap.chip2} (area: ${overlap.overlapArea.toFixed(4)})`).join(", ");console.warn(`Warning: ${overlaps.length} chip overlaps detected in final layout: ${overlapDetails}`)}return finalLayout}};var import_debug14=__toESM(require_browser(),1);init_dist6();var import_debug15=__toESM(require_browser(),1);var ConnectivityMap2=class{constructor(netMap){__publicField(this,"netMap");__publicField(this,"idToNetMap");this.netMap=netMap,this.idToNetMap={};for(let[netId,ids]of Object.entries(netMap))for(let id2 of ids)this.idToNetMap[id2]=netId}addConnections(connections){for(let connection of connections){let existingNets=new Set;for(let id2 of connection){let existingNetId=this.idToNetMap[id2];existingNetId&&existingNets.add(existingNetId)}let targetNetId;if(existingNets.size===0)targetNetId=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[targetNetId]=[];else if(existingNets.size===1)targetNetId=existingNets.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{targetNetId=existingNets.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(let netId of existingNets)if(netId!==targetNetId){let targetNet=this.netMap[targetNetId],sourceNet=this.netMap[netId];if(targetNet&&sourceNet){targetNet.push(...sourceNet),this.netMap[netId]=targetNet;for(let id2 of targetNet)this.idToNetMap[id2]=targetNetId}}}for(let id2 of connection){let targetNet=this.netMap[targetNetId];targetNet&&!targetNet.includes(id2)&&targetNet.push(id2),this.idToNetMap[id2]=targetNetId}}}getIdsConnectedToNet(netId){return this.netMap[netId]||[]}getNetConnectedToId(id2){return this.idToNetMap[id2]}areIdsConnected(id1,id2){if(id1===id2)return!0;let netId1=this.getNetConnectedToId(id1);if(!netId1)return!1;let netId2=this.getNetConnectedToId(id2);return netId2?netId1===netId2||netId2===id1||netId2===id1:!1}areAllIdsConnected(ids){if(ids.length===0)return!0;let netId=this.getNetConnectedToId(ids[0]);if(!netId)return!1;for(let id2 of ids){let nextNetId=this.getNetConnectedToId(id2);if(nextNetId===void 0||nextNetId!==netId)return!1}return!0}};init_dist5();var BaseSolver5=class{constructor(){__publicField(this,"MAX_ITERATIONS",1e5);__publicField(this,"solved",!1);__publicField(this,"failed",!1);__publicField(this,"iterations",0);__publicField(this,"progress",0);__publicField(this,"error",null);__publicField(this,"activeSubSolver");__publicField(this,"failedSubSolvers");__publicField(this,"timeToSolve");__publicField(this,"stats",{})}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e5){throw this.error=`${this.constructor.name} error: ${e5}`,this.failed=!0,e5}!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 startTime=Date.now();for(;!this.solved&&!this.failed;)this.step();let endTime=Date.now();this.timeToSolve=endTime-startTime}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}},getConnectivityMapsFromInputProblem=inputProblem=>{let directConnMap=new ConnectivityMap2({});for(let directConn of inputProblem.directConnections)directConnMap.addConnections([directConn.netId?[directConn.netId,...directConn.pinIds]:directConn.pinIds]);let netConnMap=new ConnectivityMap2(directConnMap.netMap);for(let netConn of inputProblem.netConnections)netConnMap.addConnections([[netConn.netId,...netConn.pinIds]]);return{directConnMap,netConnMap}};function getOrthogonalMinimumSpanningTree(pins,opts={}){let n4=pins.length,maxDistance=opts?.maxDistance??Number.POSITIVE_INFINITY;if(n4<=1)return[];{let seen=new Set;for(let p4 of pins){if(seen.has(p4.pinId))throw new Error(`Duplicate pinId detected: "${p4.pinId}"`);seen.add(p4.pinId)}}let manhattan=(a3,b3)=>Math.abs(a3.x-b3.x)+Math.abs(a3.y-b3.y),inTree=new Array(n4).fill(!1),bestDist=new Array(n4).fill(Number.POSITIVE_INFINITY),parent=new Array(n4).fill(-1),startIndex=0;for(let i3=1;i3<n4;i3++)pins[i3].pinId<pins[startIndex].pinId&&(startIndex=i3);bestDist[startIndex]=0;let edges=[];for(let iter=0;iter<n4;iter++){let u5=-1,best=Number.POSITIVE_INFINITY,bestId="";for(let i3=0;i3<n4;i3++)if(!inTree[i3]){let d4=bestDist[i3];(d4<best||d4===best&&(bestId===""||pins[i3].pinId<bestId))&&(best=d4,bestId=pins[i3].pinId,u5=i3)}inTree[u5]=!0,parent[u5]!==-1&&edges.push([pins[u5].pinId,pins[parent[u5]].pinId]);for(let v4=0;v4<n4;v4++)if(!inTree[v4]){let d02=manhattan(pins[u5],pins[v4]),isForbidden=opts?.forbidEdge?.(pins[u5],pins[v4])??!1,d4=d02>maxDistance||isForbidden?Number.POSITIVE_INFINITY:d02;(d4<bestDist[v4]||d4===bestDist[v4]&&pins[u5].pinId<pins[parent[v4]]?.pinId)&&(bestDist[v4]=d4,parent[v4]=u5)}}return edges}var getPinDirection2=(pin,chip)=>{let{x:x4,y:y4}=pin,{center:center2,width,height}=chip,yPlusEdge=center2.y+height/2,yMinusEdge=center2.y-height/2,xPlusEdge=center2.x+width/2,xMinusEdge=center2.x-width/2,yPlusDistance=yPlusEdge-y4,yMinusDistance=y4-yMinusEdge,xPlusDistance=xPlusEdge-x4,xMinusDistance=x4-xMinusEdge,minDistance=Math.min(yPlusDistance,yMinusDistance,xPlusDistance,xMinusDistance);return minDistance===yPlusDistance?"y+":minDistance===yMinusDistance?"y-":minDistance===xPlusDistance?"x+":"x-"},getRestrictedCenterLines=params=>{let{pins,inputProblem,pinIdMap,chipMap}=params,findAllDirectlyConnectedPins=startPinId=>{let visited=new Set,queue=[startPinId];visited.add(startPinId);let directConns=inputProblem.directConnections||[];for(;queue.length;){let cur=queue.shift();for(let dc3 of directConns)if(dc3.pinIds.includes(cur))for(let p4 of dc3.pinIds)visited.has(p4)||(visited.add(p4),queue.push(p4))}return visited},p02=pins[0].pinId,p12=pins[1].pinId,relatedPinIds=new Set([...findAllDirectlyConnectedPins(p02),...findAllDirectlyConnectedPins(p12)]),restrictedCenterLines=new Map,chipFacingMap=new Map,chipsOfFacingPins=new Set(pins.map(p4=>p4.chipId));for(let pinId of relatedPinIds){let pin=pinIdMap.get(pinId);if(!pin)continue;let chip=chipMap[pin.chipId];if(!chip)continue;let facing=pin._facingDirection??getPinDirection2(pin,chip),entry=chipFacingMap.get(chip.chipId);if(!entry){entry={center:chip.center};let counts={xPos:0,xNeg:0,yPos:0,yNeg:0};for(let cp2 of chip.pins){let cpFacing=cp2._facingDirection??getPinDirection2(cp2,chip);cpFacing==="x+"&&counts.xPos++,cpFacing==="x-"&&counts.xNeg++,cpFacing==="y+"&&counts.yPos++,cpFacing==="y-"&&counts.yNeg++}entry.counts=counts,chipFacingMap.set(chip.chipId,entry)}facing==="x+"&&(entry.hasXPos=!0),facing==="x-"&&(entry.hasXNeg=!0),facing==="y+"&&(entry.hasYPos=!0),facing==="y-"&&(entry.hasYNeg=!0)}for(let[chipId,faces]of chipFacingMap){let axes=new Set,rcl={axes},counts=faces.counts;!(counts&&(counts.xPos>1||counts.xNeg>1||counts.yPos>1||counts.yNeg>1))&&chipsOfFacingPins.has(chipId)||(faces.hasXPos&&faces.hasXNeg&&(rcl.x=faces.center.x,axes.add("x")),faces.hasYPos&&faces.hasYNeg&&(rcl.y=faces.center.y,axes.add("y"))),axes.size>0&&restrictedCenterLines.set(chipId,rcl)}return restrictedCenterLines},doesPairCrossRestrictedCenterLines=params=>{let{inputProblem,chipMap,pinIdMap,p1:p12,p2:p22}=params,restrictedCenterLines=getRestrictedCenterLines({pins:[p12,p22],inputProblem,pinIdMap,chipMap});if(restrictedCenterLines.size===0)return!1;let EPS102=1e-9,crossesSegment=(a3,b3)=>{for(let[,rcl]of restrictedCenterLines)if(rcl.axes.has("x")&&typeof rcl.x=="number"&&(a3.x-rcl.x)*(b3.x-rcl.x)<-EPS102||rcl.axes.has("y")&&typeof rcl.y=="number"&&(a3.y-rcl.y)*(b3.y-rcl.y)<-EPS102)return!0;return!1};if(Math.abs(p12.x-p22.x)<EPS102||Math.abs(p12.y-p22.y)<EPS102)return crossesSegment({x:p12.x,y:p12.y},{x:p22.x,y:p22.y});let elbowHV={x:p22.x,y:p12.y},elbowVH={x:p12.x,y:p22.y},hvCrosses=crossesSegment({x:p12.x,y:p12.y},elbowHV)||crossesSegment(elbowHV,{x:p22.x,y:p22.y}),vhCrosses=crossesSegment({x:p12.x,y:p12.y},elbowVH)||crossesSegment(elbowVH,{x:p22.x,y:p22.y});return hvCrosses&&vhCrosses},getColorFromString2=(string,alpha=1)=>`hsl(${string.split("").reduce((acc,char)=>acc*31+char.charCodeAt(0),0)%360}, 100%, 50%, ${alpha})`,getSectionNameForPin=(sectionByChipId,sectionByPinId,pin)=>{if(pin.chipId){let chipSection=sectionByChipId.get(pin.chipId);if(chipSection)return chipSection}return sectionByPinId.get(pin.pinId)},arePinsInDifferentSchematicSections=(inputProblem,p12,p22)=>{let sectionByChipId=new Map,sectionByPinId=new Map;for(let chip of inputProblem.chips)if(chip.sectionId){sectionByChipId.set(chip.chipId,chip.sectionId);for(let pin of chip.pins)sectionByPinId.set(pin.pinId,chip.sectionId)}if(sectionByChipId.size===0)return!1;let s12=getSectionNameForPin(sectionByChipId,sectionByPinId,p12),s22=getSectionNameForPin(sectionByChipId,sectionByPinId,p22);return!!s12&&!!s22&&s12!==s22},visualizeInputProblem2=(inputProblem,opts={})=>{let{connectionAlpha=.8,chipAlpha=.8}=opts,graphics={lines:[],points:[],rects:[]},pinIdMap=new Map;for(let chip of inputProblem.chips)for(let pin of chip.pins)pinIdMap.set(pin.pinId,pin);for(let chip of inputProblem.chips){graphics.rects.push({label:chip.chipId,center:chip.center,width:chip.width,height:chip.height,fill:getColorFromString2(chip.chipId,chipAlpha)});for(let pin of chip.pins)graphics.points.push({label:`${pin.pinId}
|
|
649
|
+
\u2500\u2500 Iteration ${this.iteration} \u2500\u2500 unexplored=${this.unexploredPins.length} explored=${this.exploredPins.size}`),this.unexploredPins.sort((a3,b3)=>{let aKey=`${a3.boxId}:${a3.pinId}`,bKey=`${b3.boxId}:${b3.pinId}`,netDiff=this.pinNetworkSize[aKey]-this.pinNetworkSize[bKey];return netDiff!==0?netDiff:this.pinConnectionCount[aKey]-this.pinConnectionCount[bKey]}),this.unexploredPins.length===0){this.solved=!0;return}let current3=this.unexploredPins.shift(),currentPinKey=`${current3.boxId}:${current3.pinId}`;debug4(`Exploring pin ${current3.boxId}:${current3.pinId} for partition "${current3.partitionId}"`),this.lastExploredPin={...current3,partitionId:current3.partitionId};let currentPinPartitionKey=`${current3.partitionId}[${currentPinKey}]`,currentPin=this.initialGraph.pins.find(p4=>p4.boxId===current3.boxId&&p4.pinId===current3.pinId);if(!currentPin||this.exploredPins.has(currentPinPartitionKey))return;let currentPartition=this.wipPartitions.find(p4=>p4.partitionId===current3.partitionId);if(!currentPartition)return;let pinAlreadyAcceptedIntoPartitionId=this.acceptedBoxPartitionMap.get(current3.boxId);if(pinAlreadyAcceptedIntoPartitionId&&pinAlreadyAcceptedIntoPartitionId!==current3.partitionId&&!this.splitBoxIds.has(current3.boxId)){debug4(` \u21B3 rejected (box ${current3.boxId} for partition ${current3.partitionId} already in partition ${this.acceptedBoxPartitionMap.get(current3.boxId)})`),this.exploredPins.add(currentPinPartitionKey);return}let singletonKeysForBox=this.boxSingletonKeys[current3.boxId];if(Array.from(singletonKeysForBox).some(k4=>currentPartition.filledSingletonSlots.has(k4))){debug4(` \u21B3 rejected (singleton already in partition "${current3.partitionId}")`),this.exploredPins.add(currentPinPartitionKey);return}for(let k4 of singletonKeysForBox)currentPartition.filledSingletonSlots.add(k4);currentPartition.pins.push({boxId:current3.boxId,pinId:current3.pinId}),this.allAcceptedPins.add(currentPinKey),this.addedPins.add(currentPinKey),this.splitBoxIds.has(current3.boxId)||this.acceptedBoxPartitionMap.set(current3.boxId,current3.partitionId),this.exploredPins.add(currentPinPartitionKey),debug4(` \u21B3 accepted \u2192 pins in partition now = ${currentPartition.pins.length}`);let neighbors=this.getNeighbors(currentPin);for(let neighbor of neighbors){let neighborPinKey=`${neighbor.boxId}:${neighbor.pinId}`;this.addedPins.has(neighborPinKey)||this.centerPinColors.includes(neighbor.color)||this.exploredPins.has(`${current3.partitionId}[${neighborPinKey}]`)||this.unexploredPins.push({boxId:neighbor.boxId,pinId:neighbor.pinId,partitionId:current3.partitionId})}this.unexploredPins.length===0&&(this.solved=!0),this.solved&&debug4(`Solver finished in ${this.iteration} iterations, partitions=${this.getPartitions().length}`)}getNeighbors(pin){let neighbors=[];for(let pinInNetwork of this.initialGraph.pins)pinInNetwork.networkId===pin.networkId&&(pin.boxId===pinInNetwork.boxId&&pinInNetwork.pinId===pin.pinId||neighbors.push(pinInNetwork));for(let pinInBox of this.initialGraph.pins)pinInBox.boxId===pin.boxId&&neighbors.push(pinInBox);return neighbors}solve(){for(;!this.solved&&this.iteration<1e3;)this.step()}getPartitions(){if(!this.solved)throw new Error("Graph not solved");let partitions=[];for(let part of this.wipPartitions){if(part.pins.length===0)continue;let partBoxIds=new Set(part.pins.map(p4=>p4.boxId)),partBoxes=this.initialGraph.boxes.filter(b3=>partBoxIds.has(b3.boxId));partitions.push({boxes:partBoxes,pins:this.initialGraph.pins.filter(p4=>part.pins.some(pp3=>pp3.pinId===p4.pinId&&pp3.boxId===p4.boxId)||this.centerPinColors.includes(p4.color)&&partBoxIds.has(p4.boxId))})}return partitions}getGraphicsForLastGraph(){let graphics=getGraphicsForBpcGraph(this.lastGraph,{title:`Iteration ${this.iteration}`}),total=this.wipPartitions.length,PIN_RECT_SIZE=.4;if(this.wipPartitions.forEach((part,idx)=>{if(part.pins.length===0)return;let fill=getColorByIndex(idx,total,.25);for(let{boxId,pinId}of part.pins){let{x:x4,y:y4}=getPinPosition(this.lastGraph,boxId,pinId);graphics.rects.push({center:{x:x4,y:y4},width:PIN_RECT_SIZE,height:PIN_RECT_SIZE,fill})}}),this.lastExploredPin){let{boxId,pinId,color}=this.lastExploredPin,pos=getPinPosition(this.lastGraph,boxId,pinId),size3=.25;graphics.rects.push({center:{x:pos.x,y:pos.y},width:size3,height:size3,fill:this.lastExploredPin.partitionId?getColorByIndex(this.wipPartitions.findIndex(p4=>p4.partitionId===this.lastExploredPin.partitionId),this.wipPartitions.length,1):"black"}),graphics.texts.push({x:pos.x,y:pos.y,text:`${boxId}:${pinId}-${Array.from(this.boxSingletonKeys[boxId]??[]).join(",")}`,fontSize:.1})}let unexploredRectBaseSize=PIN_RECT_SIZE;for(let pin of this.unexploredPins){let{boxId,pinId,partitionId}=pin,partitionIdx=this.wipPartitions.findIndex(p4=>p4.partitionId===partitionId);if(partitionIdx===-1)continue;let stroke=getColorByIndex(partitionIdx,this.wipPartitions.length,1),{x:x4,y:y4}=getPinPosition(this.lastGraph,boxId,pinId),scale5=1+.1*partitionIdx;graphics.rects.push({center:{x:x4,y:y4},width:unexploredRectBaseSize*scale5,height:unexploredRectBaseSize*scale5,fill:"none",stroke})}return graphics}},matchGraph=(g6,corpus,opts={})=>{opts.similarityMethod??(opts.similarityMethod="wl-distance");let distanceFn=getBpcGraphWlDistance,corpusScores=Object.fromEntries(Object.entries(corpus).map(([k4,v4])=>[k4,distanceFn(g6,v4)])),bestMatch=Object.entries(corpusScores).reduce((best,[k4,d4])=>d4<best[1]?[k4,d4]:best);return{graphName:bestMatch[0],graph:corpus[bestMatch[0]],distance:bestMatch[1],corpusScores}},getDirectionFromVec2=vec2=>vec2.x>0?"x+":vec2.x<0?"x-":vec2.y>0?"y+":vec2.y<0?"y-":null,getDirectionVec2=direction2=>{switch(direction2){case"x+":return{x:1,y:0};case"x-":return{x:-1,y:0};case"y+":return{x:0,y:1};case"y-":return{x:0,y:-1}}},getDominantPinSide=(g6,boxId)=>{let box2=g6.boxes.find(b3=>b3.boxId===boxId);if(!box2)throw new Error(`Box ${boxId} not found`);let pinDirections=g6.pins.filter(p4=>p4.boxId===boxId).map(p4=>getPinDirection(g6,box2,p4)),sideCounts={"x-":0,"x+":0,"y-":0,"y+":0};for(let dir2 of pinDirections)dir2&&sideCounts[dir2]++;let maxSideCount=Math.max(...Object.values(sideCounts));for(let key of Object.keys(sideCounts))if(sideCounts[key]===maxSideCount)return key;return null},pushFloatingBoxesAdjustingForFixedSizeDelta=(adaptedFloatingBpcGraph,fixedGraph,{floatingToFixedBoxAssignment,floatingBoxIdsWithMutablePinOffsets})=>{for(let floatingBox of adaptedFloatingBpcGraph.boxes){let fixedBoxId=floatingToFixedBoxAssignment[floatingBox.boxId];if(!fixedBoxId||!floatingBox.center||floatingBoxIdsWithMutablePinOffsets?.has(floatingBox.boxId))continue;let fixedBoxBounds=getBoundsOfBpcBox(fixedGraph,fixedBoxId),floatingBoxBounds=getBoundsOfBpcBox(adaptedFloatingBpcGraph,floatingBox.boxId),fixedDominantPinSide=getDominantPinSide(fixedGraph,fixedBoxId),floatingDominantPinSide=getDominantPinSide(adaptedFloatingBpcGraph,floatingBox.boxId);if(fixedDominantPinSide===null||floatingDominantPinSide===null||fixedDominantPinSide!==floatingDominantPinSide)continue;let shiftVec=getDirectionVec2(fixedDominantPinSide),fixedWidth=fixedBoxBounds.maxX-fixedBoxBounds.minX,floatingWidth=floatingBoxBounds.maxX-floatingBoxBounds.minX,fixedHeight=fixedBoxBounds.maxY-fixedBoxBounds.minY,floatingHeight=floatingBoxBounds.maxY-floatingBoxBounds.minY,deltaWidth=floatingWidth-fixedWidth,deltaHeight=floatingHeight-fixedHeight;if(!(deltaWidth<.001&&deltaHeight<.001))for(let otherBox of adaptedFloatingBpcGraph.boxes){if(otherBox.boxId===floatingBox.boxId||!otherBox.center)continue;let deltaPos={x:otherBox.center.x-floatingBox.center.x,y:otherBox.center.y-floatingBox.center.y};getDirectionFromVec2({x:deltaPos.x*Math.abs(shiftVec.x),y:deltaPos.y*Math.abs(shiftVec.y)})===fixedDominantPinSide&&(otherBox.center.x+=shiftVec.x*deltaWidth,otherBox.center.y+=shiftVec.y*deltaHeight)}}},netAdaptBpcGraph2=(floatingGraph,fixedGraph,opts={})=>{let{floatingBoxIdsWithMutablePinOffsets=new Set}=opts,{floatingToFixedBoxAssignment,floatingToFixedPinAssignment}=getApproximateAssignments2(floatingGraph,fixedGraph),adaptedBpcGraph=structuredClone(floatingGraph);for(let floatingPin of adaptedBpcGraph.pins)if(floatingBoxIdsWithMutablePinOffsets.has(floatingPin.boxId)&&floatingToFixedPinAssignment[floatingPin.boxId]?.[floatingPin.pinId]){let fixedPinId=floatingToFixedPinAssignment[floatingPin.boxId]?.[floatingPin.pinId],fixedBoxId=floatingToFixedBoxAssignment[floatingPin.boxId],fixedPin=fixedGraph.pins.find(p4=>p4.boxId===fixedBoxId&&p4.pinId===fixedPinId);fixedPin&&(floatingPin.offset=fixedPin.offset)}for(let box2 of adaptedBpcGraph.boxes)if(floatingToFixedBoxAssignment[box2.boxId]){let fixedBoxId=floatingToFixedBoxAssignment[box2.boxId],fixedBox=fixedGraph.boxes.find(b3=>b3.boxId===fixedBoxId);fixedBox&&(box2.center=fixedBox.center,box2.kind="fixed")}return opts.pushBoxesAsBoxesChangeSize&&pushFloatingBoxesAdjustingForFixedSizeDelta(adaptedBpcGraph,fixedGraph,{floatingToFixedBoxAssignment,floatingBoxIdsWithMutablePinOffsets}),adaptedBpcGraph},layoutSchematicGraph=(g6,{corpus,singletonKeys,centerPinColors,floatingBoxIdsWithMutablePinOffsets})=>{let processor=new SchematicPartitionProcessor(g6,{singletonKeys,centerPinColors});for(;!processor.solved&&processor.iteration<1e3;)processor.step();let adaptedGraphs=processor.getPartitions().map(getCanonicalRightFacingGraph).map(part=>{let{graph:corpusSource,distance:distance8}=matchGraph(part.g,corpus);return{adaptedBpcGraph:netAdaptBpcGraph2(structuredClone(part.g),corpusSource,{floatingBoxIdsWithMutablePinOffsets,pushBoxesAsBoxesChangeSize:!0}),reflected:part.reflected,centerBoxId:part.centerBoxId,distance:distance8}}),adaptedUnreflectedGraphs=adaptedGraphs.map(({adaptedBpcGraph,reflected,centerBoxId})=>reflected?reflectGraph({graph:adaptedBpcGraph,axis:"x",centerBoxId}):adaptedBpcGraph),remergedGraph=mergeBoxSideSubgraphs(adaptedUnreflectedGraphs),totalDistance=adaptedGraphs.reduce((sum,ag2)=>sum+(ag2.distance||0),0);return{fixedGraph:remergedGraph,distance:totalDistance}},layoutSchematicGraphVariants=(variants,{corpus,singletonKeys,centerPinColors,floatingBoxIdsWithMutablePinOffsets})=>{let variantResults=[],bestVariant=null;for(let variant of variants){let{fixedGraph,distance:distance8}=layoutSchematicGraph(variant.floatingGraph,{corpus,singletonKeys,centerPinColors,floatingBoxIdsWithMutablePinOffsets});variantResults.push({variantName:variant.variantName,distance:distance8}),(!bestVariant||distance8<bestVariant.distance)&&(bestVariant={variantName:variant.variantName,result:fixedGraph,distance:distance8})}return{result:bestVariant.result,selectedVariantName:bestVariant.variantName,variantResults}};var import_debug13=__toESM(require_browser(),1);init_dist6();init_dist6();init_dist6();var BaseSolver4=class{constructor(){__publicField(this,"MAX_ITERATIONS",1e5);__publicField(this,"solved",!1);__publicField(this,"failed",!1);__publicField(this,"iterations",0);__publicField(this,"progress",0);__publicField(this,"error",null);__publicField(this,"activeSubSolver");__publicField(this,"failedSubSolvers");__publicField(this,"timeToSolve");__publicField(this,"stats",{})}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e5){throw this.error=`${this.constructor.name} error: ${e5}`,this.failed=!0,e5}!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 startTime=Date.now();for(;!this.solved&&!this.failed;)this.step();let endTime=Date.now();this.timeToSolve=endTime-startTime}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function rotatePoint4(point7,angleDegrees){let angleRad=angleDegrees*Math.PI/180,cos6=Math.cos(angleRad),sin6=Math.sin(angleRad);return{x:point7.x*cos6-point7.y*sin6,y:point7.x*sin6+point7.y*cos6}}function getRotatedDimensions(width,height,rotation5){let normalizedRotation=(rotation5%360+360)%360;return Math.round((normalizedRotation+90)%180)===0?{width:height,height:width}:{width,height}}function getChipLabelFontSize(width,height){let smallerDimension=Math.min(width,height);return Math.min(.35,Math.max(.08,smallerDimension*.22))}function getChipFillColor(chipId,isFixed=!1){let chipType=chipId.charAt(0).toUpperCase();if(isFixed){if(chipType==="C")return"rgba(30, 64, 175, 0.35)";if(chipType==="R")return"rgba(5, 150, 105, 0.35)";if(chipType==="L")return"rgba(126, 34, 206, 0.35)";if(chipType==="U")return"rgba(180, 83, 9, 0.35)"}return chipType==="C"?"rgba(59, 130, 246, 0.18)":chipType==="R"?"rgba(16, 185, 129, 0.18)":chipType==="L"?"rgba(168, 85, 247, 0.18)":chipType==="U"?"rgba(245, 158, 11, 0.18)":"rgba(59, 130, 246, 0.12)"}function visualizeInputProblem(inputProblem,basicLayout){let inputViz={points:[],rects:[],lines:[],circles:[],texts:[]},pinToNetMap={};for(let conn of Object.keys(inputProblem.netConnMap)){let[pinId,netId]=conn.split("-");pinToNetMap[pinId]=netId}for(let[chipId,chip]of Object.entries(inputProblem.chipMap)){let chipPins=chip.pins.map(p4=>inputProblem.chipPinMap[p4]),placement=basicLayout.chipPlacements[chipId];if(!placement)continue;let width,height;if(chip.size&&Number.isFinite(chip.size.x)&&Number.isFinite(chip.size.y))width=chip.size.x,height=chip.size.y;else{let xs3=chipPins.map(p4=>p4.offset.x),ys3=chipPins.map(p4=>p4.offset.y),minX=xs3.length?Math.min(...xs3):-5,maxX=xs3.length?Math.max(...xs3):5,minY=ys3.length?Math.min(...ys3):-5,maxY=ys3.length?Math.max(...ys3):5;width=Math.max(10,maxX-minX+6),height=Math.max(10,maxY-minY+6)}let chipCenterX=placement.x,chipCenterY=placement.y,rotatedDims=getRotatedDimensions(width,height,placement.ccwRotationDegrees),chipLabel=chip.fixedPosition?`${chipId} [fixed]`:chipId;inputViz.rects.push({center:{x:chipCenterX,y:chipCenterY},width:rotatedDims.width,height:rotatedDims.height,label:chipLabel,fill:getChipFillColor(chipId,!!chip.fixedPosition),stroke:"none"}),inputViz.texts.push({x:chipCenterX,y:chipCenterY,text:chipLabel,fontSize:getChipLabelFontSize(rotatedDims.width,rotatedDims.height)});for(let pin of chipPins){let rotatedOffset=rotatePoint4(pin.offset,placement.ccwRotationDegrees),pinAbsX=placement.x+rotatedOffset.x,pinAbsY=placement.y+rotatedOffset.y,netId=pinToNetMap[pin.pinId],label=netId?`${pin.pinId} (${netId})`:pin.pinId;inputViz.points.push({x:pinAbsX,y:pinAbsY,label})}}let netToPins={};for(let[pinId,netId]of Object.entries(pinToNetMap))netToPins[netId]||(netToPins[netId]=[]),netToPins[netId].push(pinId);for(let[,pinIds]of Object.entries(netToPins)){let pinPositions=pinIds.map(pinId=>{let chipPin=inputProblem.chipPinMap[pinId];if(chipPin){for(let[chipId,chip]of Object.entries(inputProblem.chipMap))if(chip.pins.includes(pinId)){let placement=basicLayout.chipPlacements[chipId];if(placement){let rotatedOffset=rotatePoint4(chipPin.offset,placement.ccwRotationDegrees);return{x:placement.x+rotatedOffset.x,y:placement.y+rotatedOffset.y}}}return chipPin.offset}return null}).filter(Boolean);for(let i3=0;i3<pinPositions.length;i3++)for(let j4=i3+1;j4<pinPositions.length;j4++)inputViz.lines.push({points:[pinPositions[i3],pinPositions[j4]],strokeColor:"rgba(0,0,0,0.1)"})}let getAbsolutePositionForPin=pinId=>{let chipPin=inputProblem.chipPinMap[pinId];if(chipPin){for(let[chipId,chip]of Object.entries(inputProblem.chipMap))if(chip.pins.includes(pinId)){let placement=basicLayout.chipPlacements[chipId];if(placement){let rotatedOffset=rotatePoint4(chipPin.offset,placement.ccwRotationDegrees);return{x:placement.x+rotatedOffset.x,y:placement.y+rotatedOffset.y}}}return chipPin.offset}return null},seenStrongConn=new Set;for(let[connKey,connected]of Object.entries(inputProblem.pinStrongConnMap)){if(!connected)continue;let[pinA,pinB]=connKey.split("-"),uniqueKey=pinA<pinB?`${pinA}-${pinB}`:`${pinB}-${pinA}`;if(seenStrongConn.has(uniqueKey))continue;seenStrongConn.add(uniqueKey);let p12=getAbsolutePositionForPin(pinA),p22=getAbsolutePositionForPin(pinB);!p12||!p22||inputViz.lines.push({points:[p12,p22]})}return inputViz}var hashInputProblem=inputProblem=>JSON.stringify(inputProblem),cachedProblems=new Map;function doBasicInputProblemLayout(inputProblem){let problemHash=hashInputProblem(inputProblem);if(cachedProblems.has(problemHash))return structuredClone(cachedProblems.get(problemHash));let components=Object.entries(inputProblem.chipMap).map(([chipId,chip])=>{let pads=chip.pins.map(pinId=>inputProblem.chipPinMap[pinId]).map(pin=>{let networkId=pin.pinId;for(let[connKey,connected]of Object.entries(inputProblem.pinStrongConnMap))if(connected&&connKey.includes(pin.pinId)){let[pin1Id,pin2Id]=connKey.split("-");if(pin1Id===pin.pinId||pin2Id===pin.pinId){networkId=[pin1Id,pin2Id].sort().join("_");break}}return{padId:pin.pinId,networkId,type:"rect",offset:pin.offset,size:{x:.001,y:.001}}});pads.push({padId:`${chipId}-body`,networkId:chipId,type:"rect",offset:{x:0,y:0},size:{x:chip.size.x,y:chip.size.y}});let fixedRotation=chip.availableRotations?.[0]??0;return{componentId:chipId,pads,availableRotationDegrees:chip.availableRotations??[0,90,180,270],...chip.fixedPosition&&{isStatic:!0,center:chip.fixedPosition,ccwRotationOffset:fixedRotation}}}),packResult=pack({components,minGap:.4,packOrderStrategy:"largest_to_smallest",packPlacementStrategy:"shortest_connection_along_outline"}),chipPlacements={};for(let component of packResult.components)chipPlacements[component.componentId]={x:component.center.x,y:component.center.y,ccwRotationDegrees:component.ccwRotationOffset};let outputLayout={chipPlacements,groupPlacements:{}};return cachedProblems.set(problemHash,outputLayout),structuredClone(outputLayout)}var ChipPartitionsSolver=class extends BaseSolver4{constructor({inputProblem,decouplingCapGroups}){super();__publicField(this,"inputProblem");__publicField(this,"partitions",[]);__publicField(this,"decouplingCapGroups");this.inputProblem=inputProblem,this.decouplingCapGroups=decouplingCapGroups}_step(){this.partitions=this.createPartitions(this.inputProblem),this.solved=!0}createPartitions(inputProblem){let chipIds=Object.keys(inputProblem.chipMap),decapChipIdSet=new Set,decapGroupPartitions=[];if(this.decouplingCapGroups&&this.decouplingCapGroups.length>0)for(let group of this.decouplingCapGroups){let capsOnly=[];for(let capId of group.decouplingCapChipIds)inputProblem.chipMap[capId]&&capsOnly.push(capId);if(capsOnly.length>=2){decapGroupPartitions.push(capsOnly);for(let capId of capsOnly)decapChipIdSet.add(capId)}}let nonDecapChipIds=chipIds.filter(id2=>!decapChipIdSet.has(id2)),adjacencyMap=new Map;for(let chipId of nonDecapChipIds)adjacencyMap.set(chipId,new Set);for(let[connKey,isConnected]of Object.entries(inputProblem.pinStrongConnMap)){if(!isConnected)continue;let[pin1Id,pin2Id]=connKey.split("-"),owner1=this.findPinOwner(pin1Id,inputProblem),owner2=this.findPinOwner(pin2Id,inputProblem);owner1&&owner2&&owner1!==owner2&&!decapChipIdSet.has(owner1)&&!decapChipIdSet.has(owner2)&&(adjacencyMap.get(owner1).add(owner2),adjacencyMap.get(owner2).add(owner1))}let visited=new Set,nonDecapPartitions=[];for(let componentId of nonDecapChipIds)if(!visited.has(componentId)){let partition=this.dfs(componentId,adjacencyMap,visited);partition.length>0&&nonDecapPartitions.push(partition)}return[...decapGroupPartitions.map(partition=>this.createInputProblemFromPartition(partition,inputProblem,{partitionType:"decoupling_caps"})),...nonDecapPartitions.map(partition=>this.createInputProblemFromPartition(partition,inputProblem))]}findPinOwner(pinId,inputProblem){if(inputProblem.chipPinMap[pinId]){for(let[chipId,chip]of Object.entries(inputProblem.chipMap))if(chip.pins.includes(pinId))return chipId}return null}dfs(startId,adjacencyMap,visited){let partition=[],stack=[startId];for(;stack.length>0;){let currentId=stack.pop();if(visited.has(currentId))continue;visited.add(currentId),partition.push(currentId);let neighbors=adjacencyMap.get(currentId)||new Set;for(let neighborId of neighbors)visited.has(neighborId)||stack.push(neighborId)}return partition}createInputProblemFromPartition(partition,originalProblem,opts){let chipIds=partition,relevantPinIds=new Set;for(let chipId of chipIds){let chip=originalProblem.chipMap[chipId];for(let pinId of chip.pins)relevantPinIds.add(pinId)}let chipMap={},chipPinMap={},netMap={},pinStrongConnMap={},netConnMap={};for(let chipId of chipIds)chipMap[chipId]=originalProblem.chipMap[chipId];for(let pinId of relevantPinIds)originalProblem.chipPinMap[pinId]&&(chipPinMap[pinId]=originalProblem.chipPinMap[pinId]);for(let[connKey,isConnected]of Object.entries(originalProblem.pinStrongConnMap)){let[pin1Id,pin2Id]=connKey.split("-");relevantPinIds.has(pin1Id)&&relevantPinIds.has(pin2Id)&&(pinStrongConnMap[connKey]=isConnected)}let relevantNetIds=new Set;for(let[connKey,isConnected]of Object.entries(originalProblem.netConnMap)){if(!isConnected)continue;let[pinId,netId]=connKey.split("-");relevantPinIds.has(pinId)&&(relevantNetIds.add(netId),netConnMap[connKey]=isConnected)}for(let netId of relevantNetIds)originalProblem.netMap[netId]&&(netMap[netId]=originalProblem.netMap[netId]);return{...originalProblem,chipMap,chipPinMap,netMap,pinStrongConnMap,netConnMap,isPartition:!0,partitionType:opts?.partitionType}}visualize(){if(this.partitions.length===0){let layout=doBasicInputProblemLayout(this.inputProblem);return visualizeInputProblem(this.inputProblem,layout)}let partitionVisualizations=this.partitions.map(partition=>{let layout=doBasicInputProblemLayout(partition);return visualizeInputProblem(partition,layout)}),titles=this.partitions.map((_4,index)=>`partition${index}`);return stackGraphicsHorizontally(partitionVisualizations,{titles})}},getColorFromString=(string,alpha=1)=>{let hash=0;for(let i3=0;i3<string.length;i3++){let char=string.charCodeAt(i3);hash=(hash<<5)-hash+char,hash=hash&hash}return`hsl(${Math.abs(hash)%360}, 70%, 50%, ${alpha})`},IdentifyDecouplingCapsSolver=class extends BaseSolver4{constructor(inputProblem){super();__publicField(this,"inputProblem");__publicField(this,"queuedChips");__publicField(this,"outputDecouplingCapGroups",[]);__publicField(this,"groupsByMainChipId",new Map);__publicField(this,"lastChip",null);this.inputProblem=inputProblem,this.queuedChips=Object.values(inputProblem.chipMap)}isTwoPinRestrictedRotation(chip){if(chip.pins.length!==2||!chip.availableRotations)return!1;let allowed=new Set([0,180]);return chip.availableRotations.length>0&&chip.availableRotations.every(r5=>allowed.has(r5))}pinsOnOppositeYSides(chip){if(chip.pins.length!==2)return!1;let[p12,p22]=chip.pins,cp1=this.inputProblem.chipPinMap[p12],cp2=this.inputProblem.chipPinMap[p22];if(!cp1||!cp2)return!1;let sides=new Set([cp1.side,cp2.side]);return sides.has("y+")&&sides.has("y-")}getStronglyConnectedNeighborChips(pinId){let neighbors=new Set;for(let[connKey,connected]of Object.entries(this.inputProblem.pinStrongConnMap)){if(!connected)continue;let[a3,b3]=connKey.split("-");if(a3===pinId){let otherChipId=b3.split(".")[0];neighbors.add(otherChipId)}else if(b3===pinId){let otherChipId=a3.split(".")[0];neighbors.add(otherChipId)}}return neighbors}findMainChipIdForCap(capChip){let strongNeighbors=new Map;for(let pinId of capChip.pins){let neighbors=this.getStronglyConnectedNeighborChips(pinId);for(let n4 of neighbors)n4!==capChip.chipId&&strongNeighbors.set(n4,(strongNeighbors.get(n4)||0)+1)}if(strongNeighbors.size===0)return null;let best=null;for(let[id2,score]of strongNeighbors.entries())(!best||score>best.score||score===best.score&&id2<best.id)&&(best={id:id2,score});return best?best.id:null}getNetIdsForPin(pinId){let nets=new Set;for(let[connKey,connected]of Object.entries(this.inputProblem.netConnMap)){if(!connected)continue;let[p4,n4]=connKey.split("-");p4===pinId&&nets.add(n4)}return nets}getNormalizedNetPair(capChip){if(capChip.pins.length!==2)return null;let nets=new Set;for(let pinId of capChip.pins){let pinNets=this.getNetIdsForPin(pinId);for(let n4 of pinNets)nets.add(n4)}if(nets.size!==2)return null;let[a3,b3]=Array.from(nets).sort();return[a3,b3]}addToGroup(mainChipId,netPair,capChipId){let[n12,n22]=netPair,groupKey=`${mainChipId}__${n12}__${n22}`,group=this.groupsByMainChipId.get(groupKey);group||(group={decouplingCapGroupId:`decap_group_${mainChipId}__${n12}__${n22}`,mainChipId,netPair:[n12,n22],decouplingCapChipIds:[]},this.groupsByMainChipId.set(groupKey,group),this.outputDecouplingCapGroups.push(group)),group.decouplingCapChipIds.includes(capChipId)||group.decouplingCapChipIds.push(capChipId)}_step(){let currentChip=this.queuedChips.shift();if(this.lastChip=currentChip??null,!currentChip){this.solved=!0;return}if(!(this.isTwoPinRestrictedRotation(currentChip)&&this.pinsOnOppositeYSides(currentChip)))return;let mainChipId=this.findMainChipIdForCap(currentChip);if(!mainChipId)return;let netPair=this.getNormalizedNetPair(currentChip);if(!netPair)return;let[n12,n22]=netPair,net1=this.inputProblem.netMap[n12],net2=this.inputProblem.netMap[n22];(net1?.isGround&&net2?.isPositiveVoltageSource||net2?.isGround&&net1?.isPositiveVoltageSource)&&this.addToGroup(mainChipId,netPair,currentChip.chipId)}visualize(){let basicLayout=doBasicInputProblemLayout(this.inputProblem),graphics=visualizeInputProblem(this.inputProblem,basicLayout),chipDecapGroupMap=new Map;for(let group of this.outputDecouplingCapGroups){chipDecapGroupMap.set(group.mainChipId,group);for(let capChipId of group.decouplingCapChipIds)chipDecapGroupMap.set(capChipId,group)}for(let rect of graphics.rects||[])rect.label!==this.lastChip?.chipId&&(rect.fill="rgba(0,0,0,0.5)");for(let rect of graphics.rects||[]){let chipId=rect.label,group=chipDecapGroupMap.get(chipId);group&&(rect.label=`${rect.label}
|
|
650
|
+
${group.decouplingCapGroupId}`,rect.fill=getColorFromString(group.decouplingCapGroupId,.8))}return graphics}getConstructorParams(){return[this.inputProblem]}computeProgress(){let total=Object.keys(this.inputProblem.chipMap).length||1,processed=total-this.queuedChips.length;return Math.min(1,Math.max(0,processed/total))}};function createFilteredNetworkMapping(params){let{inputProblem,pinIdToStronglyConnectedPins}=params,pinToNetworkMap=new Map,filteredPins=new Set,hasStrongConnections=!1,strongConnectedChipSides=new Map;for(let[connKey,connected]of Object.entries(inputProblem.pinStrongConnMap)){if(!connected)continue;hasStrongConnections=!0;let pins=connKey.split("-");if(pins.length===2&&pins[0]&&pins[1]){let pin1=inputProblem.chipPinMap[pins[0]],pin2=inputProblem.chipPinMap[pins[1]];if(pin1&&pin2){let chip1Id=pins[0].split(".")[0],chip2Id=pins[1].split(".")[0];if(chip1Id&&chip2Id&&chip1Id!==chip2Id){let key1=`${chip1Id}-${chip2Id}`,key2=`${chip2Id}-${chip1Id}`;strongConnectedChipSides.has(key1)||strongConnectedChipSides.set(key1,new Set),strongConnectedChipSides.has(key2)||strongConnectedChipSides.set(key2,new Set),strongConnectedChipSides.get(key1).add(pin1.side),strongConnectedChipSides.get(key2).add(pin2.side)}}}}if(hasStrongConnections)for(let[connKey,connected]of Object.entries(inputProblem.netConnMap)){if(!connected)continue;let[pinId,netId]=connKey.split("-");pinId&&netId&&filteredPins.add(pinId)}else for(let[connKey,connected]of Object.entries(inputProblem.netConnMap)){if(!connected)continue;let[pinId,netId]=connKey.split("-");if(pinId&&netId){if(!inputProblem.chipPinMap[pinId])continue;let chipId=pinId.split(".")[0],shouldIncludeInNetwork=!0;for(let[strongKey,strongSides]of strongConnectedChipSides.entries()){let[fromChip,toChip]=strongKey.split("-");if(fromChip===chipId)for(let[otherConnKey,otherConnected]of Object.entries(inputProblem.netConnMap)){if(!otherConnected)continue;let[otherPinId,otherNetId]=otherConnKey.split("-");if(otherNetId===netId&&otherPinId&&otherPinId!==pinId){let otherPin=inputProblem.chipPinMap[otherPinId];if(!otherPin)continue;if(otherPinId.split(".")[0]===toChip&&!strongSides.has(otherPin.side)){shouldIncludeInNetwork=!1;break}}}}if(shouldIncludeInNetwork)pinToNetworkMap.set(pinId,netId);else{let disconnectedNetworkId=`${pinId}_opposite-strong-side-disconnected`;pinToNetworkMap.set(pinId,disconnectedNetworkId),filteredPins.add(pinId)}}}for(let[connKey,connected]of Object.entries(inputProblem.pinStrongConnMap)){if(!connected)continue;let pins=connKey.split("-");if(pins.length===2&&pins[0]&&pins[1]){let existingNet=pinToNetworkMap.get(pins[0])||pinToNetworkMap.get(pins[1]);existingNet?(pinToNetworkMap.set(pins[0],existingNet),pinToNetworkMap.set(pins[1],existingNet)):(pinToNetworkMap.set(pins[0],connKey),pinToNetworkMap.set(pins[1],connKey))}}return{pinToNetworkMap,filteredPins}}var getPadsBoundingBox=pads=>{let xs3=pads.flatMap(p4=>[p4.offset.x-p4.size.x/2,p4.offset.x+p4.size.x/2]),ys3=pads.flatMap(p4=>[p4.offset.y-p4.size.y/2,p4.offset.y+p4.size.y/2]),minX=xs3.length?Math.min(...xs3):0,maxX=xs3.length?Math.max(...xs3):0,minY=ys3.length?Math.min(...ys3):0,maxY=ys3.length?Math.max(...ys3):0;return{minX,maxX,minY,maxY}},PIN_SIZE=.1,SingleInnerPartitionPackingSolver=class extends BaseSolver4{constructor(params){super();__publicField(this,"partitionInputProblem");__publicField(this,"layout",null);__publicField(this,"pinIdToStronglyConnectedPins");this.partitionInputProblem=params.partitionInputProblem,this.pinIdToStronglyConnectedPins=params.pinIdToStronglyConnectedPins}_step(){if(!this.activeSubSolver){let pinToNetworkMap=createFilteredNetworkMapping({inputProblem:this.partitionInputProblem,pinIdToStronglyConnectedPins:this.pinIdToStronglyConnectedPins}).pinToNetworkMap,packInput=this.createPackInput(pinToNetworkMap);this.activeSubSolver=new PackSolver2(packInput)}if(this.activeSubSolver.step(),this.activeSubSolver.failed){this.failed=!0,this.error=`PackSolver2 failed: ${this.activeSubSolver.error}`;return}this.activeSubSolver.solved&&(this.layout=this.createLayoutFromPackingResult(this.activeSubSolver.packedComponents),this.solved=!0,this.activeSubSolver=null)}createPackInput(pinToNetworkMap){let packComponents=Object.entries(this.partitionInputProblem.chipMap).map(([chipId,chip])=>{let pads=[];for(let pinId of chip.pins){let pin=this.partitionInputProblem.chipPinMap[pinId];if(!pin)continue;let networkId=pinToNetworkMap.get(pinId)||`${pinId}_isolated`;pads.push({padId:pinId,networkId,type:"rect",offset:{x:pin.offset.x,y:pin.offset.y},size:{x:PIN_SIZE,y:PIN_SIZE}})}let padsBoundingBox=getPadsBoundingBox(pads),padsBoundingBoxSize={x:padsBoundingBox.maxX-padsBoundingBox.minX,y:padsBoundingBox.maxY-padsBoundingBox.minY};pads.push({padId:`${chipId}_body`,networkId:`${chipId}_body_disconnected`,type:"rect",offset:{x:0,y:0},size:{x:Math.max(padsBoundingBoxSize.x,chip.size.x),y:Math.max(padsBoundingBoxSize.y,chip.size.y)}});let fixedRotation=chip.availableRotations?.[0]??0;return{componentId:chipId,pads,availableRotationDegrees:chip.availableRotations??[0,90,180,270],...chip.fixedPosition&&{isStatic:!0,center:chip.fixedPosition,ccwRotationOffset:fixedRotation}}}),minGap=this.partitionInputProblem.chipGap;return this.partitionInputProblem.partitionType==="decoupling_caps"&&(minGap=this.partitionInputProblem.decouplingCapsGap??minGap),{components:packComponents,minGap,packOrderStrategy:"largest_to_smallest",packPlacementStrategy:"minimum_closest_sum_squared_distance"}}createLayoutFromPackingResult(packedComponents){let chipPlacements={};for(let packedComponent of packedComponents){let chipId=packedComponent.componentId;chipPlacements[chipId]={x:packedComponent.center.x,y:packedComponent.center.y,ccwRotationDegrees:packedComponent.ccwRotationDegrees??packedComponent.ccwRotationOffset??0}}return{chipPlacements,groupPlacements:{}}}visualize(){if(this.activeSubSolver&&!this.solved)return this.activeSubSolver.visualize();if(!this.layout){let basicLayout=doBasicInputProblemLayout(this.partitionInputProblem);return visualizeInputProblem(this.partitionInputProblem,basicLayout)}return visualizeInputProblem(this.partitionInputProblem,this.layout)}getConstructorParams(){return[this.partitionInputProblem]}},PackInnerPartitionsSolver=class extends BaseSolver4{constructor(params){super();__publicField(this,"partitions");__publicField(this,"packedPartitions",[]);__publicField(this,"completedSolvers",[]);__publicField(this,"activeSolver",null);__publicField(this,"currentPartitionIndex",0);__publicField(this,"pinIdToStronglyConnectedPins");this.partitions=params.partitions,this.pinIdToStronglyConnectedPins=params.pinIdToStronglyConnectedPins}_step(){if(this.currentPartitionIndex>=this.partitions.length){this.solved=!0;return}if(!this.activeSolver){let currentPartition=this.partitions[this.currentPartitionIndex];this.activeSolver=new SingleInnerPartitionPackingSolver({partitionInputProblem:currentPartition,pinIdToStronglyConnectedPins:this.pinIdToStronglyConnectedPins}),this.activeSubSolver=this.activeSolver}if(this.activeSolver.step(),this.activeSolver.failed){this.failed=!0,this.error=`Partition ${this.currentPartitionIndex} failed: ${this.activeSolver.error}`;return}if(this.activeSolver.solved){if(this.completedSolvers.push(this.activeSolver),this.activeSolver.layout)this.packedPartitions.push({inputProblem:this.partitions[this.currentPartitionIndex],layout:this.activeSolver.layout});else{this.failed=!0,this.error=`Partition ${this.currentPartitionIndex} completed but has no layout`;return}this.activeSolver=null,this.activeSubSolver=null,this.currentPartitionIndex++}}visualize(){if(this.activeSolver)return this.activeSolver.visualize();if(this.completedSolvers.length===0){let partitionVisualizations2=this.partitions.map(partition=>{let layout=doBasicInputProblemLayout(partition);return visualizeInputProblem(partition,layout)}),titles2=this.partitions.map((_4,index)=>`partition${index}`);return stackGraphicsHorizontally(partitionVisualizations2,{titles:titles2})}let partitionVisualizations=this.completedSolvers.map(solver=>solver.visualize()),titles=this.completedSolvers.map((_4,index)=>`packed_partition_${index}`);return stackGraphicsHorizontally(partitionVisualizations,{titles})}getConstructorParams(){return[this.partitions]}},PartitionPackingSolver=class extends BaseSolver4{constructor(input2){super();__publicField(this,"packedPartitions");__publicField(this,"inputProblem");__publicField(this,"finalLayout",null);__publicField(this,"packSolver2",null);this.packedPartitions=input2.packedPartitions,this.inputProblem=input2.inputProblem}partitionHasFixedChip(partitionIndex){let packedPartition=this.packedPartitions[partitionIndex];return packedPartition?Object.values(packedPartition.inputProblem.chipMap).some(chip=>chip.fixedPosition!==void 0):!1}_step(){try{if(this.packedPartitions.length===0){this.finalLayout={chipPlacements:{},groupPlacements:{}},this.solved=!0;return}if(this.packedPartitions.length===1){this.finalLayout=this.packedPartitions[0].layout,this.solved=!0;return}let partitionGroups=this.organizePackedPartitions();if(!this.packSolver2){let packInput=this.createPackInput(partitionGroups);this.packSolver2=new PackSolver2(packInput),this.activeSubSolver=this.packSolver2}if(this.packSolver2.step(),this.packSolver2.failed){this.failed=!0,this.error=`PackSolver2 failed: ${this.packSolver2.error}`;return}if(this.packSolver2.solved){let packedLayout=this.applyPackingResult(this.packSolver2.packedComponents,partitionGroups);this.finalLayout=packedLayout,this.solved=!0,this.activeSubSolver=null}}catch(error2){this.failed=!0,this.error=`Failed to pack partitions: ${error2}`}}buildConnectivityMap(){let pinToNetworkMap=new Map;for(let packedPartition of this.packedPartitions){for(let[connKey,connected]of Object.entries(packedPartition.inputProblem.netConnMap)){if(!connected)continue;let[pinId,netId]=connKey.split("-");pinId&&netId&&pinToNetworkMap.set(pinId,netId)}for(let[connKey,connected]of Object.entries(packedPartition.inputProblem.pinStrongConnMap)){if(!connected)continue;let pins=connKey.split("-");if(pins.length===2&&pins[0]&&pins[1]){let existingNet=pinToNetworkMap.get(pins[0])||pinToNetworkMap.get(pins[1]);existingNet?(pinToNetworkMap.set(pins[0],existingNet),pinToNetworkMap.set(pins[1],existingNet)):(pinToNetworkMap.set(pins[0],connKey),pinToNetworkMap.set(pins[1],connKey))}}}return pinToNetworkMap}organizePackedPartitions(){let partitionGroups=[];for(let i3=0;i3<this.packedPartitions.length;i3++){let packedPartition=this.packedPartitions[i3],partitionChipIds=Object.keys(packedPartition.layout.chipPlacements);if(partitionChipIds.length>0){let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(let chipId of partitionChipIds){let placement=packedPartition.layout.chipPlacements[chipId],chip=packedPartition.inputProblem.chipMap[chipId],chipWidth=chip.size.x,chipHeight=chip.size.y;(placement.ccwRotationDegrees===90||placement.ccwRotationDegrees===270)&&([chipWidth,chipHeight]=[chipHeight,chipWidth]);let chipMinX=placement.x-chipWidth/2,chipMaxX=placement.x+chipWidth/2,chipMinY=placement.y-chipHeight/2,chipMaxY=placement.y+chipHeight/2;minX=Math.min(minX,chipMinX),maxX=Math.max(maxX,chipMaxX),minY=Math.min(minY,chipMinY),maxY=Math.max(maxY,chipMaxY)}partitionGroups.push({partitionIndex:i3,chipIds:partitionChipIds,bounds:{minX,maxX,minY,maxY}})}}return partitionGroups}createPackInput(groups){let pinToNetworkMap=this.buildConnectivityMap();return{components:groups.map(group=>{let packedPartition=this.packedPartitions[group.partitionIndex],isFixed=this.partitionHasFixedChip(group.partitionIndex),partitionWidth=group.bounds.maxX-group.bounds.minX,partitionHeight=group.bounds.maxY-group.bounds.minY,centerX=(group.bounds.minX+group.bounds.maxX)/2,centerY=(group.bounds.minY+group.bounds.maxY)/2,pads=[{padId:`partition_${group.partitionIndex}_body`,networkId:`partition_${group.partitionIndex}_disconnected`,type:"rect",offset:{x:0,y:0},size:{x:Math.max(partitionWidth,.1),y:Math.max(partitionHeight,.1)}}],addedNetworks=new Set;for(let chipId of group.chipIds){let chipPlacement=packedPartition.layout.chipPlacements[chipId],chip=packedPartition.inputProblem.chipMap[chipId];for(let pinId of chip.pins){let chipPin=packedPartition.inputProblem.chipPinMap[pinId];if(!chipPin)continue;let rotatedPinOffset={x:chipPin.offset.x,y:chipPin.offset.y},chipRotationDeg=chipPlacement.ccwRotationDegrees??0;chipRotationDeg===90?rotatedPinOffset={x:-chipPin.offset.y,y:chipPin.offset.x}:chipRotationDeg===180?rotatedPinOffset={x:-chipPin.offset.x,y:-chipPin.offset.y}:chipRotationDeg===270&&(rotatedPinOffset={x:chipPin.offset.y,y:-chipPin.offset.x});let absolutePinX=chipPlacement.x+rotatedPinOffset.x,absolutePinY=chipPlacement.y+rotatedPinOffset.y,networkId=pinToNetworkMap.get(pinId)??`${pinId}_disconnected`;addedNetworks.has(networkId)||(addedNetworks.add(networkId),pads.push({padId:`${group.partitionIndex}_pin_${pinId}`,networkId,type:"rect",offset:{x:absolutePinX-centerX,y:absolutePinY-centerY},size:{x:.01,y:.01}}))}}return{componentId:`partition_${group.partitionIndex}`,pads,availableRotationDegrees:[0],...isFixed&&{isStatic:!0,center:{x:centerX,y:centerY},ccwRotationOffset:0}}}),minGap:this.inputProblem.partitionGap,packOrderStrategy:"largest_to_smallest",packPlacementStrategy:"minimum_sum_squared_distance_to_network"}}applyPackingResult(packedComponents,partitionGroups){let newChipPlacements={};for(let packedComponent of packedComponents){let partitionIndex=parseInt(packedComponent.componentId.replace("partition_","")),group=partitionGroups.find(g6=>g6.partitionIndex===partitionIndex),packedPartition=this.packedPartitions[partitionIndex];if(group&&packedPartition){let currentCenterX=(group.bounds.minX+group.bounds.maxX)/2,currentCenterY=(group.bounds.minY+group.bounds.maxY)/2,newCenterX=packedComponent.center.x,newCenterY=packedComponent.center.y,offsetX=newCenterX-currentCenterX,offsetY=newCenterY-currentCenterY;for(let chipId of group.chipIds){let originalPlacement=packedPartition.layout.chipPlacements[chipId];newChipPlacements[chipId]={x:originalPlacement.x+offsetX,y:originalPlacement.y+offsetY,ccwRotationDegrees:originalPlacement.ccwRotationDegrees}}}}return{chipPlacements:newChipPlacements,groupPlacements:{}}}getCombinedPackedPartitionsProblem(){let combinedProblem={chipMap:{},chipPinMap:{},pinStrongConnMap:{},netMap:{},netConnMap:{},chipGap:this.inputProblem.chipGap,partitionGap:this.inputProblem.partitionGap};for(let packedPartition of this.packedPartitions)Object.assign(combinedProblem.chipMap,packedPartition.inputProblem.chipMap),Object.assign(combinedProblem.chipPinMap,packedPartition.inputProblem.chipPinMap),Object.assign(combinedProblem.pinStrongConnMap,packedPartition.inputProblem.pinStrongConnMap),Object.assign(combinedProblem.netMap,packedPartition.inputProblem.netMap),Object.assign(combinedProblem.netConnMap,packedPartition.inputProblem.netConnMap);return combinedProblem}getCombinedPackedPartitionsLayout(){let chipPlacements={};for(let packedPartition of this.packedPartitions)Object.assign(chipPlacements,packedPartition.layout.chipPlacements);return{chipPlacements,groupPlacements:{}}}visualize(){return this.packSolver2&&!this.solved?this.packSolver2.visualize():this.finalLayout?visualizeInputProblem(this.getCombinedPackedPartitionsProblem(),this.finalLayout):this.packedPartitions.length===0?super.visualize():visualizeInputProblem(this.getCombinedPackedPartitionsProblem(),this.getCombinedPackedPartitionsLayout())}getConstructorParams(){return{packedPartitions:this.packedPartitions,inputProblem:this.inputProblem}}},getPinIdToStronglyConnectedPinsObj=inputProblem=>{let pinIdToStronglyConnectedPins={},pinIds=Object.keys(inputProblem.chipPinMap);for(let i3=0;i3<pinIds.length;i3++)for(let j4=i3+1;j4<pinIds.length;j4++){let pinId1=pinIds[i3],pinId2=pinIds[j4];(inputProblem.pinStrongConnMap[`${pinId1}-${pinId2}`]||inputProblem.pinStrongConnMap[`${pinId2}-${pinId1}`])&&(pinIdToStronglyConnectedPins[pinId1]??(pinIdToStronglyConnectedPins[pinId1]=[]),pinIdToStronglyConnectedPins[pinId2]??(pinIdToStronglyConnectedPins[pinId2]=[]),pinIdToStronglyConnectedPins[pinId1].push(inputProblem.chipPinMap[pinId2]),pinIdToStronglyConnectedPins[pinId2].push(inputProblem.chipPinMap[pinId1]))}return pinIdToStronglyConnectedPins};function definePipelineStep(solverName,solverClass,getConstructorParams,opts={}){return{solverName,solverClass,getConstructorParams,onSolved:opts.onSolved}}var LayoutPipelineSolver=class extends BaseSolver4{constructor(inputProblem){super();__publicField(this,"identifyDecouplingCapsSolver");__publicField(this,"chipPartitionsSolver");__publicField(this,"packInnerPartitionsSolver");__publicField(this,"partitionPackingSolver");__publicField(this,"startTimeOfPhase");__publicField(this,"endTimeOfPhase");__publicField(this,"timeSpentOnPhase");__publicField(this,"firstIterationOfPhase");__publicField(this,"pinIdToStronglyConnectedPins");__publicField(this,"inputProblem");__publicField(this,"chipPartitions");__publicField(this,"packedPartitions");__publicField(this,"pipelineDef",[definePipelineStep("identifyDecouplingCapsSolver",IdentifyDecouplingCapsSolver,()=>[this.inputProblem],{onSolved:_layoutSolver=>{}}),definePipelineStep("chipPartitionsSolver",ChipPartitionsSolver,()=>[{inputProblem:this.inputProblem,decouplingCapGroups:this.identifyDecouplingCapsSolver?.outputDecouplingCapGroups}],{onSolved:_layoutSolver=>{this.chipPartitions=this.chipPartitionsSolver.partitions}}),definePipelineStep("packInnerPartitionsSolver",PackInnerPartitionsSolver,()=>[{partitions:this.chipPartitions,pinIdToStronglyConnectedPins:this.pinIdToStronglyConnectedPins}],{onSolved:_solver=>{this.packedPartitions=this.packInnerPartitionsSolver.packedPartitions}}),definePipelineStep("partitionPackingSolver",PartitionPackingSolver,()=>[{packedPartitions:this.packedPartitions||[],inputProblem:this.inputProblem}],{onSolved:_solver=>{}})]);__publicField(this,"currentPipelineStepIndex",0);this.inputProblem=inputProblem,this.MAX_ITERATIONS=1e6,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={},this.firstIterationOfPhase={},this.pinIdToStronglyConnectedPins=getPinIdToStronglyConnectedPinsObj(inputProblem)}_step(){let pipelineStepDef=this.pipelineDef[this.currentPipelineStepIndex];if(!pipelineStepDef){this.solved=!0;return}if(this.activeSubSolver){this.activeSubSolver.step(),this.activeSubSolver.solved?(this.endTimeOfPhase[pipelineStepDef.solverName]=performance.now(),this.timeSpentOnPhase[pipelineStepDef.solverName]=this.endTimeOfPhase[pipelineStepDef.solverName]-this.startTimeOfPhase[pipelineStepDef.solverName],pipelineStepDef.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++):this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let constructorParams=pipelineStepDef.getConstructorParams(this);this.activeSubSolver=new pipelineStepDef.solverClass(...constructorParams),this[pipelineStepDef.solverName]=this.activeSubSolver,this.timeSpentOnPhase[pipelineStepDef.solverName]=0,this.startTimeOfPhase[pipelineStepDef.solverName]=performance.now(),this.firstIterationOfPhase[pipelineStepDef.solverName]=this.iterations}solveUntilPhase(phase){for(;this.getCurrentPhase()!==phase;)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();if(this.solved&&this.partitionPackingSolver?.solved)return this.partitionPackingSolver.visualize();let identifyDecouplingCapsViz=this.identifyDecouplingCapsSolver?.visualize(),chipPartitionsViz=this.chipPartitionsSolver?.visualize(),packInnerPartitionsViz=this.packInnerPartitionsSolver?.visualize(),partitionPackingViz=this.partitionPackingSolver?.visualize(),basicLayout=doBasicInputProblemLayout(this.inputProblem),visualizations=[visualizeInputProblem(this.inputProblem,basicLayout),identifyDecouplingCapsViz,chipPartitionsViz,packInnerPartitionsViz,partitionPackingViz].filter(Boolean).map((viz,stepIndex)=>{for(let rect of viz.rects??[])rect.step=stepIndex;for(let point7 of viz.points??[])point7.step=stepIndex;for(let circle2 of viz.circles??[])circle2.step=stepIndex;for(let text of viz.texts??[])text.step=stepIndex;for(let line2 of viz.lines??[])line2.step=stepIndex;return viz});return visualizations.length===1?visualizations[0]:{points:visualizations.flatMap(v4=>v4.points||[]),rects:visualizations.flatMap(v4=>v4.rects||[]),lines:visualizations.flatMap(v4=>v4.lines||[]),circles:visualizations.flatMap(v4=>v4.circles||[]),texts:visualizations.flatMap(v4=>v4.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():this.partitionPackingSolver?.solved?this.partitionPackingSolver.visualize():this.packInnerPartitionsSolver?.solved?this.packInnerPartitionsSolver.visualize():this.chipPartitionsSolver?.solved?this.chipPartitionsSolver.visualize():this.identifyDecouplingCapsSolver?.solved?this.identifyDecouplingCapsSolver.visualize():super.preview()}checkForOverlaps(layout){let overlaps=[],chipIds=Object.keys(layout.chipPlacements);for(let i3=0;i3<chipIds.length;i3++)for(let j4=i3+1;j4<chipIds.length;j4++){let chip1Id=chipIds[i3],chip2Id=chipIds[j4],placement1=layout.chipPlacements[chip1Id],placement2=layout.chipPlacements[chip2Id],chip1=this.inputProblem.chipMap[chip1Id],chip2=this.inputProblem.chipMap[chip2Id];if(!chip1||!chip2)continue;let bounds1=this.getRotatedBounds(placement1,chip1.size),bounds2=this.getRotatedBounds(placement2,chip2.size),overlapArea=this.calculateOverlapArea(bounds1,bounds2);overlapArea>0&&overlaps.push({chip1:chip1Id,chip2:chip2Id,overlapArea})}return overlaps}getRotatedBounds(placement,size3){let halfWidth=size3.x/2,halfHeight=size3.y/2,angleRad=placement.ccwRotationDegrees*Math.PI/180,cos6=Math.abs(Math.cos(angleRad)),sin6=Math.abs(Math.sin(angleRad)),rotatedWidth=halfWidth*cos6+halfHeight*sin6,rotatedHeight=halfWidth*sin6+halfHeight*cos6;return{minX:placement.x-rotatedWidth,maxX:placement.x+rotatedWidth,minY:placement.y-rotatedHeight,maxY:placement.y+rotatedHeight}}calculateOverlapArea(bounds1,bounds2){if(bounds1.maxX<=bounds2.minX||bounds1.minX>=bounds2.maxX||bounds1.maxY<=bounds2.minY||bounds1.minY>=bounds2.maxY)return 0;let overlapWidth=Math.min(bounds1.maxX,bounds2.maxX)-Math.max(bounds1.minX,bounds2.minX),overlapHeight=Math.min(bounds1.maxY,bounds2.maxY)-Math.max(bounds1.minY,bounds2.minY);return overlapWidth*overlapHeight}getOutputLayout(){if(!this.solved)throw new Error("Pipeline not solved yet. Call solve() or step() until solved.");let finalLayout;if(this.partitionPackingSolver?.solved&&this.partitionPackingSolver.finalLayout)finalLayout=this.partitionPackingSolver.finalLayout;else throw new Error("No layout available. Pipeline may have failed or not progressed far enough.");let overlaps=this.checkForOverlaps(finalLayout);if(overlaps.length>0){let overlapDetails=overlaps.map(overlap=>`${overlap.chip1} overlaps ${overlap.chip2} (area: ${overlap.overlapArea.toFixed(4)})`).join(", ");console.warn(`Warning: ${overlaps.length} chip overlaps detected in final layout: ${overlapDetails}`)}return finalLayout}};var import_debug14=__toESM(require_browser(),1);init_dist6();var import_debug15=__toESM(require_browser(),1);var ConnectivityMap2=class{constructor(netMap){__publicField(this,"netMap");__publicField(this,"idToNetMap");this.netMap=netMap,this.idToNetMap={};for(let[netId,ids]of Object.entries(netMap))for(let id2 of ids)this.idToNetMap[id2]=netId}addConnections(connections){for(let connection of connections){let existingNets=new Set;for(let id2 of connection){let existingNetId=this.idToNetMap[id2];existingNetId&&existingNets.add(existingNetId)}let targetNetId;if(existingNets.size===0)targetNetId=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[targetNetId]=[];else if(existingNets.size===1)targetNetId=existingNets.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{targetNetId=existingNets.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(let netId of existingNets)if(netId!==targetNetId){let targetNet=this.netMap[targetNetId],sourceNet=this.netMap[netId];if(targetNet&&sourceNet){targetNet.push(...sourceNet),this.netMap[netId]=targetNet;for(let id2 of targetNet)this.idToNetMap[id2]=targetNetId}}}for(let id2 of connection){let targetNet=this.netMap[targetNetId];targetNet&&!targetNet.includes(id2)&&targetNet.push(id2),this.idToNetMap[id2]=targetNetId}}}getIdsConnectedToNet(netId){return this.netMap[netId]||[]}getNetConnectedToId(id2){return this.idToNetMap[id2]}areIdsConnected(id1,id2){if(id1===id2)return!0;let netId1=this.getNetConnectedToId(id1);if(!netId1)return!1;let netId2=this.getNetConnectedToId(id2);return netId2?netId1===netId2||netId2===id1||netId2===id1:!1}areAllIdsConnected(ids){if(ids.length===0)return!0;let netId=this.getNetConnectedToId(ids[0]);if(!netId)return!1;for(let id2 of ids){let nextNetId=this.getNetConnectedToId(id2);if(nextNetId===void 0||nextNetId!==netId)return!1}return!0}};init_dist5();var BaseSolver5=class{constructor(){__publicField(this,"MAX_ITERATIONS",1e5);__publicField(this,"solved",!1);__publicField(this,"failed",!1);__publicField(this,"iterations",0);__publicField(this,"progress",0);__publicField(this,"error",null);__publicField(this,"activeSubSolver");__publicField(this,"failedSubSolvers");__publicField(this,"timeToSolve");__publicField(this,"stats",{})}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e5){throw this.error=`${this.constructor.name} error: ${e5}`,this.failed=!0,e5}!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 startTime=Date.now();for(;!this.solved&&!this.failed;)this.step();let endTime=Date.now();this.timeToSolve=endTime-startTime}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}},getConnectivityMapsFromInputProblem=inputProblem=>{let directConnMap=new ConnectivityMap2({});for(let directConn of inputProblem.directConnections)directConnMap.addConnections([directConn.netId?[directConn.netId,...directConn.pinIds]:directConn.pinIds]);let netConnMap=new ConnectivityMap2(directConnMap.netMap);for(let netConn of inputProblem.netConnections)netConnMap.addConnections([[netConn.netId,...netConn.pinIds]]);return{directConnMap,netConnMap}};function getOrthogonalMinimumSpanningTree(pins,opts={}){let n4=pins.length,maxDistance=opts?.maxDistance??Number.POSITIVE_INFINITY;if(n4<=1)return[];{let seen=new Set;for(let p4 of pins){if(seen.has(p4.pinId))throw new Error(`Duplicate pinId detected: "${p4.pinId}"`);seen.add(p4.pinId)}}let manhattan=(a3,b3)=>Math.abs(a3.x-b3.x)+Math.abs(a3.y-b3.y),inTree=new Array(n4).fill(!1),bestDist=new Array(n4).fill(Number.POSITIVE_INFINITY),parent=new Array(n4).fill(-1),startIndex=0;for(let i3=1;i3<n4;i3++)pins[i3].pinId<pins[startIndex].pinId&&(startIndex=i3);bestDist[startIndex]=0;let edges=[];for(let iter=0;iter<n4;iter++){let u5=-1,best=Number.POSITIVE_INFINITY,bestId="";for(let i3=0;i3<n4;i3++)if(!inTree[i3]){let d4=bestDist[i3];(d4<best||d4===best&&(bestId===""||pins[i3].pinId<bestId))&&(best=d4,bestId=pins[i3].pinId,u5=i3)}inTree[u5]=!0,parent[u5]!==-1&&edges.push([pins[u5].pinId,pins[parent[u5]].pinId]);for(let v4=0;v4<n4;v4++)if(!inTree[v4]){let d02=manhattan(pins[u5],pins[v4]),isForbidden=opts?.forbidEdge?.(pins[u5],pins[v4])??!1,d4=d02>maxDistance||isForbidden?Number.POSITIVE_INFINITY:d02;(d4<bestDist[v4]||d4===bestDist[v4]&&pins[u5].pinId<pins[parent[v4]]?.pinId)&&(bestDist[v4]=d4,parent[v4]=u5)}}return edges}var getPinDirection2=(pin,chip)=>{let{x:x4,y:y4}=pin,{center:center2,width,height}=chip,yPlusEdge=center2.y+height/2,yMinusEdge=center2.y-height/2,xPlusEdge=center2.x+width/2,xMinusEdge=center2.x-width/2,yPlusDistance=yPlusEdge-y4,yMinusDistance=y4-yMinusEdge,xPlusDistance=xPlusEdge-x4,xMinusDistance=x4-xMinusEdge,minDistance=Math.min(yPlusDistance,yMinusDistance,xPlusDistance,xMinusDistance);return minDistance===yPlusDistance?"y+":minDistance===yMinusDistance?"y-":minDistance===xPlusDistance?"x+":"x-"},getRestrictedCenterLines=params=>{let{pins,inputProblem,pinIdMap,chipMap}=params,findAllDirectlyConnectedPins=startPinId=>{let visited=new Set,queue=[startPinId];visited.add(startPinId);let directConns=inputProblem.directConnections||[];for(;queue.length;){let cur=queue.shift();for(let dc3 of directConns)if(dc3.pinIds.includes(cur))for(let p4 of dc3.pinIds)visited.has(p4)||(visited.add(p4),queue.push(p4))}return visited},p02=pins[0].pinId,p12=pins[1].pinId,relatedPinIds=new Set([...findAllDirectlyConnectedPins(p02),...findAllDirectlyConnectedPins(p12)]),restrictedCenterLines=new Map,chipFacingMap=new Map,chipsOfFacingPins=new Set(pins.map(p4=>p4.chipId));for(let pinId of relatedPinIds){let pin=pinIdMap.get(pinId);if(!pin)continue;let chip=chipMap[pin.chipId];if(!chip)continue;let facing=pin._facingDirection??getPinDirection2(pin,chip),entry=chipFacingMap.get(chip.chipId);if(!entry){entry={center:chip.center};let counts={xPos:0,xNeg:0,yPos:0,yNeg:0};for(let cp2 of chip.pins){let cpFacing=cp2._facingDirection??getPinDirection2(cp2,chip);cpFacing==="x+"&&counts.xPos++,cpFacing==="x-"&&counts.xNeg++,cpFacing==="y+"&&counts.yPos++,cpFacing==="y-"&&counts.yNeg++}entry.counts=counts,chipFacingMap.set(chip.chipId,entry)}facing==="x+"&&(entry.hasXPos=!0),facing==="x-"&&(entry.hasXNeg=!0),facing==="y+"&&(entry.hasYPos=!0),facing==="y-"&&(entry.hasYNeg=!0)}for(let[chipId,faces]of chipFacingMap){let axes=new Set,rcl={axes},counts=faces.counts;!(counts&&(counts.xPos>1||counts.xNeg>1||counts.yPos>1||counts.yNeg>1))&&chipsOfFacingPins.has(chipId)||(faces.hasXPos&&faces.hasXNeg&&(rcl.x=faces.center.x,axes.add("x")),faces.hasYPos&&faces.hasYNeg&&(rcl.y=faces.center.y,axes.add("y"))),axes.size>0&&restrictedCenterLines.set(chipId,rcl)}return restrictedCenterLines},doesPairCrossRestrictedCenterLines=params=>{let{inputProblem,chipMap,pinIdMap,p1:p12,p2:p22}=params,restrictedCenterLines=getRestrictedCenterLines({pins:[p12,p22],inputProblem,pinIdMap,chipMap});if(restrictedCenterLines.size===0)return!1;let EPS102=1e-9,crossesSegment=(a3,b3)=>{for(let[,rcl]of restrictedCenterLines)if(rcl.axes.has("x")&&typeof rcl.x=="number"&&(a3.x-rcl.x)*(b3.x-rcl.x)<-EPS102||rcl.axes.has("y")&&typeof rcl.y=="number"&&(a3.y-rcl.y)*(b3.y-rcl.y)<-EPS102)return!0;return!1};if(Math.abs(p12.x-p22.x)<EPS102||Math.abs(p12.y-p22.y)<EPS102)return crossesSegment({x:p12.x,y:p12.y},{x:p22.x,y:p22.y});let elbowHV={x:p22.x,y:p12.y},elbowVH={x:p12.x,y:p22.y},hvCrosses=crossesSegment({x:p12.x,y:p12.y},elbowHV)||crossesSegment(elbowHV,{x:p22.x,y:p22.y}),vhCrosses=crossesSegment({x:p12.x,y:p12.y},elbowVH)||crossesSegment(elbowVH,{x:p22.x,y:p22.y});return hvCrosses&&vhCrosses},getColorFromString2=(string,alpha=1)=>`hsl(${string.split("").reduce((acc,char)=>acc*31+char.charCodeAt(0),0)%360}, 100%, 50%, ${alpha})`,getSectionNameForPin=(sectionByChipId,sectionByPinId,pin)=>{if(pin.chipId){let chipSection=sectionByChipId.get(pin.chipId);if(chipSection)return chipSection}return sectionByPinId.get(pin.pinId)},arePinsInDifferentSchematicSections=(inputProblem,p12,p22)=>{let sectionByChipId=new Map,sectionByPinId=new Map;for(let chip of inputProblem.chips)if(chip.sectionId){sectionByChipId.set(chip.chipId,chip.sectionId);for(let pin of chip.pins)sectionByPinId.set(pin.pinId,chip.sectionId)}if(sectionByChipId.size===0)return!1;let s12=getSectionNameForPin(sectionByChipId,sectionByPinId,p12),s22=getSectionNameForPin(sectionByChipId,sectionByPinId,p22);return!!s12&&!!s22&&s12!==s22},visualizeInputProblem2=(inputProblem,opts={})=>{let{connectionAlpha=.8,chipAlpha=.8}=opts,graphics={lines:[],points:[],rects:[]},pinIdMap=new Map;for(let chip of inputProblem.chips)for(let pin of chip.pins)pinIdMap.set(pin.pinId,pin);for(let chip of inputProblem.chips){graphics.rects.push({label:chip.chipId,center:chip.center,width:chip.width,height:chip.height,fill:getColorFromString2(chip.chipId,chipAlpha)});for(let pin of chip.pins)graphics.points.push({label:`${pin.pinId}
|
|
651
651
|
${pin._facingDirection??getPinDirection2(pin,chip)}`,x:pin.x,y:pin.y,color:getColorFromString2(pin.pinId,.8)})}for(let directConn of inputProblem.directConnections){let[pinId1,pinId2]=directConn.pinIds,pin1=pinIdMap.get(pinId1),pin2=pinIdMap.get(pinId2);arePinsInDifferentSchematicSections(inputProblem,pin1,pin2)||graphics.lines.push({points:[{x:pin1.x,y:pin1.y},{x:pin2.x,y:pin2.y}],strokeColor:getColorFromString2(directConn.netId??`${pinId1}-${pinId2}`,connectionAlpha)})}for(let netConn of inputProblem.netConnections){let pins=netConn.pinIds.map(pinId=>pinIdMap.get(pinId));for(let i3=0;i3<pins.length-1;i3++)for(let j4=i3+1;j4<pins.length;j4++){let pin1=pins[i3],pin2=pins[j4];arePinsInDifferentSchematicSections(inputProblem,pin1,pin2)||graphics.lines.push({points:[{x:pin1.x,y:pin1.y},{x:pin2.x,y:pin2.y}],strokeColor:getColorFromString2(netConn.netId,connectionAlpha),strokeDash:"4 2"})}}return graphics},MspConnectionPairSolver=class extends BaseSolver5{constructor({inputProblem}){super();__publicField(this,"inputProblem");__publicField(this,"mspConnectionPairs",[]);__publicField(this,"dcConnMap");__publicField(this,"globalConnMap");__publicField(this,"queuedDcNetIds");__publicField(this,"chipMap");__publicField(this,"maxMspPairDistance");__publicField(this,"pinMap");__publicField(this,"userNetIdByPinId");this.inputProblem=inputProblem,this.maxMspPairDistance=inputProblem.maxMspPairDistance??1;let{directConnMap,netConnMap}=getConnectivityMapsFromInputProblem(inputProblem);this.dcConnMap=directConnMap,this.globalConnMap=netConnMap,this.pinMap={};for(let chip of inputProblem.chips)for(let pin of chip.pins)this.pinMap[pin.pinId]={...pin,chipId:chip.chipId};this.chipMap={};for(let chip of inputProblem.chips)this.chipMap[chip.chipId]=chip;this.userNetIdByPinId={};for(let dc3 of inputProblem.directConnections)if(dc3.netId){let[a3,b3]=dc3.pinIds;this.userNetIdByPinId[a3]=dc3.netId,this.userNetIdByPinId[b3]=dc3.netId}for(let nc3 of inputProblem.netConnections)for(let pid of nc3.pinIds)this.userNetIdByPinId[pid]=nc3.netId;this.queuedDcNetIds=Object.keys(netConnMap.netMap)}getConstructorParams(){return{inputProblem:this.inputProblem}}_step(){if(this.queuedDcNetIds.length===0){this.solved=!0;return}let dcNetId=this.queuedDcNetIds.shift(),directlyConnectedPins=this.globalConnMap.getIdsConnectedToNet(dcNetId).filter(id2=>!!this.pinMap[id2]);if(directlyConnectedPins.length<=1)return;if(directlyConnectedPins.length===2){let[pin1,pin2]=directlyConnectedPins,p12=this.pinMap[pin1],p22=this.pinMap[pin2];if(Math.abs(p12.x-p22.x)+Math.abs(p12.y-p22.y)>this.maxMspPairDistance||arePinsInDifferentSchematicSections(this.inputProblem,p12,p22))return;let pinIdMap2=new Map(Object.entries(this.pinMap));if(doesPairCrossRestrictedCenterLines({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:pinIdMap2,p1:p12,p2:p22}))return;let globalConnNetId=this.globalConnMap.getNetConnectedToId(pin1),userNetId=this.userNetIdByPinId[pin1]??this.userNetIdByPinId[pin2];this.mspConnectionPairs.push({mspPairId:`${pin1}-${pin2}`,dcConnNetId:dcNetId,globalConnNetId,userNetId,pins:[p12,p22]});return}let pinIdMap=new Map(Object.entries(this.pinMap)),msp=getOrthogonalMinimumSpanningTree(directlyConnectedPins.map(p4=>this.pinMap[p4]).filter(Boolean),{maxDistance:this.maxMspPairDistance,forbidEdge:(a3,b3)=>arePinsInDifferentSchematicSections(this.inputProblem,a3,b3)||doesPairCrossRestrictedCenterLines({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap,p1:a3,p2:b3})});for(let[pin1,pin2]of msp){let p1Obj=this.pinMap[pin1],p2Obj=this.pinMap[pin2];if(arePinsInDifferentSchematicSections(this.inputProblem,p1Obj,p2Obj)||doesPairCrossRestrictedCenterLines({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap,p1:p1Obj,p2:p2Obj}))continue;let globalConnNetId=this.globalConnMap.getNetConnectedToId(pin1),userNetId=this.userNetIdByPinId[pin1]??this.userNetIdByPinId[pin2];this.mspConnectionPairs.push({mspPairId:`${pin1}-${pin2}`,dcConnNetId:dcNetId,globalConnNetId,userNetId,pins:[p1Obj,p2Obj]})}}visualize(){let graphics=visualizeInputProblem2(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let pair of this.mspConnectionPairs)graphics.lines.push({points:[{x:pair.pins[0].x,y:pair.pins[0].y},{x:pair.pins[1].x,y:pair.pins[1].y}],strokeColor:getColorFromString2(pair.mspPairId,.75)});return graphics}};function getInputChipBounds(chip){let halfWidth=chip.width/2,halfHeight=chip.height/2;return{minX:chip.center.x-halfWidth,maxX:chip.center.x+halfWidth,minY:chip.center.y-halfHeight,maxY:chip.center.y+halfHeight}}var chipToRect=chip=>{let b3=getInputChipBounds(chip);return{chipId:chip.chipId,...b3}},getObstacleRects=problem=>problem.chips.map(chipToRect),EPS2=1e-9,isVertical=(a3,b3,eps=EPS2)=>Math.abs(a3.x-b3.x)<eps,isHorizontal=(a3,b3,eps=EPS2)=>Math.abs(a3.y-b3.y)<eps,segmentIntersectsRect=(a3,b3,r5,eps=EPS2)=>{let vert=isVertical(a3,b3,eps),horz=isHorizontal(a3,b3,eps);if(!vert&&!horz)return!1;if(vert){let x4=a3.x;if(x4<r5.minX-eps||x4>r5.maxX+eps)return!1;let segMinY=Math.min(a3.y,b3.y),segMaxY=Math.max(a3.y,b3.y);return Math.min(segMaxY,r5.maxY)-Math.max(segMinY,r5.minY)>eps}else{let y4=a3.y;if(y4<r5.minY-eps||y4>r5.maxY+eps)return!1;let segMinX=Math.min(a3.x,b3.x),segMaxX=Math.max(a3.x,b3.x);return Math.min(segMaxX,r5.maxX)-Math.max(segMinX,r5.minX)>eps}},findFirstCollision=(pts,rects,opts={})=>{for(let i3=0;i3<pts.length-1;i3++){let a3=pts[i3],b3=pts[i3+1],excluded=opts.excludeRectIdsForSegment?.(i3)??new Set;for(let r5 of rects)if(!excluded.has(r5.chipId)&&segmentIntersectsRect(a3,b3,r5))return{segIndex:i3,rect:r5}}return null},isPathCollidingWithObstacles=(path,obstacles)=>{for(let i3=0;i3<path.length-1;i3++)for(let obstacle of obstacles)if(segmentIntersectsRect(path[i3],path[i3+1],obstacle))return!0;return!1},EPS22=1e-9,aabbFromPoints=(a3,b3)=>({minX:Math.min(a3.x,b3.x),maxX:Math.max(a3.x,b3.x),minY:Math.min(a3.y,b3.y),maxY:Math.max(a3.y,b3.y)}),midBetweenPointAndRect=(axis,p4,r5,eps=EPS22)=>axis==="x"?p4.x<r5.minX-eps?[(p4.x+r5.minX)/2]:p4.x>r5.maxX+eps?[(p4.x+r5.maxX)/2]:[r5.minX-.2,r5.maxX+.2]:p4.y<r5.minY-eps?[(p4.y+r5.minY)/2]:p4.y>r5.maxY+eps?[(p4.y+r5.maxY)/2]:[r5.minY-.2,r5.maxY+.2],candidateMidsFromSet=(axis,colliding,rectsById,collisionRectIds,aabb,eps=EPS22)=>{let setRects=[...collisionRectIds].map(id2=>rectsById.get(id2)).filter(r5=>!!r5);if(axis==="x"){let leftBoundaries=[aabb.minX,...setRects.map(r5=>r5.maxX)].filter(v4=>v4<colliding.minX-eps),rightBoundaries=[aabb.maxX,...setRects.map(r5=>r5.minX)].filter(v4=>v4>colliding.maxX+eps),leftNeighbor=leftBoundaries.length>0?Math.max(...leftBoundaries):void 0,rightNeighbor=rightBoundaries.length>0?Math.min(...rightBoundaries):void 0,out=[];return leftNeighbor!==void 0&&out.push((leftNeighbor+colliding.minX)/2),rightNeighbor!==void 0&&out.push((colliding.maxX+rightNeighbor)/2),out}else{let bottomBoundaries=[aabb.minY,...setRects.map(r5=>r5.maxY)].filter(v4=>v4<colliding.minY-eps),topBoundaries=[aabb.maxY,...setRects.map(r5=>r5.minY)].filter(v4=>v4>colliding.maxY+eps),bottomNeighbor=bottomBoundaries.length>0?Math.max(...bottomBoundaries):void 0,topNeighbor=topBoundaries.length>0?Math.min(...topBoundaries):void 0,out=[];return bottomNeighbor!==void 0&&out.push((bottomNeighbor+colliding.minY)/2),topNeighbor!==void 0&&out.push((colliding.maxY+topNeighbor)/2),out}},EPS3=1e-9,shiftSegmentOrth=(pts,segIndex,axis,newCoord,eps=EPS3)=>{if(segIndex<0||segIndex>=pts.length-1)return null;let a3=pts[segIndex],b3=pts[segIndex+1],vert=isVertical(a3,b3,eps),horz=isHorizontal(a3,b3,eps);if(!vert&&!horz||vert&&axis!=="x"||horz&&axis!=="y")return null;let out=pts.map(p4=>({...p4}));if(axis==="x"){if(Math.abs(a3.x-newCoord)<eps&&Math.abs(b3.x-newCoord)<eps)return null;out[segIndex]={...out[segIndex],x:newCoord},out[segIndex+1]={...out[segIndex+1],x:newCoord}}else{if(Math.abs(a3.y-newCoord)<eps&&Math.abs(b3.y-newCoord)<eps)return null;out[segIndex]={...out[segIndex],y:newCoord},out[segIndex+1]={...out[segIndex+1],y:newCoord}}if(segIndex-1>=0){let p4=out[segIndex-1],q4=out[segIndex];if(Math.abs(p4.x-q4.x)+Math.abs(p4.y-q4.y)<eps)return null}if(segIndex+2<=out.length-1){let p4=out[segIndex+1],q4=out[segIndex+2];if(Math.abs(p4.x-q4.x)+Math.abs(p4.y-q4.y)<eps)return null}for(let i3=0;i3<out.length-1;i3++){let u5=out[i3],v4=out[i3+1];if(!isHorizontal(u5,v4,eps)&&!isVertical(u5,v4,eps))return null}return out},pathKey=(pts,decimals=6)=>pts.map(p4=>`${p4.x.toFixed(decimals)},${p4.y.toFixed(decimals)}`).join("|"),SchematicTraceSingleLineSolver2=class extends BaseSolver5{constructor(params){super();__publicField(this,"pins");__publicField(this,"inputProblem");__publicField(this,"chipMap");__publicField(this,"obstacles");__publicField(this,"rectById");__publicField(this,"aabb");__publicField(this,"baseElbow");__publicField(this,"solvedTracePath",null);__publicField(this,"queue",[]);__publicField(this,"visited",new Set);this.pins=params.pins,this.inputProblem=params.inputProblem,this.chipMap=params.chipMap;for(let pin of this.pins)if(!pin._facingDirection){let chip=this.chipMap[pin.chipId];pin._facingDirection=getPinDirection2(pin,chip)}this.obstacles=getObstacleRects(this.inputProblem),this.rectById=new Map(this.obstacles.map(r5=>[r5.chipId,r5]));let[pin1,pin2]=this.pins;this.baseElbow=calculateElbow({x:pin1.x,y:pin1.y,facingDirection:pin1._facingDirection},{x:pin2.x,y:pin2.y,facingDirection:pin2._facingDirection},{overshoot:.2}),this.aabb=aabbFromPoints({x:pin1.x,y:pin1.y},{x:pin2.x,y:pin2.y}),this.queue.push({path:this.baseElbow,collisionChipIds:new Set}),this.visited.add(pathKey(this.baseElbow))}getConstructorParams(){return{chipMap:this.chipMap,pins:this.pins,inputProblem:this.inputProblem}}axisOfSegment(a3,b3){return isVertical(a3,b3)?"x":isHorizontal(a3,b3)?"y":null}pathLength(pts){let sum=0;for(let i3=0;i3<pts.length-1;i3++)sum+=Math.abs(pts[i3+1].x-pts[i3].x)+Math.abs(pts[i3+1].y-pts[i3].y);return sum}_step(){if(this.solvedTracePath){this.solved=!0;return}let state2=this.queue.shift();if(!state2){this.failed=!0,this.error="No collision-free path found";return}let{path,collisionChipIds}=state2,[PA2,PB]=this.pins,collision=findFirstCollision(path,this.obstacles);if(!collision){let first=path[0],last=path[path.length-1],EPS102=1e-9,samePoint2=(p4,q4)=>Math.abs(p4.x-q4.x)<EPS102&&Math.abs(p4.y-q4.y)<EPS102;samePoint2(first,{x:PA2.x,y:PA2.y})&&samePoint2(last,{x:PB.x,y:PB.y})&&(this.solvedTracePath=path,this.solved=!0);return}let{segIndex,rect}=collision,isFirstSegment=segIndex===0,isLastSegment=segIndex===path.length-2;if(isFirstSegment){if(path.length<3)return;segIndex=1}else if(isLastSegment){if(path.length<3)return;segIndex=path.length-3}let a3=path[segIndex],b3=path[segIndex+1],axis=this.axisOfSegment(a3,b3);if(!axis)return;let candidates=[];if(collisionChipIds.size===0){let m12=midBetweenPointAndRect(axis,{x:PA2.x,y:PA2.y},rect),m22=midBetweenPointAndRect(axis,{x:PB.x,y:PB.y},rect),allCandidates=[...m12,...m22],uniqueCandidates=[...new Set(allCandidates)];candidates.push(...uniqueCandidates)}else{let mids=candidateMidsFromSet(axis,rect,this.rectById,collisionChipIds,this.aabb);candidates.push(...mids)}let newStates=[];for(let coord of candidates){let newPath=shiftSegmentOrth(path,segIndex,axis,coord);if(!newPath)continue;let key=pathKey(newPath);if(this.visited.has(key))continue;this.visited.add(key);let nextSet=new Set(collisionChipIds);nextSet.add(rect.chipId);let len=this.pathLength(newPath);newStates.push({path:newPath,collisionRectIds:nextSet,len})}newStates.sort((a22,b22)=>a22.len-b22.len);for(let st3 of newStates)this.queue.push({path:st3.path,collisionChipIds:st3.collisionRectIds})}visualize(){let g6=visualizeInputProblem2(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});g6.lines.push({points:this.baseElbow,strokeColor:"red",strokeDash:"4 4"});let[pin1,pin2]=this.pins;g6.lines.push({points:[{x:pin1.x,y:pin1.y},{x:pin2.x,y:pin2.y}],strokeColor:"blue",strokeDash:"5 5"});for(let{path,collisionChipIds:collisionRectIds}of this.queue)g6.lines.push({points:path,strokeColor:"teal",strokeDash:"2 2"});return this.solvedTracePath?g6.lines.push({points:this.solvedTracePath,strokeColor:"green"}):this.queue.length>0&&g6.lines.push({points:this.queue[0].path,strokeColor:"orange"}),g6}},SchematicTraceLinesSolver=class extends BaseSolver5{constructor(params){super();__publicField(this,"inputProblem");__publicField(this,"mspConnectionPairs");__publicField(this,"dcConnMap");__publicField(this,"globalConnMap");__publicField(this,"queuedConnectionPairs");__publicField(this,"chipMap");__publicField(this,"currentConnectionPair",null);__publicField(this,"solvedTracePaths",[]);__publicField(this,"failedConnectionPairs",[]);this.inputProblem=params.inputProblem,this.mspConnectionPairs=params.mspConnectionPairs,this.dcConnMap=params.dcConnMap,this.globalConnMap=params.globalConnMap,this.chipMap=params.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 connectionPair=this.queuedConnectionPairs.shift();if(!connectionPair){this.solved=!0;return}this.currentConnectionPair=connectionPair;let{pins}=connectionPair;this.activeSubSolver=new SchematicTraceSingleLineSolver2({inputProblem:this.inputProblem,pins,chipMap:this.chipMap})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let graphics=visualizeInputProblem2(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let{mspPairId,tracePath}of this.solvedTracePaths)graphics.lines.push({points:tracePath,strokeColor:"green"});for(let pair of this.failedConnectionPairs)graphics.lines.push({points:[{x:pair.pins[0].x,y:pair.pins[0].y},{x:pair.pins[1].x,y:pair.pins[1].y}],strokeColor:"red",strokeDash:"4 2"});return graphics}},applyJogToTerminalSegment=({pts,segmentIndex:si3,offset,JOG_SIZE,EPS:EPS102=1e-6})=>{if(si3!==0&&si3!==pts.length-2)return;let start=pts[si3],end=pts[si3+1],isVertical4=Math.abs(start.x-end.x)<EPS102,isHorizontal3=Math.abs(start.y-end.y)<EPS102;if(!isVertical4&&!isHorizontal3)return;let segDir=isVertical4?end.y>start.y?1:-1:end.x>start.x?1:-1;if(si3===0)if(isVertical4){let jogY=start.y+segDir*JOG_SIZE;pts.splice(1,1,{x:start.x,y:jogY},{x:start.x+offset,y:jogY},{x:end.x+offset,y:end.y})}else{let jogX=start.x+segDir*JOG_SIZE;pts.splice(1,1,{x:jogX,y:start.y},{x:jogX,y:start.y+offset},{x:end.x,y:end.y+offset})}else if(isVertical4){let jogY=end.y-segDir*JOG_SIZE;pts.splice(si3,1,{x:start.x+offset,y:start.y},{x:end.x+offset,y:jogY},{x:end.x,y:jogY})}else{let jogX=end.x-segDir*JOG_SIZE;pts.splice(si3,1,{x:start.x,y:start.y+offset},{x:jogX,y:end.y+offset},{x:jogX,y:end.y})}},TraceOverlapIssueSolver=class extends BaseSolver5{constructor(params){super();__publicField(this,"overlappingTraceSegments");__publicField(this,"traceNetIslands");__publicField(this,"SHIFT_DISTANCE",.1);__publicField(this,"correctedTraceMap",{});this.overlappingTraceSegments=params.overlappingTraceSegments,this.traceNetIslands=params.traceNetIslands;for(let{connNetId,pathsWithOverlap}of this.overlappingTraceSegments)for(let{solvedTracePathIndex,traceSegmentIndex}of pathsWithOverlap){let mspPairId=this.traceNetIslands[connNetId][solvedTracePathIndex].mspPairId;this.correctedTraceMap[mspPairId]=this.traceNetIslands[connNetId][solvedTracePathIndex]}}_step(){let offsets=this.overlappingTraceSegments.map((_4,idx)=>{let n4=Math.floor(idx/2)+1;return(idx%2===0?-n4:n4)*this.SHIFT_DISTANCE}),eq=(a3,b3)=>Math.abs(a3-b3)<1e-6,samePoint2=(p4,q4)=>!!p4&&!!q4&&eq(p4.x,q4.x)&&eq(p4.y,q4.y);this.overlappingTraceSegments.forEach((group,gidx)=>{let offset=offsets[gidx],byPath=new Map;for(let loc of group.pathsWithOverlap)byPath.has(loc.solvedTracePathIndex)||byPath.set(loc.solvedTracePathIndex,new Set),byPath.get(loc.solvedTracePathIndex).add(loc.traceSegmentIndex);for(let[pathIdx,segIdxSet]of byPath){let original=this.traceNetIslands[group.connNetId][pathIdx],current3=this.correctedTraceMap[original.mspPairId]??original,pts=current3.tracePath.map(p4=>({...p4})),segIdxs=Array.from(segIdxSet).sort((a3,b3)=>a3-b3),segIdxsRev=Array.from(segIdxSet).sort((a3,b3)=>a3-b3).reverse(),JOG_SIZE=this.SHIFT_DISTANCE;for(let si3 of segIdxsRev)if(!(si3<0||si3>=pts.length-1))if(si3===0||si3===pts.length-2)applyJogToTerminalSegment({pts,segmentIndex:si3,offset,JOG_SIZE,EPS:1e-6});else{let start=pts[si3],end=pts[si3+1],isVertical4=Math.abs(start.x-end.x)<1e-6,isHorizontal3=Math.abs(start.y-end.y)<1e-6;if(!isVertical4&&!isHorizontal3)continue;isVertical4?(start.x+=offset,end.x+=offset):(start.y+=offset,end.y+=offset)}let cleaned=[];for(let p4 of pts)(cleaned.length===0||!samePoint2(cleaned[cleaned.length-1],p4))&&cleaned.push(p4);this.correctedTraceMap[original.mspPairId]={...current3,tracePath:cleaned}}}),this.solved=!0}visualize(){let graphics={lines:[],points:[],rects:[],circles:[]};for(let group of this.overlappingTraceSegments)for(let{solvedTracePathIndex,traceSegmentIndex}of group.pathsWithOverlap){let path=this.traceNetIslands[group.connNetId][solvedTracePathIndex],segStart=path.tracePath[traceSegmentIndex],segEnd=path.tracePath[traceSegmentIndex+1];graphics.lines.push({points:[segStart,segEnd],strokeColor:"red"})}for(let trace of Object.values(this.correctedTraceMap))graphics.lines.push({points:trace.tracePath,strokeColor:"blue",strokeDash:"4 2"});return graphics}},TraceOverlapShiftSolver=class extends BaseSolver5{constructor(params){super();__publicField(this,"inputProblem");__publicField(this,"inputTracePaths");__publicField(this,"globalConnMap");__publicField(this,"traceNetIslands",{});__publicField(this,"correctedTraceMap",{});__publicField(this,"cleanupPhase",null);this.inputProblem=params.inputProblem,this.inputTracePaths=params.inputTracePaths,this.globalConnMap=params.globalConnMap;for(let tracePath of this.inputTracePaths){let{mspPairId}=tracePath;this.correctedTraceMap[mspPairId]=tracePath}this.traceNetIslands=this.computeTraceNetIslands()}getConstructorParams(){return{inputProblem:this.inputProblem,inputTracePaths:this.inputTracePaths,globalConnMap:this.globalConnMap}}computeTraceNetIslands(){let islands={};for(let original of this.inputTracePaths){let path=this.correctedTraceMap[original.mspPairId]??original,key=path.globalConnNetId;islands[key]||(islands[key]=[]),islands[key].push(path)}return islands}findNextOverlapIssue(){let netIds=Object.keys(this.traceNetIslands);for(let i3=0;i3<netIds.length;i3++)for(let j4=i3+1;j4<netIds.length;j4++){let netA=netIds[i3],netB=netIds[j4],pathsA=this.traceNetIslands[netA]||[],pathsB=this.traceNetIslands[netB]||[],overlapsA=[],overlapsB=[],seenA=new Set,seenB=new Set,overlaps1D=(a12,a22,b12,b22)=>{let minA=Math.min(a12,a22),maxA=Math.max(a12,a22),minB=Math.min(b12,b22),maxB=Math.max(b12,b22);return Math.min(maxA,maxB)-Math.max(minA,minB)>.002};for(let pa3=0;pa3<pathsA.length;pa3++){let ptsA=pathsA[pa3].tracePath;for(let sa3=0;sa3<ptsA.length-1;sa3++){let a12=ptsA[sa3],a22=ptsA[sa3+1],aVert=Math.abs(a12.x-a22.x)<.002,aHorz=Math.abs(a12.y-a22.y)<.002;if(!(!aVert&&!aHorz))for(let pb2=0;pb2<pathsB.length;pb2++){let ptsB=pathsB[pb2].tracePath;for(let sb3=0;sb3<ptsB.length-1;sb3++){let b12=ptsB[sb3],b22=ptsB[sb3+1],bVert=Math.abs(b12.x-b22.x)<.002,bHorz=Math.abs(b12.y-b22.y)<.002;if(!(!bVert&&!bHorz)){if(aVert&&bVert){if(Math.abs(a12.x-b12.x)<.002&&overlaps1D(a12.y,a22.y,b12.y,b22.y)){let keyA=`${pa3}:${sa3}`,keyB=`${pb2}:${sb3}`;seenA.has(keyA)||(overlapsA.push({solvedTracePathIndex:pa3,traceSegmentIndex:sa3}),seenA.add(keyA)),seenB.has(keyB)||(overlapsB.push({solvedTracePathIndex:pb2,traceSegmentIndex:sb3}),seenB.add(keyB))}}else if(aHorz&&bHorz&&Math.abs(a12.y-b12.y)<.002&&overlaps1D(a12.x,a22.x,b12.x,b22.x)){let keyA=`${pa3}:${sa3}`,keyB=`${pb2}:${sb3}`;seenA.has(keyA)||(overlapsA.push({solvedTracePathIndex:pa3,traceSegmentIndex:sa3}),seenA.add(keyA)),seenB.has(keyB)||(overlapsB.push({solvedTracePathIndex:pb2,traceSegmentIndex:sb3}),seenB.add(keyB))}}}}}}if(overlapsA.length>0&&overlapsB.length>0)return{overlappingTraceSegments:[{connNetId:netA,pathsWithOverlap:overlapsA},{connNetId:netB,pathsWithOverlap:overlapsB}]}}return null}findNextDiagonalSegment(){for(let mspPairId in this.correctedTraceMap){let tracePath=this.correctedTraceMap[mspPairId].tracePath;for(let i3=0;i3<tracePath.length-1;i3++){let p12=tracePath[i3],p22=tracePath[i3+1],isHorizontal3=Math.abs(p12.y-p22.y)<.002,isVertical4=Math.abs(p12.x-p22.x)<.002;if(!isHorizontal3&&!isVertical4)return{mspPairId,tracePath,i:i3,p1:p12,p2:p22}}}return null}findAndFixNextDiagonalSegment(){let diagonalInfo=this.findNextDiagonalSegment();if(!diagonalInfo)return!1;let{mspPairId,tracePath,i:i3,p1:p12,p2:p22}=diagonalInfo,EPS102=.002,p02=i3>0?tracePath[i3-1]:null,p32=i3+2<tracePath.length?tracePath[i3+2]:null,prevIsVertical=p02?Math.abs(p02.x-p12.x)<EPS102:!1,prevIsHorizontal=p02?Math.abs(p02.y-p12.y)<EPS102:!1,nextIsVertical=p32?Math.abs(p22.x-p32.x)<EPS102:!1,nextIsHorizontal=p32?Math.abs(p22.y-p32.y)<EPS102:!1,elbow1={x:p12.x,y:p22.y},elbow2={x:p22.x,y:p12.y},score1=0;prevIsVertical&&score1++,nextIsHorizontal&&score1++;let score2=0;prevIsHorizontal&&score2++,nextIsVertical&&score2++;let elbowPoint=score1<score2?elbow1:elbow2;return tracePath.splice(i3+1,0,elbowPoint),!0}_step(){if(this.activeSubSolver?.solved){for(let[mspPairId,newTrace]of Object.entries(this.activeSubSolver.correctedTraceMap))this.correctedTraceMap[mspPairId]=newTrace;this.activeSubSolver=null,this.traceNetIslands=this.computeTraceNetIslands()}if(this.activeSubSolver){this.activeSubSolver.step();return}let overlapIssue=this.findNextOverlapIssue();if(overlapIssue===null){if(this.cleanupPhase===null&&(this.cleanupPhase="diagonals"),this.cleanupPhase==="diagonals"){this.findAndFixNextDiagonalSegment()||(this.cleanupPhase="done",this.solved=!0);return}this.solved=!0;return}let{overlappingTraceSegments}=overlapIssue;this.activeSubSolver=new TraceOverlapIssueSolver({overlappingTraceSegments,traceNetIslands:this.traceNetIslands})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let graphics=visualizeInputProblem2(this.inputProblem);graphics.circles=graphics.circles||[];for(let trace of Object.values(this.correctedTraceMap))graphics.lines.push({points:trace.tracePath,strokeColor:"purple"});if(this.cleanupPhase==="diagonals"){let diagonalInfo=this.findNextDiagonalSegment();diagonalInfo&&graphics.lines.push({points:[diagonalInfo.p1,diagonalInfo.p2],strokeColor:"red",strokeWidth:.05})}return graphics}},ChipObstacleSpatialIndex=class{constructor(chips){__publicField(this,"chips");__publicField(this,"spatialIndex");__publicField(this,"spatialIndexIdToChip");this.chips=chips.map(chip=>({...chip,bounds:getInputChipBounds(chip),spatialIndexId:null})),this.spatialIndexIdToChip=new Map,this.spatialIndex=new Flatbush(chips.length);for(let chip of this.chips)chip.spatialIndexId=this.spatialIndex.add(chip.bounds.minX,chip.bounds.minY,chip.bounds.maxX,chip.bounds.maxY),this.spatialIndexIdToChip.set(chip.spatialIndexId,chip);this.spatialIndex.finish()}getChipsInBounds(bounds){return this.spatialIndex.search(bounds.minX,bounds.minY,bounds.maxX,bounds.maxY).map(id2=>this.spatialIndexIdToChip.get(id2))}doesOrthogonalLineIntersectChip(line2,opts={}){let excludeChipIds=opts.excludeChipIds??[],[p12,p22]=line2,{x:x12,y:y12}=p12,{x:x22,y:y22}=p22;return this.getChipsInBounds({minX:Math.min(x12,x22),minY:Math.min(y12,y22),maxX:Math.max(x12,x22),maxY:Math.max(y12,y22)}).filter(chip=>!excludeChipIds.includes(chip.chipId)).length>0}},NET_LABEL_HORIZONTAL_WIDTH=.45,NET_LABEL_HORIZONTAL_HEIGHT=.2;function getDimsForOrientation(params){let{orientation:orientation4,netLabelWidth,netLabelHeight}=params,horizWidth=typeof netLabelWidth=="number"?netLabelWidth:NET_LABEL_HORIZONTAL_WIDTH,horizHeight=typeof netLabelHeight=="number"?netLabelHeight:NET_LABEL_HORIZONTAL_HEIGHT;return orientation4==="y+"||orientation4==="y-"?{width:horizHeight,height:horizWidth}:{width:horizWidth,height:horizHeight}}function getCenterFromAnchor(anchor,orientation4,width,height){switch(orientation4){case"x+":return{x:anchor.x+width/2,y:anchor.y};case"x-":return{x:anchor.x-width/2,y:anchor.y};case"y+":return{x:anchor.x,y:anchor.y+height/2};case"y-":return{x:anchor.x,y:anchor.y-height/2}}}function getRectBounds(center2,w4,h6){return{minX:center2.x-w4/2,minY:center2.y-h6/2,maxX:center2.x+w4/2,maxY:center2.y+h6/2}}function segmentIntersectsRect2(p12,p22,rect,EPS102=1e-9){let isVert=Math.abs(p12.x-p22.x)<EPS102,isHorz=Math.abs(p12.y-p22.y)<EPS102;if(!isVert&&!isHorz)return!1;if(isVert){let x4=p12.x;if(x4<rect.minX-EPS102||x4>rect.maxX+EPS102)return!1;let segMinY=Math.min(p12.y,p22.y),segMaxY=Math.max(p12.y,p22.y);return Math.min(segMaxY,rect.maxY)-Math.max(segMinY,rect.minY)>EPS102}else{let y4=p12.y;if(y4<rect.minY-EPS102||y4>rect.maxY+EPS102)return!1;let segMinX=Math.min(p12.x,p22.x),segMaxX=Math.max(p12.x,p22.x);return Math.min(segMaxX,rect.maxX)-Math.max(segMinX,rect.minX)>EPS102}}function rectIntersectsAnyTrace(bounds,inputTraceMap,hostPathId,hostSegIndex){for(let[pairId,solved]of Object.entries(inputTraceMap)){let pts=solved.tracePath;for(let i3=0;i3<pts.length-1;i3++)if(!(pairId===hostPathId&&i3===hostSegIndex)&&segmentIntersectsRect2(pts[i3],pts[i3+1],bounds))return{hasIntersection:!0,mspPairId:pairId,segIndex:i3}}return{hasIntersection:!1}}function lengthOfTrace(path){let sum=0,pts=path.tracePath;for(let i3=0;i3<pts.length-1;i3++)sum+=Math.abs(pts[i3+1].x-pts[i3].x)+Math.abs(pts[i3+1].y-pts[i3].y);return sum}function chooseHostTraceForGroup(params){let{inputProblem,inputTraceMap,globalConnNetId,fallbackTrace,mspConnectionPairIds}=params,chipsById=Object.fromEntries(inputProblem.chips.map(c4=>[c4.chipId,c4])),groupTraces=Object.values(inputTraceMap).filter(t52=>t52.globalConnNetId===globalConnNetId);if(mspConnectionPairIds&&mspConnectionPairIds.length>0){let idSet=new Set(mspConnectionPairIds);groupTraces=groupTraces.filter(t52=>t52.mspConnectionPairIds.some(id2=>idSet.has(id2)))}let chipIdsInGroup=new Set;for(let t52 of groupTraces)chipIdsInGroup.add(t52.pins[0].chipId),chipIdsInGroup.add(t52.pins[1].chipId);let largestChipId=null,largestPinCount=-1;for(let id2 of chipIdsInGroup){let count=chipsById[id2]?.pins?.length??0;count>largestPinCount&&(largestPinCount=count,largestChipId=id2)}let hostCandidates=largestChipId==null?[]:groupTraces.filter(t52=>t52.pins[0].chipId===largestChipId||t52.pins[1].chipId===largestChipId);return hostCandidates.length>0?hostCandidates.reduce((a3,b3)=>lengthOfTrace(a3)>=lengthOfTrace(b3)?a3:b3):fallbackTrace}function anchorsForSegment(a3,b3){return[{x:a3.x,y:a3.y},{x:(a3.x+b3.x)/2,y:(a3.y+b3.y)/2},{x:b3.x,y:b3.y}]}function solveNetLabelPlacementForPortOnlyPin(params){let{inputProblem,inputTraceMap,chipObstacleSpatialIndex,overlappingSameNetTraceGroup,availableOrientations,netLabelWidth,netLabelHeight}=params,pinId=overlappingSameNetTraceGroup.portOnlyPinId;if(!pinId)return{placement:null,testedCandidates:[],error:"No portOnlyPinId provided"};let pin=null,pinFacingDirection=null;for(let chip of inputProblem.chips){let p4=chip.pins.find(pp3=>pp3.pinId===pinId);if(p4){pin={x:p4.x,y:p4.y},pinFacingDirection=p4._facingDirection||getPinDirection2(p4,chip);break}}if(!pin||!pinFacingDirection)return{placement:null,testedCandidates:[],error:`Port-only pin not found: ${pinId}`};let orientations=availableOrientations.length>0?availableOrientations:["x+","x-","y+","y-"],anchor={x:pin.x,y:pin.y},outwardOf=o4=>o4==="x+"?{x:1,y:0}:o4==="x-"?{x:-1,y:0}:o4==="y+"?{x:0,y:1}:{x:0,y:-1},testedCandidates=[];for(let orientation4 of orientations){let{width:width2,height:height2}=getDimsForOrientation({orientation:orientation4,netLabelWidth,netLabelHeight}),baseCenter2=getCenterFromAnchor(anchor,orientation4,width2,height2),outward2=outwardOf(orientation4),offset2=.001,center2={x:baseCenter2.x+outward2.x*offset2,y:baseCenter2.y+outward2.y*offset2},bounds=getRectBounds(center2,width2,height2);if(chipObstacleSpatialIndex.getChipsInBounds(bounds).length>0){testedCandidates.push({center:center2,width:width2,height:height2,bounds,anchor,orientation:orientation4,status:"chip-collision",hostSegIndex:-1});continue}if(rectIntersectsAnyTrace(bounds,inputTraceMap,"",-1).hasIntersection){testedCandidates.push({center:center2,width:width2,height:height2,bounds,anchor,orientation:orientation4,status:"trace-collision",hostSegIndex:-1});continue}return testedCandidates.push({center:center2,width:width2,height:height2,bounds,anchor,orientation:orientation4,status:"ok",hostSegIndex:-1}),{placement:{globalConnNetId:overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:void 0,netId:overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[],pinIds:[pinId],orientation:orientation4,anchorPoint:anchor,width:width2,height:height2,center:center2},testedCandidates}}let fallbackOrientation=pinFacingDirection,{width,height}=getDimsForOrientation({orientation:fallbackOrientation,netLabelWidth}),baseCenter=getCenterFromAnchor(anchor,fallbackOrientation,width,height),outward=outwardOf(fallbackOrientation),offset=.001,fallbackCenter={x:baseCenter.x+outward.x*offset,y:baseCenter.y+outward.y*offset};return{placement:{globalConnNetId:overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:void 0,netId:overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[],pinIds:[pinId],orientation:fallbackOrientation,anchorPoint:anchor,width,height,center:fallbackCenter},testedCandidates}}function visualizeSingleNetLabelPlacementSolver(solver){let graphics=visualizeInputProblem2(solver.inputProblem),groupId=solver.overlappingSameNetTraceGroup.globalConnNetId,host=chooseHostTraceForGroup({inputProblem:solver.inputProblem,inputTraceMap:solver.inputTraceMap,globalConnNetId:groupId,fallbackTrace:solver.overlappingSameNetTraceGroup.overlappingTraces}),groupStroke=getColorFromString2(groupId,.9),groupFill=getColorFromString2(groupId,.5);for(let trace of Object.values(solver.inputTraceMap)){let isHost=host?trace.mspPairId===host.mspPairId:!1;graphics.lines.push({points:trace.tracePath})}for(let c4 of solver.testedCandidates){let fill=c4.status==="ok"?"rgba(0, 180, 0, 0.25)":c4.status==="chip-collision"?"rgba(220, 0, 0, 0.25)":c4.status==="trace-collision"?"rgba(220, 140, 0, 0.25)":"rgba(120, 120, 120, 0.15)",stroke=c4.status==="ok"?"green":c4.status==="chip-collision"?"red":c4.status==="trace-collision"?"orange":"gray",candidateLabel=c4.status==="ok"?"status: ok(valid net label candidate)":c4.status==="chip-collision"?"status: chip-collision":c4.status==="trace-collision"?"status: trace-collision":"status: parallel-to-segment";graphics.rects.push({center:{x:(c4.bounds.minX+c4.bounds.maxX)/2,y:(c4.bounds.minY+c4.bounds.maxY)/2},width:c4.width,height:c4.height,fill,strokeColor:stroke,label:`${candidateLabel}
|
|
652
652
|
orientation: ${c4.orientation}`}),graphics.points.push({x:c4.anchor.x,y:c4.anchor.y,color:stroke,label:`anchor
|
|
653
653
|
orientation: ${c4.orientation}`})}if(solver.netLabelPlacement){let p4=solver.netLabelPlacement;graphics.rects.push({center:p4.center,width:p4.width,height:p4.height,fill:"rgba(0, 128, 255, 0.35)",strokeColor:"blue",label:`netId: ${p4.netId}
|
|
@@ -797,7 +797,7 @@ ${spiceString}`)}catch(error2){debug11(`Failed to convert circuit JSON to SPICE:
|
|
|
797
797
|
`)}},__publicField(_a367,"token","generated"),__publicField(_a367,"parentToken","kicad_pcb"),_a367);SxClass.register(Generated);var _a368,PcbArc=(_a368=class extends SxClass{constructor(params={}){super();__publicField(this,"token","arc");__publicField(this,"_start");__publicField(this,"_mid");__publicField(this,"_end");__publicField(this,"_sxWidth");__publicField(this,"_sxLayer");__publicField(this,"_net");__publicField(this,"_sxUuid");params.start!==void 0&&(this.start=params.start),params.mid!==void 0&&(this.mid=params.mid),params.end!==void 0&&(this.end=params.end),params.width!==void 0&&(this.width=params.width),params.layer!==void 0&&(this.layer=params.layer),params.net!==void 0&&(this.net=params.net),params.uuid!==void 0&&(this.uuid=params.uuid)}static fromSexprPrimitives(primitiveSexprs){let arc2=new _a368;for(let primitive of primitiveSexprs){if(!Array.isArray(primitive)||primitive.length===0)throw new Error(`arc encountered unsupported child: ${JSON.stringify(primitive)}`);let[token,...args]=primitive;if(token==="start"){arc2._start=parsePoint(args,"start");continue}if(token==="mid"){arc2._mid=parsePoint(args,"mid");continue}if(token==="end"){arc2._end=parsePoint(args,"end");continue}if(token==="width"){arc2._sxWidth=new Width(parseNumber(args[0],"width"));continue}if(token==="layer"){let layerName=parseLayer(args);arc2._sxLayer=new Layer([layerName]);continue}if(token==="net"){arc2._net=parseNumber(args[0],"net");continue}if(token==="uuid"){arc2._sxUuid=new Uuid(parseString(args[0],"uuid"));continue}throw new Error(`arc encountered unsupported child token "${token}"`)}if(!arc2._start||!arc2._mid||!arc2._end)throw new Error("arc requires start, mid, and end child tokens");if(!arc2._sxLayer)throw new Error("arc requires a layer child token");return arc2}get start(){return this._start?{...this._start}:void 0}set start(value){this._start=value?{...value}:void 0}get mid(){return this._mid?{...this._mid}:void 0}set mid(value){this._mid=value?{...value}:void 0}get end(){return this._end?{...this._end}:void 0}set end(value){this._end=value?{...value}:void 0}get width(){return this._sxWidth?.value}set width(value){if(value===void 0){this._sxWidth=void 0;return}this._sxWidth=value instanceof Width?value:new Width(value)}get layer(){return this._sxLayer}set layer(value){if(value===void 0){this._sxLayer=void 0;return}this._sxLayer=value instanceof Layer?value:new Layer([value])}get net(){return this._net}set net(value){this._net=value}get uuid(){return this._sxUuid}set uuid(value){if(value===void 0){this._sxUuid=void 0;return}this._sxUuid=value instanceof Uuid?value:new Uuid(value)}getChildren(){return[]}getString(){let lines=["(arc"];return this._start&&lines.push(renderPoint("start",this._start)),this._mid&&lines.push(renderPoint("mid",this._mid)),this._end&&lines.push(renderPoint("end",this._end)),this._sxWidth&&lines.push(this._sxWidth.getStringIndented()),this._sxLayer&&lines.push(this._sxLayer.getStringIndented()),this._net!==void 0&&lines.push(` (net ${this._net})`),this._sxUuid&&lines.push(this._sxUuid.getStringIndented()),lines.push(")"),lines.join(`
|
|
798
798
|
`)}},__publicField(_a368,"token","arc"),__publicField(_a368,"parentToken","kicad_pcb"),_a368);SxClass.register(PcbArc);function parsePoint(args,label){if(args.length!==2)throw new Error(`arc ${label} expects two numeric values`);return{x:parseNumber(args[0],`${label}.x`),y:parseNumber(args[1],`${label}.y`)}}function parseNumber(value,label){let numeric=toNumberValue(value);if(numeric===void 0)throw new Error(`arc ${label} expects a numeric value`);return numeric}function parseString(value,label){if(typeof value!="string")throw new Error(`arc ${label} expects a string value`);return value}function parseLayer(args){if(args.length!==1)throw new Error("arc layer expects a single string value");return parseString(args[0],"layer")}function renderPoint(label,point7){return` (${label} ${point7.x} ${point7.y})`}var _a369,SegmentEnd=(_a369=class extends SxClass{constructor(x4,y4){super();__publicField(this,"token","end");__publicField(this,"_x");__publicField(this,"_y");this._x=x4,this._y=y4}static fromSexprPrimitives(primitiveSexprs){let[rawX,rawY]=primitiveSexprs,x4=toNumberValue(rawX),y4=toNumberValue(rawY);if(x4===void 0||y4===void 0)throw new Error("end expects two numeric arguments");return new _a369(x4,y4)}get x(){return this._x}set x(value){this._x=value}get y(){return this._y}set y(value){this._y=value}toObject(){return{x:this._x,y:this._y}}getChildren(){return[]}getString(){return`(end ${this._x} ${this._y})`}},__publicField(_a369,"token","end"),__publicField(_a369,"parentToken","segment"),_a369);SxClass.register(SegmentEnd);var truthyStrings4=new Set(["true","yes","1"]),_a370,SegmentLocked=(_a370=class extends SxPrimitiveBoolean{constructor(value){super(value);__publicField(this,"token","locked")}static fromSexprPrimitives(primitiveSexprs){let[rawValue]=primitiveSexprs;return typeof rawValue=="boolean"?new _a370(rawValue):typeof rawValue=="string"?new _a370(truthyStrings4.has(rawValue.toLowerCase())):new _a370(!1)}getString(){return`(locked ${this.value?"yes":"no"})`}},__publicField(_a370,"token","locked"),__publicField(_a370,"parentToken","segment"),_a370);SxClass.register(SegmentLocked);var _a371,SegmentNet=(_a371=class extends SxClass{constructor(idOrName,name){super();__publicField(this,"token","net");__publicField(this,"_id");__publicField(this,"_name");if(typeof idOrName=="number"){this._id=idOrName,this._name=name;return}this._name=idOrName}static fromSexprPrimitives(primitiveSexprs){let[rawId,rawName]=primitiveSexprs,id2=toNumberValue(rawId);if(id2!==void 0){let name2=rawName===void 0?void 0:toStringValue(rawName);return new _a371(id2,name2??void 0)}let name=toStringValue(rawId);if(name===void 0)throw new Error("net expects a numeric identifier or string name");return new _a371(name)}get id(){return this._id}set id(value){this._id=value}get name(){return this._name}set name(value){this._name=value===""?void 0:value}toObject(){return this._name===void 0?{id:this._id}:{id:this._id,name:this._name}}getChildren(){return[]}getString(){if(this._id===void 0)return`(net ${quoteSExprString(this._name??"")})`;let namePart=this._name?` ${quoteSExprString(this._name)}`:"";return`(net ${this._id}${namePart})`}},__publicField(_a371,"token","net"),__publicField(_a371,"parentToken","segment"),_a371);SxClass.register(SegmentNet);var _a372,SegmentStart=(_a372=class extends SxClass{constructor(x4,y4){super();__publicField(this,"token","start");__publicField(this,"_x");__publicField(this,"_y");this._x=x4,this._y=y4}static fromSexprPrimitives(primitiveSexprs){let[rawX,rawY]=primitiveSexprs,x4=toNumberValue(rawX),y4=toNumberValue(rawY);if(x4===void 0||y4===void 0)throw new Error("start expects two numeric arguments");return new _a372(x4,y4)}get x(){return this._x}set x(value){this._x=value}get y(){return this._y}set y(value){this._y=value}toObject(){return{x:this._x,y:this._y}}getChildren(){return[]}getString(){return`(start ${this._x} ${this._y})`}},__publicField(_a372,"token","start"),__publicField(_a372,"parentToken","segment"),_a372);SxClass.register(SegmentStart);var SUPPORTED_SINGLE_TOKENS12=new Set(["start","end","width","layer","net","tstamp","uuid","locked"]),_a373,Segment3=(_a373=class extends SxClass{constructor(params={}){super();__publicField(this,"token","segment");__publicField(this,"_sxStart");__publicField(this,"_sxEnd");__publicField(this,"_sxWidth");__publicField(this,"_sxLayer");__publicField(this,"_sxNet");__publicField(this,"_sxTstamp");__publicField(this,"_sxUuid");__publicField(this,"_sxLocked");params.start!==void 0&&(this.start=params.start),params.end!==void 0&&(this.end=params.end),params.width!==void 0&&(this.width=params.width),params.layer!==void 0&&(this.layer=params.layer),params.net!==void 0&&(this.net=params.net),params.tstamp!==void 0&&(this.tstamp=params.tstamp),params.uuid!==void 0&&(this.uuid=params.uuid),params.locked!==void 0&&(this.locked=params.locked)}static fromSexprPrimitives(primitiveSexprs){let segment2=new _a373,{propertyMap,arrayPropertyMap}=SxClass.parsePrimitivesToClassProperties(primitiveSexprs,this.token),unexpectedSingleTokens=Object.keys(propertyMap).filter(token=>!SUPPORTED_SINGLE_TOKENS12.has(token));if(unexpectedSingleTokens.length>0)throw new Error(`Unsupported child tokens inside segment expression: ${unexpectedSingleTokens.join(", ")}`);for(let[token,entries]of Object.entries(arrayPropertyMap)){if(!SUPPORTED_SINGLE_TOKENS12.has(token))throw new Error(`Unsupported child tokens inside segment expression: ${token}`);if(entries.length>1)throw new Error(`Segment does not support repeated child tokens: ${token}`)}segment2._sxStart=arrayPropertyMap.start?.[0]??propertyMap.start,segment2._sxEnd=arrayPropertyMap.end?.[0]??propertyMap.end,segment2._sxWidth=arrayPropertyMap.width?.[0]??propertyMap.width,segment2._sxLayer=arrayPropertyMap.layer?.[0]??propertyMap.layer,segment2._sxNet=arrayPropertyMap.net?.[0]??propertyMap.net;let locked=arrayPropertyMap.locked?.[0]??propertyMap.locked;return segment2._sxLocked=locked&&locked.value?locked:void 0,segment2._sxTstamp=arrayPropertyMap.tstamp?.[0]??propertyMap.tstamp,segment2._sxUuid=arrayPropertyMap.uuid?.[0]??propertyMap.uuid,segment2}get start(){return this._sxStart}set start(value){this._sxStart=this.normalizeStart(value)}get end(){return this._sxEnd}set end(value){this._sxEnd=this.normalizeEnd(value)}get startPoint(){return this._sxStart?.toObject()}get endPoint(){return this._sxEnd?.toObject()}get width(){return this._sxWidth?.value}set width(value){if(value===void 0){this._sxWidth=void 0;return}this._sxWidth=value instanceof Width?value:new Width(value)}get widthClass(){return this._sxWidth}set widthClass(value){this._sxWidth=value}get layer(){return this._sxLayer}set layer(value){if(value===void 0){this._sxLayer=void 0;return}if(value instanceof Layer){this._sxLayer=value;return}let names=Array.isArray(value)?value:[value];this._sxLayer=new Layer(names)}get net(){return this._sxNet}set net(value){if(value===void 0){this._sxNet=void 0;return}if(value instanceof SegmentNet){this._sxNet=value;return}this._sxNet=new SegmentNet(value.id,value.name)}get tstamp(){return this._sxTstamp}set tstamp(value){if(value===void 0){this._sxTstamp=void 0;return}this._sxTstamp=value instanceof Tstamp?value:new Tstamp(value)}get uuid(){return this._sxUuid}set uuid(value){if(value===void 0){this._sxUuid=void 0;return}this._sxUuid=value instanceof Uuid?value:new Uuid(value)}get locked(){return this._sxLocked?.value??!1}set locked(value){this._sxLocked=value?new SegmentLocked(!0):void 0}getChildren(){let children=[];return this._sxStart&&children.push(this._sxStart),this._sxEnd&&children.push(this._sxEnd),this._sxWidth&&children.push(this._sxWidth),this._sxLayer&&children.push(this._sxLayer),this._sxNet&&children.push(this._sxNet),this._sxLocked&&children.push(this._sxLocked),this._sxTstamp&&children.push(this._sxTstamp),this._sxUuid&&children.push(this._sxUuid),children}normalizeStart(value){if(value!==void 0)return value instanceof SegmentStart?value:new SegmentStart(value.x,value.y)}normalizeEnd(value){if(value!==void 0)return value instanceof SegmentEnd?value:new SegmentEnd(value.x,value.y)}},__publicField(_a373,"token","segment"),_a373);SxClass.register(Segment3);var SingleValueProperty=class extends SxClass{constructor(value){super();__publicField(this,"_value");__publicField(this,"quoteStringValue",!1);this._value=value}static fromSexprPrimitives(primitiveSexprs){let[valuePrimitive]=primitiveSexprs,value=this.parsePrimitiveValue(valuePrimitive),Constructor=this;return new Constructor(value)}static parsePrimitiveValue(value){let stringValue=toStringValue(value);if(stringValue===void 0)throw new Error(`${this.name} expects a primitive value`);return stringValue}get value(){return this._value}set value(value){this._value=value}getChildren(){return[]}formatValue(){return typeof this._value=="string"?this.quoteStringValue?quoteSExprString(this._value):this._value:`${this._value}`}getString(){return`(${this.token} ${this.formatValue()})`}},NumericListProperty=class extends SxClass{constructor(values){super();__publicField(this,"_values");this._values=values}static fromSexprPrimitives(primitiveSexprs){let values=primitiveSexprs.map(primitive=>{let value=toNumberValue(primitive);if(value===void 0)throw new Error(`${this.name} expects numeric primitives but received ${primitive}`);return value}),Constructor=this;return new Constructor(values)}get values(){return[...this._values]}set values(values){this._values=[...values]}getChildren(){return[]}getString(){return`(${this.token} ${this._values.join(" ")})`}},CoordinateProperty=class extends SxClass{constructor(x4,y4){super();__publicField(this,"_x");__publicField(this,"_y");this._x=x4,this._y=y4}static fromSexprPrimitives(primitiveSexprs){let[xPrimitive,yPrimitive]=primitiveSexprs,x4=toNumberValue(xPrimitive),y4=toNumberValue(yPrimitive);if(x4===void 0||y4===void 0)throw new Error(`${this.name} expects two numeric values`);let Constructor=this;return new Constructor(x4,y4)}get x(){return this._x}set x(value){this._x=value}get y(){return this._y}set y(value){this._y=value}getChildren(){return[]}getString(){return`(${this.token} ${this._x} ${this._y})`}},_a374,Capping=(_a374=class extends SingleValueProperty{constructor(){super(...arguments);__publicField(this,"token","capping")}},__publicField(_a374,"token","capping"),_a374);SxClass.register(Capping);var _a375,Back=(_a375=class extends SingleValueProperty{constructor(){super(...arguments);__publicField(this,"token","back")}},__publicField(_a375,"token","back"),_a375);SxClass.register(Back);var _a376,Front=(_a376=class extends SingleValueProperty{constructor(){super(...arguments);__publicField(this,"token","front")}},__publicField(_a376,"token","front"),_a376);SxClass.register(Front);var _a377,Covering=(_a377=class extends SxClass{constructor(params={}){super();__publicField(this,"token","covering");__publicField(this,"_sxFront");__publicField(this,"_sxBack");params.front!==void 0&&(this.front=params.front),params.back!==void 0&&(this.back=params.back)}static fromSexprPrimitives(primitiveSexprs){let{propertyMap}=SxClass.parsePrimitivesToClassProperties(primitiveSexprs,this.token);return new _a377({front:propertyMap.front,back:propertyMap.back})}get front(){return this._sxFront?.value}set front(value){if(value===void 0){this._sxFront=void 0;return}this._sxFront=value instanceof Front?value:new Front(value)}get back(){return this._sxBack?.value}set back(value){if(value===void 0){this._sxBack=void 0;return}this._sxBack=value instanceof Back?value:new Back(value)}getChildren(){let children=[];return this._sxFront&&children.push(this._sxFront),this._sxBack&&children.push(this._sxBack),children}},__publicField(_a377,"token","covering"),_a377);SxClass.register(Covering);var _a378,Filling=(_a378=class extends SingleValueProperty{constructor(){super(...arguments);__publicField(this,"token","filling")}},__publicField(_a378,"token","filling"),_a378);SxClass.register(Filling);var _a379,PlotParamProperty=(_a379=class extends SingleValueProperty{},__publicField(_a379,"parentToken","pcbplotparams"),_a379),PlotParamNumberProperty=class extends PlotParamProperty{static parsePrimitiveValue(value){let parsed=toNumberValue(value);if(parsed===void 0)throw new Error(`pcbplotparams ${this.token} expects a numeric value`);return parsed}},_a380,PlotParamLayerSelection=(_a380=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","layerselection")}},__publicField(_a380,"token","layerselection"),_a380);SxClass.register(PlotParamLayerSelection);var _a381,PlotParamPlotOnAllLayersSelection=(_a381=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","plot_on_all_layers_selection")}},__publicField(_a381,"token","plot_on_all_layers_selection"),_a381);SxClass.register(PlotParamPlotOnAllLayersSelection);var _a382,PlotParamDashedLineDashRatio=(_a382=class extends PlotParamNumberProperty{constructor(){super(...arguments);__publicField(this,"token","dashed_line_dash_ratio")}},__publicField(_a382,"token","dashed_line_dash_ratio"),_a382);SxClass.register(PlotParamDashedLineDashRatio);var _a383,PlotParamDashedLineGapRatio=(_a383=class extends PlotParamNumberProperty{constructor(){super(...arguments);__publicField(this,"token","dashed_line_gap_ratio")}},__publicField(_a383,"token","dashed_line_gap_ratio"),_a383);SxClass.register(PlotParamDashedLineGapRatio);var _a384,PlotParamSvgPrecision=(_a384=class extends PlotParamNumberProperty{constructor(){super(...arguments);__publicField(this,"token","svgprecision")}},__publicField(_a384,"token","svgprecision"),_a384);SxClass.register(PlotParamSvgPrecision);var _a385,PlotParamLineWidth=(_a385=class extends PlotParamNumberProperty{constructor(){super(...arguments);__publicField(this,"token","linewidth")}},__publicField(_a385,"token","linewidth"),_a385);SxClass.register(PlotParamLineWidth);var _a386,PlotParamMode=(_a386=class extends PlotParamNumberProperty{constructor(){super(...arguments);__publicField(this,"token","mode")}},__publicField(_a386,"token","mode"),_a386);SxClass.register(PlotParamMode);var _a387,PlotParamHpglPenNumber=(_a387=class extends PlotParamNumberProperty{constructor(){super(...arguments);__publicField(this,"token","hpglpennumber")}},__publicField(_a387,"token","hpglpennumber"),_a387);SxClass.register(PlotParamHpglPenNumber);var _a388,PlotParamHpglPenSpeed=(_a388=class extends PlotParamNumberProperty{constructor(){super(...arguments);__publicField(this,"token","hpglpenspeed")}},__publicField(_a388,"token","hpglpenspeed"),_a388);SxClass.register(PlotParamHpglPenSpeed);var _a389,PlotParamHpglPenDiameter=(_a389=class extends PlotParamNumberProperty{constructor(){super(...arguments);__publicField(this,"token","hpglpendiameter")}},__publicField(_a389,"token","hpglpendiameter"),_a389);SxClass.register(PlotParamHpglPenDiameter);var _a390,PlotParamHpglPenOverlay=(_a390=class extends PlotParamNumberProperty{constructor(){super(...arguments);__publicField(this,"token","hpglpenoverlay")}},__publicField(_a390,"token","hpglpenoverlay"),_a390);SxClass.register(PlotParamHpglPenOverlay);var _a391,PlotParamOutputFormat=(_a391=class extends PlotParamNumberProperty{constructor(){super(...arguments);__publicField(this,"token","outputformat")}},__publicField(_a391,"token","outputformat"),_a391);SxClass.register(PlotParamOutputFormat);var _a392,PlotParamDrillShape=(_a392=class extends PlotParamNumberProperty{constructor(){super(...arguments);__publicField(this,"token","drillshape")}},__publicField(_a392,"token","drillshape"),_a392);SxClass.register(PlotParamDrillShape);var _a393,PlotParamScaleSelection=(_a393=class extends PlotParamNumberProperty{constructor(){super(...arguments);__publicField(this,"token","scaleselection")}},__publicField(_a393,"token","scaleselection"),_a393);SxClass.register(PlotParamScaleSelection);var _a394,PlotParamPlotFpText=(_a394=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","plotfptext")}},__publicField(_a394,"token","plotfptext"),_a394);SxClass.register(PlotParamPlotFpText);var _a395,PlotParamDisableApertMacros=(_a395=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","disableapertmacros")}},__publicField(_a395,"token","disableapertmacros"),_a395);SxClass.register(PlotParamDisableApertMacros);var _a396,PlotParamUseGerberExtensions=(_a396=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","usegerberextensions")}},__publicField(_a396,"token","usegerberextensions"),_a396);SxClass.register(PlotParamUseGerberExtensions);var _a397,PlotParamUseGerberAttributes=(_a397=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","usegerberattributes")}},__publicField(_a397,"token","usegerberattributes"),_a397);SxClass.register(PlotParamUseGerberAttributes);var _a398,PlotParamUseGerberAdvancedAttributes=(_a398=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","usegerberadvancedattributes")}},__publicField(_a398,"token","usegerberadvancedattributes"),_a398);SxClass.register(PlotParamUseGerberAdvancedAttributes);var _a399,PlotParamCreateGerberJobFile=(_a399=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","creategerberjobfile")}},__publicField(_a399,"token","creategerberjobfile"),_a399);SxClass.register(PlotParamCreateGerberJobFile);var _a400,PlotParamExcludeEdgeLayer=(_a400=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","excludeedgelayer")}},__publicField(_a400,"token","excludeedgelayer"),_a400);SxClass.register(PlotParamExcludeEdgeLayer);var _a401,PlotParamPlotFrameRef=(_a401=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","plotframeref")}},__publicField(_a401,"token","plotframeref"),_a401);SxClass.register(PlotParamPlotFrameRef);var _a402,PlotParamViaOnMask=(_a402=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","viasonmask")}},__publicField(_a402,"token","viasonmask"),_a402);SxClass.register(PlotParamViaOnMask);var _a403,PlotParamUseAuxOrigin=(_a403=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","useauxorigin")}},__publicField(_a403,"token","useauxorigin"),_a403);SxClass.register(PlotParamUseAuxOrigin);var _a404,PlotParamPdfFrontFpPropertyPopups=(_a404=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","pdf_front_fp_property_popups")}},__publicField(_a404,"token","pdf_front_fp_property_popups"),_a404);SxClass.register(PlotParamPdfFrontFpPropertyPopups);var _a405,PlotParamPdfBackFpPropertyPopups=(_a405=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","pdf_back_fp_property_popups")}},__publicField(_a405,"token","pdf_back_fp_property_popups"),_a405);SxClass.register(PlotParamPdfBackFpPropertyPopups);var _a406,PlotParamPdfMetadata=(_a406=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","pdf_metadata")}},__publicField(_a406,"token","pdf_metadata"),_a406);SxClass.register(PlotParamPdfMetadata);var _a407,PlotParamPdfSingleDocument=(_a407=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","pdf_single_document")}},__publicField(_a407,"token","pdf_single_document"),_a407);SxClass.register(PlotParamPdfSingleDocument);var _a408,PlotParamDxfPolygonMode=(_a408=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","dxfpolygonmode")}},__publicField(_a408,"token","dxfpolygonmode"),_a408);SxClass.register(PlotParamDxfPolygonMode);var _a409,PlotParamDxfImperialUnits=(_a409=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","dxfimperialunits")}},__publicField(_a409,"token","dxfimperialunits"),_a409);SxClass.register(PlotParamDxfImperialUnits);var _a410,PlotParamDxfUsePcbnewFont=(_a410=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","dxfusepcbnewfont")}},__publicField(_a410,"token","dxfusepcbnewfont"),_a410);SxClass.register(PlotParamDxfUsePcbnewFont);var _a411,PlotParamPsNegative=(_a411=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","psnegative")}},__publicField(_a411,"token","psnegative"),_a411);SxClass.register(PlotParamPsNegative);var _a412,PlotParamPsA4Output=(_a412=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","psa4output")}},__publicField(_a412,"token","psa4output"),_a412);SxClass.register(PlotParamPsA4Output);var _a413,PlotParamPlotReference=(_a413=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","plotreference")}},__publicField(_a413,"token","plotreference"),_a413);SxClass.register(PlotParamPlotReference);var _a414,PlotParamPlotValue=(_a414=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","plotvalue")}},__publicField(_a414,"token","plotvalue"),_a414);SxClass.register(PlotParamPlotValue);var _a415,PlotParamPlotOtherText=(_a415=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","plotothertext")}},__publicField(_a415,"token","plotothertext"),_a415);SxClass.register(PlotParamPlotOtherText);var _a416,PlotParamPlotInvisibleText=(_a416=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","plotinvisibletext")}},__publicField(_a416,"token","plotinvisibletext"),_a416);SxClass.register(PlotParamPlotInvisibleText);var _a417,PlotParamPadOnSilk=(_a417=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","padsonsilk")}},__publicField(_a417,"token","padsonsilk"),_a417);SxClass.register(PlotParamPadOnSilk);var _a418,PlotParamSketchPadsOnFab=(_a418=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","sketchpadsonfab")}},__publicField(_a418,"token","sketchpadsonfab"),_a418);SxClass.register(PlotParamSketchPadsOnFab);var _a419,PlotParamPlotPadNumbers=(_a419=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","plotpadnumbers")}},__publicField(_a419,"token","plotpadnumbers"),_a419);SxClass.register(PlotParamPlotPadNumbers);var _a420,PlotParamHideDnpOnFab=(_a420=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","hidednponfab")}},__publicField(_a420,"token","hidednponfab"),_a420);SxClass.register(PlotParamHideDnpOnFab);var _a421,PlotParamSketchDnpOnFab=(_a421=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","sketchdnponfab")}},__publicField(_a421,"token","sketchdnponfab"),_a421);SxClass.register(PlotParamSketchDnpOnFab);var _a422,PlotParamCrossoutDnpOnFab=(_a422=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","crossoutdnponfab")}},__publicField(_a422,"token","crossoutdnponfab"),_a422);SxClass.register(PlotParamCrossoutDnpOnFab);var _a423,PlotParamSubtractMaskFromSilk=(_a423=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","subtractmaskfromsilk")}},__publicField(_a423,"token","subtractmaskfromsilk"),_a423);SxClass.register(PlotParamSubtractMaskFromSilk);var _a424,PlotParamPlotBlackAndWhite=(_a424=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","plot_black_and_white")}},__publicField(_a424,"token","plot_black_and_white"),_a424);SxClass.register(PlotParamPlotBlackAndWhite);var _a425,PlotParamMirror=(_a425=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","mirror")}},__publicField(_a425,"token","mirror"),_a425);SxClass.register(PlotParamMirror);var _a426,PlotParamOutputDirectory=(_a426=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","outputdirectory");__publicField(this,"quoteStringValue",!0)}},__publicField(_a426,"token","outputdirectory"),_a426);SxClass.register(PlotParamOutputDirectory);var _a427,PlotParamPlotOnAllLayers=(_a427=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","plot_on_all_layers")}},__publicField(_a427,"token","plot_on_all_layers"),_a427);SxClass.register(PlotParamPlotOnAllLayers);var _a428,PlotParamPlotInvisible=(_a428=class extends PlotParamProperty{constructor(){super(...arguments);__publicField(this,"token","plotinvisible")}},__publicField(_a428,"token","plotinvisible"),_a428);SxClass.register(PlotParamPlotInvisible);var TOKEN_TO_KEY={layerselection:"layerselection",plot_on_all_layers_selection:"plot_on_all_layers_selection",disableapertmacros:"disableapertmacros",usegerberextensions:"usegerberextensions",usegerberattributes:"usegerberattributes",usegerberadvancedattributes:"usegerberadvancedattributes",creategerberjobfile:"creategerberjobfile",excludeedgelayer:"excludeedgelayer",dashed_line_dash_ratio:"dashed_line_dash_ratio",dashed_line_gap_ratio:"dashed_line_gap_ratio",svgprecision:"svgprecision",linewidth:"linewidth",plotframeref:"plotframeref",plotreference:"plotreference",plotvalue:"plotvalue",plotfptext:"plotfptext",plotothertext:"plotothertext",plotinvisibletext:"plotinvisibletext",padsonsilk:"padsonsilk",sketchpadsonfab:"sketchpadsonfab",plotpadnumbers:"plotpadnumbers",hidednponfab:"hidednponfab",sketchdnponfab:"sketchdnponfab",crossoutdnponfab:"crossoutdnponfab",subtractmaskfromsilk:"subtractmaskfromsilk",plot_black_and_white:"plot_black_and_white",plot_on_all_layers:"plot_on_all_layers",plotinvisible:"plotinvisible",mode:"mode",useauxorigin:"useauxorigin",viasonmask:"viasonmask",hpglpennumber:"hpglpennumber",hpglpenspeed:"hpglpenspeed",hpglpendiameter:"hpglpendiameter",hpglpenoverlay:"hpglpenoverlay",pdf_front_fp_property_popups:"pdf_front_fp_property_popups",pdf_back_fp_property_popups:"pdf_back_fp_property_popups",pdf_metadata:"pdf_metadata",pdf_single_document:"pdf_single_document",dxfpolygonmode:"dxfpolygonmode",dxfimperialunits:"dxfimperialunits",dxfusepcbnewfont:"dxfusepcbnewfont",psnegative:"psnegative",psa4output:"psa4output",mirror:"mirror",outputformat:"outputformat",drillshape:"drillshape",scaleselection:"scaleselection",outputdirectory:"outputdirectory"},PCB_PLOT_PARAM_CHILD_ORDER=["layerselection","plot_on_all_layers_selection","disableapertmacros","usegerberextensions","usegerberattributes","usegerberadvancedattributes","creategerberjobfile","excludeedgelayer","dashed_line_dash_ratio","dashed_line_gap_ratio","svgprecision","linewidth","plotframeref","plotreference","plotvalue","plotfptext","plotothertext","mode","useauxorigin","viasonmask","hpglpennumber","hpglpenspeed","hpglpendiameter","hpglpenoverlay","pdf_front_fp_property_popups","pdf_back_fp_property_popups","pdf_metadata","pdf_single_document","dxfpolygonmode","dxfimperialunits","dxfusepcbnewfont","psnegative","psa4output","plot_black_and_white","plot_on_all_layers","plotinvisible","plotinvisibletext","padsonsilk","sketchpadsonfab","plotpadnumbers","hidednponfab","sketchdnponfab","crossoutdnponfab","subtractmaskfromsilk","outputformat","mirror","drillshape","scaleselection","outputdirectory"],_a429,PcbPlotParams=(_a429=class extends SxClass{constructor(){super(...arguments);__publicField(this,"token","pcbplotparams");__publicField(this,"_properties",{})}static fromSexprPrimitives(primitiveSexprs){let params=new _a429,{propertyMap}=SxClass.parsePrimitivesToClassProperties(primitiveSexprs,this.token);for(let[token,instance]of Object.entries(propertyMap)){let key=TOKEN_TO_KEY[token];if(!key)throw new Error(`Unsupported pcbplotparams token: ${token}`);params._properties[key]=instance}return params}getChildren(){let children=[];for(let key of PCB_PLOT_PARAM_CHILD_ORDER){let child=this._properties[key];child&&children.push(child)}return children}clearProperty(key){delete this._properties[key]}setStringProperty(key,value,ClassRef){if(value===void 0){this.clearProperty(key);return}this._properties[key]=new ClassRef(value)}setNumberProperty(key,value,ClassRef){if(value===void 0){this.clearProperty(key);return}this._properties[key]=new ClassRef(value)}setStringOrNumberProperty(key,value,ClassRef){if(value===void 0){this.clearProperty(key);return}this._properties[key]=new ClassRef(value)}get layerselection(){return this._properties.layerselection?.value}set layerselection(value){this.setStringOrNumberProperty("layerselection",value,PlotParamLayerSelection)}get plot_on_all_layers_selection(){return this._properties.plot_on_all_layers_selection?.value}set plot_on_all_layers_selection(value){this.setStringOrNumberProperty("plot_on_all_layers_selection",value,PlotParamPlotOnAllLayersSelection)}get disableapertmacros(){return this._properties.disableapertmacros?.value}set disableapertmacros(value){this.setStringProperty("disableapertmacros",value,PlotParamDisableApertMacros)}get usegerberextensions(){return this._properties.usegerberextensions?.value}set usegerberextensions(value){this.setStringProperty("usegerberextensions",value,PlotParamUseGerberExtensions)}get usegerberattributes(){return this._properties.usegerberattributes?.value}set usegerberattributes(value){this.setStringProperty("usegerberattributes",value,PlotParamUseGerberAttributes)}get usegerberadvancedattributes(){return this._properties.usegerberadvancedattributes?.value}set usegerberadvancedattributes(value){this.setStringProperty("usegerberadvancedattributes",value,PlotParamUseGerberAdvancedAttributes)}get creategerberjobfile(){return this._properties.creategerberjobfile?.value}set creategerberjobfile(value){this.setStringProperty("creategerberjobfile",value,PlotParamCreateGerberJobFile)}get excludeedgelayer(){return this._properties.excludeedgelayer?.value}set excludeedgelayer(value){this.setStringProperty("excludeedgelayer",value,PlotParamExcludeEdgeLayer)}get dashed_line_dash_ratio(){return this._properties.dashed_line_dash_ratio?.value}set dashed_line_dash_ratio(value){this.setNumberProperty("dashed_line_dash_ratio",value,PlotParamDashedLineDashRatio)}get dashed_line_gap_ratio(){return this._properties.dashed_line_gap_ratio?.value}set dashed_line_gap_ratio(value){this.setNumberProperty("dashed_line_gap_ratio",value,PlotParamDashedLineGapRatio)}get svgprecision(){return this._properties.svgprecision?.value}set svgprecision(value){this.setNumberProperty("svgprecision",value,PlotParamSvgPrecision)}get linewidth(){return this._properties.linewidth?.value}set linewidth(value){this.setNumberProperty("linewidth",value,PlotParamLineWidth)}get plotframeref(){return this._properties.plotframeref?.value}set plotframeref(value){this.setStringProperty("plotframeref",value,PlotParamPlotFrameRef)}get plotreference(){return this._properties.plotreference?.value}set plotreference(value){this.setStringProperty("plotreference",value,PlotParamPlotReference)}get plotvalue(){return this._properties.plotvalue?.value}set plotvalue(value){this.setStringProperty("plotvalue",value,PlotParamPlotValue)}get plotfptext(){return this._properties.plotfptext?.value}set plotfptext(value){this.setStringProperty("plotfptext",value,PlotParamPlotFpText)}get plotothertext(){return this._properties.plotothertext?.value}set plotothertext(value){this.setStringProperty("plotothertext",value,PlotParamPlotOtherText)}get plotinvisibletext(){return this._properties.plotinvisibletext?.value}set plotinvisibletext(value){this.setStringProperty("plotinvisibletext",value,PlotParamPlotInvisibleText)}get padsonsilk(){return this._properties.padsonsilk?.value}set padsonsilk(value){this.setStringProperty("padsonsilk",value,PlotParamPadOnSilk)}get plotpadnumbers(){return this._properties.plotpadnumbers?.value}set plotpadnumbers(value){this.setStringProperty("plotpadnumbers",value,PlotParamPlotPadNumbers)}get sketchpadsonfab(){return this._properties.sketchpadsonfab?.value}set sketchpadsonfab(value){this.setStringProperty("sketchpadsonfab",value,PlotParamSketchPadsOnFab)}get hidednponfab(){return this._properties.hidednponfab?.value}set hidednponfab(value){this.setStringProperty("hidednponfab",value,PlotParamHideDnpOnFab)}get sketchdnponfab(){return this._properties.sketchdnponfab?.value}set sketchdnponfab(value){this.setStringProperty("sketchdnponfab",value,PlotParamSketchDnpOnFab)}get crossoutdnponfab(){return this._properties.crossoutdnponfab?.value}set crossoutdnponfab(value){this.setStringProperty("crossoutdnponfab",value,PlotParamCrossoutDnpOnFab)}get subtractmaskfromsilk(){return this._properties.subtractmaskfromsilk?.value}set subtractmaskfromsilk(value){this.setStringProperty("subtractmaskfromsilk",value,PlotParamSubtractMaskFromSilk)}get plot_black_and_white(){return this._properties.plot_black_and_white?.value}set plot_black_and_white(value){this.setStringProperty("plot_black_and_white",value,PlotParamPlotBlackAndWhite)}get plot_on_all_layers(){return this._properties.plot_on_all_layers?.value}set plot_on_all_layers(value){this.setStringProperty("plot_on_all_layers",value,PlotParamPlotOnAllLayers)}get plotinvisible(){return this._properties.plotinvisible?.value}set plotinvisible(value){this.setStringProperty("plotinvisible",value,PlotParamPlotInvisible)}get mode(){return this._properties.mode?.value}set mode(value){this.setNumberProperty("mode",value,PlotParamMode)}get useauxorigin(){return this._properties.useauxorigin?.value}set useauxorigin(value){this.setStringProperty("useauxorigin",value,PlotParamUseAuxOrigin)}get viasonmask(){return this._properties.viasonmask?.value}set viasonmask(value){this.setStringProperty("viasonmask",value,PlotParamViaOnMask)}get hpglpennumber(){return this._properties.hpglpennumber?.value}set hpglpennumber(value){this.setNumberProperty("hpglpennumber",value,PlotParamHpglPenNumber)}get hpglpenspeed(){return this._properties.hpglpenspeed?.value}set hpglpenspeed(value){this.setNumberProperty("hpglpenspeed",value,PlotParamHpglPenSpeed)}get hpglpendiameter(){return this._properties.hpglpendiameter?.value}set hpglpendiameter(value){this.setNumberProperty("hpglpendiameter",value,PlotParamHpglPenDiameter)}get hpglpenoverlay(){return this._properties.hpglpenoverlay?.value}set hpglpenoverlay(value){this.setNumberProperty("hpglpenoverlay",value,PlotParamHpglPenOverlay)}get pdf_front_fp_property_popups(){return this._properties.pdf_front_fp_property_popups?.value}set pdf_front_fp_property_popups(value){this.setStringProperty("pdf_front_fp_property_popups",value,PlotParamPdfFrontFpPropertyPopups)}get pdf_back_fp_property_popups(){return this._properties.pdf_back_fp_property_popups?.value}set pdf_back_fp_property_popups(value){this.setStringProperty("pdf_back_fp_property_popups",value,PlotParamPdfBackFpPropertyPopups)}get pdf_metadata(){return this._properties.pdf_metadata?.value}set pdf_metadata(value){this.setStringProperty("pdf_metadata",value,PlotParamPdfMetadata)}get pdf_single_document(){return this._properties.pdf_single_document?.value}set pdf_single_document(value){this.setStringProperty("pdf_single_document",value,PlotParamPdfSingleDocument)}get dxfpolygonmode(){return this._properties.dxfpolygonmode?.value}set dxfpolygonmode(value){this.setStringProperty("dxfpolygonmode",value,PlotParamDxfPolygonMode)}get dxfimperialunits(){return this._properties.dxfimperialunits?.value}set dxfimperialunits(value){this.setStringProperty("dxfimperialunits",value,PlotParamDxfImperialUnits)}get dxfusepcbnewfont(){return this._properties.dxfusepcbnewfont?.value}set dxfusepcbnewfont(value){this.setStringProperty("dxfusepcbnewfont",value,PlotParamDxfUsePcbnewFont)}get psnegative(){return this._properties.psnegative?.value}set psnegative(value){this.setStringProperty("psnegative",value,PlotParamPsNegative)}get psa4output(){return this._properties.psa4output?.value}set psa4output(value){this.setStringProperty("psa4output",value,PlotParamPsA4Output)}get mirror(){return this._properties.mirror?.value}set mirror(value){this.setStringProperty("mirror",value,PlotParamMirror)}get outputformat(){return this._properties.outputformat?.value}set outputformat(value){this.setNumberProperty("outputformat",value,PlotParamOutputFormat)}get drillshape(){return this._properties.drillshape?.value}set drillshape(value){this.setNumberProperty("drillshape",value,PlotParamDrillShape)}get scaleselection(){return this._properties.scaleselection?.value}set scaleselection(value){this.setNumberProperty("scaleselection",value,PlotParamScaleSelection)}get outputdirectory(){return this._properties.outputdirectory?.value}set outputdirectory(value){this.setStringProperty("outputdirectory",value,PlotParamOutputDirectory)}},__publicField(_a429,"token","pcbplotparams"),__publicField(_a429,"parentToken","setup"),_a429);SxClass.register(PcbPlotParams);var _a430,Plugging=(_a430=class extends SxClass{constructor(params={}){super();__publicField(this,"token","plugging");__publicField(this,"_sxFront");__publicField(this,"_sxBack");params.front!==void 0&&(this.front=params.front),params.back!==void 0&&(this.back=params.back)}static fromSexprPrimitives(primitiveSexprs){let{propertyMap}=SxClass.parsePrimitivesToClassProperties(primitiveSexprs,this.token);return new _a430({front:propertyMap.front,back:propertyMap.back})}get front(){return this._sxFront?.value}set front(value){if(value===void 0){this._sxFront=void 0;return}this._sxFront=value instanceof Front?value:new Front(value)}get back(){return this._sxBack?.value}set back(value){if(value===void 0){this._sxBack=void 0;return}this._sxBack=value instanceof Back?value:new Back(value)}getChildren(){let children=[];return this._sxFront&&children.push(this._sxFront),this._sxBack&&children.push(this._sxBack),children}},__publicField(_a430,"token","plugging"),_a430);SxClass.register(Plugging);var _a431,SetupStringProperty=(_a431=class extends SingleValueProperty{},__publicField(_a431,"parentToken","setup"),_a431),_a432,SetupZone45Only=(_a432=class extends SetupStringProperty{constructor(){super(...arguments);__publicField(this,"token","zone_45_only")}},__publicField(_a432,"token","zone_45_only"),_a432);SxClass.register(SetupZone45Only);var _a433,SetupAllowSoldermaskBridgesInFootprints=(_a433=class extends SetupStringProperty{constructor(){super(...arguments);__publicField(this,"token","allow_soldermask_bridges_in_footprints")}},__publicField(_a433,"token","allow_soldermask_bridges_in_footprints"),_a433);SxClass.register(SetupAllowSoldermaskBridgesInFootprints);var _a434,SetupVisibleElements=(_a434=class extends SetupStringProperty{constructor(){super(...arguments);__publicField(this,"token","visible_elements")}},__publicField(_a434,"token","visible_elements"),_a434);SxClass.register(SetupVisibleElements);var _a435,SetupUviasAllowed=(_a435=class extends SetupStringProperty{constructor(){super(...arguments);__publicField(this,"token","uvias_allowed")}},__publicField(_a435,"token","uvias_allowed"),_a435);SxClass.register(SetupUviasAllowed);var _a436,SetupTenting=(_a436=class extends SxClass{constructor(sides=[]){super();__publicField(this,"token","tenting");__publicField(this,"_sides",[]);__publicField(this,"_sxFront");__publicField(this,"_sxBack");this.sides=sides}static fromSexprPrimitives(primitiveSexprs){if(primitiveSexprs.some(primitive=>Array.isArray(primitive))){let{propertyMap}=SxClass.parsePrimitivesToClassProperties(primitiveSexprs,this.token),tenting=new _a436;return tenting._sxFront=propertyMap.front,tenting._sxBack=propertyMap.back,tenting}let sides=primitiveSexprs.map(primitive=>toStringValue(primitive)).filter(value=>value!==void 0);return new _a436(sides)}get sides(){return[...this._sides]}set sides(sides){this._sides=sides.map(side=>String(side))}getChildren(){let children=[];return this._sxFront&&children.push(this._sxFront),this._sxBack&&children.push(this._sxBack),children}getString(){return this._sxFront||this._sxBack?super.getString():this._sides.length===0?"(tenting)":`(tenting ${this._sides.join(" ")})`}},__publicField(_a436,"token","tenting"),__publicField(_a436,"parentToken","setup"),_a436);SxClass.register(SetupTenting);var _a437,SetupNumericListProperty=(_a437=class extends NumericListProperty{},__publicField(_a437,"parentToken","setup"),_a437),_a438,SetupCoordinateProperty=(_a438=class extends CoordinateProperty{},__publicField(_a438,"parentToken","setup"),_a438),_a439,SetupPcbTextSize=(_a439=class extends SetupNumericListProperty{constructor(){super(...arguments);__publicField(this,"token","pcb_text_size")}},__publicField(_a439,"token","pcb_text_size"),_a439);SxClass.register(SetupPcbTextSize);var _a440,SetupModTextSize=(_a440=class extends SetupNumericListProperty{constructor(){super(...arguments);__publicField(this,"token","mod_text_size")}},__publicField(_a440,"token","mod_text_size"),_a440);SxClass.register(SetupModTextSize);var _a441,SetupPadSize=(_a441=class extends SetupNumericListProperty{constructor(){super(...arguments);__publicField(this,"token","pad_size")}},__publicField(_a441,"token","pad_size"),_a441);SxClass.register(SetupPadSize);var _a442,SetupPadToPasteClearanceValues=(_a442=class extends SetupNumericListProperty{constructor(){super(...arguments);__publicField(this,"token","pad_to_paste_clearance_values")}},__publicField(_a442,"token","pad_to_paste_clearance_values"),_a442);SxClass.register(SetupPadToPasteClearanceValues);var _a443,SetupTraceWidth=(_a443=class extends SetupNumericListProperty{constructor(){super(...arguments);__publicField(this,"token","trace_width")}},__publicField(_a443,"token","trace_width"),_a443);SxClass.register(SetupTraceWidth);var _a444,SetupAuxAxisOrigin=(_a444=class extends SetupCoordinateProperty{constructor(){super(...arguments);__publicField(this,"token","aux_axis_origin")}},__publicField(_a444,"token","aux_axis_origin"),_a444);SxClass.register(SetupAuxAxisOrigin);var _a445,SetupGridOrigin=(_a445=class extends SetupCoordinateProperty{constructor(){super(...arguments);__publicField(this,"token","grid_origin")}},__publicField(_a445,"token","grid_origin"),_a445);SxClass.register(SetupGridOrigin);var _a446,SetupNumberProperty=(_a446=class extends SingleValueProperty{static parsePrimitiveValue(value){let parsed=toNumberValue(value);if(parsed===void 0)throw new Error(`${this.name} expects a numeric value`);return parsed}},__publicField(_a446,"parentToken","setup"),_a446),_a447,SetupPadToMaskClearance=(_a447=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","pad_to_mask_clearance")}},__publicField(_a447,"token","pad_to_mask_clearance"),_a447);SxClass.register(SetupPadToMaskClearance);var _a448,SetupSolderMaskMinWidth=(_a448=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","solder_mask_min_width")}},__publicField(_a448,"token","solder_mask_min_width"),_a448);SxClass.register(SetupSolderMaskMinWidth);var _a449,SetupPadToPasteClearance=(_a449=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","pad_to_paste_clearance")}},__publicField(_a449,"token","pad_to_paste_clearance"),_a449);SxClass.register(SetupPadToPasteClearance);var _a450,SetupPadToPasteClearanceRatio=(_a450=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","pad_to_paste_clearance_ratio")}},__publicField(_a450,"token","pad_to_paste_clearance_ratio"),_a450);SxClass.register(SetupPadToPasteClearanceRatio);var _a451,SetupLastTraceWidth=(_a451=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","last_trace_width")}},__publicField(_a451,"token","last_trace_width"),_a451);SxClass.register(SetupLastTraceWidth);var _a452,SetupTraceClearance=(_a452=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","trace_clearance")}},__publicField(_a452,"token","trace_clearance"),_a452);SxClass.register(SetupTraceClearance);var _a453,SetupZoneClearance=(_a453=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","zone_clearance")}},__publicField(_a453,"token","zone_clearance"),_a453);SxClass.register(SetupZoneClearance);var _a454,SetupTraceMin=(_a454=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","trace_min")}},__publicField(_a454,"token","trace_min"),_a454);SxClass.register(SetupTraceMin);var _a455,SetupSegmentWidth=(_a455=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","segment_width")}},__publicField(_a455,"token","segment_width"),_a455);SxClass.register(SetupSegmentWidth);var _a456,SetupEdgeWidth=(_a456=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","edge_width")}},__publicField(_a456,"token","edge_width"),_a456);SxClass.register(SetupEdgeWidth);var _a457,SetupViaSize=(_a457=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","via_size")}},__publicField(_a457,"token","via_size"),_a457);SxClass.register(SetupViaSize);var _a458,SetupViaDrill=(_a458=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","via_drill")}},__publicField(_a458,"token","via_drill"),_a458);SxClass.register(SetupViaDrill);var _a459,SetupViaMinSize=(_a459=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","via_min_size")}},__publicField(_a459,"token","via_min_size"),_a459);SxClass.register(SetupViaMinSize);var _a460,SetupViaMinDrill=(_a460=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","via_min_drill")}},__publicField(_a460,"token","via_min_drill"),_a460);SxClass.register(SetupViaMinDrill);var _a461,SetupUviaSize=(_a461=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","uvia_size")}},__publicField(_a461,"token","uvia_size"),_a461);SxClass.register(SetupUviaSize);var _a462,SetupUviaDrill=(_a462=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","uvia_drill")}},__publicField(_a462,"token","uvia_drill"),_a462);SxClass.register(SetupUviaDrill);var _a463,SetupUviaMinSize=(_a463=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","uvia_min_size")}},__publicField(_a463,"token","uvia_min_size"),_a463);SxClass.register(SetupUviaMinSize);var _a464,SetupUviaMinDrill=(_a464=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","uvia_min_drill")}},__publicField(_a464,"token","uvia_min_drill"),_a464);SxClass.register(SetupUviaMinDrill);var _a465,SetupPcbTextWidth=(_a465=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","pcb_text_width")}},__publicField(_a465,"token","pcb_text_width"),_a465);SxClass.register(SetupPcbTextWidth);var _a466,SetupModEdgeWidth=(_a466=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","mod_edge_width")}},__publicField(_a466,"token","mod_edge_width"),_a466);SxClass.register(SetupModEdgeWidth);var _a467,SetupModTextWidth=(_a467=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","mod_text_width")}},__publicField(_a467,"token","mod_text_width"),_a467);SxClass.register(SetupModTextWidth);var _a468,SetupPadDrill=(_a468=class extends SetupNumberProperty{constructor(){super(...arguments);__publicField(this,"token","pad_drill")}},__publicField(_a468,"token","pad_drill"),_a468);SxClass.register(SetupPadDrill);var _a469,StackupSingleValueProperty=(_a469=class extends SingleValueProperty{},__publicField(_a469,"parentToken","stackup"),_a469),_a470,StackupCopperFinish=(_a470=class extends StackupSingleValueProperty{constructor(){super(...arguments);__publicField(this,"token","copper_finish");__publicField(this,"quoteStringValue",!0)}},__publicField(_a470,"token","copper_finish"),_a470);SxClass.register(StackupCopperFinish);var _a471,StackupDielectricConstraints=(_a471=class extends StackupSingleValueProperty{constructor(){super(...arguments);__publicField(this,"token","dielectric_constraints")}},__publicField(_a471,"token","dielectric_constraints"),_a471);SxClass.register(StackupDielectricConstraints);var _a472,StackupEdgeConnector=(_a472=class extends StackupSingleValueProperty{constructor(){super(...arguments);__publicField(this,"token","edge_connector")}},__publicField(_a472,"token","edge_connector"),_a472);SxClass.register(StackupEdgeConnector);var _a473,StackupCastellatedPads=(_a473=class extends StackupSingleValueProperty{constructor(){super(...arguments);__publicField(this,"token","castellated_pads")}},__publicField(_a473,"token","castellated_pads"),_a473);SxClass.register(StackupCastellatedPads);var _a474,StackupEdgePlating=(_a474=class extends StackupSingleValueProperty{constructor(){super(...arguments);__publicField(this,"token","edge_plating")}},__publicField(_a474,"token","edge_plating"),_a474);SxClass.register(StackupEdgePlating);var _a475,StackupLayerProperty=(_a475=class extends SingleValueProperty{},__publicField(_a475,"parentToken","layer"),_a475),_a476,StackupLayerType=(_a476=class extends StackupLayerProperty{constructor(){super(...arguments);__publicField(this,"token","type");__publicField(this,"quoteStringValue",!0)}},__publicField(_a476,"token","type"),_a476);SxClass.register(StackupLayerType);var _a477,StackupLayerColor=(_a477=class extends StackupLayerProperty{constructor(){super(...arguments);__publicField(this,"token","color");__publicField(this,"quoteStringValue",!0)}},__publicField(_a477,"token","color"),_a477);SxClass.register(StackupLayerColor);var _a478,StackupLayerThickness=(_a478=class extends StackupLayerProperty{constructor(){super(...arguments);__publicField(this,"token","thickness")}static parsePrimitiveValue(value){let parsed=toNumberValue(value);if(parsed===void 0)throw new Error("Stackup layer thickness expects a numeric value");return parsed}},__publicField(_a478,"token","thickness"),_a478);SxClass.register(StackupLayerThickness);var _a479,StackupLayerMaterial=(_a479=class extends StackupLayerProperty{constructor(){super(...arguments);__publicField(this,"token","material");__publicField(this,"quoteStringValue",!0)}},__publicField(_a479,"token","material"),_a479);SxClass.register(StackupLayerMaterial);var _a480,StackupLayerEpsilonR=(_a480=class extends StackupLayerProperty{constructor(){super(...arguments);__publicField(this,"token","epsilon_r")}static parsePrimitiveValue(value){let parsed=toNumberValue(value);if(parsed===void 0)throw new Error("Stackup layer epsilon_r expects a numeric value");return parsed}},__publicField(_a480,"token","epsilon_r"),_a480);SxClass.register(StackupLayerEpsilonR);var _a481,StackupLayerLossTangent=(_a481=class extends StackupLayerProperty{constructor(){super(...arguments);__publicField(this,"token","loss_tangent")}static parsePrimitiveValue(value){let parsed=toNumberValue(value);if(parsed===void 0)throw new Error("Stackup layer loss_tangent expects a numeric value");return parsed}},__publicField(_a481,"token","loss_tangent"),_a481);SxClass.register(StackupLayerLossTangent);var _a482,StackupLayer=(_a482=class extends SxClass{constructor(name,opts={}){super();__publicField(this,"token","layer");__publicField(this,"_name");__publicField(this,"_number");__publicField(this,"_sxType");__publicField(this,"_sxColor");__publicField(this,"_sxThickness");__publicField(this,"_sxMaterial");__publicField(this,"_sxEpsilonR");__publicField(this,"_sxLossTangent");this._name=name,this._number=opts.number,this._sxType=opts.type,this._sxColor=opts.color,this._sxThickness=opts.thickness,this._sxMaterial=opts.material,this._sxEpsilonR=opts.epsilonR,this._sxLossTangent=opts.lossTangent}static fromSexprPrimitives(primitiveSexprs){if(primitiveSexprs.length===0)throw new Error("Stackup layer requires at least a name");let name=toStringValue(primitiveSexprs[0]);if(name===void 0)throw new Error("Stackup layer name must be a string");let propertyIndex=1,number,maybeNumber2=primitiveSexprs[propertyIndex],numericLayerNumber=toNumberValue(maybeNumber2);numericLayerNumber!==void 0&&(number=numericLayerNumber,propertyIndex+=1);let propertyPrimitives=primitiveSexprs.slice(propertyIndex),{propertyMap}=SxClass.parsePrimitivesToClassProperties(propertyPrimitives,this.token);return new _a482(name,{number,type:propertyMap.type,color:propertyMap.color,thickness:propertyMap.thickness,material:propertyMap.material,epsilonR:propertyMap.epsilon_r,lossTangent:propertyMap.loss_tangent})}get name(){return this._name}set name(value){let parsed=toStringValue(value);if(parsed===void 0)throw new Error("Stackup layer name must be a string");this._name=parsed}get number(){return this._number}set number(value){if(value===void 0){this._number=void 0;return}let parsed=toNumberValue(value);if(parsed===void 0)throw new Error("Stackup layer number must be numeric");this._number=parsed}get type(){return this._sxType?.value}set type(value){if(value===void 0){this._sxType=void 0;return}this._sxType=value instanceof StackupLayerType?value:new StackupLayerType(value)}get color(){return this._sxColor?.value}set color(value){if(value===void 0){this._sxColor=void 0;return}this._sxColor=value instanceof StackupLayerColor?value:new StackupLayerColor(value)}get thickness(){return this._sxThickness?.value}set thickness(value){if(value===void 0){this._sxThickness=void 0;return}this._sxThickness=value instanceof StackupLayerThickness?value:new StackupLayerThickness(value)}get material(){return this._sxMaterial?.value}set material(value){if(value===void 0){this._sxMaterial=void 0;return}this._sxMaterial=value instanceof StackupLayerMaterial?value:new StackupLayerMaterial(value)}get epsilonR(){return this._sxEpsilonR?.value}set epsilonR(value){if(value===void 0){this._sxEpsilonR=void 0;return}this._sxEpsilonR=value instanceof StackupLayerEpsilonR?value:new StackupLayerEpsilonR(value)}get lossTangent(){return this._sxLossTangent?.value}set lossTangent(value){if(value===void 0){this._sxLossTangent=void 0;return}this._sxLossTangent=value instanceof StackupLayerLossTangent?value:new StackupLayerLossTangent(value)}getChildren(){let children=[];return this._sxType&&children.push(this._sxType),this._sxColor&&children.push(this._sxColor),this._sxThickness&&children.push(this._sxThickness),this._sxMaterial&&children.push(this._sxMaterial),this._sxEpsilonR&&children.push(this._sxEpsilonR),this._sxLossTangent&&children.push(this._sxLossTangent),children}getString(){let header=`(layer ${quoteSExprString(this._name)}${this._number!==void 0?` ${this._number}`:""}`,children=this.getChildren();if(children.length===0)return`${header})`;let lines=[header];for(let child of children)lines.push(child.getStringIndented());return lines.push(")"),lines.join(`
|
|
799
799
|
`)}},__publicField(_a482,"token","layer"),__publicField(_a482,"parentToken","stackup"),_a482);SxClass.register(StackupLayer);var _a483,Stackup=(_a483=class extends SxClass{constructor(opts={}){super();__publicField(this,"token","stackup");__publicField(this,"_layers",[]);__publicField(this,"_sxCopperFinish");__publicField(this,"_sxDielectricConstraints");__publicField(this,"_sxEdgeConnector");__publicField(this,"_sxCastellatedPads");__publicField(this,"_sxEdgePlating");this.layers=opts.layers??[],this._sxCopperFinish=opts.copperFinish,this._sxDielectricConstraints=opts.dielectricConstraints,this._sxEdgeConnector=opts.edgeConnector,this._sxCastellatedPads=opts.castellatedPads,this._sxEdgePlating=opts.edgePlating}static fromSexprPrimitives(primitiveSexprs){let{propertyMap,arrayPropertyMap}=SxClass.parsePrimitivesToClassProperties(primitiveSexprs,this.token);return new _a483({layers:arrayPropertyMap.layer??[],copperFinish:propertyMap.copper_finish,dielectricConstraints:propertyMap.dielectric_constraints,edgeConnector:propertyMap.edge_connector,castellatedPads:propertyMap.castellated_pads,edgePlating:propertyMap.edge_plating})}get layers(){return[...this._layers]}set layers(layers){this._layers=layers.map(layer=>{if(!(layer instanceof StackupLayer))throw new Error("Stackup layers must be StackupLayer instances");return layer})}get copperFinish(){return this._sxCopperFinish?.value}set copperFinish(value){this._sxCopperFinish=value?new StackupCopperFinish(value):void 0}get dielectricConstraints(){return this._sxDielectricConstraints?.value}set dielectricConstraints(value){this._sxDielectricConstraints=value?new StackupDielectricConstraints(value):void 0}get edgeConnector(){return this._sxEdgeConnector?.value}set edgeConnector(value){this._sxEdgeConnector=value?new StackupEdgeConnector(value):void 0}get castellatedPads(){return this._sxCastellatedPads?.value}set castellatedPads(value){this._sxCastellatedPads=value?new StackupCastellatedPads(value):void 0}get edgePlating(){return this._sxEdgePlating?.value}set edgePlating(value){this._sxEdgePlating=value?new StackupEdgePlating(value):void 0}getChildren(){let children=[...this._layers],optionalChildren=[this._sxCopperFinish,this._sxDielectricConstraints,this._sxEdgeConnector,this._sxCastellatedPads,this._sxEdgePlating];for(let child of optionalChildren)child&&children.push(child);return children}},__publicField(_a483,"token","stackup"),__publicField(_a483,"parentToken","setup"),_a483);SxClass.register(Stackup);var TOKEN_TO_KEY2={stackup:"stackup",pcbplotparams:"pcbPlotParams",pad_to_mask_clearance:"padToMaskClearance",solder_mask_min_width:"solderMaskMinWidth",pad_to_paste_clearance:"padToPasteClearance",pad_to_paste_clearance_ratio:"padToPasteClearanceRatio",last_trace_width:"lastTraceWidth",trace_clearance:"traceClearance",zone_clearance:"zoneClearance",zone_45_only:"zone45Only",trace_min:"traceMin",segment_width:"segmentWidth",edge_width:"edgeWidth",via_size:"viaSize",via_drill:"viaDrill",via_min_size:"viaMinSize",via_min_drill:"viaMinDrill",uvias_allowed:"uviasAllowed",uvia_size:"uviaSize",uvia_drill:"uviaDrill",uvia_min_size:"uviaMinSize",uvia_min_drill:"uviaMinDrill",pcb_text_width:"pcbTextWidth",pcb_text_size:"pcbTextSize",mod_edge_width:"modEdgeWidth",mod_text_size:"modTextSize",mod_text_width:"modTextWidth",pad_size:"padSize",pad_drill:"padDrill",allow_soldermask_bridges_in_footprints:"allowSoldermaskBridgesInFootprints",tenting:"tenting",covering:"covering",plugging:"plugging",capping:"capping",filling:"filling",aux_axis_origin:"auxAxisOrigin",grid_origin:"gridOrigin",visible_elements:"visibleElements",pad_to_paste_clearance_values:"padToPasteClearanceValues",trace_width:"traceWidth"},SETUP_CHILD_ORDER=["stackup","padToMaskClearance","solderMaskMinWidth","padToPasteClearance","padToPasteClearanceRatio","lastTraceWidth","traceClearance","zoneClearance","zone45Only","traceMin","segmentWidth","edgeWidth","viaSize","viaDrill","viaMinSize","viaMinDrill","uviaSize","uviaDrill","uviasAllowed","uviaMinSize","uviaMinDrill","pcbTextWidth","pcbTextSize","modEdgeWidth","modTextSize","modTextWidth","padSize","padDrill","allowSoldermaskBridgesInFootprints","tenting","covering","plugging","capping","filling","auxAxisOrigin","gridOrigin","visibleElements","padToPasteClearanceValues","traceWidth","pcbPlotParams"],_a484,Setup=(_a484=class extends SxClass{constructor(){super(...arguments);__publicField(this,"token","setup");__publicField(this,"_properties",{})}static fromSexprPrimitives(primitiveSexprs){let setup=new _a484,{propertyMap}=SxClass.parsePrimitivesToClassProperties(primitiveSexprs,this.token);for(let[token,instance]of Object.entries(propertyMap)){let key=TOKEN_TO_KEY2[token];if(!key)throw new Error(`Unsupported setup property token: ${token}`);setup._properties[key]=instance}return setup}getChildren(){let children=[];for(let key of SETUP_CHILD_ORDER){let child=this._properties[key];child&&children.push(child)}return children}setProperty(key,instance){if(instance){this._properties[key]=instance;return}delete this._properties[key]}setNumberProperty(key,value,ClassRef){if(value===void 0){delete this._properties[key];return}this._properties[key]=new ClassRef(value)}getPropertyInstance(key,ClassRef){let value=this._properties[key];return value instanceof ClassRef?value:void 0}get stackup(){return this.getPropertyInstance("stackup",Stackup)}set stackup(value){if(value!==void 0&&!(value instanceof Stackup))throw new Error("stackup must be a Stackup instance");this.setProperty("stackup",value)}get pcbPlotParams(){return this.getPropertyInstance("pcbPlotParams",PcbPlotParams)}set pcbPlotParams(value){if(value!==void 0&&!(value instanceof PcbPlotParams))throw new Error("pcbPlotParams must be a PcbPlotParams instance");this.setProperty("pcbPlotParams",value)}get padToMaskClearance(){return this.getPropertyInstance("padToMaskClearance",SetupPadToMaskClearance)?.value}set padToMaskClearance(value){this.setNumberProperty("padToMaskClearance",value,SetupPadToMaskClearance)}get solderMaskMinWidth(){return this.getPropertyInstance("solderMaskMinWidth",SetupSolderMaskMinWidth)?.value}set solderMaskMinWidth(value){this.setNumberProperty("solderMaskMinWidth",value,SetupSolderMaskMinWidth)}get padToPasteClearance(){return this.getPropertyInstance("padToPasteClearance",SetupPadToPasteClearance)?.value}set padToPasteClearance(value){this.setNumberProperty("padToPasteClearance",value,SetupPadToPasteClearance)}get padToPasteClearanceRatio(){return this.getPropertyInstance("padToPasteClearanceRatio",SetupPadToPasteClearanceRatio)?.value}set padToPasteClearanceRatio(value){this.setNumberProperty("padToPasteClearanceRatio",value,SetupPadToPasteClearanceRatio)}get lastTraceWidth(){return this.getPropertyInstance("lastTraceWidth",SetupLastTraceWidth)?.value}set lastTraceWidth(value){this.setNumberProperty("lastTraceWidth",value,SetupLastTraceWidth)}get traceClearance(){return this.getPropertyInstance("traceClearance",SetupTraceClearance)?.value}set traceClearance(value){this.setNumberProperty("traceClearance",value,SetupTraceClearance)}get zoneClearance(){return this.getPropertyInstance("zoneClearance",SetupZoneClearance)?.value}set zoneClearance(value){this.setNumberProperty("zoneClearance",value,SetupZoneClearance)}get zone45Only(){return this.getPropertyInstance("zone45Only",SetupZone45Only)?.value}set zone45Only(value){this.setProperty("zone45Only",value===void 0?void 0:new SetupZone45Only(value))}get traceMin(){return this.getPropertyInstance("traceMin",SetupTraceMin)?.value}set traceMin(value){this.setNumberProperty("traceMin",value,SetupTraceMin)}get segmentWidth(){return this.getPropertyInstance("segmentWidth",SetupSegmentWidth)?.value}set segmentWidth(value){this.setNumberProperty("segmentWidth",value,SetupSegmentWidth)}get edgeWidth(){return this.getPropertyInstance("edgeWidth",SetupEdgeWidth)?.value}set edgeWidth(value){this.setNumberProperty("edgeWidth",value,SetupEdgeWidth)}get viaSize(){return this.getPropertyInstance("viaSize",SetupViaSize)?.value}set viaSize(value){this.setNumberProperty("viaSize",value,SetupViaSize)}get viaDrill(){return this.getPropertyInstance("viaDrill",SetupViaDrill)?.value}set viaDrill(value){this.setNumberProperty("viaDrill",value,SetupViaDrill)}get viaMinSize(){return this.getPropertyInstance("viaMinSize",SetupViaMinSize)?.value}set viaMinSize(value){this.setNumberProperty("viaMinSize",value,SetupViaMinSize)}get viaMinDrill(){return this.getPropertyInstance("viaMinDrill",SetupViaMinDrill)?.value}set viaMinDrill(value){this.setNumberProperty("viaMinDrill",value,SetupViaMinDrill)}get uviasAllowed(){return this.getPropertyInstance("uviasAllowed",SetupUviasAllowed)?.value}set uviasAllowed(value){this.setProperty("uviasAllowed",value===void 0?void 0:new SetupUviasAllowed(value))}get uviaSize(){return this.getPropertyInstance("uviaSize",SetupUviaSize)?.value}set uviaSize(value){this.setNumberProperty("uviaSize",value,SetupUviaSize)}get uviaDrill(){return this.getPropertyInstance("uviaDrill",SetupUviaDrill)?.value}set uviaDrill(value){this.setNumberProperty("uviaDrill",value,SetupUviaDrill)}get uviaMinSize(){return this.getPropertyInstance("uviaMinSize",SetupUviaMinSize)?.value}set uviaMinSize(value){this.setNumberProperty("uviaMinSize",value,SetupUviaMinSize)}get uviaMinDrill(){return this.getPropertyInstance("uviaMinDrill",SetupUviaMinDrill)?.value}set uviaMinDrill(value){this.setNumberProperty("uviaMinDrill",value,SetupUviaMinDrill)}get pcbTextWidth(){return this.getPropertyInstance("pcbTextWidth",SetupPcbTextWidth)?.value}set pcbTextWidth(value){this.setNumberProperty("pcbTextWidth",value,SetupPcbTextWidth)}get pcbTextSize(){return this.getPropertyInstance("pcbTextSize",SetupPcbTextSize)?.values}set pcbTextSize(values){if(values===void 0){delete this._properties.pcbTextSize;return}this.setProperty("pcbTextSize",new SetupPcbTextSize(values))}get modEdgeWidth(){return this.getPropertyInstance("modEdgeWidth",SetupModEdgeWidth)?.value}set modEdgeWidth(value){this.setNumberProperty("modEdgeWidth",value,SetupModEdgeWidth)}get modTextSize(){return this.getPropertyInstance("modTextSize",SetupModTextSize)?.values}set modTextSize(values){if(values===void 0){delete this._properties.modTextSize;return}this.setProperty("modTextSize",new SetupModTextSize(values))}get modTextWidth(){return this.getPropertyInstance("modTextWidth",SetupModTextWidth)?.value}set modTextWidth(value){this.setNumberProperty("modTextWidth",value,SetupModTextWidth)}get padSize(){return this.getPropertyInstance("padSize",SetupPadSize)?.values}set padSize(values){if(values===void 0){delete this._properties.padSize;return}this.setProperty("padSize",new SetupPadSize(values))}get padDrill(){return this.getPropertyInstance("padDrill",SetupPadDrill)?.value}set padDrill(value){this.setNumberProperty("padDrill",value,SetupPadDrill)}get allowSoldermaskBridgesInFootprints(){return this.getPropertyInstance("allowSoldermaskBridgesInFootprints",SetupAllowSoldermaskBridgesInFootprints)?.value}set allowSoldermaskBridgesInFootprints(value){this.setProperty("allowSoldermaskBridgesInFootprints",value===void 0?void 0:new SetupAllowSoldermaskBridgesInFootprints(value))}get tenting(){return this.getPropertyInstance("tenting",SetupTenting)?.sides}set tenting(sides){if(sides===void 0){delete this._properties.tenting;return}this.setProperty("tenting",new SetupTenting(sides))}get covering(){return this.getPropertyInstance("covering",Covering)}set covering(value){this.setProperty("covering",value)}get plugging(){return this.getPropertyInstance("plugging",Plugging)}set plugging(value){this.setProperty("plugging",value)}get capping(){return this.getPropertyInstance("capping",Capping)?.value}set capping(value){this.setProperty("capping",value===void 0?void 0:new Capping(value))}get filling(){return this.getPropertyInstance("filling",Filling)?.value}set filling(value){this.setProperty("filling",value===void 0?void 0:new Filling(value))}get auxAxisOrigin(){let origin=this.getPropertyInstance("auxAxisOrigin",SetupAuxAxisOrigin);if(origin)return{x:origin.x,y:origin.y}}set auxAxisOrigin(origin){if(!origin){delete this._properties.auxAxisOrigin;return}this.setProperty("auxAxisOrigin",new SetupAuxAxisOrigin(origin.x,origin.y))}get gridOrigin(){let origin=this.getPropertyInstance("gridOrigin",SetupGridOrigin);if(origin)return{x:origin.x,y:origin.y}}set gridOrigin(origin){if(!origin){delete this._properties.gridOrigin;return}this.setProperty("gridOrigin",new SetupGridOrigin(origin.x,origin.y))}get visibleElements(){return this.getPropertyInstance("visibleElements",SetupVisibleElements)?.value}set visibleElements(value){this.setProperty("visibleElements",value===void 0?void 0:new SetupVisibleElements(value))}get padToPasteClearanceValues(){return this.getPropertyInstance("padToPasteClearanceValues",SetupPadToPasteClearanceValues)?.values}set padToPasteClearanceValues(values){if(values===void 0){delete this._properties.padToPasteClearanceValues;return}this.setProperty("padToPasteClearanceValues",new SetupPadToPasteClearanceValues(values))}get traceWidth(){return this.getPropertyInstance("traceWidth",SetupTraceWidth)?.values}set traceWidth(values){if(values===void 0){delete this._properties.traceWidth;return}this.setProperty("traceWidth",new SetupTraceWidth(values))}},__publicField(_a484,"token","setup"),_a484);SxClass.register(Setup);var _a485,PcbGeneralThickness=(_a485=class extends SxPrimitiveNumber{constructor(){super(...arguments);__publicField(this,"token","thickness")}},__publicField(_a485,"token","thickness"),__publicField(_a485,"parentToken","general"),_a485);SxClass.register(PcbGeneralThickness);var _a486,PcbGeneralLegacyTeardrops=(_a486=class extends SxClass{constructor(enabled){super();__publicField(this,"token","legacy_teardrops");__publicField(this,"_enabled");this._enabled=enabled}static fromSexprPrimitives(primitiveSexprs){let value=toStringValue(primitiveSexprs[0]);if(value===void 0)throw new Error("legacy_teardrops expects a string value");let enabled=/^(yes|true)$/iu.test(value);return new _a486(enabled)}get enabled(){return this._enabled}set enabled(value){this._enabled=value}getChildren(){return[]}getString(){return`(legacy_teardrops ${this._enabled?"yes":"no"})`}},__publicField(_a486,"token","legacy_teardrops"),__publicField(_a486,"parentToken","general"),_a486);SxClass.register(PcbGeneralLegacyTeardrops);var SINGLE_TOKENS6=new Set(["thickness","legacy_teardrops"]),_a487,PcbGeneral=(_a487=class extends SxClass{constructor(){super(...arguments);__publicField(this,"token","general");__publicField(this,"_sxThickness");__publicField(this,"_sxLegacyTeardrops")}static fromSexprPrimitives(primitiveSexprs){let general=new _a487,{propertyMap,arrayPropertyMap}=SxClass.parsePrimitivesToClassProperties(primitiveSexprs,this.token);for(let token of Object.keys(propertyMap))if(!SINGLE_TOKENS6.has(token))throw new Error(`general encountered unsupported child token "${token}"`);for(let[token,entries]of Object.entries(arrayPropertyMap)){if(!SINGLE_TOKENS6.has(token))throw new Error(`general encountered unsupported child token "${token}"`);if(entries.length>1)throw new Error(`general encountered repeated child token "${token}"`)}return general._sxThickness=arrayPropertyMap.thickness?.[0]??propertyMap.thickness,general._sxLegacyTeardrops=arrayPropertyMap.legacy_teardrops?.[0]??propertyMap.legacy_teardrops,general}get thickness(){return this._sxThickness?.value}set thickness(value){this._sxThickness=value===void 0?void 0:new PcbGeneralThickness(value)}get legacyTeardrops(){return this._sxLegacyTeardrops?.enabled}set legacyTeardrops(value){if(value===void 0){this._sxLegacyTeardrops=void 0;return}this._sxLegacyTeardrops=new PcbGeneralLegacyTeardrops(value)}getChildren(){let children=[];return this._sxThickness&&children.push(this._sxThickness),this._sxLegacyTeardrops&&children.push(this._sxLegacyTeardrops),children}},__publicField(_a487,"token","general"),__publicField(_a487,"parentToken","kicad_pcb"),_a487);SxClass.register(PcbGeneral);var _a488,PcbLayerDefinition=(_a488=class extends SxClass{constructor(options){super();__publicField(this,"token","__pcb_layer_definition__");__publicField(this,"_index");__publicField(this,"_name");__publicField(this,"_type");__publicField(this,"_userName");this._index=options.index,this._name=options.name,this._type=options.type,this._userName=options.userName}static fromPrimitive(primitive){if(!Array.isArray(primitive)||primitive.length<3)throw new Error(`layers entry must be an array with at least index, name, and type: ${JSON.stringify(primitive)}`);let[rawIndex,rawName,rawType,rawUser]=primitive,index=toNumberValue(rawIndex),name=toStringValue(rawName),type=toStringValue(rawType),userName=rawUser===void 0?void 0:toStringValue(rawUser);if(index===void 0||name===void 0||type===void 0)throw new Error(`layers entry is missing required values: ${JSON.stringify(primitive)}`);return new _a488({index,name,type,userName})}get index(){return this._index}set index(value){this._index=value}get name(){return this._name}set name(value){this._name=value}get type(){return this._type}set type(value){this._type=value}get userName(){return this._userName}set userName(value){this._userName=value}getChildren(){return[]}getString(){if(this._index===void 0||this._name===void 0||this._type===void 0)return"()";let tokens=[String(this._index),quoteSExprString(this._name),this._type];return this._userName!==void 0&&tokens.push(quoteSExprString(this._userName)),`(${tokens.join(" ")})`}},__publicField(_a488,"token","__pcb_layer_definition__"),__publicField(_a488,"parentToken","layers"),_a488);SxClass.register(PcbLayerDefinition);var _a489,PcbLayers=(_a489=class extends SxClass{constructor(){super(...arguments);__publicField(this,"token","layers");__publicField(this,"_definitions",[])}static fromSexprPrimitives(primitiveSexprs){let layers=new _a489;return layers._definitions=primitiveSexprs.map(primitive=>PcbLayerDefinition.fromPrimitive(primitive)),layers}get definitions(){return[...this._definitions]}set definitions(value){this._definitions=[...value]}getChildren(){return[...this._definitions]}},__publicField(_a489,"token","layers"),__publicField(_a489,"parentToken","kicad_pcb"),_a489);SxClass.register(PcbLayers);var _a490,PcbNet=(_a490=class extends SxClass{constructor(id2,name){super();__publicField(this,"token","net");__publicField(this,"_id");__publicField(this,"_name");this._id=id2,this._name=name}static fromSexprPrimitives(primitiveSexprs){let id2=toNumberValue(primitiveSexprs[0]),name=toStringValue(primitiveSexprs[1]);if(id2===void 0||name===void 0)throw new Error("net requires numeric id and string name");return new _a490(id2,name)}get id(){return this._id}set id(value){this._id=value}get name(){return this._name}set name(value){this._name=value}getChildren(){return[]}getString(){return`(net ${this._id} ${quoteSExprString(this._name)})`}},__publicField(_a490,"token","net"),__publicField(_a490,"parentToken","kicad_pcb"),_a490);SxClass.register(PcbNet);var _a491,PcbVersion=(_a491=class extends SxPrimitiveNumber{constructor(){super(...arguments);__publicField(this,"token","version")}},__publicField(_a491,"token","version"),__publicField(_a491,"parentToken","kicad_pcb"),_a491);SxClass.register(PcbVersion);var isSymbol3=value=>/^[A-Za-z0-9._-]+$/.test(value),_a492,PcbGenerator=(_a492=class extends SxPrimitiveString{constructor(){super(...arguments);__publicField(this,"token","generator")}getString(){return`(generator ${isSymbol3(this.value)?this.value:quoteSExprString(this.value)})`}},__publicField(_a492,"token","generator"),__publicField(_a492,"parentToken","kicad_pcb"),_a492);SxClass.register(PcbGenerator);var isSymbol4=value=>/^[A-Za-z0-9._-]+$/.test(value),_a493,PcbGeneratorVersion=(_a493=class extends SxPrimitiveString{constructor(){super(...arguments);__publicField(this,"token","generator_version")}getString(){return`(generator_version ${isSymbol4(this.value)?this.value:quoteSExprString(this.value)})`}},__publicField(_a493,"token","generator_version"),__publicField(_a493,"parentToken","kicad_pcb"),_a493);SxClass.register(PcbGeneratorVersion);var _a494,ViaNet=(_a494=class extends SxClass{constructor(idOrName,name){super();__publicField(this,"token","net");__publicField(this,"_id");__publicField(this,"_name");if(typeof idOrName=="number"){this._id=idOrName,this._name=name;return}this._name=idOrName}static fromSexprPrimitives(primitiveSexprs){let id2=toNumberValue(primitiveSexprs[0]);if(id2!==void 0){let name2=primitiveSexprs.length>1?toStringValue(primitiveSexprs[1]):void 0;return new _a494(id2,name2)}let name=toStringValue(primitiveSexprs[0]);if(name===void 0)throw new Error("via net requires a numeric id or string name");return new _a494(name)}get id(){return this._id}set id(value){this._id=value}get name(){return this._name}set name(value){this._name=value}getChildren(){return[]}getString(){return this._id===void 0?`(net ${quoteSExprString(this._name??"")})`:this._name!==void 0?`(net ${this._id} ${quoteSExprString(this._name)})`:`(net ${this._id})`}},__publicField(_a494,"token","net"),__publicField(_a494,"parentToken","via"),_a494);SxClass.register(ViaNet);var BARE_FLAGS=new Set(["locked","free","remove_unused_layers","keep_end_layers"]),_a495,Via2=(_a495=class extends SxClass{constructor(params={}){super();__publicField(this,"token","via");__publicField(this,"_type");__publicField(this,"_locked",!1);__publicField(this,"_free",!1);__publicField(this,"_removeUnusedLayers",!1);__publicField(this,"_keepEndLayers",!1);__publicField(this,"_sxAt");__publicField(this,"_size");__publicField(this,"_drill");__publicField(this,"_sxLayers");__publicField(this,"_sxNet");__publicField(this,"_sxUuid");__publicField(this,"_sxTstamp");__publicField(this,"_sxTeardrops");__publicField(this,"_sxCapping");__publicField(this,"_sxCovering");__publicField(this,"_sxPlugging");__publicField(this,"_sxFilling");params.type!==void 0&&(this.type=params.type),params.locked!==void 0&&(this.locked=params.locked),params.free!==void 0&&(this.free=params.free),params.removeUnusedLayers!==void 0&&(this.removeUnusedLayers=params.removeUnusedLayers),params.keepEndLayers!==void 0&&(this.keepEndLayers=params.keepEndLayers),params.at!==void 0&&(this.at=params.at),params.size!==void 0&&(this.size=params.size),params.drill!==void 0&&(this.drill=params.drill),params.layers!==void 0&&(this.layers=params.layers),params.net!==void 0&&(this.net=params.net),params.uuid!==void 0&&(this.uuid=params.uuid),params.tstamp!==void 0&&(this.tstamp=params.tstamp),params.teardrops!==void 0&&(this.teardrops=params.teardrops),params.capping!==void 0&&(this.capping=params.capping),params.covering!==void 0&&(this.covering=params.covering),params.plugging!==void 0&&(this.plugging=params.plugging),params.filling!==void 0&&(this.filling=params.filling)}static fromSexprPrimitives(primitiveSexprs){let via=new _a495;for(let primitive of primitiveSexprs){if(typeof primitive=="string"){via.consumeBareToken(primitive);continue}if(!Array.isArray(primitive)||primitive.length===0)throw new Error(`via encountered unsupported primitive child: ${JSON.stringify(primitive)}`);let[token,...rest]=primitive;if(typeof token!="string")throw new Error(`via encountered child with non-string token: ${JSON.stringify(primitive)}`);via.consumeNode(token,rest)}return via}consumeBareToken(token){if(token==="blind"||token==="micro"){this._type=token;return}if(!BARE_FLAGS.has(token))throw new Error(`via encountered unsupported flag "${token}"`);switch(token){case"locked":this._locked=!0;break;case"free":this._free=!0;break;case"remove_unused_layers":this._removeUnusedLayers=!0;break;case"keep_end_layers":this._keepEndLayers=!0;break}}consumeNode(token,args){switch(token){case"type":{let value=toStringValue(args[0]);if(value===void 0)throw new Error("via type expects a string value");this._type=value;return}case"locked":this._locked=this.parseYesNo(args);return;case"free":this._free=this.parseYesNo(args);return;case"remove_unused_layers":this._removeUnusedLayers=this.parseYesNo(args);return;case"keep_end_layers":this._keepEndLayers=this.parseYesNo(args);return;case"at":{let parsed=SxClass.parsePrimitiveSexpr(["at",...args],{parentToken:this.token});if(!(parsed instanceof At3))throw new Error("via failed to parse at child");this._sxAt=parsed;return}case"size":{let value=toNumberValue(args[0]);if(value===void 0)throw new Error("via size expects a numeric value");this._size=value;return}case"drill":{let value=toNumberValue(args[0]);if(value===void 0)throw new Error("via drill expects a numeric value");this._drill=value;return}case"layers":{this._sxLayers=Layers.fromSexprPrimitives(args);return}case"net":{this._sxNet=ViaNet.fromSexprPrimitives(args);return}case"teardrops":{this._sxTeardrops=PadTeardrops.fromSexprPrimitives(args);return}case"capping":{let parsed=SxClass.parsePrimitiveSexpr(["capping",...args],{parentToken:this.token});if(!(parsed instanceof Capping))throw new Error("via failed to parse capping child");this._sxCapping=parsed;return}case"covering":{let parsed=SxClass.parsePrimitiveSexpr(["covering",...args],{parentToken:this.token});if(!(parsed instanceof Covering))throw new Error("via failed to parse covering child");this._sxCovering=parsed;return}case"plugging":{let parsed=SxClass.parsePrimitiveSexpr(["plugging",...args],{parentToken:this.token});if(!(parsed instanceof Plugging))throw new Error("via failed to parse plugging child");this._sxPlugging=parsed;return}case"filling":{let parsed=SxClass.parsePrimitiveSexpr(["filling",...args],{parentToken:this.token});if(!(parsed instanceof Filling))throw new Error("via failed to parse filling child");this._sxFilling=parsed;return}case"uuid":{let value=toStringValue(args[0]);if(value===void 0)throw new Error("via uuid expects a string value");this._sxUuid=new Uuid(value);return}case"tstamp":{let value=toStringValue(args[0]);if(value===void 0)throw new Error("via tstamp expects a string value");this._sxTstamp=new Tstamp(value);return}default:throw new Error(`via encountered unsupported child token "${token}"`)}}parseYesNo(args){if(args.length===0)return!0;let value=toStringValue(args[0]);if(value===void 0)throw new Error("Expected string when parsing via boolean child");return/^(yes|true)$/iu.test(value)}get type(){return this._type}set type(value){this._type=value}get locked(){return this._locked}set locked(value){this._locked=value}get free(){return this._free}set free(value){this._free=value}get removeUnusedLayers(){return this._removeUnusedLayers}set removeUnusedLayers(value){this._removeUnusedLayers=value}get keepEndLayers(){return this._keepEndLayers}set keepEndLayers(value){this._keepEndLayers=value}get at(){return this._sxAt}set at(value){this._sxAt=value!==void 0?At3.from(value):void 0}get size(){return this._size}set size(value){this._size=value}get drill(){return this._drill}set drill(value){this._drill=value}get layers(){return this._sxLayers}set layers(value){if(value===void 0){this._sxLayers=void 0;return}this._sxLayers=value instanceof Layers?value:new Layers(value)}get net(){return this._sxNet}set net(value){this._sxNet=value}get uuid(){return this._sxUuid}set uuid(value){if(value===void 0){this._sxUuid=void 0;return}this._sxUuid=value instanceof Uuid?value:new Uuid(value)}get teardrops(){return this._sxTeardrops}set teardrops(value){this._sxTeardrops=value}get capping(){return this._sxCapping?.value}set capping(value){if(value===void 0){this._sxCapping=void 0;return}this._sxCapping=value instanceof Capping?value:new Capping(value)}get covering(){return this._sxCovering}set covering(value){this._sxCovering=value}get plugging(){return this._sxPlugging}set plugging(value){this._sxPlugging=value}get filling(){return this._sxFilling?.value}set filling(value){if(value===void 0){this._sxFilling=void 0;return}this._sxFilling=value instanceof Filling?value:new Filling(value)}get tstamp(){return this._sxTstamp}set tstamp(value){if(value===void 0){this._sxTstamp=void 0;return}this._sxTstamp=value instanceof Tstamp?value:new Tstamp(value)}getChildren(){let children=[];return this._sxAt&&children.push(this._sxAt),this._sxLayers&&children.push(this._sxLayers),this._sxCapping&&children.push(this._sxCapping),this._sxCovering&&children.push(this._sxCovering),this._sxPlugging&&children.push(this._sxPlugging),this._sxFilling&&children.push(this._sxFilling),this._sxNet&&children.push(this._sxNet),this._sxUuid&&children.push(this._sxUuid),this._sxTstamp&&children.push(this._sxTstamp),this._sxTeardrops&&children.push(this._sxTeardrops),children}getString(){let lines=["(via"];return this._type!==void 0&&lines.push(` (type ${this._type})`),this._locked&&lines.push(" (locked)"),this._free&&lines.push(" (free)"),this._removeUnusedLayers&&lines.push(" (remove_unused_layers)"),this._keepEndLayers&&lines.push(" (keep_end_layers)"),this._sxAt&&lines.push(this._sxAt.getStringIndented()),this._size!==void 0&&lines.push(` (size ${this._size})`),this._drill!==void 0&&lines.push(` (drill ${this._drill})`),this._sxLayers&&lines.push(this._sxLayers.getStringIndented()),this._sxCapping&&lines.push(this._sxCapping.getStringIndented()),this._sxCovering&&lines.push(this._sxCovering.getStringIndented()),this._sxPlugging&&lines.push(this._sxPlugging.getStringIndented()),this._sxFilling&&lines.push(this._sxFilling.getStringIndented()),this._sxNet&&lines.push(this._sxNet.getStringIndented()),this._sxUuid&&lines.push(this._sxUuid.getStringIndented()),this._sxTstamp&&lines.push(this._sxTstamp.getStringIndented()),this._sxTeardrops&&lines.push(this._sxTeardrops.getStringIndented()),lines.push(")"),lines.join(`
|
|
800
|
-
`)}},__publicField(_a495,"token","via"),_a495);SxClass.register(Via2);var _a496,KicadPcb=(_a496=class extends SxClass{constructor(params={}){super();__publicField(this,"token","kicad_pcb");__publicField(this,"_sxVersion");__publicField(this,"_sxGenerator");__publicField(this,"_sxGeneratorVersion");__publicField(this,"_sxGeneral");__publicField(this,"_sxPaper");__publicField(this,"_sxTitleBlock");__publicField(this,"_sxLayers");__publicField(this,"_sxSetup");__publicField(this,"_properties",[]);__publicField(this,"_nets",[]);__publicField(this,"_footprints",[]);__publicField(this,"_images",[]);__publicField(this,"_segments",[]);__publicField(this,"_arcs",[]);__publicField(this,"_grArcs",[]);__publicField(this,"_grCircles",[]);__publicField(this,"_grCurves",[]);__publicField(this,"_grLines",[]);__publicField(this,"_grTexts",[]);__publicField(this,"_grPolys",[]);__publicField(this,"_grRects",[]);__publicField(this,"_vias",[]);__publicField(this,"_zones",[]);__publicField(this,"_sxEmbeddedFonts");__publicField(this,"_sxEmbeddedFiles");__publicField(this,"_otherChildren",[]);params.version!==void 0&&(this.version=params.version),params.generator!==void 0&&(this.generator=params.generator),params.generatorVersion!==void 0&&(this.generatorVersion=params.generatorVersion),params.general!==void 0&&(this.general=params.general),params.paper!==void 0&&(this.paper=params.paper),params.titleBlock!==void 0&&(this.titleBlock=params.titleBlock),params.layers!==void 0&&(this.layers=params.layers),params.setup!==void 0&&(this.setup=params.setup),params.properties!==void 0&&(this.properties=params.properties),params.nets!==void 0&&(this.nets=params.nets),params.footprints!==void 0&&(this.footprints=params.footprints),params.images!==void 0&&(this.images=params.images),params.segments!==void 0&&(this.segments=params.segments),params.arcs!==void 0&&(this.arcs=params.arcs),params.graphicArcs!==void 0&&(this.graphicArcs=params.graphicArcs),params.graphicCircles!==void 0&&(this.graphicCircles=params.graphicCircles),params.graphicCurves!==void 0&&(this.graphicCurves=params.graphicCurves),params.graphicLines!==void 0&&(this.graphicLines=params.graphicLines),params.graphicTexts!==void 0&&(this.graphicTexts=params.graphicTexts),params.graphicPolys!==void 0&&(this.graphicPolys=params.graphicPolys),params.graphicRects!==void 0&&(this.graphicRects=params.graphicRects),params.vias!==void 0&&(this.vias=params.vias),params.zones!==void 0&&(this.zones=params.zones),params.embeddedFonts!==void 0&&(this.embeddedFonts=params.embeddedFonts),params.embeddedFiles!==void 0&&(this.embeddedFiles=params.embeddedFiles),params.otherChildren!==void 0&&(this.otherChildren=params.otherChildren)}static fromSexprPrimitives(primitiveSexprs){let pcb=new _a496;for(let primitive of primitiveSexprs){if(!Array.isArray(primitive)||primitive.length===0)throw new Error(`kicad_pcb encountered unsupported primitive child: ${JSON.stringify(primitive)}`);let parsed=SxClass.parsePrimitiveSexpr(primitive,{parentToken:_a496.token});if(!(parsed instanceof SxClass))throw new Error(`kicad_pcb expected SxClass child, received ${JSON.stringify(primitive)}`);pcb.consumeChild(parsed)}return pcb}consumeChild(child){if(child instanceof PcbVersion){this._sxVersion=child;return}if(child instanceof PcbGenerator){this._sxGenerator=child;return}if(child instanceof PcbGeneratorVersion){this._sxGeneratorVersion=child;return}if(child instanceof PcbGeneral){this._sxGeneral=child;return}if(child instanceof Paper){this._sxPaper=child;return}if(child instanceof TitleBlock){this._sxTitleBlock=child;return}if(child instanceof PcbLayers){this._sxLayers=child;return}if(child instanceof Setup){this._sxSetup=child;return}if(child instanceof Property){this._properties.push(child);return}if(child instanceof PcbNet){this._nets.push(child);return}if(child instanceof Footprint2){this._footprints.push(child);return}if(child instanceof Image){this._images.push(child);return}if(child instanceof Segment3){this._segments.push(child);return}if(child instanceof PcbArc){this._arcs.push(child);return}if(child instanceof GrArc){this._grArcs.push(child);return}if(child instanceof GrCircle){this._grCircles.push(child);return}if(child instanceof GrCurve){this._grCurves.push(child);return}if(child instanceof GrLine){this._grLines.push(child);return}if(child instanceof GrText){this._grTexts.push(child);return}if(child instanceof GrPoly){this._grPolys.push(child);return}if(child instanceof GrRect){this._grRects.push(child);return}if(child instanceof Via2){this._vias.push(child);return}if(child instanceof Zone){this._zones.push(child);return}if(child instanceof EmbeddedFonts){this._sxEmbeddedFonts=child;return}if(child instanceof EmbeddedFiles){this._sxEmbeddedFiles=child;return}this._otherChildren.push(child)}get version(){return this._sxVersion?.value}set version(value){this._sxVersion=value===void 0?void 0:new PcbVersion(value)}get generator(){return this._sxGenerator?.value}set generator(value){this._sxGenerator=value===void 0?void 0:new PcbGenerator(value)}get generatorVersion(){return this._sxGeneratorVersion?.value}set generatorVersion(value){this._sxGeneratorVersion=value===void 0?void 0:new PcbGeneratorVersion(value)}get general(){return this._sxGeneral}set general(value){this._sxGeneral=value}get paper(){return this._sxPaper}set paper(value){this._sxPaper=value}get titleBlock(){return this._sxTitleBlock}set titleBlock(value){this._sxTitleBlock=value}get layers(){return this._sxLayers}set layers(value){this._sxLayers=value}get setup(){return this._sxSetup}set setup(value){this._sxSetup=value}get properties(){return[...this._properties]}set properties(value){this._properties=[...value]}get nets(){return[...this._nets]}set nets(value){this._nets=[...value]}get footprints(){return[...this._footprints]}set footprints(value){this._footprints=[...value]}get images(){return[...this._images]}set images(value){this._images=[...value]}get segments(){return[...this._segments]}set segments(value){this._segments=[...value]}get arcs(){return[...this._arcs]}set arcs(value){this._arcs=[...value]}get graphicArcs(){return[...this._grArcs]}set graphicArcs(value){this._grArcs=[...value]}get graphicCircles(){return[...this._grCircles]}set graphicCircles(value){this._grCircles=[...value]}get graphicCurves(){return[...this._grCurves]}set graphicCurves(value){this._grCurves=[...value]}get graphicLines(){return[...this._grLines]}set graphicLines(value){this._grLines=[...value]}get graphicTexts(){return[...this._grTexts]}set graphicTexts(value){this._grTexts=[...value]}get graphicPolys(){return[...this._grPolys]}set graphicPolys(value){this._grPolys=[...value]}get graphicRects(){return[...this._grRects]}set graphicRects(value){this._grRects=[...value]}get vias(){return[...this._vias]}set vias(value){this._vias=[...value]}get zones(){return[...this._zones]}set zones(value){this._zones=[...value]}get embeddedFonts(){return this._sxEmbeddedFonts}set embeddedFonts(value){this._sxEmbeddedFonts=value}get embeddedFiles(){return this._sxEmbeddedFiles}set embeddedFiles(value){this._sxEmbeddedFiles=value}get otherChildren(){return[...this._otherChildren]}set otherChildren(value){this._otherChildren=[...value]}getChildren(){let children=[];return this._sxVersion&&children.push(this._sxVersion),this._sxGenerator&&children.push(this._sxGenerator),this._sxGeneratorVersion&&children.push(this._sxGeneratorVersion),this._sxGeneral&&children.push(this._sxGeneral),this._sxPaper&&children.push(this._sxPaper),this._sxTitleBlock&&children.push(this._sxTitleBlock),this._sxLayers&&children.push(this._sxLayers),this._sxSetup&&children.push(this._sxSetup),children.push(...this._properties),children.push(...this._nets),children.push(...this._footprints),children.push(...this._images),children.push(...this._segments),children.push(...this._arcs),children.push(...this._grArcs),children.push(...this._grCircles),children.push(...this._grCurves),children.push(...this._grLines),children.push(...this._grTexts),children.push(...this._grPolys),children.push(...this._grRects),children.push(...this._vias),children.push(...this._zones),this._sxEmbeddedFonts&&children.push(this._sxEmbeddedFonts),this._sxEmbeddedFiles&&children.push(this._sxEmbeddedFiles),children.push(...this._otherChildren),children}},__publicField(_a496,"token","kicad_pcb"),_a496);SxClass.register(KicadPcb);var parseKicadSexpr=sexpr=>SxClass.parse(sexpr),parseKicadSch=sexpr=>{let[root]=parseKicadSexpr(sexpr);if(!(root instanceof KicadSch))throw new Error(`Expected KicadSch root, got ${root?.constructor.name??"undefined"}`);return root},parseKicadPcb=sexpr=>{let[root]=parseKicadSexpr(sexpr);if(!(root instanceof KicadPcb))throw new Error(`Expected KicadPcb root, got ${root?.constructor.name??"undefined"}`);return root};init_src();init_src();init_src();init_src();init_src();init_src();init_src();init_src();init_src();init_src();init_src();init_src();var ConverterStage=class{constructor(ctx){__publicField(this,"ctx");__publicField(this,"MAX_ITERATIONS",100);__publicField(this,"iterationCount",0);__publicField(this,"finished",!1);this.ctx=ctx}runUntilFinished(){for(this.iterationCount=0;!this.finished&&this.iterationCount<this.MAX_ITERATIONS;)this.step()||(this.finished=!0),this.iterationCount++;this.iterationCount>=this.MAX_ITERATIONS&&(this.ctx.warnings=this.ctx.warnings||[],this.ctx.warnings.push(`Stage ${this.constructor.name} exceeded maximum iterations (${this.MAX_ITERATIONS})`),this.finished=!0)}},INNER_COPPER_LAYER_REGEX=/^In([1-6])\.Cu$/;function dedupeLayerRefs(layers){return[...new Set(layers)]}function extractKicadLayerNames(layer){return layer?typeof layer=="string"?[layer]:Array.isArray(layer)?layer.filter(name=>typeof name=="string"):[...layer.names||[],...layer._names||[],...layer._layers||[],...layer.name?[layer.name]:[],...layer._name?[layer._name]:[]].filter(name=>typeof name=="string"):[]}function mapKicadLayerToPcbRenderLayer(layer){let layerNames=extractKicadLayerNames(layer);for(let layerName of layerNames){let copperLayer=mapKicadLayerNameToLayerRef(layerName);if(copperLayer)return`${copperLayer}_copper`;if(layerName.includes("Edge.Cuts"))return"edge_cuts";let side=mapKicadLayerToVisibleLayer(layerName);if(layerName.includes("CrtYd"))return`${side}_courtyard`;if(layerName.includes("Fab"))return`${side}_fabrication_note`;if(layerName.includes("SilkS"))return`${side}_silkscreen`}}function isPcbAnnotationRenderLayer(renderLayer){return renderLayer?.endsWith("_silkscreen")||renderLayer?.endsWith("_fabrication_note")||renderLayer?.endsWith("_courtyard")||!1}function isPcbTextRenderLayer(renderLayer){return renderLayer?.endsWith("_silkscreen")||renderLayer?.endsWith("_fabrication_note")||renderLayer?.endsWith("_copper")||!1}function mapKicadLayerNameToLayerRef(layerName){if(layerName==="F.Cu")return"top";if(layerName==="B.Cu")return"bottom";let innerLayerMatch=layerName.match(INNER_COPPER_LAYER_REGEX);if(innerLayerMatch)return`inner${innerLayerMatch[1]}`}function mapKicadLayerToLayerRef(layer){let layerNames=extractKicadLayerNames(layer);for(let layerName of layerNames){let mappedLayer=mapKicadLayerNameToLayerRef(layerName);if(mappedLayer)return mappedLayer}let layerLabel=layerNames.join(" ");return layerLabel.includes("B.")||layerLabel.includes("Back")||layerLabel.includes("Bottom")?"bottom":"top"}function mapKicadLayerToVisibleLayer(layer){return mapKicadLayerToLayerRef(layer)==="bottom"?"bottom":"top"}function getPcbCopperLayerRefs(kicadPcb){let copperLayers=(Array.isArray(kicadPcb?.layers?._definitions)?(kicadPcb?.layers)._definitions:[]).map(definition=>mapKicadLayerNameToLayerRef(definition?._name)).filter(layer=>!!layer);return copperLayers.length>0?dedupeLayerRefs(copperLayers):["top","bottom"]}function getLayerRefsFromLayers(layers,kicadPcb){let layerNames=extractKicadLayerNames(layers),mappedLayers=[];for(let layerName of layerNames){if(layerName==="*.Cu"){mappedLayers.push(...getPcbCopperLayerRefs(kicadPcb));continue}let mappedLayer=mapKicadLayerNameToLayerRef(layerName);mappedLayer&&mappedLayers.push(mappedLayer)}return dedupeLayerRefs(mappedLayers)}function expandCopperLayerSpan(layers,kicadPcb){if(layers.length<=1)return layers;let copperStack=getPcbCopperLayerRefs(kicadPcb),startIndex=copperStack.indexOf(layers[0]),endIndex=copperStack.indexOf(layers[layers.length-1]);if(startIndex===-1||endIndex===-1)return dedupeLayerRefs(layers);let[fromIndex,toIndex]=startIndex<=endIndex?[startIndex,endIndex]:[endIndex,startIndex];return copperStack.slice(fromIndex,toIndex+1)}function getCopperSpanLayerRefsFromLayers(layers,kicadPcb){return expandCopperLayerSpan(getLayerRefsFromLayers(layers,kicadPcb),kicadPcb)}function getComponentLayer(footprint){return mapKicadLayerToVisibleLayer(footprint.layer)}function determineLayerFromLayers(layers){return mapKicadLayerToLayerRef(extractKicadLayerNames(layers))}function mapTextLayer(kicadLayer){return mapKicadLayerToVisibleLayer(kicadLayer)}function insertFootprintRoute(options){let{ctx,componentId,layer,renderLayer,route,strokeWidth}=options;if(renderLayer.endsWith("_silkscreen")){ctx.db.pcb_silkscreen_path.insert({pcb_component_id:componentId,layer,route,stroke_width:strokeWidth});return}if(renderLayer.endsWith("_fabrication_note")){ctx.db.pcb_fabrication_note_path.insert({pcb_component_id:componentId,layer,route,stroke_width:strokeWidth});return}ctx.db.pcb_courtyard_outline.insert({pcb_component_id:componentId,layer,outline:route})}function rotatePoint7(x4,y4,rotationDeg){let rotationRad=rotationDeg*Math.PI/180;return{x:x4*Math.cos(rotationRad)-y4*Math.sin(rotationRad),y:x4*Math.sin(rotationRad)+y4*Math.cos(rotationRad)}}function processFootprintGraphics(ctx,footprint,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;let lines=footprint.fpLines||[],lineArray=Array.isArray(lines)?lines:lines?[lines]:[];for(let line2 of lineArray)createFootprintLine(ctx,line2,componentId,kicadComponentPos,componentRotation);let rects=footprint.fpRects||[],rectArray=Array.isArray(rects)?rects:rects?[rects]:[];for(let rect of rectArray)createFootprintRect(ctx,rect,componentId,kicadComponentPos,componentRotation);let circles=footprint.fpCircles||[],circleArray=Array.isArray(circles)?circles:circles?[circles]:[];for(let circle2 of circleArray)createFootprintCircle(ctx,circle2,componentId,kicadComponentPos,componentRotation);let arcs=footprint.fpArcs||[],arcArray=Array.isArray(arcs)?arcs:arcs?[arcs]:[];for(let arc2 of arcArray)createFootprintArc(ctx,arc2,componentId,kicadComponentPos,componentRotation);let polys=footprint.fpPolys||[],polyArray=Array.isArray(polys)?polys:polys?[polys]:[];for(let poly of polyArray)createFootprintPoly(ctx,poly,componentId,kicadComponentPos,componentRotation)}function createFootprintLine(ctx,line2,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;let renderLayer=mapKicadLayerToPcbRenderLayer(line2.layer);if(!isPcbAnnotationRenderLayer(renderLayer))return;let start=line2.start||{x:0,y:0},end=line2.end||{x:0,y:0},rotatedStart=rotatePoint7(start.x,start.y,-componentRotation),rotatedEnd=rotatePoint7(end.x,end.y,-componentRotation),startKicadPos={x:kicadComponentPos.x+rotatedStart.x,y:kicadComponentPos.y+rotatedStart.y},endKicadPos={x:kicadComponentPos.x+rotatedEnd.x,y:kicadComponentPos.y+rotatedEnd.y},startPos=applyToPoint(ctx.k2cMatPcb,startKicadPos),endPos=applyToPoint(ctx.k2cMatPcb,endKicadPos),layer=mapTextLayer(line2.layer),strokeWidth=line2.stroke?.width||line2.width||.12;insertFootprintRoute({ctx,componentId,layer,renderLayer,route:[startPos,endPos],strokeWidth})}function createFootprintRect(ctx,rect,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;let renderLayer=mapKicadLayerToPcbRenderLayer(rect.layer);if(!isPcbAnnotationRenderLayer(renderLayer))return;let start=rect.start||{x:0,y:0},end=rect.end||{x:0,y:0},center2={x:(start.x+end.x)/2,y:(start.y+end.y)/2},rotatedCenter=rotatePoint7(center2.x,center2.y,-componentRotation),centerKicadPos={x:kicadComponentPos.x+rotatedCenter.x,y:kicadComponentPos.y+rotatedCenter.y},centerPos=applyToPoint(ctx.k2cMatPcb,centerKicadPos),layer=mapTextLayer(rect.layer),width=Math.abs(end.x-start.x),height=Math.abs(end.y-start.y),strokeWidth=rect.stroke?.width||rect.width||.12;if(renderLayer.endsWith("_courtyard")){ctx.db.pcb_courtyard_rect.insert({pcb_component_id:componentId,center:centerPos,width,height,layer,ccw_rotation:-componentRotation});return}if(renderLayer.endsWith("_fabrication_note")){ctx.db.pcb_fabrication_note_rect.insert({pcb_component_id:componentId,center:centerPos,width,height,layer,stroke_width:strokeWidth,is_filled:rect.fill?.filled===!0,has_stroke:!0});return}let route=[{x:start.x,y:start.y},{x:end.x,y:start.y},{x:end.x,y:end.y},{x:start.x,y:end.y},{x:start.x,y:start.y}].map(point7=>{let rotated=rotatePoint7(point7.x,point7.y,-componentRotation),kicadPos={x:kicadComponentPos.x+rotated.x,y:kicadComponentPos.y+rotated.y};return applyToPoint(ctx.k2cMatPcb,kicadPos)});insertFootprintRoute({ctx,componentId,layer,renderLayer,route,strokeWidth})}function createFootprintCircle(ctx,circle2,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;let renderLayer=mapKicadLayerToPcbRenderLayer(circle2.layer);if(!isPcbAnnotationRenderLayer(renderLayer))return;let center2=circle2.center||{x:0,y:0},end=circle2.end||{x:0,y:0},radius=Math.sqrt((end.x-center2.x)**2+(end.y-center2.y)**2),rotatedCenter=rotatePoint7(center2.x,center2.y,-componentRotation),centerKicadPos={x:kicadComponentPos.x+rotatedCenter.x,y:kicadComponentPos.y+rotatedCenter.y},centerPos=applyToPoint(ctx.k2cMatPcb,centerKicadPos),layer=mapTextLayer(circle2.layer),strokeWidth=circle2.stroke?.width||circle2.width||.12;if(renderLayer.endsWith("_courtyard")){ctx.db.pcb_courtyard_circle.insert({pcb_component_id:componentId,center:centerPos,radius,layer});return}let numPoints=16,circleRoute=[];for(let i3=0;i3<=numPoints;i3++){let angle=i3/numPoints*2*Math.PI,x4=centerPos.x+radius*Math.cos(angle),y4=centerPos.y+radius*Math.sin(angle);circleRoute.push({x:x4,y:y4})}insertFootprintRoute({ctx,componentId,layer,renderLayer,route:circleRoute,strokeWidth})}function calculateArcCenter(p12,p22,p32){let ax3=p12.x-p22.x,ay3=p12.y-p22.y,bx3=p22.x-p32.x,by3=p22.y-p32.y,denom=2*(ax3*by3-ay3*bx3);if(Math.abs(denom)<1e-10)return null;let d12=p12.x*p12.x+p12.y*p12.y-p22.x*p22.x-p22.y*p22.y,d22=p22.x*p22.x+p22.y*p22.y-p32.x*p32.x-p32.y*p32.y,cx3=(d12*by3-d22*ay3)/denom,cy3=(ax3*d22-bx3*d12)/denom,radius=Math.sqrt((p12.x-cx3)**2+(p12.y-cy3)**2);return{center:{x:cx3,y:cy3},radius}}function createFootprintArc(ctx,arc2,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;let renderLayer=mapKicadLayerToPcbRenderLayer(arc2.layer);if(!isPcbAnnotationRenderLayer(renderLayer))return;let start=arc2.start||{x:0,y:0},mid=arc2.mid||{x:0,y:0},end=arc2.end||{x:0,y:0},rotatedStart=rotatePoint7(start.x,start.y,-componentRotation),rotatedMid=rotatePoint7(mid.x,mid.y,-componentRotation),rotatedEnd=rotatePoint7(end.x,end.y,-componentRotation),startKicadPos={x:kicadComponentPos.x+rotatedStart.x,y:kicadComponentPos.y+rotatedStart.y},midKicadPos={x:kicadComponentPos.x+rotatedMid.x,y:kicadComponentPos.y+rotatedMid.y},endKicadPos={x:kicadComponentPos.x+rotatedEnd.x,y:kicadComponentPos.y+rotatedEnd.y},layer=mapTextLayer(arc2.layer),strokeWidth=arc2.stroke?.width||arc2.width||.12,arcInfo=calculateArcCenter(startKicadPos,midKicadPos,endKicadPos);if(!arcInfo){let startPos=applyToPoint(ctx.k2cMatPcb,startKicadPos),endPos=applyToPoint(ctx.k2cMatPcb,endKicadPos);insertFootprintRoute({ctx,componentId,layer,renderLayer,route:[startPos,endPos],strokeWidth});return}let{center:center2,radius}=arcInfo,startAngle=Math.atan2(startKicadPos.y-center2.y,startKicadPos.x-center2.x),midAngle=Math.atan2(midKicadPos.y-center2.y,midKicadPos.x-center2.x),sweepAngle=Math.atan2(endKicadPos.y-center2.y,endKicadPos.x-center2.x)-startAngle,midSweep=midAngle-startAngle;for(;sweepAngle>Math.PI;)sweepAngle-=2*Math.PI;for(;sweepAngle<-Math.PI;)sweepAngle+=2*Math.PI;for(;midSweep>Math.PI;)midSweep-=2*Math.PI;for(;midSweep<-Math.PI;)midSweep+=2*Math.PI;let isCCW=sweepAngle>0;isCCW&&midSweep>0&&midSweep<sweepAngle||!isCCW&&midSweep<0&&midSweep>sweepAngle||(sweepAngle=sweepAngle>0?sweepAngle-2*Math.PI:sweepAngle+2*Math.PI);let arcLength2=Math.abs(radius*sweepAngle),numSegments=Math.max(2,Math.ceil(arcLength2/.1)),arcRoute=[];for(let i3=0;i3<=numSegments;i3++){let t52=i3/numSegments,angle=startAngle+sweepAngle*t52,kicadPoint={x:center2.x+radius*Math.cos(angle),y:center2.y+radius*Math.sin(angle)},cjPoint=applyToPoint(ctx.k2cMatPcb,kicadPoint);arcRoute.push(cjPoint)}insertFootprintRoute({ctx,componentId,layer,renderLayer,route:arcRoute,strokeWidth})}function createFootprintPoly(ctx,poly,componentId,kicadComponentPos,componentCcwRotationDegrees){if(!ctx.k2cMatPcb)return;let renderLayer=mapKicadLayerToPcbRenderLayer(poly.layer);if(!isPcbAnnotationRenderLayer(renderLayer))return;let ptArray=poly.points?.points||[];if(ptArray.length===0)return;let layer=mapTextLayer(poly.layer),strokeWidth=poly.stroke?.width||poly.width||.12,transformedPts=ptArray.map(p4=>{let x4=p4.x??p4.xy?.x??0,y4=p4.y??p4.xy?.y??0,rotated=rotatePoint7(x4,y4,-componentCcwRotationDegrees),kicadPos={x:kicadComponentPos.x+rotated.x,y:kicadComponentPos.y+rotated.y};return applyToPoint(ctx.k2cMatPcb,kicadPos)});if(renderLayer.endsWith("_courtyard")){ctx.db.pcb_courtyard_outline.insert({pcb_component_id:componentId,layer,outline:transformedPts});return}insertFootprintRoute({ctx,componentId,layer,renderLayer,route:transformedPts,strokeWidth})}function createPcbPort({ctx,componentId,padInfo}){if(!padInfo.layers||padInfo.layers.length===0)return;let sourcePortId=`${componentId}_port_${padInfo.padNumber}`;return ctx.db.pcb_port.insert({pcb_component_id:componentId,source_port_id:sourcePortId,x:padInfo.position.x,y:padInfo.position.y,layers:padInfo.layers}).pcb_port_id}function processPads(ctx,footprint,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;let pads=footprint.fpPads||[],padArray=Array.isArray(pads)?pads:[pads];for(let pad2 of padArray)processPad({ctx,pad:pad2,componentId,kicadComponentPos,componentRotation})}function processPad({ctx,pad:pad2,componentId,kicadComponentPos,componentRotation}){if(!ctx.k2cMatPcb)return;let padAt=pad2.at||{x:0,y:0,angle:0},padType=pad2.padType||pad2.type||"thru_hole",padShape=pad2.shape||"circle",rotationRad=-componentRotation*Math.PI/180,rotatedPadX=padAt.x*Math.cos(rotationRad)-padAt.y*Math.sin(rotationRad),rotatedPadY=padAt.x*Math.sin(rotationRad)+padAt.y*Math.cos(rotationRad),padKicadPos={x:kicadComponentPos.x+rotatedPadX,y:kicadComponentPos.y+rotatedPadY},globalPos=applyToPoint(ctx.k2cMatPcb,padKicadPos),sizeX=1,sizeY=1;pad2.size&&(Array.isArray(pad2.size)?(sizeX=pad2.size[0]||1,sizeY=pad2.size[1]||1):typeof pad2.size=="object"&&(sizeX=pad2.size._width||pad2.size.x||1,sizeY=pad2.size._height||pad2.size.y||1));let size3={x:sizeX,y:sizeY},drill=pad2.drill,mappedCopperLayers=padType==="thru_hole"?getCopperSpanLayerRefsFromLayers(pad2.layers||[],ctx.kicadPcb):getLayerRefsFromLayers(pad2.layers||[],ctx.kicadPcb),copperLayers=mappedCopperLayers.length>0?mappedCopperLayers:padType==="thru_hole"?getPcbCopperLayerRefs(ctx.kicadPcb):[],totalCcwRotationDegrees=padAt.angle||0,padNumber=pad2.number?.toString(),pcbPortId,sourcePortId;if(padNumber){let padLayers=padType==="smd"?copperLayers.slice(0,1):padType==="thru_hole"?copperLayers:[];pcbPortId=createPcbPort({ctx,componentId,padInfo:{padNumber,padType,layers:padLayers,position:globalPos}}),pcbPortId&&(sourcePortId=`${componentId}_port_${padNumber}`)}if(padType==="smd"){if(copperLayers.length===0)return;createSmdPad({ctx,pad:pad2,componentId,pos:globalPos,size:size3,shape:padShape,pcbPortId,sourcePortId,padKicadPos,totalCcwRotationDegrees})}else padType==="np_thru_hole"?createNpthHole(ctx,pad2,componentId,globalPos,drill):createPlatedHole(ctx,pad2,componentId,globalPos,size3,drill,padShape,copperLayers,totalCcwRotationDegrees,pcbPortId,sourcePortId)}function createSmdPad({ctx,pad:pad2,componentId,pos,size:size3,shape,pcbPortId,sourcePortId:_sourcePortId,padKicadPos,totalCcwRotationDegrees=0}){let layers=pad2.layers||[],layer=determineLayerFromLayers(layers);if(shape==="custom"){let primitives=pad2._sxPrimitives?._graphics||pad2.primitives||[],primitivesArray=Array.isArray(primitives)?primitives:[primitives],primitivesProcessed=0;for(let primitive of primitivesArray){if(primitive.token==="gr_poly"){let grPoly=primitive.gr_poly||primitive,rawPts=[],ptsContainer=grPoly._sxPts||grPoly.points||grPoly.pts,contours=grPoly._contours||grPoly.contours;if(ptsContainer)Array.isArray(ptsContainer)?rawPts=ptsContainer:Array.isArray(ptsContainer.points)?rawPts=ptsContainer.points:Array.isArray(ptsContainer.pts)&&(rawPts=ptsContainer.pts);else if(Array.isArray(contours))for(let contour of contours){let contourPts=contour.points||contour.pts||[];rawPts.push(...Array.isArray(contourPts)?contourPts:[contourPts])}let points=[];for(let pt3 of rawPts){let x4=pt3.x??pt3.xy?.x,y4=pt3.y??pt3.xy?.y;if(x4!==void 0&&y4!==void 0){let rotated=rotatePoint7(x4,y4,totalCcwRotationDegrees),kicadPos={x:padKicadPos.x+rotated.x,y:padKicadPos.y+rotated.y};points.push(applyToPoint(ctx.k2cMatPcb,kicadPos))}}if(points.length>0){let smtpad2={type:"pcb_smtpad",shape:"polygon",pcb_component_id:componentId,pcb_port_id:pcbPortId,pcb_smtpad_id:"pcb_smtpad_id",layer,port_hints:[pad2.number.toString()],points};ctx.db.pcb_smtpad.insert(smtpad2),primitivesProcessed++}}if(primitive.token==="gr_circle"){let grCircle=primitive.gr_circle||primitive,center2=grCircle.center||grCircle._sxCenter||{x:0,y:0},end=grCircle.end||grCircle._sxEnd||{x:0,y:0},centerlineRadius=Math.sqrt((end.x-center2.x)**2+(end.y-center2.y)**2),strokeWidth=grCircle.stroke?.width||grCircle.width||grCircle._sxWidth?.value||0,radius=(grCircle.fill?.value||grCircle.fill||grCircle._sxFill?.value)==="no"&&strokeWidth>0?centerlineRadius+strokeWidth/2:centerlineRadius,rotatedCenter=rotatePoint7(center2.x,center2.y,totalCcwRotationDegrees),kicadCenterPos={x:padKicadPos.x+rotatedCenter.x,y:padKicadPos.y+rotatedCenter.y},globalCenter=applyToPoint(ctx.k2cMatPcb,kicadCenterPos),smtpad2={type:"pcb_smtpad",shape:"circle",pcb_component_id:componentId,pcb_port_id:pcbPortId,pcb_smtpad_id:"pcb_smtpad_id",layer,port_hints:[pad2.number.toString()],x:globalCenter.x,y:globalCenter.y,width:radius*2,height:radius*2,radius};ctx.db.pcb_smtpad.insert(smtpad2),primitivesProcessed++}}if(primitivesProcessed>0){ctx.stats&&(ctx.stats.pads=(ctx.stats.pads||0)+primitivesProcessed);return}}let ccwRotationDegrees=pad2.at?.angle;if(shape==="circle"){let smtpad2={type:"pcb_smtpad",pcb_component_id:componentId,pcb_smtpad_id:"pcb_smtpad_id",x:pos.x,y:pos.y,width:size3.x,height:size3.y,layer,pcb_port_id:pcbPortId,port_hints:[pad2.number?.toString()],shape:"circle",radius:Math.max(size3.x,size3.y)/2};ctx.db.pcb_smtpad.insert(smtpad2)}else if(shape==="rect"||shape==="roundrect"){let roundrectRatio=pad2._sxRoundrectRatio?.value??pad2.roundrect_rratio,cornerRadius;shape==="roundrect"&&roundrectRatio!==void 0&&(cornerRadius=Math.min(size3.x,size3.y)*roundrectRatio/2);let normalizedCcwRotation=normalizeRotationDegrees(ccwRotationDegrees),rightAngleTurns=getRightAngleTurns(normalizedCcwRotation);if(rightAngleTurns===null&&normalizedCcwRotation!==0){let rotatedsmtpad={type:"pcb_smtpad",pcb_component_id:componentId,x:pos.x,y:pos.y,width:size3.x,height:size3.y,layer,pcb_port_id:pcbPortId,port_hints:[pad2.number.toString()],shape:"rotated_rect",ccw_rotation:normalizedCcwRotation,corner_radius:cornerRadius};ctx.db.pcb_smtpad.insert(rotatedsmtpad);return}let shouldSwapDimensions=rightAngleTurns!==null&&Math.abs(rightAngleTurns)%2===1,smtpad2={type:"pcb_smtpad",pcb_component_id:componentId,x:pos.x,y:pos.y,width:shouldSwapDimensions?size3.y:size3.x,height:shouldSwapDimensions?size3.x:size3.y,layer,pcb_port_id:pcbPortId,port_hints:[pad2.number.toString()],shape:"rect",corner_radius:cornerRadius};ctx.db.pcb_smtpad.insert(smtpad2)}else ctx.db.pcb_smtpad.insert({type:"pcb_smtpad",pcb_component_id:componentId,x:pos.x,y:pos.y,width:size3.x,height:size3.y,layer,pcb_port_id:pcbPortId,port_hints:[pad2.number?.toString()],shape:"rect"});ctx.stats&&(ctx.stats.pads=(ctx.stats.pads||0)+1)}function normalizeRotationDegrees(rotationDegrees){if(!rotationDegrees)return 0;let normalized=rotationDegrees%360;return normalized<0?normalized+360:normalized}function getRightAngleTurns(rotationDegrees){let quarterTurns=rotationDegrees/90;return Math.abs(quarterTurns-Math.round(quarterTurns))>1e-9?null:Math.round(quarterTurns)}function createPlatedHole(ctx,pad2,componentId,pos,size3,drill,shape,layers,_rotation=0,pcbPortId,_sourcePortId=void 0){let drillX=typeof drill=="object"?drill?.x||drill?._width||drill?.diameter||.8:drill||.8,drillY=typeof drill=="object"?drill?.y||drill?._height||drill?.diameter||drillX:drill||.8,holeDiameter=Math.max(drillX,drillY),drillIsOval=typeof drill=="object"&&drillX!==void 0&&drillY!==void 0&&drillX!==drillY,outerWidth=size3.x,outerHeight=size3.y;if(shape==="circle"){let platedHole={type:"pcb_plated_hole",shape:"circle",pcb_component_id:componentId,pcb_port_id:pcbPortId,x:pos.x,y:pos.y,port_hints:[pad2.number?.toString()],hole_diameter:holeDiameter,outer_diameter:Math.max(outerWidth,outerHeight),layers};ctx.db.pcb_plated_hole.insert(platedHole)}else if(shape==="oval"){let platedHole={type:"pcb_plated_hole",shape:"pill",pcb_component_id:componentId,pcb_port_id:pcbPortId,x:pos.x,y:pos.y,port_hints:[pad2.number?.toString()],hole_width:drillY,hole_height:drillX,outer_width:outerWidth,outer_height:outerHeight,ccw_rotation:pad2.at?.angle||0,layers};ctx.db.pcb_plated_hole.insert(platedHole)}else if(shape==="rect"||shape==="square"||shape==="roundrect"){let normalizedCcwRotationDegrees=normalizeRotationDegrees(pad2.at?.angle);if(drillIsOval)if(normalizedCcwRotationDegrees===0){let platedHole={type:"pcb_plated_hole",shape:"pill_hole_with_rect_pad",pcb_component_id:componentId,pcb_port_id:pcbPortId,x:pos.x,y:pos.y,port_hints:[pad2.number?.toString()],hole_shape:"pill",pad_shape:"rect",hole_width:drillY,hole_height:drillX,rect_pad_width:outerWidth,rect_pad_height:outerHeight,hole_offset_x:0,hole_offset_y:0,layers};if(shape==="roundrect"){let roundrectRatio=pad2._sxRoundrectRatio?.value??pad2.roundrect_rratio;if(roundrectRatio!==void 0){let minDimension=Math.min(outerWidth,outerHeight);platedHole.rect_border_radius=minDimension*roundrectRatio/2}}ctx.db.pcb_plated_hole.insert(platedHole)}else{let platedHole={type:"pcb_plated_hole",shape:"rotated_pill_hole_with_rect_pad",pcb_component_id:componentId,pcb_port_id:pcbPortId,x:pos.x,y:pos.y,port_hints:[pad2.number?.toString()],hole_shape:"rotated_pill",pad_shape:"rect",hole_width:drillY,hole_height:drillX,hole_ccw_rotation:normalizedCcwRotationDegrees,rect_ccw_rotation:normalizedCcwRotationDegrees,rect_pad_width:outerWidth,rect_pad_height:outerHeight,hole_offset_x:0,hole_offset_y:0,layers};if(shape==="roundrect"){let roundrectRatio=pad2._sxRoundrectRatio?.value??pad2.roundrect_rratio;if(roundrectRatio!==void 0){let minDimension=Math.min(outerWidth,outerHeight);platedHole.rect_border_radius=minDimension*roundrectRatio/2}}ctx.db.pcb_plated_hole.insert(platedHole)}else{let platedHole={type:"pcb_plated_hole",shape:"circular_hole_with_rect_pad",pcb_component_id:componentId,pcb_port_id:pcbPortId,pcb_plated_hole_id:"pcb_plated_hole_id",x:pos.x,y:pos.y,port_hints:[pad2.number?.toString()],hole_shape:"circle",pad_shape:"rect",hole_diameter:holeDiameter,rect_ccw_rotation:pad2.at?.angle||0,rect_pad_width:outerWidth,rect_pad_height:outerHeight,hole_offset_x:0,hole_offset_y:0,layers};if(shape==="roundrect"){let roundrectRatio=pad2._sxRoundrectRatio?.value??pad2.roundrect_rratio;if(roundrectRatio!==void 0){let minDimension=Math.min(outerWidth,outerHeight);platedHole.rect_border_radius=minDimension*roundrectRatio/2}}ctx.db.pcb_plated_hole.insert(platedHole)}}ctx.stats&&(ctx.stats.pads=(ctx.stats.pads||0)+1)}function createNpthHole(ctx,_pad,componentId,pos,drill){let holeDiameter=drill?.diameter||drill||1,hole={type:"pcb_hole",hole_shape:"circle",pcb_component_id:componentId,x:pos.x,y:pos.y,hole_diameter:holeDiameter};ctx.db.pcb_hole.insert(hole)}function getTextValue(footprint,type){let texts=footprint.fpTexts||[];return(Array.isArray(texts)?texts:[texts]).find(t52=>t52.type===type)?.text}function getPropertyValue(footprint,propertyName){let properties=footprint.properties||[];return(Array.isArray(properties)?properties:[properties]).find(p4=>p4.key===propertyName)?.value}function substituteKicadVariables(text,footprint){let result=text,reference=getPropertyValue(footprint,"Reference")||getTextValue(footprint,"reference")||"?",value=getPropertyValue(footprint,"Value")||getTextValue(footprint,"value")||"";return result=result.replace(/\$\{REFERENCE\}/g,reference),result=result.replace(/\$\{VALUE\}/g,value),result}function mapKicadJustifyToAnchorAlignment(justify){if(!justify)return"center";let horizontal=justify.horizontal||"center",vertical=justify.vertical||"center";if(vertical==="top"){if(horizontal==="left")return"top_left";if(horizontal==="center")return"top_center";if(horizontal==="right")return"top_right"}if(vertical==="center"){if(horizontal==="left")return"center_left";if(horizontal==="center")return"center";if(horizontal==="right")return"center_right"}if(vertical==="bottom"){if(horizontal==="left")return"bottom_left";if(horizontal==="center")return"bottom_center";if(horizontal==="right")return"bottom_right"}return"center"}function processFootprintText(ctx,footprint,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;processFootprintProperties(ctx,footprint,componentId,kicadComponentPos,componentRotation);let texts=footprint.fpTexts||[],textArray=Array.isArray(texts)?texts:[texts];for(let text of textArray){let renderLayer=mapKicadLayerToPcbRenderLayer(text.layer);if(!isPcbTextRenderLayer(renderLayer))continue;let textElement={text:text.text,at:text._sxPosition||text.at,layer:text.layer,effects:text._sxEffects||text.effects,_sxEffects:text._sxEffects};createGraphicText(ctx,textElement,renderLayer,componentId,kicadComponentPos,componentRotation,footprint)}}function processFootprintProperties(ctx,footprint,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;let properties=footprint.properties||[],propertyArray=Array.isArray(properties)?properties:[properties];for(let property of propertyArray){if(!property.layer)continue;let renderLayer=mapKicadLayerToPcbRenderLayer(property.layer),isPropertyHidden=property.hidden;if(!isPcbTextRenderLayer(renderLayer)||isPropertyHidden)continue;let textElement={text:property.value,at:property._sxAt,layer:property.layer,effects:property._sxEffects||property.effects,_sxEffects:property._sxEffects};createGraphicText(ctx,textElement,renderLayer,componentId,kicadComponentPos,componentRotation,footprint)}}function createGraphicText(ctx,text,renderLayer,componentId,kicadComponentPos,componentRotation,footprint){if(!ctx.k2cMatPcb)return;let at3=text.at,textLocalX=at3?.x??0,textLocalY=at3?.y??0,rotationRad=-componentRotation*Math.PI/180,rotatedTextX=textLocalX*Math.cos(rotationRad)-textLocalY*Math.sin(rotationRad),rotatedTextY=textLocalX*Math.sin(rotationRad)+textLocalY*Math.cos(rotationRad),textKicadPos={x:kicadComponentPos.x+rotatedTextX,y:kicadComponentPos.y+rotatedTextY},pos=applyToPoint(ctx.k2cMatPcb,textKicadPos),layer=mapTextLayer(text.layer),processedText=substituteKicadVariables(text.text||"",footprint),kicadFontSize=text._sxEffects?._sxFont?._sxSize?._height||text.effects?.font?.size?.y||1,justify=text._sxEffects?._sxJustify||text.effects?.justify,anchorAlignment=mapKicadJustifyToAnchorAlignment(justify);if(renderLayer.endsWith("_silkscreen")){ctx.db.pcb_silkscreen_text.insert({pcb_component_id:componentId,font:"tscircuit2024",font_size:kicadFontSize*1.5,text:processedText,anchor_position:pos,anchor_alignment:anchorAlignment,layer});return}if(renderLayer.endsWith("_fabrication_note")){ctx.db.pcb_fabrication_note_text.insert({pcb_component_id:componentId,font:"tscircuit2024",font_size:kicadFontSize*1.5,text:processedText,anchor_position:pos,anchor_alignment:anchorAlignment,layer});return}renderLayer.endsWith("_copper")&&ctx.db.pcb_copper_text.insert({pcb_component_id:componentId,font:"tscircuit2024",font_size:kicadFontSize*1.5,text:processedText,anchor_position:pos,anchor_alignment:anchorAlignment,layer})}function inferComponentType(reference){if(!reference)return"simple_chip";switch(reference.match(/^([A-Z]+)/)?.[1]){case"R":return"simple_resistor";case"C":return"simple_capacitor";case"L":return"simple_inductor";case"D":return"simple_diode";case"LED":return"simple_diode";case"Q":return"simple_transistor";case"U":case"IC":return"simple_chip";case"J":case"P":return"simple_chip";default:return"simple_chip"}}function inferTransistorTypeFromFootprint(footprint,value){let lowerValue=(value||"").toLowerCase();if(lowerValue.includes("pnp"))return"pnp";if(lowerValue.includes("npn"))return"npn";let lowerLibId=(footprint.libraryId||"").toLowerCase();return lowerLibId.includes("pnp")?"pnp":(lowerLibId.includes("npn"),"npn")}function getFootprintProperties(footprint){let properties=footprint.properties||[];return Array.isArray(properties)?properties:[properties]}function getFootprintPropertyName(property){return property?.key}function getFootprintPropertyValue(property){return property?.value}function findFootprintProperty(footprint,propertyNames){let names=Array.isArray(propertyNames)?propertyNames:[propertyNames];return getFootprintProperties(footprint).find(property=>names.includes(getFootprintPropertyName(property)??""))}function findFootprintPropertyValue(footprint,propertyNames){let property=findFootprintProperty(footprint,propertyNames);return getFootprintPropertyValue(property)}function parseSupplierPartNumbers(value){if(!value)return;let partNumbers=value.split(/[,;]/).map(partNumber=>partNumber.trim()).filter(Boolean);return partNumbers.length>0?partNumbers:void 0}function processFootprint(ctx,footprint){if(!ctx.k2cMatPcb)return;let position4=footprint.position,kicadPos={x:position4?.x??0,y:position4?.y??0},cjPos=applyToPoint(ctx.k2cMatPcb,kicadPos),rotation5=position4?.angle??0,uuid=footprint.uuid?.value||footprint.tstamp?.value;if(!uuid)return;let refdes=getFootprintReference(footprint),value=getFootprintValue(footprint),jlcpcbPartNumbers=getJlcpcbPartNumbers(footprint),ftype=inferComponentType(refdes),sourceComponentData={name:refdes||"U",ftype};if(ftype==="simple_transistor"&&(sourceComponentData.transistor_type=inferTransistorTypeFromFootprint(footprint,value)),jlcpcbPartNumbers&&(sourceComponentData.supplier_part_numbers={jlcpcb:jlcpcbPartNumbers}),value){let sanitizedValue=value.replace(/,/g,".");switch(ftype){case"simple_resistor":sourceComponentData.resistance=sanitizedValue;break;case"simple_capacitor":sourceComponentData.capacitance=sanitizedValue;break;case"simple_inductor":sourceComponentData.inductance=sanitizedValue;break}}let sourceComponentId=ctx.db.source_component.insert(sourceComponentData).source_component_id,componentId=ctx.db.pcb_component.insert({center:{x:cjPos.x,y:cjPos.y},layer:getComponentLayer(footprint),rotation:-rotation5,width:0,height:0,source_component_id:sourceComponentId}).pcb_component_id;ctx.footprintUuidToComponentId?.set(uuid,componentId),ctx.footprintUuidToSourceComponentId?.set(uuid,sourceComponentId),processPads(ctx,footprint,componentId,kicadPos,rotation5),processFootprintText(ctx,footprint,componentId,kicadPos,rotation5),processFootprintGraphics(ctx,footprint,componentId,kicadPos,rotation5),ctx.stats&&(ctx.stats.components=(ctx.stats.components||0)+1)}function getFootprintReference(footprint){let propertyValue=findFootprintPropertyValue(footprint,"Reference");if(propertyValue)return propertyValue;let textItems=footprint.fpTexts||[],textArray=Array.isArray(textItems)?textItems:[textItems];for(let text of textArray)if(text.type==="reference")return text.text}function getFootprintValue(footprint){let propertyValue=findFootprintPropertyValue(footprint,"Value");if(propertyValue)return propertyValue;let textItems=footprint.fpTexts||[],textArray=Array.isArray(textItems)?textItems:[textItems];for(let text of textArray)if(text.type==="value")return text.text}function getJlcpcbPartNumbers(footprint){return parseSupplierPartNumbers(findFootprintPropertyValue(footprint,["JLCPCB Part #","Supplier Part Number"]))}var CollectFootprintsStage=class extends ConverterStage{constructor(){super(...arguments);__publicField(this,"processedFootprints",new Set)}step(){if(!this.ctx.kicadPcb||!this.ctx.k2cMatPcb)return this.finished=!0,!1;let footprints=this.ctx.kicadPcb.footprints||[],footprintArray=Array.isArray(footprints)?footprints:[footprints];for(let footprint of footprintArray){let uuid=footprint.uuid?.value||footprint.tstamp?.value;uuid&&(this.processedFootprints.has(uuid)||(processFootprint(this.ctx,footprint),this.processedFootprints.add(uuid)))}return this.finished=!0,!1}},FULL_TURN=Math.PI*2;function normalizeToArray(value){return value?Array.isArray(value)?value:[value]:[]}function getLayerNames(layer){return layer?typeof layer=="string"?[layer]:layer.names||[]:[]}function getGraphicLayerNames(graphic){return getLayerNames(graphic?.layer)}function getPcbPoint(point7){return{x:point7?.x??0,y:point7?.y??0}}function getLineStartEnd(line2){return{start:getPcbPoint(line2.start),end:getPcbPoint(line2.end)}}function getArcStartMidEnd(arc2){return{start:getPcbPoint(arc2.start),mid:getPcbPoint(arc2.mid),end:getPcbPoint(arc2.end)}}function getCircleCenterEnd(circle2){return{center:getPcbPoint(circle2.center),end:getPcbPoint(circle2.end)}}function getGraphicArcs(kicadPcb){return normalizeToArray(kicadPcb.graphicArcs)}function getGraphicCircles(kicadPcb){return normalizeToArray(kicadPcb.graphicCircles)}function getGraphicCurves(kicadPcb){return normalizeToArray(kicadPcb.graphicCurves)}function getTopLevelCopperArcs(kicadPcb){return normalizeToArray(kicadPcb.arcs)}function approximateArcPoints(start,mid,end,options){let geometry=getArcGeometry(start,mid,end);if(!geometry)return[start,end];let segmentLength=options?.segmentLength??.25,minSegments=options?.minSegments??8,arcLength2=Math.abs(geometry.radius*geometry.sweepAngle),numSegments=Math.max(2,minSegments,Math.ceil(arcLength2/segmentLength)),points=[];for(let i3=0;i3<=numSegments;i3++){let t52=i3/numSegments,angle=geometry.startAngle+geometry.sweepAngle*t52;points.push({x:geometry.center.x+geometry.radius*Math.cos(angle),y:geometry.center.y+geometry.radius*Math.sin(angle)})}return points}function getCurvePoints(curve){let xyPoints=(curve.points?.points??[]).filter(point7=>point7.token==="xy").map(point7=>getPcbPoint(point7));return xyPoints.length<4?null:{start:xyPoints[0],control1:xyPoints[1],control2:xyPoints[2],end:xyPoints[3]}}function approximateCubicBezierPoints(start,control1,control2,end,options){let segmentLength=options?.segmentLength??.25,minSegments=options?.minSegments??8,controlPolygonLength=getDistance4(start,control1)+getDistance4(control1,control2)+getDistance4(control2,end),numSegments=Math.max(2,minSegments,Math.ceil(controlPolygonLength/segmentLength)),points=[];for(let i3=0;i3<=numSegments;i3++){let t52=i3/numSegments,omt=1-t52;points.push({x:omt**3*start.x+3*omt**2*t52*control1.x+3*omt*t52**2*control2.x+t52**3*end.x,y:omt**3*start.y+3*omt**2*t52*control1.y+3*omt*t52**2*control2.y+t52**3*end.y})}return points}function approximateCirclePoints(center2,end,options){let radius=getDistance4(center2,end);if(radius<=0)return[center2];let segmentLength=options?.segmentLength??.25,minSegments=options?.minSegments??16,circumference=FULL_TURN*radius,numSegments=Math.max(8,minSegments,Math.ceil(circumference/segmentLength)),startAngle=Math.atan2(end.y-center2.y,end.x-center2.x),points=[];for(let i3=0;i3<=numSegments;i3++){let t52=i3/numSegments,angle=startAngle+FULL_TURN*t52;points.push({x:center2.x+radius*Math.cos(angle),y:center2.y+radius*Math.sin(angle)})}return points}function getArcGeometry(start,mid,end){let circle2=calculateArcCenter2(start,mid,end);if(!circle2)return null;let startAngle=Math.atan2(start.y-circle2.center.y,start.x-circle2.center.x),midAngle=Math.atan2(mid.y-circle2.center.y,mid.x-circle2.center.x),endAngle=Math.atan2(end.y-circle2.center.y,end.x-circle2.center.x),sweepAngle=normalizeSignedAngle(endAngle-startAngle),midSweep=normalizeSignedAngle(midAngle-startAngle),isCounterClockwise=sweepAngle>0;return isCounterClockwise&&midSweep>0&&midSweep<sweepAngle||!isCounterClockwise&&midSweep<0&&midSweep>sweepAngle||(sweepAngle=sweepAngle>0?sweepAngle-FULL_TURN:sweepAngle+FULL_TURN),{center:circle2.center,radius:circle2.radius,startAngle,sweepAngle}}function normalizeSignedAngle(angle){for(;angle<=-Math.PI;)angle+=FULL_TURN;for(;angle>Math.PI;)angle-=FULL_TURN;return angle}function calculateArcCenter2(p12,p22,p32){let ax3=p12.x,ay3=p12.y,bx3=p22.x,by3=p22.y,cx3=p32.x,cy3=p32.y,determinant=2*(ax3*(by3-cy3)+bx3*(cy3-ay3)+cx3*(ay3-by3));if(Math.abs(determinant)<1e-10)return null;let ux3=((ax3*ax3+ay3*ay3)*(by3-cy3)+(bx3*bx3+by3*by3)*(cy3-ay3)+(cx3*cx3+cy3*cy3)*(ay3-by3))/determinant,uy3=((ax3*ax3+ay3*ay3)*(cx3-bx3)+(bx3*bx3+by3*by3)*(ax3-cx3)+(cx3*cx3+cy3*cy3)*(bx3-ax3))/determinant;return{center:{x:ux3,y:uy3},radius:Math.sqrt((ax3-ux3)**2+(ay3-uy3)**2)}}function getDistance4(a3,b3){return Math.hypot(b3.x-a3.x,b3.y-a3.y)}var CollectGraphicsStage=class extends ConverterStage{step(){if(!this.ctx.kicadPcb||!this.ctx.k2cMatPcb)return this.finished=!0,!1;let lines=this.ctx.kicadPcb.graphicLines||[],lineArray=Array.isArray(lines)?lines:[lines],arcArray=getGraphicArcs(this.ctx.kicadPcb),circleArray=getGraphicCircles(this.ctx.kicadPcb),curveArray=getGraphicCurves(this.ctx.kicadPcb),edgeCutPrimitives=[];for(let line2 of lineArray){let layerStr=getGraphicLayerNames(line2).join(" ");if(layerStr.includes("Edge.Cuts")){let{start,end}=getLineStartEnd(line2);edgeCutPrimitives.push({type:"line",start,end})}else if(layerStr.includes("SilkS")||layerStr.includes("Fab")||layerStr.includes("CrtYd")){let renderLayer=mapKicadLayerToPcbRenderLayer(line2.layer);renderLayer&&this.createGraphicPath(line2,renderLayer)}}for(let arc2 of arcArray){let layerStr=getGraphicLayerNames(arc2).join(" ");if(layerStr.includes("Edge.Cuts")){let{start,mid,end}=getArcStartMidEnd(arc2);edgeCutPrimitives.push({type:"arc",start,mid,end})}else if(layerStr.includes("SilkS")||layerStr.includes("Fab")||layerStr.includes("CrtYd")){let renderLayer=mapKicadLayerToPcbRenderLayer(arc2.layer);renderLayer&&this.createGraphicArc(arc2,renderLayer)}}for(let circle2 of circleArray){if(!getGraphicLayerNames(circle2).join(" ").includes("Edge.Cuts"))continue;let{center:center2,end}=getCircleCenterEnd(circle2);edgeCutPrimitives.push({type:"circle",center:center2,start:end,end})}for(let curve of curveArray){if(!getGraphicLayerNames(curve).join(" ").includes("Edge.Cuts"))continue;let points=getCurvePoints(curve);points&&edgeCutPrimitives.push({type:"curve",start:points.start,control1:points.control1,control2:points.control2,end:points.end})}edgeCutPrimitives.length>0&&this.createBoardOutline(edgeCutPrimitives);let grRects=this.ctx.kicadPcb.graphicRects||[];for(let rect of grRects)this.processRectangle(rect);let grPolys=this.ctx.kicadPcb.graphicPolys||[],polyArray=Array.isArray(grPolys)?grPolys:[grPolys];for(let poly of polyArray)this.processPolygon(poly);let texts=this.ctx.kicadPcb.graphicTexts||[],textArray=Array.isArray(texts)?texts:[texts];for(let text of textArray){let renderLayer=mapKicadLayerToPcbRenderLayer(text.layer);renderLayer&&this.createGraphicText(text,renderLayer)}return this.finished=!0,!1}createBoardOutline(primitives){if(!this.ctx.k2cMatPcb)return;let orderedSegments=[],remainingSegments=[...primitives];if(remainingSegments.length>0)for(orderedSegments.push(remainingSegments.shift());remainingSegments.length>0;){let lastEnd=orderedSegments[orderedSegments.length-1].end,foundIndex=remainingSegments.findIndex(seg=>this.pointsEqualKicad(seg.start,lastEnd));if(foundIndex===-1&&(foundIndex=remainingSegments.findIndex(seg=>this.pointsEqualKicad(seg.end,lastEnd)),foundIndex!==-1)){let seg=remainingSegments[foundIndex];orderedSegments.push(seg.type==="arc"?{type:"arc",start:seg.end,mid:seg.mid,end:seg.start}:seg.type==="circle"?{type:"circle",center:seg.center,start:seg.end,end:seg.start}:seg.type==="curve"?{type:"curve",start:seg.end,control1:seg.control2,control2:seg.control1,end:seg.start}:{type:"line",start:seg.end,end:seg.start}),remainingSegments.splice(foundIndex,1);continue}foundIndex!==-1?orderedSegments.push(remainingSegments.splice(foundIndex,1)[0]):orderedSegments.push(remainingSegments.shift())}let points=[];for(let segment2 of orderedSegments){let kicadPoints;segment2.type==="arc"?kicadPoints=approximateArcPoints(segment2.start,segment2.mid,segment2.end,{segmentLength:.25,minSegments:16}):segment2.type==="circle"?kicadPoints=approximateCirclePoints(segment2.center,segment2.end,{segmentLength:.25,minSegments:16}):segment2.type==="curve"?kicadPoints=approximateCubicBezierPoints(segment2.start,segment2.control1,segment2.control2,segment2.end,{segmentLength:.25,minSegments:16}):kicadPoints=[segment2.start,segment2.end];for(let kicadPoint of kicadPoints){let point7=applyToPoint(this.ctx.k2cMatPcb,kicadPoint),lastPoint=points[points.length-1];(!lastPoint||!this.pointsEqual(lastPoint,point7))&&points.push(point7)}}let existingBoard=this.ctx.db.pcb_board.list()[0];existingBoard?(existingBoard.outline=points,existingBoard.width=this.calculateWidth(points),existingBoard.height=this.calculateHeight(points)):this.ctx.db.pcb_board.insert({outline:points,width:this.calculateWidth(points),height:this.calculateHeight(points)})}createGraphicPath(line2,renderLayer){if(!this.ctx.k2cMatPcb)return;let{start,end}=getLineStartEnd(line2),startPos=applyToPoint(this.ctx.k2cMatPcb,start),endPos=applyToPoint(this.ctx.k2cMatPcb,end),layer=mapKicadLayerToVisibleLayer(line2.layer),strokeWidth=line2.width||.15;this.insertRouteGraphic({layer,renderLayer,pcbComponentId:"",route:[startPos,endPos],strokeWidth})}createGraphicArc(arc2,renderLayer){if(!this.ctx.k2cMatPcb)return;let{start,mid,end}=getArcStartMidEnd(arc2),route=approximateArcPoints(start,mid,end,{segmentLength:.1,minSegments:8}).map(point7=>applyToPoint(this.ctx.k2cMatPcb,point7)),layer=mapKicadLayerToVisibleLayer(arc2.layer),strokeWidth=arc2.stroke?.width??arc2._sxStroke?._sxWidth?.value??arc2.width??.15;this.insertRouteGraphic({layer,renderLayer,pcbComponentId:"",route,strokeWidth})}insertRouteGraphic(options){let{layer,renderLayer,pcbComponentId,route,strokeWidth}=options;if(renderLayer.endsWith("_silkscreen")){this.ctx.db.pcb_silkscreen_path.insert({pcb_component_id:pcbComponentId,layer,route,stroke_width:strokeWidth});return}if(renderLayer.endsWith("_fabrication_note")){this.ctx.db.pcb_fabrication_note_path.insert({pcb_component_id:pcbComponentId,layer,route,stroke_width:strokeWidth});return}this.ctx.db.pcb_courtyard_outline.insert({pcb_component_id:pcbComponentId,layer,outline:route})}processRectangle(rect){if(!this.ctx.k2cMatPcb)return;let start={x:rect._sxStart?._x??0,y:rect._sxStart?._y??0},end={x:rect._sxEnd?._x??0,y:rect._sxEnd?._y??0},renderLayer=mapKicadLayerToPcbRenderLayer(rect._sxLayer),isFilled=rect._sxFill&&(rect._sxFill.isFilled===!0||String(rect._sxFill).includes("fill yes")),isCopperLayer=renderLayer?.endsWith("_copper"),centerKicad={x:(start.x+end.x)/2,y:(start.y+end.y)/2},widthKicad=Math.abs(end.x-start.x),heightKicad=Math.abs(end.y-start.y),centerCJ=applyToPoint(this.ctx.k2cMatPcb,centerKicad);if(isFilled&&isCopperLayer){let layer2=mapKicadLayerToLayerRef(rect._sxLayer);this.ctx.db.pcb_smtpad.insert({pcb_component_id:"",x:centerCJ.x,y:centerCJ.y,width:widthKicad,height:heightKicad,layer:layer2,shape:"rect",port_hints:[]}),this.ctx.stats&&(this.ctx.stats.pads=(this.ctx.stats.pads||0)+1);return}let layer=mapKicadLayerToVisibleLayer(rect._sxLayer),strokeWidth=rect.stroke?.width??rect._sxStroke?._sxWidth?.value??rect.width??.15;if(renderLayer?.endsWith("_fabrication_note")){this.ctx.db.pcb_fabrication_note_rect.insert({pcb_component_id:"",center:centerCJ,width:widthKicad,height:heightKicad,layer,stroke_width:strokeWidth,is_filled:isFilled,has_stroke:!0});return}renderLayer?.endsWith("_courtyard")&&this.ctx.db.pcb_courtyard_rect.insert({pcb_component_id:"",center:centerCJ,width:widthKicad,height:heightKicad,layer})}createGraphicText(text,renderLayer){if(!this.ctx.k2cMatPcb)return;let at3=text.at||text._sxPosition,pos=applyToPoint(this.ctx.k2cMatPcb,{x:at3?.x??0,y:at3?.y??0}),layer=mapKicadLayerToVisibleLayer(text.layer),fontSize=(text._sxEffects?._sxFont?._sxSize?._height||text.effects?.font?.size?.y||1)*1.5,textValue=text.text||text._text||"",justify=text._sxEffects?._sxJustify||text.effects?.justify,anchorAlignment=mapKicadJustifyToAnchorAlignment(justify);if(renderLayer.endsWith("_silkscreen")){this.ctx.db.pcb_silkscreen_text.insert({pcb_component_id:"",text:textValue,anchor_position:pos,anchor_alignment:anchorAlignment,layer,font_size:fontSize,font:"tscircuit2024"});return}if(renderLayer.endsWith("_fabrication_note")){this.ctx.db.pcb_fabrication_note_text.insert({pcb_component_id:"",text:textValue,anchor_position:pos,anchor_alignment:anchorAlignment,layer,font_size:fontSize,font:"tscircuit2024"});return}renderLayer.endsWith("_copper")&&this.ctx.db.pcb_copper_text.insert({pcb_component_id:"",text:textValue,anchor_position:pos,anchor_alignment:anchorAlignment,layer,font_size:fontSize,font:"tscircuit2024"})}pointsEqual(p12,p22){return Math.abs(p12.x-p22.x)<.001&&Math.abs(p12.y-p22.y)<.001}pointsEqualKicad(p12,p22){return Math.abs(p12.x-p22.x)<.001&&Math.abs(p12.y-p22.y)<.001}calculateWidth(points){if(points.length===0)return 0;let xs3=points.map(p4=>p4.x);return Math.max(...xs3)-Math.min(...xs3)}calculateHeight(points){if(points.length===0)return 0;let ys3=points.map(p4=>p4.y);return Math.max(...ys3)-Math.min(...ys3)}processPolygon(poly){if(!this.ctx.k2cMatPcb)return;let renderLayer=mapKicadLayerToPcbRenderLayer(poly._sxLayer),isFilled=poly._sxFill?.filled===!0,isCopperLayer=renderLayer?.endsWith("_copper");if(!isFilled&&!renderLayer?.endsWith("_courtyard"))return;let ptsData=poly._sxPts?.points||[],points=[];for(let pt3 of ptsData)if(pt3.token==="xy")points.push({x:pt3.x,y:pt3.y});else if(pt3.token==="arc"){let arcPoints=approximateArcPoints({x:pt3._sxStart?._x,y:pt3._sxStart?._y},{x:pt3._sxMid?._x,y:pt3._sxMid?._y},{x:pt3._sxEnd?._x,y:pt3._sxEnd?._y});points.push(...arcPoints)}if(points.length<3)return;let transformedPoints=points.map(pt3=>applyToPoint(this.ctx.k2cMatPcb,pt3));if(isFilled&&isCopperLayer){let layer=mapKicadLayerToLayerRef(poly._sxLayer);this.ctx.db.pcb_smtpad.insert({pcb_component_id:"",shape:"polygon",points:transformedPoints,layer,port_hints:[]}),this.ctx.stats&&(this.ctx.stats.pads=(this.ctx.stats.pads||0)+1);return}if(renderLayer?.endsWith("_courtyard")){let layer=mapKicadLayerToVisibleLayer(poly._sxLayer);this.ctx.db.pcb_courtyard_outline.insert({pcb_component_id:"",layer,outline:transformedPoints})}}};function sanitizeCircuitJsonNetName(rawName,fallbackName){let name=(rawName?.trim()||fallbackName).replace(/\+/g,"_P").replace(/-/g,"_").replace(/[^A-Za-z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"")||fallbackName;return/^\d/.test(name)?`net_${name}`:name}var CollectNetsStage=class extends ConverterStage{step(){if(!this.ctx.kicadPcb||!this.ctx.netNumToName)return this.finished=!0,!1;let nets=this.ctx.kicadPcb.nets||[],netArray=Array.isArray(nets)?nets:[nets],usedNetNames=new Set;for(let net of netArray){let netNum=net._id??net.number??net.ordinal??0,rawNetName=net._name??net.name,sanitizedNetName=sanitizeCircuitJsonNetName(rawNetName,`Net_${netNum}`),netName=usedNetNames.has(sanitizedNetName)?`${sanitizedNetName}_${netNum}`:sanitizedNetName;usedNetNames.add(netName),this.ctx.netNumToName.set(netNum,netName)}return this.ctx.netNumToName.has(0)||this.ctx.netNumToName.set(0,""),this.finished=!0,!1}},CollectSourceTracesStage=class extends ConverterStage{constructor(){super(...arguments);__publicField(this,"processedNets",new Set)}step(){if(!this.ctx.kicadPcb||!this.ctx.netNumToName)return this.finished=!0,!1;let netToPads=new Map,footprints=this.ctx.kicadPcb.footprints||[],footprintArray=Array.isArray(footprints)?footprints:[footprints];for(let footprint of footprintArray)this.processFootprintPads(footprint,netToPads);this.collectNetsFromCopper(netToPads);for(let[netNum,pads]of netToPads.entries())this.processedNets.has(netNum)||(this.ctx.netNumToSourcePortIds?.set(netNum,pads.map(p4=>p4.sourcePortId)),this.createSourceNet(netNum),this.processedNets.add(netNum));return this.finished=!0,!1}collectNetsFromCopper(netToPads){if(!this.ctx.kicadPcb)return;let segments=this.ctx.kicadPcb.segments||[],segmentArray=Array.isArray(segments)?segments:[segments];for(let segment2 of segmentArray){let netNum=this.getSegmentNet(segment2);netNum&&(netToPads.has(netNum)||netToPads.set(netNum,[]))}let arcArray=getTopLevelCopperArcs(this.ctx.kicadPcb);for(let arc2 of arcArray){let netNum=this.getSegmentNet(arc2);netNum&&(netToPads.has(netNum)||netToPads.set(netNum,[]))}}getSegmentNet(segment2){let net=segment2?.net;return net?typeof net=="number"?net:typeof net=="object"?net._id??net.number??net.ordinal??null:null:null}processFootprintPads(footprint,netToPads){let footprintUuid=footprint.uuid?.value||footprint.tstamp?.value;if(!footprintUuid)return;let componentId=this.ctx.footprintUuidToComponentId?.get(footprintUuid);if(!componentId)return;let pads=footprint.fpPads||[],padArray=Array.isArray(pads)?pads:[pads];for(let pad2 of padArray){let padNumber=pad2.number?.toString();if(!padNumber)continue;let netNum=this.getPadNet(pad2);if(netNum==null||netNum===0)continue;let sourcePortId=this.getOrCreateSourcePort(componentId,padNumber,footprint);netToPads.has(netNum)||netToPads.set(netNum,[]),netToPads.get(netNum).push({componentId,padNumber,sourcePortId})}}getPadNet(pad2){let net=pad2._sxNet||pad2.net;return net?typeof net=="number"?net:typeof net=="object"?net._id??net.number??net.ordinal??null:null:null}getOrCreateSourcePort(componentId,padNumber,footprint){let sourcePortId=`${componentId}_port_${padNumber}`;if(!this.ctx.db.source_port.list().find(sp3=>sp3.source_port_id===sourcePortId)){let footprintUuid=footprint.uuid?.value||footprint.tstamp?.value,sourceComponentId=footprintUuid&&this.ctx.footprintUuidToSourceComponentId?this.ctx.footprintUuidToSourceComponentId.get(footprintUuid):void 0;this.ctx.db.source_port.insert({source_port_id:sourcePortId,source_component_id:sourceComponentId||componentId,name:this.getSourcePortName(padNumber),pin_number:this.getSourcePortPinNumber(padNumber)})}return sourcePortId}getSourcePortName(padNumber){return/^\d+$/.test(padNumber)?`pin${Number(padNumber)}`:padNumber}getSourcePortPinNumber(padNumber){return/^\d+$/.test(padNumber)?Number(padNumber):padNumber}createSourceNet(netNum){let netName=this.ctx.netNumToName?.get(netNum)||`Net-${netNum}`,sourceNet=this.ctx.db.source_net.insert({name:netName,member_source_group_ids:[]});this.ctx.netNumToSourceNetId?.set(netNum,sourceNet.source_net_id),this.ctx.stats&&(this.ctx.stats.traces=(this.ctx.stats.traces||0)+1)}},CollectTracesStage=class extends ConverterStage{constructor(){super(...arguments);__publicField(this,"PORT_MATCH_TOLERANCE",.001);__publicField(this,"POINT_KEY_PRECISION",1e6)}step(){if(!this.ctx.kicadPcb||!this.ctx.k2cMatPcb||!this.ctx.netNumToName||!this.ctx.netNumToSourceNetId)return this.finished=!0,!1;let segments=this.ctx.kicadPcb.segments||[],segmentArray=Array.isArray(segments)?segments:[segments],arcArray=getTopLevelCopperArcs(this.ctx.kicadPcb),primitives=[];for(let segment2 of segmentArray){let primitive=this.getTracePrimitiveFromSegment(segment2);primitive&&primitives.push(primitive)}for(let arc2 of arcArray){let primitive=this.getTracePrimitiveFromArc(arc2);primitive&&primitives.push(primitive)}let vias=this.ctx.kicadPcb.vias||[],viaArray=Array.isArray(vias)?vias:[vias];for(let via of viaArray){let primitive=this.getTracePrimitiveFromVia(via);primitive&&primitives.push(primitive)}return this.annotatePrimitivesWithConnectedSourcePorts(primitives),this.createTracesFromPrimitives(primitives),this.finished=!0,!1}getTracePrimitiveFromSegment(segment2){if(!this.ctx.k2cMatPcb)return;let start=segment2.start||{x:0,y:0},end=segment2.end||{x:0,y:0},width=segment2.width||.2,layer=segment2.layer,layerStr=getLayerNames(layer).join(" "),mappedLayer=mapKicadLayerToLayerRef(layerStr),netNum=this.getSegmentNet(segment2),startPoint={x:start.x,y:start.y},endPoint={x:end.x,y:end.y};if(!this.pointsMatch(startPoint,endPoint))return{primitiveType:"wire",start:startPoint,end:endPoint,points:[startPoint,endPoint],width,layer:mappedLayer,netNum}}getTracePrimitiveFromArc(arc2){if(!this.ctx.k2cMatPcb)return;let{start,mid,end}=getArcStartMidEnd(arc2),width=arc2.width??arc2._sxWidth?.value??.2,layerStr=getLayerNames(arc2.layer).join(" "),mappedLayer=mapKicadLayerToLayerRef(layerStr),netNum=this.getSegmentNet(arc2),points=approximateArcPoints(start,mid,end,{segmentLength:Math.max(width,.1),minSegments:8}),startPoint=points[0],endPoint=points[points.length-1];if(!(!startPoint||!endPoint||this.pointsMatch(startPoint,endPoint)))return{primitiveType:"wire",start:startPoint,end:endPoint,points,width,layer:mappedLayer,netNum}}getTracePrimitiveFromVia(via){let netNum=this.getSegmentNet(via);if(netNum===null)return;let at3=via.at||{x:0,y:0},point7={x:at3.x,y:at3.y},viaLayers=via.layers?getCopperSpanLayerRefsFromLayers(via.layers,this.ctx.kicadPcb):[],layers=viaLayers.length>0?viaLayers:getPcbCopperLayerRefs(this.ctx.kicadPcb),fromLayer=layers[0],toLayer=layers[layers.length-1];if(!(!fromLayer||!toLayer||fromLayer===toLayer))return{primitiveType:"via",start:point7,end:point7,points:[point7],fromLayer,toLayer,outerDiameter:via.size||.8,holeDiameter:via.drill||.4,netNum}}createTracesFromPrimitives(primitives){let groupedPrimitives=new Map;for(let primitive of primitives){let key=this.getPrimitiveGroupKey(primitive),group=groupedPrimitives.get(key)??[];group.push(primitive),groupedPrimitives.set(key,group)}for(let group of groupedPrimitives.values())this.createTracesFromPrimitiveGroup(group)}createTracesFromPrimitiveGroup(primitives){let graph=this.createTraceGraph(primitives),visitedEdgeIds=new Set,isTerminal=nodeKey=>this.isTerminalNode(nodeKey,graph);for(let nodeKey of graph.adjacency.keys())if(isTerminal(nodeKey))for(let edgeId of graph.adjacency.get(nodeKey)??[]){if(visitedEdgeIds.has(edgeId))continue;let path=this.walkTracePath(nodeKey,edgeId,graph,visitedEdgeIds);this.insertTracePath(path)}for(let edge of graph.edges){if(visitedEdgeIds.has(edge.id))continue;let path=this.walkTracePath(edge.startKey,edge.id,graph,visitedEdgeIds);this.insertTracePath(path)}}createTraceGraph(primitives){let edges=[],adjacency=new Map;for(let primitive of primitives){let id2=edges.length,startLayer=primitive.primitiveType==="via"?primitive.fromLayer:primitive.layer,endLayer=primitive.primitiveType==="via"?primitive.toLayer:primitive.layer,startKey=this.getTraceGraphNodeKey(primitive.start,startLayer),endKey=this.getTraceGraphNodeKey(primitive.end,endLayer),edge={...primitive,id:id2,startKey,endKey};edges.push(edge);for(let nodeKey of[startKey,endKey]){let edgeIds=adjacency.get(nodeKey)??[];edgeIds.push(id2),adjacency.set(nodeKey,edgeIds)}}return{edges,adjacency}}walkTracePath(startNodeKey,firstEdgeId,graph,visitedEdgeIds){let path=[],currentNodeKey=startNodeKey,edgeId=firstEdgeId;for(;!visitedEdgeIds.has(edgeId);){let edge=graph.edges[edgeId];if(!edge)break;let reversed=edge.endKey===currentNodeKey;if(path.push({edge,reversed}),visitedEdgeIds.add(edgeId),currentNodeKey=reversed?edge.startKey:edge.endKey,this.isTerminalNode(currentNodeKey,graph))break;let nextEdgeId=(graph.adjacency.get(currentNodeKey)??[]).find(candidateEdgeId=>candidateEdgeId!==edgeId&&!visitedEdgeIds.has(candidateEdgeId));if(nextEdgeId===void 0)break;edgeId=nextEdgeId}return path}insertTracePath(path){if(!this.ctx.k2cMatPcb||!this.ctx.netNumToSourceNetId||path.length===0)return;let routePoints=this.getPathRoutePoints(path);if(routePoints.length<2)return;let firstNode=this.getTraceGraphNodeFromKey(this.getOrientedTraceEdgeStartKey(path[0])),lastNode=this.getTraceGraphNodeFromKey(this.getOrientedTraceEdgeEndKey(path[path.length-1])),netNum=path[0].edge.netNum,sourceNetId=netNum!==null?this.ctx.netNumToSourceNetId.get(netNum)??void 0:void 0,startPoint=applyToPoint(this.ctx.k2cMatPcb,firstNode.point),lastPoint=applyToPoint(this.ctx.k2cMatPcb,lastNode.point),startPcbPortId=this.findPortAtPosition(startPoint,firstNode.layer),endPcbPortId=this.findPortAtPosition(lastPoint,lastNode.layer),connectedSourcePortIds=this.getConnectedSourcePortIds([startPcbPortId,endPcbPortId]),traceConnectedSourcePortIds=this.getTraceConnectedSourcePortIds(path),inferredSourcePortIds=this.getSourcePortIdsForTrace({netNum,connectedSourcePortIds,traceConnectedSourcePortIds}),sourceTraceId=sourceNetId?this.createSourceTraceForPath({sourceNetId,connectedSourcePortIds:inferredSourcePortIds,netNum}):void 0,firstWireIndex=routePoints.findIndex(point7=>point7.routeType==="wire"),lastWireIndex=routePoints.findLastIndex(point7=>point7.routeType==="wire");if(firstWireIndex===-1)return;let route=routePoints.map((point7,index)=>point7.routeType==="via"?{route_type:"via",x:point7.x,y:point7.y,from_layer:point7.fromLayer,to_layer:point7.toLayer,...point7.outerDiameter?{outer_diameter:point7.outerDiameter}:{},...point7.holeDiameter?{hole_diameter:point7.holeDiameter}:{}}:{route_type:"wire",x:point7.x,y:point7.y,width:point7.width,layer:point7.layer,...index===firstWireIndex&&startPcbPortId?{start_pcb_port_id:startPcbPortId}:{},...index===lastWireIndex&&endPcbPortId?{end_pcb_port_id:endPcbPortId}:{}});this.ctx.db.pcb_trace.insert({route,source_trace_id:sourceTraceId,pcb_port_id:void 0}),this.ctx.stats&&(this.ctx.stats.traces=(this.ctx.stats.traces||0)+1)}getPathRoutePoints(path){let routePoints=[],lastRawPoint,lastWireLayer;for(let{edge,reversed}of path){if(edge.primitiveType==="via"){let point7=edge.start,transformedPoint=applyToPoint(this.ctx.k2cMatPcb,point7);routePoints.push({routeType:"via",x:transformedPoint.x,y:transformedPoint.y,fromLayer:reversed?edge.toLayer:edge.fromLayer,toLayer:reversed?edge.fromLayer:edge.toLayer,outerDiameter:edge.outerDiameter,holeDiameter:edge.holeDiameter});continue}let edgePoints=reversed?[...edge.points].reverse():edge.points,layer=edge.layer,width=edge.width;for(let point7 of edgePoints){if(lastRawPoint&&lastWireLayer===layer&&this.pointsMatch(lastRawPoint,point7))continue;let transformedPoint=applyToPoint(this.ctx.k2cMatPcb,point7);routePoints.push({routeType:"wire",x:transformedPoint.x,y:transformedPoint.y,width,layer}),lastRawPoint=point7,lastWireLayer=layer}}return routePoints}isTerminalNode(nodeKey,graph){if((graph.adjacency.get(nodeKey)??[]).length!==2)return!0;let{point:point7,layer}=this.getTraceGraphNodeFromKey(nodeKey),transformedPoint=applyToPoint(this.ctx.k2cMatPcb,point7);return!!this.findPortAtPosition(transformedPoint,layer)}getPrimitiveGroupKey(primitive){return`${primitive.netNum??"no-net"}`}getPointKey(point7){let x4=Math.round(point7.x*this.POINT_KEY_PRECISION),y4=Math.round(point7.y*this.POINT_KEY_PRECISION);return`${x4},${y4}`}getPointFromKey(pointKey4){let[x4,y4]=pointKey4.split(",").map(Number);return{x:(x4??0)/this.POINT_KEY_PRECISION,y:(y4??0)/this.POINT_KEY_PRECISION}}getTraceGraphNodeKey(point7,layer){return`${layer}:${this.getPointKey(point7)}`}getTraceGraphNodeFromKey(nodeKey){let[layer,...pointKeyParts]=nodeKey.split(":");return{layer,point:this.getPointFromKey(pointKeyParts.join(":"))}}getOrientedTraceEdgeStartKey({edge,reversed}){return reversed?edge.endKey:edge.startKey}getOrientedTraceEdgeEndKey({edge,reversed}){return reversed?edge.startKey:edge.endKey}pointsMatch(a3,b3){return this.getPointKey(a3)===this.getPointKey(b3)}getPcbTraceNodeKey({netNum,layer,point:point7}){return`${netNum??"no-net"}:${layer}:${this.getPointKey(point7)}`}annotatePrimitivesWithConnectedSourcePorts(primitives){if(!this.ctx.k2cMatPcb||primitives.length===0)return;let nodes=new Map,adjacency=new Map,ensureNode=(netNum,layer,point7)=>{let key=this.getPcbTraceNodeKey({netNum,layer,point:point7});return nodes.has(key)||nodes.set(key,{key,point:point7,layer,netNum}),adjacency.has(key)||adjacency.set(key,new Set),key},connectNodes=(a3,b3)=>{adjacency.get(a3)?.add(b3),adjacency.get(b3)?.add(a3)};for(let primitive of primitives){if(primitive.primitiveType!=="wire")continue;let startKey=ensureNode(primitive.netNum,primitive.layer,primitive.start),endKey=ensureNode(primitive.netNum,primitive.layer,primitive.end);connectNodes(startKey,endKey)}let vias=this.ctx.kicadPcb?.vias||[],viaArray=Array.isArray(vias)?vias:[vias];for(let via of viaArray){let netNum=this.getSegmentNet(via);if(netNum===null)continue;let at3=via.at||{x:0,y:0},point7={x:at3.x,y:at3.y},viaLayers=via.layers?getCopperSpanLayerRefsFromLayers(via.layers,this.ctx.kicadPcb):[],viaNodeKeys=(viaLayers.length>0?viaLayers:getPcbCopperLayerRefs(this.ctx.kicadPcb)).map(layer=>ensureNode(netNum,layer,point7));for(let i3=1;i3<viaNodeKeys.length;i3++)connectNodes(viaNodeKeys[0],viaNodeKeys[i3])}let connectedSourcePortIdsByNodeKey=new Map,visited=new Set;for(let startNodeKey of nodes.keys()){if(visited.has(startNodeKey))continue;let traceNodeKeys=[],traceConnectedSourcePortIds=new Set,stack=[startNodeKey];for(visited.add(startNodeKey);stack.length>0;){let nodeKey=stack.pop(),node=nodes.get(nodeKey);if(!node)continue;traceNodeKeys.push(nodeKey);let transformedPoint=applyToPoint(this.ctx.k2cMatPcb,node.point),pcbPortId=this.findPortAtPosition(transformedPoint,node.layer),sourcePortId=this.getConnectedSourcePortIds([pcbPortId])[0];sourcePortId&&traceConnectedSourcePortIds.add(sourcePortId);for(let neighborNodeKey of adjacency.get(nodeKey)??[])visited.has(neighborNodeKey)||(visited.add(neighborNodeKey),stack.push(neighborNodeKey))}let sourcePortIds=[...traceConnectedSourcePortIds];for(let nodeKey of traceNodeKeys)connectedSourcePortIdsByNodeKey.set(nodeKey,sourcePortIds)}for(let primitive of primitives){if(primitive.primitiveType!=="wire")continue;let nodeKey=this.getPcbTraceNodeKey({netNum:primitive.netNum,layer:primitive.layer,point:primitive.start});primitive.connectedSourcePortIds=connectedSourcePortIdsByNodeKey.get(nodeKey)??[]}}getSegmentNet(segment2){let net=segment2?.net;return net?typeof net=="number"?net:typeof net=="object"?net._id??net.number??net.ordinal??null:null:null}findPortAtPosition(point7,layer){let ports=this.ctx.db.pcb_port.list();for(let port of ports){let layers=port.layers;if(!(layers?.length&&!layers.includes(layer))&&Math.abs((port.x??0)-point7.x)<=this.PORT_MATCH_TOLERANCE&&Math.abs((port.y??0)-point7.y)<=this.PORT_MATCH_TOLERANCE)return port.pcb_port_id}}getConnectedSourcePortIds(pcbPortIds){let connectedSourcePortIds=[];for(let pcbPortId of pcbPortIds){if(!pcbPortId)continue;let sourcePortId=this.ctx.db.pcb_port.get(pcbPortId)?.source_port_id;!sourcePortId||connectedSourcePortIds.includes(sourcePortId)||connectedSourcePortIds.push(sourcePortId)}return connectedSourcePortIds}getSourcePortIdsForTrace({netNum,connectedSourcePortIds,traceConnectedSourcePortIds}){if(netNum===null||connectedSourcePortIds.length>=2)return connectedSourcePortIds;let inferredSourcePortIds=[...connectedSourcePortIds];for(let sourcePortId of traceConnectedSourcePortIds)if(inferredSourcePortIds.includes(sourcePortId)||inferredSourcePortIds.push(sourcePortId),inferredSourcePortIds.length>=2)return inferredSourcePortIds.slice(0,2);let netSourcePortIds=this.ctx.netNumToSourcePortIds?.get(netNum)??[];for(let sourcePortId of netSourcePortIds)if(inferredSourcePortIds.includes(sourcePortId)||inferredSourcePortIds.push(sourcePortId),inferredSourcePortIds.length>=2)return inferredSourcePortIds.slice(0,2);return inferredSourcePortIds}getTraceConnectedSourcePortIds(path){let sourcePortIds=[];for(let{edge}of path)for(let sourcePortId of edge.connectedSourcePortIds??[])sourcePortIds.includes(sourcePortId)||sourcePortIds.push(sourcePortId);return sourcePortIds}createSourceTraceForPath({sourceNetId,connectedSourcePortIds,netNum}){let netName=netNum!==null?this.ctx.netNumToName?.get(netNum)??`Net-${netNum}`:void 0;return this.ctx.db.source_trace.insert({connected_source_port_ids:connectedSourcePortIds,connected_source_net_ids:[sourceNetId],display_name:netName}).source_trace_id}},CollectViasStage=class extends ConverterStage{constructor(){super(...arguments);__publicField(this,"POINT_KEY_PRECISION",1e6)}step(){if(!this.ctx.kicadPcb||!this.ctx.k2cMatPcb||!this.ctx.netNumToName)return this.finished=!0,!1;let vias=this.ctx.kicadPcb.vias||[],viaArray=Array.isArray(vias)?vias:[vias];for(let via of viaArray)this.processVia(via);return this.finished=!0,!1}processVia(via){if(!this.ctx.k2cMatPcb||!this.ctx.netNumToName)return;let at3=via.at||{x:0,y:0},pos=applyToPoint(this.ctx.k2cMatPcb,{x:at3.x,y:at3.y}),size3=via.size||.8,drill=via.drill||.4,mappedLayers=via.layers?getCopperSpanLayerRefsFromLayers(via.layers,this.ctx.kicadPcb):[],layers=mappedLayers.length>0?mappedLayers:getPcbCopperLayerRefs(this.ctx.kicadPcb);if(this.hasMatchingTraceRouteVia(pos,layers)){this.ctx.stats&&(this.ctx.stats.vias=(this.ctx.stats.vias||0)+1);return}this.ctx.db.pcb_via.insert({x:pos.x,y:pos.y,outer_diameter:size3,hole_diameter:drill,layers}),this.ctx.stats&&(this.ctx.stats.vias=(this.ctx.stats.vias||0)+1)}hasMatchingTraceRouteVia(point7,layers){let pointKey4=this.getPointKey(point7),layerSet=new Set(layers);return this.ctx.db.pcb_trace.list().some(trace=>(trace.route??[]).some(routePoint=>routePoint.route_type==="via"&&this.getPointKey(routePoint)===pointKey4&&layerSet.has(routePoint.from_layer)&&layerSet.has(routePoint.to_layer)))}getPointKey(point7){let x4=Math.round(point7.x*this.POINT_KEY_PRECISION),y4=Math.round(point7.y*this.POINT_KEY_PRECISION);return`${x4},${y4}`}},CollectZonesStage=class extends ConverterStage{step(){if(!this.ctx.kicadPcb||!this.ctx.k2cMatPcb||!this.ctx.netNumToName)return this.finished=!0,!1;let zones=this.ctx.kicadPcb.zones||[],zoneArray=Array.isArray(zones)?zones:[zones];for(let zone of zoneArray)this.isZoneFilled(zone)&&this.createCopperPourFromZone(zone);return this.finished=!0,!1}isZoneFilled(zone){if(!zone._rawChildren||!Array.isArray(zone._rawChildren))return!1;let fillEntry=zone._rawChildren.find(child=>Array.isArray(child)&&child[0]==="fill");return fillEntry&&fillEntry[1]==="yes"?!0:zone._rawChildren.some(child=>Array.isArray(child)&&child[0]==="filled_polygon")}createCopperPourFromZone(zone){if(!this.ctx.k2cMatPcb||!this.ctx.netNumToName||!zone._rawChildren||!Array.isArray(zone._rawChildren))return;let zoneData=this.parseZoneData(zone._rawChildren),filledPolygons=this.extractFilledPolygons(zone._rawChildren);if(filledPolygons.length===0){let mainPolygon=this.extractMainPolygon(zone._rawChildren);mainPolygon.length>0&&filledPolygons.push(mainPolygon)}if(filledPolygons.length===0){this.ctx.warnings&&this.ctx.warnings.push(`Zone on layer ${zoneData.layer||"unknown"} has no valid polygon points`);return}let layer=mapKicadLayerToLayerRef(zoneData.layer),netNum=zoneData.net||0,netName=this.ctx.netNumToName.get(netNum)||zoneData.netName||"";for(let polygonPoints of filledPolygons){let transformedPoints=polygonPoints.map(point7=>applyToPoint(this.ctx.k2cMatPcb,{x:point7.x,y:point7.y}));this.ctx.db.pcb_copper_pour.insert({layer,net_name:netName,points:transformedPoints,shape:"polygon"}),this.ctx.stats&&(this.ctx.stats.copper_pours=(this.ctx.stats.copper_pours||0)+1)}}parseZoneData(children){let data={};for(let child of children)if(Array.isArray(child))switch(child[0]){case"net":data.net=child[1];break;case"net_name":data.netName=child[1];break;case"layer":data.layer=child[1];break}return data}extractMainPolygon(children){let polygonEntry=children.find(child=>Array.isArray(child)&&child[0]==="polygon");return polygonEntry?this.extractPointsFromPolygonEntry(polygonEntry):[]}extractFilledPolygons(children){let filledPolygonEntries=children.filter(child=>Array.isArray(child)&&child[0]==="filled_polygon"),polygons=[];for(let entry of filledPolygonEntries){let points=this.extractPointsFromPolygonEntry(entry);points.length>0&&polygons.push(points)}return polygons}extractPointsFromPolygonEntry(polygonEntry){let points=[],ptsEntry=polygonEntry.find(child=>Array.isArray(child)&&child[0]==="pts");if(!ptsEntry)return[];for(let i3=1;i3<ptsEntry.length;i3++){let item=ptsEntry[i3];if(Array.isArray(item)&&item[0]==="xy"&&item.length>=3){let x4=item[1],y4=item[2];typeof x4=="number"&&typeof y4=="number"&&points.push({x:x4,y:y4})}}return points}},InitializePcbContextStage=class extends ConverterStage{step(){if(!this.ctx.kicadPcb)return this.finished=!0,!1;let center2=this.calculateBoardCenter();return this.ctx.k2cMatPcb=compose(scale(1,-1),translate(-center2.x,-center2.y)),this.ctx.netNumToName=new Map,this.ctx.netNumToSourceNetId=new Map,this.ctx.netNumToSourcePortIds=new Map,this.ctx.footprintUuidToComponentId=new Map,this.ctx.footprintUuidToSourceComponentId=new Map,this.finished=!0,!1}calculateBoardCenter(){if(!this.ctx.kicadPcb)return{x:0,y:0};let lines=this.ctx.kicadPcb.graphicLines||[],lineArray=Array.isArray(lines)?lines:[lines],arcArray=getGraphicArcs(this.ctx.kicadPcb),circleArray=getGraphicCircles(this.ctx.kicadPcb),curveArray=getGraphicCurves(this.ctx.kicadPcb),xs3=[],ys3=[];for(let line2 of lineArray){if(!getGraphicLayerNames(line2).join(" ").includes("Edge.Cuts"))continue;let{start,end}=getLineStartEnd(line2);xs3.push(start.x,end.x),ys3.push(start.y,end.y)}for(let arc2 of arcArray){if(!getGraphicLayerNames(arc2).join(" ").includes("Edge.Cuts"))continue;let{start,mid,end}=getArcStartMidEnd(arc2);for(let point7 of approximateArcPoints(start,mid,end,{segmentLength:.25,minSegments:16}))xs3.push(point7.x),ys3.push(point7.y)}for(let circle2 of circleArray){if(!getGraphicLayerNames(circle2).join(" ").includes("Edge.Cuts"))continue;let{center:center2,end}=getCircleCenterEnd(circle2);for(let point7 of approximateCirclePoints(center2,end,{segmentLength:.25,minSegments:16}))xs3.push(point7.x),ys3.push(point7.y)}for(let curve of curveArray){if(!getGraphicLayerNames(curve).join(" ").includes("Edge.Cuts"))continue;let points=getCurvePoints(curve);if(points)for(let point7 of approximateCubicBezierPoints(points.start,points.control1,points.control2,points.end,{segmentLength:.25,minSegments:16}))xs3.push(point7.x),ys3.push(point7.y)}if(xs3.length===0||ys3.length===0)return{x:0,y:0};let minX=Math.min(...xs3),maxX=Math.max(...xs3),minY=Math.min(...ys3),maxY=Math.max(...ys3);return{x:(minX+maxX)/2,y:(minY+maxY)/2}}};function rotationToDirection(rotation5){let normalized=(rotation5%360+360)%360;return normalized>=315||normalized<45?"up":normalized>=45&&normalized<135?"right":normalized>=135&&normalized<225?"down":"left"}function inferSymbolName({libId,reference,rotation:rotation5}){let lower=libId.toLowerCase(),direction2=rotationToDirection(rotation5);if(lower.includes(":r_")||lower.includes(":r")&&reference.startsWith("R"))return`boxresistor_${direction2}`;if(lower.includes(":c_")||lower.includes(":c")&&reference.startsWith("C"))return lower.includes("polarized")||lower.includes("_pol")?`capacitor_${direction2}`:`capacitor_${direction2}`;if(lower.includes(":l_")||lower.includes(":l")&&reference.startsWith("L"))return`inductor_${direction2}`;if(lower.includes(":d_")||lower.includes("diode")||reference.startsWith("D"))return lower.includes("led")?`led_${direction2}`:lower.includes("schottky")?`schottky_diode_${direction2}`:lower.includes("zener")?`zener_diode_${direction2}`:`diode_${direction2}`;if(lower.includes(":q_")||reference.startsWith("Q"))return lower.includes("npn")?`npn_bipolar_transistor_${direction2}`:lower.includes("pnp")?`pnp_bipolar_transistor_${direction2}`:lower.includes("_n_")||lower.includes("nmos")?`n_channel_mosfet_transistor_${direction2}`:lower.includes("_p_")||lower.includes("pmos")?`p_channel_mosfet_transistor_${direction2}`:`npn_bipolar_transistor_${direction2}`;lower.includes("gnd")||lower.includes("ground")||lower.includes("vcc")||lower.includes("vdd")||lower.includes("power")}var CollectLibrarySymbolsStage=class extends ConverterStage{constructor(){super(...arguments);__publicField(this,"processedSymbols",new Set)}step(){if(!this.ctx.kicadSch||!this.ctx.k2cMatSch)return this.finished=!0,!1;let symbols=this.ctx.kicadSch.symbols||[];for(let symbol of symbols){let uuid=symbol.uuid;!uuid||this.processedSymbols.has(uuid)||(this.processSymbol(symbol),this.processedSymbols.add(uuid))}return this.finished=!0,!1}processSymbol(symbol){if(!this.ctx.k2cMatSch)return;let reference=this.getProperty(symbol,"Reference")||"U?",value=this.getProperty(symbol,"Value")||"",libId=symbol.libraryId||"",at3=symbol.at,kicadPos={x:at3?.x??0,y:at3?.y??0},cjPos=applyToPoint(this.ctx.k2cMatSch,kicadPos),rotation5=at3?.angle??0,ftype=this.inferFtype(libId,reference),sourceComponentId=`${libId}_source`;this.ctx.db.source_component.list().find(sc2=>sc2.source_component_id===sourceComponentId)||this.ctx.db.source_component.insert({name:libId||reference,ftype,manufacturer_part_number:value||void 0});let uuid=symbol.uuid;if(!uuid)return;let symbolName=inferSymbolName({libId,reference,rotation:rotation5}),componentId=this.ctx.db.schematic_component.insert({source_component_id:sourceComponentId,center:{x:cjPos.x,y:cjPos.y},size:this.estimateSize(symbol),...symbolName?{symbol_name:symbolName}:{}}).schematic_component_id;this.ctx.symbolUuidToComponentId?.set(uuid,componentId),this.createPorts(symbol,componentId),this.ctx.stats&&(this.ctx.stats.components=(this.ctx.stats.components||0)+1)}getProperty(symbol,propName){return(symbol.properties||[]).find(p4=>p4.key===propName)?.value}inferFtype(libId,reference){let lower=libId.toLowerCase();return lower.includes(":r_")||reference.startsWith("R")?"simple_resistor":lower.includes(":c_")||reference.startsWith("C")?"simple_capacitor":lower.includes(":l_")||reference.startsWith("L")?"simple_inductor":lower.includes(":d_")||reference.startsWith("D")?"simple_diode":lower.includes(":led")||reference.startsWith("LED")?"simple_led":lower.includes(":q_")||reference.startsWith("Q")?"simple_transistor":"simple_chip"}estimateSize(symbol){return{width:1,height:1}}createPorts(symbol,componentId){let libId=symbol.libraryId,libSymbol=this.ctx.kicadSch?.libSymbols?.symbols?.find(ls3=>ls3.libraryId===libId);if(!libSymbol)return;let allPins=[];if(libSymbol.pins&&Array.isArray(libSymbol.pins)&&libSymbol.pins.length>0?allPins.push(...libSymbol.pins):libSymbol.pins&&!Array.isArray(libSymbol.pins)&&allPins.push(libSymbol.pins),libSymbol.subSymbols&&Array.isArray(libSymbol.subSymbols))for(let subSymbol of libSymbol.subSymbols)subSymbol.pins&&Array.isArray(subSymbol.pins)&&subSymbol.pins.length>0?allPins.push(...subSymbol.pins):subSymbol.pins&&!Array.isArray(subSymbol.pins)&&allPins.push(subSymbol.pins);if(allPins.length===0)return;let componentRotation=symbol.at?.angle??0;for(let pin of allPins){let pinAt=pin._sxAt;if(!pinAt)continue;let rotRad=componentRotation*Math.PI/180,cosR=Math.cos(rotRad),sinR=Math.sin(rotRad),rotatedPinPos={x:pinAt.x*cosR-pinAt.y*sinR,y:pinAt.x*sinR+pinAt.y*cosR},scaleFactor=Math.abs(this.ctx.k2cMatSch?.a||1/15),relativePos={x:rotatedPinPos.x*scaleFactor,y:-rotatedPinPos.y*scaleFactor};this.ctx.db.schematic_port.insert({schematic_component_id:componentId,center:relativePos,facing_direction:this.inferPinDirection(pin,componentRotation),pin_number:pin._sxNumber?.value??pin.pinNumber??void 0})}}inferPinDirection(pin,componentRotation){let totalAngle=(pin.at?.angle??0)+componentRotation;return rotationToDirection(totalAngle)}},CollectSchematicTracesStage=class extends ConverterStage{step(){if(!this.ctx.kicadSch||!this.ctx.k2cMatSch)return this.finished=!0,!1;let wires=this.ctx.kicadSch.wires||[],wireArray=Array.isArray(wires)?wires:[wires];for(let wire of wireArray)this.processWire(wire);let junctions=this.ctx.kicadSch.junctions||[],junctionArray=Array.isArray(junctions)?junctions:[junctions];for(let junction of junctionArray)this.processJunction(junction);return this.finished=!0,!1}processWire(wire){if(!this.ctx.k2cMatSch||!wire.pts)return;let pts=Array.isArray(wire.pts.xy)?wire.pts.xy:[wire.pts.xy];if(pts.length<2)return;let edges=[];for(let i3=0;i3<pts.length-1;i3++){let from=applyToPoint(this.ctx.k2cMatSch,{x:pts[i3].x,y:pts[i3].y}),to3=applyToPoint(this.ctx.k2cMatSch,{x:pts[i3+1].x,y:pts[i3+1].y});edges.push({from,to:to3})}this.ctx.db.schematic_trace.insert({edges}),this.ctx.stats&&(this.ctx.stats.traces=(this.ctx.stats.traces||0)+1)}processJunction(junction){if(!this.ctx.k2cMatSch||!junction.at)return;let pos=applyToPoint(this.ctx.k2cMatSch,{x:junction.at.x,y:junction.at.y});this.ctx.db.schematic_trace.insert({edges:[],junctions:[pos]})}},InitializeSchematicContextStage=class extends ConverterStage{step(){if(!this.ctx.kicadSch)return this.finished=!0,!1;let KICAD_CENTER_X=105,KICAD_CENTER_Y=148.5,kicadCenterX=KICAD_CENTER_X,kicadCenterY=KICAD_CENTER_Y,cjCenterX=0,cjCenterY=0;return this.ctx.k2cMatSch=compose(translate(cjCenterX,cjCenterY),scale(1/15,-1/15),translate(-kicadCenterX,-kicadCenterY)),this.ctx.symbolUuidToComponentId=new Map,this.ctx.warnings=this.ctx.warnings||[],this.ctx.stats=this.ctx.stats||{},this.finished=!0,!1}},KicadToCircuitJsonConverter=class{constructor(){__publicField(this,"fsMap",{});__publicField(this,"ctx");__publicField(this,"currentStageIndex",0);__publicField(this,"pipeline")}get currentStage(){return this.pipeline?.[this.currentStageIndex]}addFile(filePath,content){this.fsMap[filePath]=content}_findFileWithExtension(extension){let filesWithExtension=Object.keys(this.fsMap).filter(key=>key.endsWith(extension));if(filesWithExtension.length>1)throw new Error(`Expected 0 or 1 file with extension ${extension}, got ${filesWithExtension.length}. Files: ${filesWithExtension.join(", ")}`);return filesWithExtension[0]??null}initializePipeline(){let pcbFile=this._findFileWithExtension(".kicad_pcb"),schFile=this._findFileWithExtension(".kicad_sch");this.ctx={db:cju_default([]),kicadPcb:pcbFile?parseKicadPcb(this.fsMap[pcbFile]):void 0,kicadSch:schFile?parseKicadSch(this.fsMap[schFile]):void 0,warnings:[],stats:{}},this.pipeline=[],this.ctx.kicadSch&&this.pipeline.push(new InitializeSchematicContextStage(this.ctx),new CollectLibrarySymbolsStage(this.ctx),new CollectSchematicTracesStage(this.ctx)),this.ctx.kicadPcb&&this.pipeline.push(new InitializePcbContextStage(this.ctx),new CollectNetsStage(this.ctx),new CollectFootprintsStage(this.ctx),new CollectSourceTracesStage(this.ctx),new CollectTracesStage(this.ctx),new CollectViasStage(this.ctx),new CollectZonesStage(this.ctx),new CollectGraphicsStage(this.ctx))}step(){return this.pipeline||this.initializePipeline(),this.currentStage?((!this.currentStage.step()||this.currentStage.finished)&&this.currentStageIndex++,this.currentStageIndex<(this.pipeline?.length||0)):!1}runUntilFinished(){this.pipeline||this.initializePipeline();for(let stage of this.pipeline||[])stage.runUntilFinished()}getOutput(){this.ctx||(this.initializePipeline(),this.runUntilFinished());let elements=[],tableNames=["source_component","source_port","source_net","source_trace","schematic_component","schematic_port","schematic_trace","schematic_net_label","pcb_component","pcb_port","pcb_smtpad","pcb_plated_hole","pcb_hole","pcb_trace","pcb_via","pcb_copper_pour","pcb_board","pcb_copper_text","pcb_silkscreen_text","pcb_silkscreen_path","pcb_fabrication_note_text","pcb_fabrication_note_path","pcb_fabrication_note_rect","pcb_courtyard_rect","pcb_courtyard_outline","pcb_courtyard_circle"];for(let tableName of tableNames){let table=this.ctx.db[tableName];if(table&&typeof table.list=="function"){let items=table.list();items&&Array.isArray(items)&&elements.push(...items)}}return elements}getOutputString(){return JSON.stringify(this.getOutput(),null,2)}getWarnings(){return this.ctx?.warnings||[]}getStats(){return this.ctx?.stats||{}}};var React=__toESM(require_react(),1),KICAD_FOOTPRINT_CACHE_URL="https://kicad-mod-cache.tscircuit.com",ngspiceEngineCache=null,toJlcpcbSupplierPartNumber=partNumber=>/^\d+$/.test(partNumber)?`C${partNumber}`:/^c\d+$/i.test(partNumber)?`C${partNumber.slice(1)}`:partNumber,loadKicadPcbStaticFile=async fileContent=>{let kicadPcbContent=typeof fileContent=="string"?fileContent:new TextDecoder().decode(fileContent);if(kicadPcbContent==="__STATIC_ASSET__"||kicadPcbContent.startsWith("blob:"))throw new Error(".kicad_pcb imports require local file contents. Static asset URLs are not supported.");let converter=new KicadToCircuitJsonConverter;converter.addFile("imported.kicad_pcb",kicadPcbContent),converter.runUntilFinished();let circuitJson=converter.getOutput(),boardContentCircuitJson=circuitJson.filter(elm=>elm.type!=="pcb_board");return{__esModule:!0,default:circuitJson,Board:props=>React.createElement("board",{...props,circuitJson}),boardContentCircuitJson,circuitJson}},getPlatformConfig=(overrides={},options={})=>{let partsEngine2=overrides.partsEngine??jlcPartsEngine;return!overrides.partsEngine&&options.easyEdaProxyConfig&&(partsEngine2=new JlcPcbPartsEngine({platformFetch:overrides.platformFetch,easyEdaProxyConfig:options.easyEdaProxyConfig})),{localCacheEngine:overrides.localCacheEngine,partsEngine:partsEngine2,autorouterMap:{krt:{createAutorouter:createKiCadRoutingToolsAutorouter({gridStep:.1,clearance:.2,maxIterations:3e5})},...overrides.autorouterMap},spiceEngineMap:{ngspice:{simulate:async spice=>{if(!ngspiceEngineCache){let createNgspiceSpiceEngine=await dynamicallyLoadDependencyWithCdnBackup("@tscircuit/ngspice-spice-engine").catch(error2=>{throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.",{cause:error2})});createNgspiceSpiceEngine&&(ngspiceEngineCache=await createNgspiceSpiceEngine())}if(!ngspiceEngineCache)throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.");return ngspiceEngineCache.simulate(spice)}}},footprintLibraryMap:{kicad:async footprintName=>{let baseUrl=`${KICAD_FOOTPRINT_CACHE_URL}/${footprintName}`,circuitJsonUrl=`${baseUrl}.circuit.json`,res2=await fetch(circuitJsonUrl);if(!res2.ok){let bodyPreview=(await res2.text()).slice(0,200);throw new Error(`Failed to load KiCad footprint "${footprintName}" from ${circuitJsonUrl} (HTTP ${res2.status}). ${bodyPreview}`)}let raw;try{raw=await res2.json()}catch{throw new Error(`Failed to parse KiCad footprint JSON for "${footprintName}" from ${circuitJsonUrl}`)}let filtered=Array.isArray(raw)?raw.filter(el3=>el3?.type==="pcb_silkscreen_text"?el3?.text==="REF**":!0):[raw],wrlUrl=`${baseUrl}.wrl`,stepUrl=`${baseUrl}.step`;return{footprintCircuitJson:filtered,cadModel:{wrlUrl,stepUrl,modelUnitToMmScale:2.54}}},jlcpcb:async partNumber=>{if(!partsEngine2.fetchPartCircuitJson)throw new Error("Configured parts engine does not support fetchPartCircuitJson, required for jlcpcb footprints.");let supplierPartNumber=toJlcpcbSupplierPartNumber(partNumber),footprintCircuitJson=await partsEngine2.fetchPartCircuitJson({supplierPartNumber,platformFetch:overrides.platformFetch});if(!Array.isArray(footprintCircuitJson))throw new Error(`Failed to load JLCPCB footprint "${supplierPartNumber}" from parts engine.`);return{footprintCircuitJson,cadModel:extractCadModelFromCircuitJson2(footprintCircuitJson)}}},footprintFileParserMap:{kicad_mod:{loadFromUrl:async url2=>{let kicadContent=await fetch(url2).then(res2=>res2.text()),kicadJson=await parseKicadModToCircuitJson(kicadContent);return{footprintCircuitJson:Array.isArray(kicadJson)?kicadJson:[kicadJson]}}}},staticFileLoaderMap:{kicad_pcb:loadKicadPcbStaticFile,...overrides.staticFileLoaderMap}}};var tslib_es6_exports={};__export(tslib_es6_exports,{__addDisposableResource:()=>__addDisposableResource,__assign:()=>__assign,__asyncDelegator:()=>__asyncDelegator,__asyncGenerator:()=>__asyncGenerator,__asyncValues:()=>__asyncValues,__await:()=>__await,__awaiter:()=>__awaiter,__classPrivateFieldGet:()=>__classPrivateFieldGet,__classPrivateFieldIn:()=>__classPrivateFieldIn,__classPrivateFieldSet:()=>__classPrivateFieldSet,__createBinding:()=>__createBinding,__decorate:()=>__decorate,__disposeResources:()=>__disposeResources,__esDecorate:()=>__esDecorate,__exportStar:()=>__exportStar,__extends:()=>__extends,__generator:()=>__generator,__importDefault:()=>__importDefault,__importStar:()=>__importStar,__makeTemplateObject:()=>__makeTemplateObject,__metadata:()=>__metadata,__param:()=>__param,__propKey:()=>__propKey,__read:()=>__read,__rest:()=>__rest,__rewriteRelativeImportExtension:()=>__rewriteRelativeImportExtension,__runInitializers:()=>__runInitializers,__setFunctionName:()=>__setFunctionName,__spread:()=>__spread,__spreadArray:()=>__spreadArray,__spreadArrays:()=>__spreadArrays,__values:()=>__values,default:()=>tslib_es6_default});var extendStatics=function(d4,b3){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d5,b4){d5.__proto__=b4}||function(d5,b4){for(var p4 in b4)Object.prototype.hasOwnProperty.call(b4,p4)&&(d5[p4]=b4[p4])},extendStatics(d4,b3)};function __extends(d4,b3){if(typeof b3!="function"&&b3!==null)throw new TypeError("Class extends value "+String(b3)+" is not a constructor or null");extendStatics(d4,b3);function __2(){this.constructor=d4}d4.prototype=b3===null?Object.create(b3):(__2.prototype=b3.prototype,new __2)}var __assign=function(){return __assign=Object.assign||function(t52){for(var s3,i3=1,n4=arguments.length;i3<n4;i3++){s3=arguments[i3];for(var p4 in s3)Object.prototype.hasOwnProperty.call(s3,p4)&&(t52[p4]=s3[p4])}return t52},__assign.apply(this,arguments)};function __rest(s3,e5){var t52={};for(var p4 in s3)Object.prototype.hasOwnProperty.call(s3,p4)&&e5.indexOf(p4)<0&&(t52[p4]=s3[p4]);if(s3!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i3=0,p4=Object.getOwnPropertySymbols(s3);i3<p4.length;i3++)e5.indexOf(p4[i3])<0&&Object.prototype.propertyIsEnumerable.call(s3,p4[i3])&&(t52[p4[i3]]=s3[p4[i3]]);return t52}function __decorate(decorators,target,key,desc){var c4=arguments.length,r5=c4<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d4;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r5=Reflect.decorate(decorators,target,key,desc);else for(var i3=decorators.length-1;i3>=0;i3--)(d4=decorators[i3])&&(r5=(c4<3?d4(r5):c4>3?d4(target,key,r5):d4(target,key))||r5);return c4>3&&r5&&Object.defineProperty(target,key,r5),r5}function __param(paramIndex,decorator){return function(target,key){decorator(target,key,paramIndex)}}function __esDecorate(ctor,descriptorIn,decorators,contextIn,initializers,extraInitializers){function accept(f3){if(f3!==void 0&&typeof f3!="function")throw new TypeError("Function expected");return f3}for(var kind=contextIn.kind,key=kind==="getter"?"get":kind==="setter"?"set":"value",target=!descriptorIn&&ctor?contextIn.static?ctor:ctor.prototype:null,descriptor=descriptorIn||(target?Object.getOwnPropertyDescriptor(target,contextIn.name):{}),_4,done=!1,i3=decorators.length-1;i3>=0;i3--){var context={};for(var p4 in contextIn)context[p4]=p4==="access"?{}:contextIn[p4];for(var p4 in contextIn.access)context.access[p4]=contextIn.access[p4];context.addInitializer=function(f3){if(done)throw new TypeError("Cannot add initializers after decoration has completed");extraInitializers.push(accept(f3||null))};var result=(0,decorators[i3])(kind==="accessor"?{get:descriptor.get,set:descriptor.set}:descriptor[key],context);if(kind==="accessor"){if(result===void 0)continue;if(result===null||typeof result!="object")throw new TypeError("Object expected");(_4=accept(result.get))&&(descriptor.get=_4),(_4=accept(result.set))&&(descriptor.set=_4),(_4=accept(result.init))&&initializers.unshift(_4)}else(_4=accept(result))&&(kind==="field"?initializers.unshift(_4):descriptor[key]=_4)}target&&Object.defineProperty(target,contextIn.name,descriptor),done=!0}function __runInitializers(thisArg,initializers,value){for(var useValue=arguments.length>2,i3=0;i3<initializers.length;i3++)value=useValue?initializers[i3].call(thisArg,value):initializers[i3].call(thisArg);return useValue?value:void 0}function __propKey(x4){return typeof x4=="symbol"?x4:"".concat(x4)}function __setFunctionName(f3,name,prefix){return typeof name=="symbol"&&(name=name.description?"[".concat(name.description,"]"):""),Object.defineProperty(f3,"name",{configurable:!0,value:prefix?"".concat(prefix," ",name):name})}function __metadata(metadataKey,metadataValue){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(metadataKey,metadataValue)}function __awaiter(thisArg,_arguments,P4,generator){function adopt(value){return value instanceof P4?value:new P4(function(resolve){resolve(value)})}return new(P4||(P4=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e5){reject(e5)}}function rejected(value){try{step(generator.throw(value))}catch(e5){reject(e5)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})}function __generator(thisArg,body){var _4={label:0,sent:function(){if(t52[0]&1)throw t52[1];return t52[1]},trys:[],ops:[]},f3,y4,t52,g6=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return g6.next=verb(0),g6.throw=verb(1),g6.return=verb(2),typeof Symbol=="function"&&(g6[Symbol.iterator]=function(){return this}),g6;function verb(n4){return function(v4){return step([n4,v4])}}function step(op3){if(f3)throw new TypeError("Generator is already executing.");for(;g6&&(g6=0,op3[0]&&(_4=0)),_4;)try{if(f3=1,y4&&(t52=op3[0]&2?y4.return:op3[0]?y4.throw||((t52=y4.return)&&t52.call(y4),0):y4.next)&&!(t52=t52.call(y4,op3[1])).done)return t52;switch(y4=0,t52&&(op3=[op3[0]&2,t52.value]),op3[0]){case 0:case 1:t52=op3;break;case 4:return _4.label++,{value:op3[1],done:!1};case 5:_4.label++,y4=op3[1],op3=[0];continue;case 7:op3=_4.ops.pop(),_4.trys.pop();continue;default:if(t52=_4.trys,!(t52=t52.length>0&&t52[t52.length-1])&&(op3[0]===6||op3[0]===2)){_4=0;continue}if(op3[0]===3&&(!t52||op3[1]>t52[0]&&op3[1]<t52[3])){_4.label=op3[1];break}if(op3[0]===6&&_4.label<t52[1]){_4.label=t52[1],t52=op3;break}if(t52&&_4.label<t52[2]){_4.label=t52[2],_4.ops.push(op3);break}t52[2]&&_4.ops.pop(),_4.trys.pop();continue}op3=body.call(thisArg,_4)}catch(e5){op3=[6,e5],y4=0}finally{f3=t52=0}if(op3[0]&5)throw op3[1];return{value:op3[0]?op3[1]:void 0,done:!0}}}var __createBinding=Object.create?(function(o4,m4,k4,k22){k22===void 0&&(k22=k4);var desc=Object.getOwnPropertyDescriptor(m4,k4);(!desc||("get"in desc?!m4.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m4[k4]}}),Object.defineProperty(o4,k22,desc)}):(function(o4,m4,k4,k22){k22===void 0&&(k22=k4),o4[k22]=m4[k4]});function __exportStar(m4,o4){for(var p4 in m4)p4!=="default"&&!Object.prototype.hasOwnProperty.call(o4,p4)&&__createBinding(o4,m4,p4)}function __values(o4){var s3=typeof Symbol=="function"&&Symbol.iterator,m4=s3&&o4[s3],i3=0;if(m4)return m4.call(o4);if(o4&&typeof o4.length=="number")return{next:function(){return o4&&i3>=o4.length&&(o4=void 0),{value:o4&&o4[i3++],done:!o4}}};throw new TypeError(s3?"Object is not iterable.":"Symbol.iterator is not defined.")}function __read(o4,n4){var m4=typeof Symbol=="function"&&o4[Symbol.iterator];if(!m4)return o4;var i3=m4.call(o4),r5,ar3=[],e5;try{for(;(n4===void 0||n4-- >0)&&!(r5=i3.next()).done;)ar3.push(r5.value)}catch(error2){e5={error:error2}}finally{try{r5&&!r5.done&&(m4=i3.return)&&m4.call(i3)}finally{if(e5)throw e5.error}}return ar3}function __spread(){for(var ar3=[],i3=0;i3<arguments.length;i3++)ar3=ar3.concat(__read(arguments[i3]));return ar3}function __spreadArrays(){for(var s3=0,i3=0,il3=arguments.length;i3<il3;i3++)s3+=arguments[i3].length;for(var r5=Array(s3),k4=0,i3=0;i3<il3;i3++)for(var a3=arguments[i3],j4=0,jl3=a3.length;j4<jl3;j4++,k4++)r5[k4]=a3[j4];return r5}function __spreadArray(to3,from,pack2){if(pack2||arguments.length===2)for(var i3=0,l4=from.length,ar3;i3<l4;i3++)(ar3||!(i3 in from))&&(ar3||(ar3=Array.prototype.slice.call(from,0,i3)),ar3[i3]=from[i3]);return to3.concat(ar3||Array.prototype.slice.call(from))}function __await(v4){return this instanceof __await?(this.v=v4,this):new __await(v4)}function __asyncGenerator(thisArg,_arguments,generator){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var g6=generator.apply(thisArg,_arguments||[]),i3,q4=[];return i3=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",awaitReturn),i3[Symbol.asyncIterator]=function(){return this},i3;function awaitReturn(f3){return function(v4){return Promise.resolve(v4).then(f3,reject)}}function verb(n4,f3){g6[n4]&&(i3[n4]=function(v4){return new Promise(function(a3,b3){q4.push([n4,v4,a3,b3])>1||resume(n4,v4)})},f3&&(i3[n4]=f3(i3[n4])))}function resume(n4,v4){try{step(g6[n4](v4))}catch(e5){settle(q4[0][3],e5)}}function step(r5){r5.value instanceof __await?Promise.resolve(r5.value.v).then(fulfill,reject):settle(q4[0][2],r5)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f3,v4){f3(v4),q4.shift(),q4.length&&resume(q4[0][0],q4[0][1])}}function __asyncDelegator(o4){var i3,p4;return i3={},verb("next"),verb("throw",function(e5){throw e5}),verb("return"),i3[Symbol.iterator]=function(){return this},i3;function verb(n4,f3){i3[n4]=o4[n4]?function(v4){return(p4=!p4)?{value:__await(o4[n4](v4)),done:!1}:f3?f3(v4):v4}:f3}}function __asyncValues(o4){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var m4=o4[Symbol.asyncIterator],i3;return m4?m4.call(o4):(o4=typeof __values=="function"?__values(o4):o4[Symbol.iterator](),i3={},verb("next"),verb("throw"),verb("return"),i3[Symbol.asyncIterator]=function(){return this},i3);function verb(n4){i3[n4]=o4[n4]&&function(v4){return new Promise(function(resolve,reject){v4=o4[n4](v4),settle(resolve,reject,v4.done,v4.value)})}}function settle(resolve,reject,d4,v4){Promise.resolve(v4).then(function(v5){resolve({value:v5,done:d4})},reject)}}function __makeTemplateObject(cooked,raw){return Object.defineProperty?Object.defineProperty(cooked,"raw",{value:raw}):cooked.raw=raw,cooked}var __setModuleDefault=Object.create?(function(o4,v4){Object.defineProperty(o4,"default",{enumerable:!0,value:v4})}):function(o4,v4){o4.default=v4},ownKeys=function(o4){return ownKeys=Object.getOwnPropertyNames||function(o6){var ar3=[];for(var k4 in o6)Object.prototype.hasOwnProperty.call(o6,k4)&&(ar3[ar3.length]=k4);return ar3},ownKeys(o4)};function __importStar(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k4=ownKeys(mod),i3=0;i3<k4.length;i3++)k4[i3]!=="default"&&__createBinding(result,mod,k4[i3]);return __setModuleDefault(result,mod),result}function __importDefault(mod){return mod&&mod.__esModule?mod:{default:mod}}function __classPrivateFieldGet(receiver,state2,kind,f3){if(kind==="a"&&!f3)throw new TypeError("Private accessor was defined without a getter");if(typeof state2=="function"?receiver!==state2||!f3:!state2.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f3:kind==="a"?f3.call(receiver):f3?f3.value:state2.get(receiver)}function __classPrivateFieldSet(receiver,state2,value,kind,f3){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f3)throw new TypeError("Private accessor was defined without a setter");if(typeof state2=="function"?receiver!==state2||!f3:!state2.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f3.call(receiver,value):f3?f3.value=value:state2.set(receiver,value),value}function __classPrivateFieldIn(state2,receiver){if(receiver===null||typeof receiver!="object"&&typeof receiver!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof state2=="function"?receiver===state2:state2.has(receiver)}function __addDisposableResource(env,value,async){if(value!=null){if(typeof value!="object"&&typeof value!="function")throw new TypeError("Object expected.");var dispose,inner;if(async){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose],async&&(inner=dispose)}if(typeof dispose!="function")throw new TypeError("Object not disposable.");inner&&(dispose=function(){try{inner.call(this)}catch(e5){return Promise.reject(e5)}}),env.stack.push({value,dispose,async})}else async&&env.stack.push({async:!0});return value}var _SuppressedError=typeof SuppressedError=="function"?SuppressedError:function(error2,suppressed,message){var e5=new Error(message);return e5.name="SuppressedError",e5.error=error2,e5.suppressed=suppressed,e5};function __disposeResources(env){function fail(e5){env.error=env.hasError?new _SuppressedError(e5,env.error,"An error was suppressed during disposal."):e5,env.hasError=!0}var r5,s3=0;function next2(){for(;r5=env.stack.pop();)try{if(!r5.async&&s3===1)return s3=0,env.stack.push(r5),Promise.resolve().then(next2);if(r5.dispose){var result=r5.dispose.call(r5.value);if(r5.async)return s3|=2,Promise.resolve(result).then(next2,function(e5){return fail(e5),next2()})}else s3|=1}catch(e5){fail(e5)}if(s3===1)return env.hasError?Promise.reject(env.error):Promise.resolve();if(env.hasError)throw env.error}return next2()}function __rewriteRelativeImportExtension(path,preserveJsx){return typeof path=="string"&&/^\.\.?\//.test(path)?path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m4,tsx,d4,ext,cm3){return tsx?preserveJsx?".jsx":".js":d4&&(!ext||!cm3)?m4:d4+ext+"."+cm3.toLowerCase()+"js"}):path}var tslib_es6_default={__extends,__assign,__rest,__decorate,__param,__esDecorate,__runInitializers,__propKey,__setFunctionName,__metadata,__awaiter,__generator,__createBinding,__exportStar,__values,__read,__spread,__spreadArrays,__spreadArray,__await,__asyncGenerator,__asyncDelegator,__asyncValues,__makeTemplateObject,__importStar,__importDefault,__classPrivateFieldGet,__classPrivateFieldSet,__classPrivateFieldIn,__addDisposableResource,__disposeResources,__rewriteRelativeImportExtension};var import_debug23=__toESM(require_browser(),1),debug13=(0,import_debug23.default)("tsci:eval:execution-context");function createExecutionContext(webWorkerConfiguration,opts={}){globalThis.React=React3;let basePlatform=opts.platform||getPlatformConfig({},{easyEdaProxyConfig:webWorkerConfiguration.easyEdaProxyConfig}),platform=opts.projectConfig?{...basePlatform,...opts.projectConfig}:basePlatform;platform.partsEngineDisabled&&(platform.partsEngine=void 0);let circuit=new RootCircuit({platform});opts.name&&(circuit.name=opts.name),opts.debugNamespace&&circuit.enableDebug(opts.debugNamespace);let logs=[];return{fsMap:{},entrypoint:"",logger:{info:message=>{logs.push({msg:message})},getLogs:()=>logs,stringifyLogs:()=>logs.map(log=>log.msg).join(`
|
|
800
|
+
`)}},__publicField(_a495,"token","via"),_a495);SxClass.register(Via2);var _a496,KicadPcb=(_a496=class extends SxClass{constructor(params={}){super();__publicField(this,"token","kicad_pcb");__publicField(this,"_sxVersion");__publicField(this,"_sxGenerator");__publicField(this,"_sxGeneratorVersion");__publicField(this,"_sxGeneral");__publicField(this,"_sxPaper");__publicField(this,"_sxTitleBlock");__publicField(this,"_sxLayers");__publicField(this,"_sxSetup");__publicField(this,"_properties",[]);__publicField(this,"_nets",[]);__publicField(this,"_footprints",[]);__publicField(this,"_images",[]);__publicField(this,"_segments",[]);__publicField(this,"_arcs",[]);__publicField(this,"_grArcs",[]);__publicField(this,"_grCircles",[]);__publicField(this,"_grCurves",[]);__publicField(this,"_grLines",[]);__publicField(this,"_grTexts",[]);__publicField(this,"_grPolys",[]);__publicField(this,"_grRects",[]);__publicField(this,"_vias",[]);__publicField(this,"_zones",[]);__publicField(this,"_sxEmbeddedFonts");__publicField(this,"_sxEmbeddedFiles");__publicField(this,"_otherChildren",[]);params.version!==void 0&&(this.version=params.version),params.generator!==void 0&&(this.generator=params.generator),params.generatorVersion!==void 0&&(this.generatorVersion=params.generatorVersion),params.general!==void 0&&(this.general=params.general),params.paper!==void 0&&(this.paper=params.paper),params.titleBlock!==void 0&&(this.titleBlock=params.titleBlock),params.layers!==void 0&&(this.layers=params.layers),params.setup!==void 0&&(this.setup=params.setup),params.properties!==void 0&&(this.properties=params.properties),params.nets!==void 0&&(this.nets=params.nets),params.footprints!==void 0&&(this.footprints=params.footprints),params.images!==void 0&&(this.images=params.images),params.segments!==void 0&&(this.segments=params.segments),params.arcs!==void 0&&(this.arcs=params.arcs),params.graphicArcs!==void 0&&(this.graphicArcs=params.graphicArcs),params.graphicCircles!==void 0&&(this.graphicCircles=params.graphicCircles),params.graphicCurves!==void 0&&(this.graphicCurves=params.graphicCurves),params.graphicLines!==void 0&&(this.graphicLines=params.graphicLines),params.graphicTexts!==void 0&&(this.graphicTexts=params.graphicTexts),params.graphicPolys!==void 0&&(this.graphicPolys=params.graphicPolys),params.graphicRects!==void 0&&(this.graphicRects=params.graphicRects),params.vias!==void 0&&(this.vias=params.vias),params.zones!==void 0&&(this.zones=params.zones),params.embeddedFonts!==void 0&&(this.embeddedFonts=params.embeddedFonts),params.embeddedFiles!==void 0&&(this.embeddedFiles=params.embeddedFiles),params.otherChildren!==void 0&&(this.otherChildren=params.otherChildren)}static fromSexprPrimitives(primitiveSexprs){let pcb=new _a496;for(let primitive of primitiveSexprs){if(!Array.isArray(primitive)||primitive.length===0)throw new Error(`kicad_pcb encountered unsupported primitive child: ${JSON.stringify(primitive)}`);let parsed=SxClass.parsePrimitiveSexpr(primitive,{parentToken:_a496.token});if(!(parsed instanceof SxClass))throw new Error(`kicad_pcb expected SxClass child, received ${JSON.stringify(primitive)}`);pcb.consumeChild(parsed)}return pcb}consumeChild(child){if(child instanceof PcbVersion){this._sxVersion=child;return}if(child instanceof PcbGenerator){this._sxGenerator=child;return}if(child instanceof PcbGeneratorVersion){this._sxGeneratorVersion=child;return}if(child instanceof PcbGeneral){this._sxGeneral=child;return}if(child instanceof Paper){this._sxPaper=child;return}if(child instanceof TitleBlock){this._sxTitleBlock=child;return}if(child instanceof PcbLayers){this._sxLayers=child;return}if(child instanceof Setup){this._sxSetup=child;return}if(child instanceof Property){this._properties.push(child);return}if(child instanceof PcbNet){this._nets.push(child);return}if(child instanceof Footprint2){this._footprints.push(child);return}if(child instanceof Image){this._images.push(child);return}if(child instanceof Segment3){this._segments.push(child);return}if(child instanceof PcbArc){this._arcs.push(child);return}if(child instanceof GrArc){this._grArcs.push(child);return}if(child instanceof GrCircle){this._grCircles.push(child);return}if(child instanceof GrCurve){this._grCurves.push(child);return}if(child instanceof GrLine){this._grLines.push(child);return}if(child instanceof GrText){this._grTexts.push(child);return}if(child instanceof GrPoly){this._grPolys.push(child);return}if(child instanceof GrRect){this._grRects.push(child);return}if(child instanceof Via2){this._vias.push(child);return}if(child instanceof Zone){this._zones.push(child);return}if(child instanceof EmbeddedFonts){this._sxEmbeddedFonts=child;return}if(child instanceof EmbeddedFiles){this._sxEmbeddedFiles=child;return}this._otherChildren.push(child)}get version(){return this._sxVersion?.value}set version(value){this._sxVersion=value===void 0?void 0:new PcbVersion(value)}get generator(){return this._sxGenerator?.value}set generator(value){this._sxGenerator=value===void 0?void 0:new PcbGenerator(value)}get generatorVersion(){return this._sxGeneratorVersion?.value}set generatorVersion(value){this._sxGeneratorVersion=value===void 0?void 0:new PcbGeneratorVersion(value)}get general(){return this._sxGeneral}set general(value){this._sxGeneral=value}get paper(){return this._sxPaper}set paper(value){this._sxPaper=value}get titleBlock(){return this._sxTitleBlock}set titleBlock(value){this._sxTitleBlock=value}get layers(){return this._sxLayers}set layers(value){this._sxLayers=value}get setup(){return this._sxSetup}set setup(value){this._sxSetup=value}get properties(){return[...this._properties]}set properties(value){this._properties=[...value]}get nets(){return[...this._nets]}set nets(value){this._nets=[...value]}get footprints(){return[...this._footprints]}set footprints(value){this._footprints=[...value]}get images(){return[...this._images]}set images(value){this._images=[...value]}get segments(){return[...this._segments]}set segments(value){this._segments=[...value]}get arcs(){return[...this._arcs]}set arcs(value){this._arcs=[...value]}get graphicArcs(){return[...this._grArcs]}set graphicArcs(value){this._grArcs=[...value]}get graphicCircles(){return[...this._grCircles]}set graphicCircles(value){this._grCircles=[...value]}get graphicCurves(){return[...this._grCurves]}set graphicCurves(value){this._grCurves=[...value]}get graphicLines(){return[...this._grLines]}set graphicLines(value){this._grLines=[...value]}get graphicTexts(){return[...this._grTexts]}set graphicTexts(value){this._grTexts=[...value]}get graphicPolys(){return[...this._grPolys]}set graphicPolys(value){this._grPolys=[...value]}get graphicRects(){return[...this._grRects]}set graphicRects(value){this._grRects=[...value]}get vias(){return[...this._vias]}set vias(value){this._vias=[...value]}get zones(){return[...this._zones]}set zones(value){this._zones=[...value]}get embeddedFonts(){return this._sxEmbeddedFonts}set embeddedFonts(value){this._sxEmbeddedFonts=value}get embeddedFiles(){return this._sxEmbeddedFiles}set embeddedFiles(value){this._sxEmbeddedFiles=value}get otherChildren(){return[...this._otherChildren]}set otherChildren(value){this._otherChildren=[...value]}getChildren(){let children=[];return this._sxVersion&&children.push(this._sxVersion),this._sxGenerator&&children.push(this._sxGenerator),this._sxGeneratorVersion&&children.push(this._sxGeneratorVersion),this._sxGeneral&&children.push(this._sxGeneral),this._sxPaper&&children.push(this._sxPaper),this._sxTitleBlock&&children.push(this._sxTitleBlock),this._sxLayers&&children.push(this._sxLayers),this._sxSetup&&children.push(this._sxSetup),children.push(...this._properties),children.push(...this._nets),children.push(...this._footprints),children.push(...this._images),children.push(...this._segments),children.push(...this._arcs),children.push(...this._grArcs),children.push(...this._grCircles),children.push(...this._grCurves),children.push(...this._grLines),children.push(...this._grTexts),children.push(...this._grPolys),children.push(...this._grRects),children.push(...this._vias),children.push(...this._zones),this._sxEmbeddedFonts&&children.push(this._sxEmbeddedFonts),this._sxEmbeddedFiles&&children.push(this._sxEmbeddedFiles),children.push(...this._otherChildren),children}},__publicField(_a496,"token","kicad_pcb"),_a496);SxClass.register(KicadPcb);var parseKicadSexpr=sexpr=>SxClass.parse(sexpr),parseKicadSch=sexpr=>{let[root]=parseKicadSexpr(sexpr);if(!(root instanceof KicadSch))throw new Error(`Expected KicadSch root, got ${root?.constructor.name??"undefined"}`);return root},parseKicadPcb=sexpr=>{let[root]=parseKicadSexpr(sexpr);if(!(root instanceof KicadPcb))throw new Error(`Expected KicadPcb root, got ${root?.constructor.name??"undefined"}`);return root};init_src();init_src();init_src();init_src();init_src();init_src();init_src();init_src();init_src();init_src();init_src();init_src();var ConverterStage=class{constructor(ctx){__publicField(this,"ctx");__publicField(this,"MAX_ITERATIONS",100);__publicField(this,"iterationCount",0);__publicField(this,"finished",!1);this.ctx=ctx}runUntilFinished(){for(this.iterationCount=0;!this.finished&&this.iterationCount<this.MAX_ITERATIONS;)this.step()||(this.finished=!0),this.iterationCount++;this.iterationCount>=this.MAX_ITERATIONS&&(this.ctx.warnings=this.ctx.warnings||[],this.ctx.warnings.push(`Stage ${this.constructor.name} exceeded maximum iterations (${this.MAX_ITERATIONS})`),this.finished=!0)}},INNER_COPPER_LAYER_REGEX=/^In([1-6])\.Cu$/;function dedupeLayerRefs(layers){return[...new Set(layers)]}function extractKicadLayerNames(layer){return layer?typeof layer=="string"?[layer]:Array.isArray(layer)?layer.filter(name=>typeof name=="string"):[...layer.names||[],...layer._names||[],...layer._layers||[],...layer.name?[layer.name]:[],...layer._name?[layer._name]:[]].filter(name=>typeof name=="string"):[]}function mapKicadLayerToPcbRenderLayer(layer){let layerNames=extractKicadLayerNames(layer);for(let layerName of layerNames){let copperLayer=mapKicadLayerNameToLayerRef(layerName);if(copperLayer)return`${copperLayer}_copper`;if(layerName.includes("Edge.Cuts"))return"edge_cuts";let side=mapKicadLayerToVisibleLayer(layerName);if(layerName.includes("CrtYd"))return`${side}_courtyard`;if(layerName.includes("Fab"))return`${side}_fabrication_note`;if(layerName.includes("SilkS"))return`${side}_silkscreen`}}function isPcbAnnotationRenderLayer(renderLayer){return renderLayer?.endsWith("_silkscreen")||renderLayer?.endsWith("_fabrication_note")||renderLayer?.endsWith("_courtyard")||!1}function isPcbTextRenderLayer(renderLayer){return renderLayer?.endsWith("_silkscreen")||renderLayer?.endsWith("_fabrication_note")||renderLayer?.endsWith("_copper")||!1}function mapKicadLayerNameToLayerRef(layerName){if(layerName==="F.Cu")return"top";if(layerName==="B.Cu")return"bottom";let innerLayerMatch=layerName.match(INNER_COPPER_LAYER_REGEX);if(innerLayerMatch)return`inner${innerLayerMatch[1]}`}function mapKicadLayerToLayerRef(layer){let layerNames=extractKicadLayerNames(layer);for(let layerName of layerNames){let mappedLayer=mapKicadLayerNameToLayerRef(layerName);if(mappedLayer)return mappedLayer}let layerLabel=layerNames.join(" ");return layerLabel.includes("B.")||layerLabel.includes("Back")||layerLabel.includes("Bottom")?"bottom":"top"}function mapKicadLayerToVisibleLayer(layer){return mapKicadLayerToLayerRef(layer)==="bottom"?"bottom":"top"}function getPcbCopperLayerRefs(kicadPcb){let copperLayers=(Array.isArray(kicadPcb?.layers?._definitions)?(kicadPcb?.layers)._definitions:[]).map(definition=>mapKicadLayerNameToLayerRef(definition?._name)).filter(layer=>!!layer);return copperLayers.length>0?dedupeLayerRefs(copperLayers):["top","bottom"]}function getLayerRefsFromLayers(layers,kicadPcb){let layerNames=extractKicadLayerNames(layers),mappedLayers=[];for(let layerName of layerNames){if(layerName==="*.Cu"){mappedLayers.push(...getPcbCopperLayerRefs(kicadPcb));continue}let mappedLayer=mapKicadLayerNameToLayerRef(layerName);mappedLayer&&mappedLayers.push(mappedLayer)}return dedupeLayerRefs(mappedLayers)}function expandCopperLayerSpan(layers,kicadPcb){if(layers.length<=1)return layers;let copperStack=getPcbCopperLayerRefs(kicadPcb),startIndex=copperStack.indexOf(layers[0]),endIndex=copperStack.indexOf(layers[layers.length-1]);if(startIndex===-1||endIndex===-1)return dedupeLayerRefs(layers);let[fromIndex,toIndex]=startIndex<=endIndex?[startIndex,endIndex]:[endIndex,startIndex];return copperStack.slice(fromIndex,toIndex+1)}function getCopperSpanLayerRefsFromLayers(layers,kicadPcb){return expandCopperLayerSpan(getLayerRefsFromLayers(layers,kicadPcb),kicadPcb)}function getComponentLayer(footprint){return mapKicadLayerToVisibleLayer(footprint.layer)}function determineLayerFromLayers(layers){return mapKicadLayerToLayerRef(extractKicadLayerNames(layers))}function mapTextLayer(kicadLayer){return mapKicadLayerToVisibleLayer(kicadLayer)}function insertFootprintRoute(options){let{ctx,componentId,layer,renderLayer,route,strokeWidth}=options;if(renderLayer.endsWith("_silkscreen")){ctx.db.pcb_silkscreen_path.insert({pcb_component_id:componentId,layer,route,stroke_width:strokeWidth});return}if(renderLayer.endsWith("_fabrication_note")){ctx.db.pcb_fabrication_note_path.insert({pcb_component_id:componentId,layer,route,stroke_width:strokeWidth});return}ctx.db.pcb_courtyard_outline.insert({pcb_component_id:componentId,layer,outline:route})}function rotatePoint7(x4,y4,rotationDeg){let rotationRad=rotationDeg*Math.PI/180;return{x:x4*Math.cos(rotationRad)-y4*Math.sin(rotationRad),y:x4*Math.sin(rotationRad)+y4*Math.cos(rotationRad)}}function processFootprintGraphics(ctx,footprint,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;let lines=footprint.fpLines||[],lineArray=Array.isArray(lines)?lines:lines?[lines]:[];for(let line2 of lineArray)createFootprintLine(ctx,line2,componentId,kicadComponentPos,componentRotation);let rects=footprint.fpRects||[],rectArray=Array.isArray(rects)?rects:rects?[rects]:[];for(let rect of rectArray)createFootprintRect(ctx,rect,componentId,kicadComponentPos,componentRotation);let circles=footprint.fpCircles||[],circleArray=Array.isArray(circles)?circles:circles?[circles]:[];for(let circle2 of circleArray)createFootprintCircle(ctx,circle2,componentId,kicadComponentPos,componentRotation);let arcs=footprint.fpArcs||[],arcArray=Array.isArray(arcs)?arcs:arcs?[arcs]:[];for(let arc2 of arcArray)createFootprintArc(ctx,arc2,componentId,kicadComponentPos,componentRotation);let polys=footprint.fpPolys||[],polyArray=Array.isArray(polys)?polys:polys?[polys]:[];for(let poly of polyArray)createFootprintPoly(ctx,poly,componentId,kicadComponentPos,componentRotation)}function createFootprintLine(ctx,line2,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;let renderLayer=mapKicadLayerToPcbRenderLayer(line2.layer);if(!isPcbAnnotationRenderLayer(renderLayer))return;let start=line2.start||{x:0,y:0},end=line2.end||{x:0,y:0},rotatedStart=rotatePoint7(start.x,start.y,-componentRotation),rotatedEnd=rotatePoint7(end.x,end.y,-componentRotation),startKicadPos={x:kicadComponentPos.x+rotatedStart.x,y:kicadComponentPos.y+rotatedStart.y},endKicadPos={x:kicadComponentPos.x+rotatedEnd.x,y:kicadComponentPos.y+rotatedEnd.y},startPos=applyToPoint(ctx.k2cMatPcb,startKicadPos),endPos=applyToPoint(ctx.k2cMatPcb,endKicadPos),layer=mapTextLayer(line2.layer),strokeWidth=line2.stroke?.width||line2.width||.12;insertFootprintRoute({ctx,componentId,layer,renderLayer,route:[startPos,endPos],strokeWidth})}function createFootprintRect(ctx,rect,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;let renderLayer=mapKicadLayerToPcbRenderLayer(rect.layer);if(!isPcbAnnotationRenderLayer(renderLayer))return;let start=rect.start||{x:0,y:0},end=rect.end||{x:0,y:0},center2={x:(start.x+end.x)/2,y:(start.y+end.y)/2},rotatedCenter=rotatePoint7(center2.x,center2.y,-componentRotation),centerKicadPos={x:kicadComponentPos.x+rotatedCenter.x,y:kicadComponentPos.y+rotatedCenter.y},centerPos=applyToPoint(ctx.k2cMatPcb,centerKicadPos),layer=mapTextLayer(rect.layer),width=Math.abs(end.x-start.x),height=Math.abs(end.y-start.y),strokeWidth=rect.stroke?.width||rect.width||.12;if(renderLayer.endsWith("_courtyard")){ctx.db.pcb_courtyard_rect.insert({pcb_component_id:componentId,center:centerPos,width,height,layer,ccw_rotation:-componentRotation});return}if(renderLayer.endsWith("_fabrication_note")){ctx.db.pcb_fabrication_note_rect.insert({pcb_component_id:componentId,center:centerPos,width,height,layer,stroke_width:strokeWidth,is_filled:rect.fill?.filled===!0,has_stroke:!0});return}let route=[{x:start.x,y:start.y},{x:end.x,y:start.y},{x:end.x,y:end.y},{x:start.x,y:end.y},{x:start.x,y:start.y}].map(point7=>{let rotated=rotatePoint7(point7.x,point7.y,-componentRotation),kicadPos={x:kicadComponentPos.x+rotated.x,y:kicadComponentPos.y+rotated.y};return applyToPoint(ctx.k2cMatPcb,kicadPos)});insertFootprintRoute({ctx,componentId,layer,renderLayer,route,strokeWidth})}function createFootprintCircle(ctx,circle2,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;let renderLayer=mapKicadLayerToPcbRenderLayer(circle2.layer);if(!isPcbAnnotationRenderLayer(renderLayer))return;let center2=circle2.center||{x:0,y:0},end=circle2.end||{x:0,y:0},radius=Math.sqrt((end.x-center2.x)**2+(end.y-center2.y)**2),rotatedCenter=rotatePoint7(center2.x,center2.y,-componentRotation),centerKicadPos={x:kicadComponentPos.x+rotatedCenter.x,y:kicadComponentPos.y+rotatedCenter.y},centerPos=applyToPoint(ctx.k2cMatPcb,centerKicadPos),layer=mapTextLayer(circle2.layer),strokeWidth=circle2.stroke?.width||circle2.width||.12;if(renderLayer.endsWith("_courtyard")){ctx.db.pcb_courtyard_circle.insert({pcb_component_id:componentId,center:centerPos,radius,layer});return}let numPoints=16,circleRoute=[];for(let i3=0;i3<=numPoints;i3++){let angle=i3/numPoints*2*Math.PI,x4=centerPos.x+radius*Math.cos(angle),y4=centerPos.y+radius*Math.sin(angle);circleRoute.push({x:x4,y:y4})}insertFootprintRoute({ctx,componentId,layer,renderLayer,route:circleRoute,strokeWidth})}function calculateArcCenter(p12,p22,p32){let ax3=p12.x-p22.x,ay3=p12.y-p22.y,bx3=p22.x-p32.x,by3=p22.y-p32.y,denom=2*(ax3*by3-ay3*bx3);if(Math.abs(denom)<1e-10)return null;let d12=p12.x*p12.x+p12.y*p12.y-p22.x*p22.x-p22.y*p22.y,d22=p22.x*p22.x+p22.y*p22.y-p32.x*p32.x-p32.y*p32.y,cx3=(d12*by3-d22*ay3)/denom,cy3=(ax3*d22-bx3*d12)/denom,radius=Math.sqrt((p12.x-cx3)**2+(p12.y-cy3)**2);return{center:{x:cx3,y:cy3},radius}}function createFootprintArc(ctx,arc2,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;let renderLayer=mapKicadLayerToPcbRenderLayer(arc2.layer);if(!isPcbAnnotationRenderLayer(renderLayer))return;let start=arc2.start||{x:0,y:0},mid=arc2.mid||{x:0,y:0},end=arc2.end||{x:0,y:0},rotatedStart=rotatePoint7(start.x,start.y,-componentRotation),rotatedMid=rotatePoint7(mid.x,mid.y,-componentRotation),rotatedEnd=rotatePoint7(end.x,end.y,-componentRotation),startKicadPos={x:kicadComponentPos.x+rotatedStart.x,y:kicadComponentPos.y+rotatedStart.y},midKicadPos={x:kicadComponentPos.x+rotatedMid.x,y:kicadComponentPos.y+rotatedMid.y},endKicadPos={x:kicadComponentPos.x+rotatedEnd.x,y:kicadComponentPos.y+rotatedEnd.y},layer=mapTextLayer(arc2.layer),strokeWidth=arc2.stroke?.width||arc2.width||.12,arcInfo=calculateArcCenter(startKicadPos,midKicadPos,endKicadPos);if(!arcInfo){let startPos=applyToPoint(ctx.k2cMatPcb,startKicadPos),endPos=applyToPoint(ctx.k2cMatPcb,endKicadPos);insertFootprintRoute({ctx,componentId,layer,renderLayer,route:[startPos,endPos],strokeWidth});return}let{center:center2,radius}=arcInfo,startAngle=Math.atan2(startKicadPos.y-center2.y,startKicadPos.x-center2.x),midAngle=Math.atan2(midKicadPos.y-center2.y,midKicadPos.x-center2.x),sweepAngle=Math.atan2(endKicadPos.y-center2.y,endKicadPos.x-center2.x)-startAngle,midSweep=midAngle-startAngle;for(;sweepAngle>Math.PI;)sweepAngle-=2*Math.PI;for(;sweepAngle<-Math.PI;)sweepAngle+=2*Math.PI;for(;midSweep>Math.PI;)midSweep-=2*Math.PI;for(;midSweep<-Math.PI;)midSweep+=2*Math.PI;let isCCW=sweepAngle>0;isCCW&&midSweep>0&&midSweep<sweepAngle||!isCCW&&midSweep<0&&midSweep>sweepAngle||(sweepAngle=sweepAngle>0?sweepAngle-2*Math.PI:sweepAngle+2*Math.PI);let arcLength2=Math.abs(radius*sweepAngle),numSegments=Math.max(2,Math.ceil(arcLength2/.1)),arcRoute=[];for(let i3=0;i3<=numSegments;i3++){let t52=i3/numSegments,angle=startAngle+sweepAngle*t52,kicadPoint={x:center2.x+radius*Math.cos(angle),y:center2.y+radius*Math.sin(angle)},cjPoint=applyToPoint(ctx.k2cMatPcb,kicadPoint);arcRoute.push(cjPoint)}insertFootprintRoute({ctx,componentId,layer,renderLayer,route:arcRoute,strokeWidth})}function createFootprintPoly(ctx,poly,componentId,kicadComponentPos,componentCcwRotationDegrees){if(!ctx.k2cMatPcb)return;let renderLayer=mapKicadLayerToPcbRenderLayer(poly.layer);if(!isPcbAnnotationRenderLayer(renderLayer))return;let ptArray=poly.points?.points||[];if(ptArray.length===0)return;let layer=mapTextLayer(poly.layer),strokeWidth=poly.stroke?.width||poly.width||.12,transformedPts=ptArray.map(p4=>{let x4=p4.x??p4.xy?.x??0,y4=p4.y??p4.xy?.y??0,rotated=rotatePoint7(x4,y4,-componentCcwRotationDegrees),kicadPos={x:kicadComponentPos.x+rotated.x,y:kicadComponentPos.y+rotated.y};return applyToPoint(ctx.k2cMatPcb,kicadPos)});if(renderLayer.endsWith("_courtyard")){ctx.db.pcb_courtyard_outline.insert({pcb_component_id:componentId,layer,outline:transformedPts});return}insertFootprintRoute({ctx,componentId,layer,renderLayer,route:transformedPts,strokeWidth})}function createPcbPort({ctx,componentId,padInfo}){if(!padInfo.layers||padInfo.layers.length===0)return;let sourcePortId=`${componentId}_port_${padInfo.padNumber}`;return ctx.db.pcb_port.insert({pcb_component_id:componentId,source_port_id:sourcePortId,x:padInfo.position.x,y:padInfo.position.y,layers:padInfo.layers}).pcb_port_id}function processPads(ctx,footprint,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;let pads=footprint.fpPads||[],padArray=Array.isArray(pads)?pads:[pads];for(let pad2 of padArray)processPad({ctx,pad:pad2,componentId,kicadComponentPos,componentRotation})}function processPad({ctx,pad:pad2,componentId,kicadComponentPos,componentRotation}){if(!ctx.k2cMatPcb)return;let padAt=pad2.at||{x:0,y:0,angle:0},padType=pad2.padType||pad2.type||"thru_hole",padShape=pad2.shape||"circle",rotationRad=-componentRotation*Math.PI/180,rotatedPadX=padAt.x*Math.cos(rotationRad)-padAt.y*Math.sin(rotationRad),rotatedPadY=padAt.x*Math.sin(rotationRad)+padAt.y*Math.cos(rotationRad),padKicadPos={x:kicadComponentPos.x+rotatedPadX,y:kicadComponentPos.y+rotatedPadY},globalPos=applyToPoint(ctx.k2cMatPcb,padKicadPos),sizeX=1,sizeY=1;pad2.size&&(Array.isArray(pad2.size)?(sizeX=pad2.size[0]||1,sizeY=pad2.size[1]||1):typeof pad2.size=="object"&&(sizeX=pad2.size._width||pad2.size.x||1,sizeY=pad2.size._height||pad2.size.y||1));let size3={x:sizeX,y:sizeY},drill=pad2.drill,mappedCopperLayers=padType==="thru_hole"?getCopperSpanLayerRefsFromLayers(pad2.layers||[],ctx.kicadPcb):getLayerRefsFromLayers(pad2.layers||[],ctx.kicadPcb),copperLayers=mappedCopperLayers.length>0?mappedCopperLayers:padType==="thru_hole"?getPcbCopperLayerRefs(ctx.kicadPcb):[],totalCcwRotationDegrees=padAt.angle||0,padNumber=pad2.number?.toString(),pcbPortId,sourcePortId;if(padNumber){let padLayers=padType==="smd"?copperLayers.slice(0,1):padType==="thru_hole"?copperLayers:[];pcbPortId=createPcbPort({ctx,componentId,padInfo:{padNumber,padType,layers:padLayers,position:globalPos}}),pcbPortId&&(sourcePortId=`${componentId}_port_${padNumber}`)}if(padType==="smd"){if(copperLayers.length===0)return;createSmdPad({ctx,pad:pad2,componentId,pos:globalPos,size:size3,shape:padShape,pcbPortId,sourcePortId,padKicadPos,totalCcwRotationDegrees})}else padType==="np_thru_hole"?createNpthHole(ctx,pad2,componentId,globalPos,drill):createPlatedHole(ctx,pad2,componentId,globalPos,size3,drill,padShape,copperLayers,totalCcwRotationDegrees,pcbPortId,sourcePortId)}function createSmdPad({ctx,pad:pad2,componentId,pos,size:size3,shape,pcbPortId,sourcePortId:_sourcePortId,padKicadPos,totalCcwRotationDegrees=0}){let layers=pad2.layers||[],layer=determineLayerFromLayers(layers);if(shape==="custom"){let primitives=pad2._sxPrimitives?._graphics||pad2.primitives||[],primitivesArray=Array.isArray(primitives)?primitives:[primitives],primitivesProcessed=0;for(let primitive of primitivesArray){if(primitive.token==="gr_poly"){let grPoly=primitive.gr_poly||primitive,rawPts=[],ptsContainer=grPoly._sxPts||grPoly.points||grPoly.pts,contours=grPoly._contours||grPoly.contours;if(ptsContainer)Array.isArray(ptsContainer)?rawPts=ptsContainer:Array.isArray(ptsContainer.points)?rawPts=ptsContainer.points:Array.isArray(ptsContainer.pts)&&(rawPts=ptsContainer.pts);else if(Array.isArray(contours))for(let contour of contours){let contourPts=contour.points||contour.pts||[];rawPts.push(...Array.isArray(contourPts)?contourPts:[contourPts])}let points=[];for(let pt3 of rawPts){let x4=pt3.x??pt3.xy?.x,y4=pt3.y??pt3.xy?.y;if(x4!==void 0&&y4!==void 0){let rotated=rotatePoint7(x4,y4,totalCcwRotationDegrees),kicadPos={x:padKicadPos.x+rotated.x,y:padKicadPos.y+rotated.y};points.push(applyToPoint(ctx.k2cMatPcb,kicadPos))}}if(points.length>0){let smtpad2={type:"pcb_smtpad",shape:"polygon",pcb_component_id:componentId,pcb_port_id:pcbPortId,pcb_smtpad_id:"pcb_smtpad_id",layer,port_hints:[pad2.number.toString()],points};ctx.db.pcb_smtpad.insert(smtpad2),primitivesProcessed++}}if(primitive.token==="gr_circle"){let grCircle=primitive.gr_circle||primitive,center2=grCircle.center||grCircle._sxCenter||{x:0,y:0},end=grCircle.end||grCircle._sxEnd||{x:0,y:0},centerlineRadius=Math.sqrt((end.x-center2.x)**2+(end.y-center2.y)**2),strokeWidth=grCircle.stroke?.width||grCircle.width||grCircle._sxWidth?.value||0,radius=(grCircle.fill?.value||grCircle.fill||grCircle._sxFill?.value)==="no"&&strokeWidth>0?centerlineRadius+strokeWidth/2:centerlineRadius,rotatedCenter=rotatePoint7(center2.x,center2.y,totalCcwRotationDegrees),kicadCenterPos={x:padKicadPos.x+rotatedCenter.x,y:padKicadPos.y+rotatedCenter.y},globalCenter=applyToPoint(ctx.k2cMatPcb,kicadCenterPos),smtpad2={type:"pcb_smtpad",shape:"circle",pcb_component_id:componentId,pcb_port_id:pcbPortId,pcb_smtpad_id:"pcb_smtpad_id",layer,port_hints:[pad2.number.toString()],x:globalCenter.x,y:globalCenter.y,width:radius*2,height:radius*2,radius};ctx.db.pcb_smtpad.insert(smtpad2),primitivesProcessed++}}if(primitivesProcessed>0){ctx.stats&&(ctx.stats.pads=(ctx.stats.pads||0)+primitivesProcessed);return}}let ccwRotationDegrees=pad2.at?.angle;if(shape==="circle"){let smtpad2={type:"pcb_smtpad",pcb_component_id:componentId,pcb_smtpad_id:"pcb_smtpad_id",x:pos.x,y:pos.y,width:size3.x,height:size3.y,layer,pcb_port_id:pcbPortId,port_hints:[pad2.number?.toString()],shape:"circle",radius:Math.max(size3.x,size3.y)/2};ctx.db.pcb_smtpad.insert(smtpad2)}else if(shape==="rect"||shape==="roundrect"){let roundrectRatio=pad2._sxRoundrectRatio?.value??pad2.roundrect_rratio,cornerRadius;shape==="roundrect"&&roundrectRatio!==void 0&&(cornerRadius=Math.min(size3.x,size3.y)*roundrectRatio/2);let normalizedCcwRotation=normalizeRotationDegrees(ccwRotationDegrees),rightAngleTurns=getRightAngleTurns(normalizedCcwRotation);if(rightAngleTurns===null&&normalizedCcwRotation!==0){let rotatedsmtpad={type:"pcb_smtpad",pcb_component_id:componentId,x:pos.x,y:pos.y,width:size3.x,height:size3.y,layer,pcb_port_id:pcbPortId,port_hints:[pad2.number.toString()],shape:"rotated_rect",ccw_rotation:normalizedCcwRotation,corner_radius:cornerRadius};ctx.db.pcb_smtpad.insert(rotatedsmtpad);return}let shouldSwapDimensions=rightAngleTurns!==null&&Math.abs(rightAngleTurns)%2===1,smtpad2={type:"pcb_smtpad",pcb_component_id:componentId,x:pos.x,y:pos.y,width:shouldSwapDimensions?size3.y:size3.x,height:shouldSwapDimensions?size3.x:size3.y,layer,pcb_port_id:pcbPortId,port_hints:[pad2.number.toString()],shape:"rect",corner_radius:cornerRadius};ctx.db.pcb_smtpad.insert(smtpad2)}else ctx.db.pcb_smtpad.insert({type:"pcb_smtpad",pcb_component_id:componentId,x:pos.x,y:pos.y,width:size3.x,height:size3.y,layer,pcb_port_id:pcbPortId,port_hints:[pad2.number?.toString()],shape:"rect"});ctx.stats&&(ctx.stats.pads=(ctx.stats.pads||0)+1)}function normalizeRotationDegrees(rotationDegrees){if(!rotationDegrees)return 0;let normalized=rotationDegrees%360;return normalized<0?normalized+360:normalized}function getRightAngleTurns(rotationDegrees){let quarterTurns=rotationDegrees/90;return Math.abs(quarterTurns-Math.round(quarterTurns))>1e-9?null:Math.round(quarterTurns)}function createPlatedHole(ctx,pad2,componentId,pos,size3,drill,shape,layers,_rotation=0,pcbPortId,_sourcePortId=void 0){let drillX=typeof drill=="object"?drill?.x||drill?._width||drill?.diameter||.8:drill||.8,drillY=typeof drill=="object"?drill?.y||drill?._height||drill?.diameter||drillX:drill||.8,holeDiameter=Math.max(drillX,drillY),drillIsOval=typeof drill=="object"&&drillX!==void 0&&drillY!==void 0&&drillX!==drillY,outerWidth=size3.x,outerHeight=size3.y;if(shape==="circle"){let platedHole={type:"pcb_plated_hole",shape:"circle",pcb_component_id:componentId,pcb_port_id:pcbPortId,x:pos.x,y:pos.y,port_hints:[pad2.number?.toString()],hole_diameter:holeDiameter,outer_diameter:Math.max(outerWidth,outerHeight),layers};ctx.db.pcb_plated_hole.insert(platedHole)}else if(shape==="oval"){let platedHole={type:"pcb_plated_hole",shape:"pill",pcb_component_id:componentId,pcb_port_id:pcbPortId,x:pos.x,y:pos.y,port_hints:[pad2.number?.toString()],hole_width:drillY,hole_height:drillX,outer_width:outerWidth,outer_height:outerHeight,ccw_rotation:pad2.at?.angle||0,layers};ctx.db.pcb_plated_hole.insert(platedHole)}else if(shape==="rect"||shape==="square"||shape==="roundrect"){let normalizedCcwRotationDegrees=normalizeRotationDegrees(pad2.at?.angle);if(drillIsOval)if(normalizedCcwRotationDegrees===0){let platedHole={type:"pcb_plated_hole",shape:"pill_hole_with_rect_pad",pcb_component_id:componentId,pcb_port_id:pcbPortId,x:pos.x,y:pos.y,port_hints:[pad2.number?.toString()],hole_shape:"pill",pad_shape:"rect",hole_width:drillY,hole_height:drillX,rect_pad_width:outerWidth,rect_pad_height:outerHeight,hole_offset_x:0,hole_offset_y:0,layers};if(shape==="roundrect"){let roundrectRatio=pad2._sxRoundrectRatio?.value??pad2.roundrect_rratio;if(roundrectRatio!==void 0){let minDimension=Math.min(outerWidth,outerHeight);platedHole.rect_border_radius=minDimension*roundrectRatio/2}}ctx.db.pcb_plated_hole.insert(platedHole)}else{let platedHole={type:"pcb_plated_hole",shape:"rotated_pill_hole_with_rect_pad",pcb_component_id:componentId,pcb_port_id:pcbPortId,x:pos.x,y:pos.y,port_hints:[pad2.number?.toString()],hole_shape:"rotated_pill",pad_shape:"rect",hole_width:drillY,hole_height:drillX,hole_ccw_rotation:normalizedCcwRotationDegrees,rect_ccw_rotation:normalizedCcwRotationDegrees,rect_pad_width:outerWidth,rect_pad_height:outerHeight,hole_offset_x:0,hole_offset_y:0,layers};if(shape==="roundrect"){let roundrectRatio=pad2._sxRoundrectRatio?.value??pad2.roundrect_rratio;if(roundrectRatio!==void 0){let minDimension=Math.min(outerWidth,outerHeight);platedHole.rect_border_radius=minDimension*roundrectRatio/2}}ctx.db.pcb_plated_hole.insert(platedHole)}else{let platedHole={type:"pcb_plated_hole",shape:"circular_hole_with_rect_pad",pcb_component_id:componentId,pcb_port_id:pcbPortId,pcb_plated_hole_id:"pcb_plated_hole_id",x:pos.x,y:pos.y,port_hints:[pad2.number?.toString()],hole_shape:"circle",pad_shape:"rect",hole_diameter:holeDiameter,rect_ccw_rotation:pad2.at?.angle||0,rect_pad_width:outerWidth,rect_pad_height:outerHeight,hole_offset_x:0,hole_offset_y:0,layers};if(shape==="roundrect"){let roundrectRatio=pad2._sxRoundrectRatio?.value??pad2.roundrect_rratio;if(roundrectRatio!==void 0){let minDimension=Math.min(outerWidth,outerHeight);platedHole.rect_border_radius=minDimension*roundrectRatio/2}}ctx.db.pcb_plated_hole.insert(platedHole)}}ctx.stats&&(ctx.stats.pads=(ctx.stats.pads||0)+1)}function createNpthHole(ctx,_pad,componentId,pos,drill){let holeDiameter=drill?.diameter||drill||1,hole={type:"pcb_hole",hole_shape:"circle",pcb_component_id:componentId,x:pos.x,y:pos.y,hole_diameter:holeDiameter};ctx.db.pcb_hole.insert(hole)}function getTextValue(footprint,type){let texts=footprint.fpTexts||[];return(Array.isArray(texts)?texts:[texts]).find(t52=>t52.type===type)?.text}function getPropertyValue(footprint,propertyName){let properties=footprint.properties||[];return(Array.isArray(properties)?properties:[properties]).find(p4=>p4.key===propertyName)?.value}function substituteKicadVariables(text,footprint){let result=text,reference=getPropertyValue(footprint,"Reference")||getTextValue(footprint,"reference")||"?",value=getPropertyValue(footprint,"Value")||getTextValue(footprint,"value")||"";return result=result.replace(/\$\{REFERENCE\}/g,reference),result=result.replace(/\$\{VALUE\}/g,value),result}function mapKicadJustifyToAnchorAlignment(justify){if(!justify)return"center";let horizontal=justify.horizontal||"center",vertical=justify.vertical||"center";if(vertical==="top"){if(horizontal==="left")return"top_left";if(horizontal==="center")return"top_center";if(horizontal==="right")return"top_right"}if(vertical==="center"){if(horizontal==="left")return"center_left";if(horizontal==="center")return"center";if(horizontal==="right")return"center_right"}if(vertical==="bottom"){if(horizontal==="left")return"bottom_left";if(horizontal==="center")return"bottom_center";if(horizontal==="right")return"bottom_right"}return"center"}function processFootprintText(ctx,footprint,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;processFootprintProperties(ctx,footprint,componentId,kicadComponentPos,componentRotation);let texts=footprint.fpTexts||[],textArray=Array.isArray(texts)?texts:[texts];for(let text of textArray){let renderLayer=mapKicadLayerToPcbRenderLayer(text.layer);if(!isPcbTextRenderLayer(renderLayer))continue;let textElement={text:text.text,at:text._sxPosition||text.at,layer:text.layer,effects:text._sxEffects||text.effects,_sxEffects:text._sxEffects};createGraphicText(ctx,textElement,renderLayer,componentId,kicadComponentPos,componentRotation,footprint)}}function processFootprintProperties(ctx,footprint,componentId,kicadComponentPos,componentRotation){if(!ctx.k2cMatPcb)return;let properties=footprint.properties||[],propertyArray=Array.isArray(properties)?properties:[properties];for(let property of propertyArray){if(!property.layer)continue;let renderLayer=mapKicadLayerToPcbRenderLayer(property.layer),isPropertyHidden=property.hidden;if(!isPcbTextRenderLayer(renderLayer)||isPropertyHidden)continue;let textElement={text:property.value,at:property._sxAt,layer:property.layer,effects:property._sxEffects||property.effects,_sxEffects:property._sxEffects};createGraphicText(ctx,textElement,renderLayer,componentId,kicadComponentPos,componentRotation,footprint)}}function createGraphicText(ctx,text,renderLayer,componentId,kicadComponentPos,componentRotation,footprint){if(!ctx.k2cMatPcb)return;let at3=text.at,textLocalX=at3?.x??0,textLocalY=at3?.y??0,rotationRad=-componentRotation*Math.PI/180,rotatedTextX=textLocalX*Math.cos(rotationRad)-textLocalY*Math.sin(rotationRad),rotatedTextY=textLocalX*Math.sin(rotationRad)+textLocalY*Math.cos(rotationRad),textKicadPos={x:kicadComponentPos.x+rotatedTextX,y:kicadComponentPos.y+rotatedTextY},pos=applyToPoint(ctx.k2cMatPcb,textKicadPos),layer=mapTextLayer(text.layer),processedText=substituteKicadVariables(text.text||"",footprint),kicadFontSize=text._sxEffects?._sxFont?._sxSize?._height||text.effects?.font?.size?.y||1,justify=text._sxEffects?._sxJustify||text.effects?.justify,anchorAlignment=mapKicadJustifyToAnchorAlignment(justify);if(renderLayer.endsWith("_silkscreen")){ctx.db.pcb_silkscreen_text.insert({pcb_component_id:componentId,font:"tscircuit2024",font_size:kicadFontSize*1.5,text:processedText,anchor_position:pos,anchor_alignment:anchorAlignment,layer});return}if(renderLayer.endsWith("_fabrication_note")){ctx.db.pcb_fabrication_note_text.insert({pcb_component_id:componentId,font:"tscircuit2024",font_size:kicadFontSize*1.5,text:processedText,anchor_position:pos,anchor_alignment:anchorAlignment,layer});return}renderLayer.endsWith("_copper")&&ctx.db.pcb_copper_text.insert({pcb_component_id:componentId,font:"tscircuit2024",font_size:kicadFontSize*1.5,text:processedText,anchor_position:pos,anchor_alignment:anchorAlignment,layer})}function inferComponentType(reference){if(!reference)return"simple_chip";switch(reference.match(/^([A-Z]+)/)?.[1]){case"R":return"simple_resistor";case"C":return"simple_capacitor";case"L":return"simple_inductor";case"D":return"simple_diode";case"LED":return"simple_diode";case"Q":return"simple_transistor";case"U":case"IC":return"simple_chip";case"J":case"P":return"simple_chip";default:return"simple_chip"}}function inferTransistorTypeFromFootprint(footprint,value){let lowerValue=(value||"").toLowerCase();if(lowerValue.includes("pnp"))return"pnp";if(lowerValue.includes("npn"))return"npn";let lowerLibId=(footprint.libraryId||"").toLowerCase();return lowerLibId.includes("pnp")?"pnp":(lowerLibId.includes("npn"),"npn")}function getFootprintProperties(footprint){let properties=footprint.properties||[];return Array.isArray(properties)?properties:[properties]}function getFootprintPropertyName(property){return property?.key}function getFootprintPropertyValue(property){return property?.value}function findFootprintProperty(footprint,propertyNames){let names=Array.isArray(propertyNames)?propertyNames:[propertyNames];return getFootprintProperties(footprint).find(property=>names.includes(getFootprintPropertyName(property)??""))}function findFootprintPropertyValue(footprint,propertyNames){let property=findFootprintProperty(footprint,propertyNames);return getFootprintPropertyValue(property)}function parseSupplierPartNumbers(value){if(!value)return;let partNumbers=value.split(/[,;]/).map(partNumber=>partNumber.trim()).filter(Boolean);return partNumbers.length>0?partNumbers:void 0}function processFootprint(ctx,footprint){if(!ctx.k2cMatPcb)return;let position4=footprint.position,kicadPos={x:position4?.x??0,y:position4?.y??0},cjPos=applyToPoint(ctx.k2cMatPcb,kicadPos),rotation5=position4?.angle??0,uuid=footprint.uuid?.value||footprint.tstamp?.value;if(!uuid)return;let refdes=getFootprintReference(footprint),value=getFootprintValue(footprint),jlcpcbPartNumbers=getJlcpcbPartNumbers(footprint),ftype=inferComponentType(refdes),sourceComponentData={name:refdes||"U",ftype};if(ftype==="simple_transistor"&&(sourceComponentData.transistor_type=inferTransistorTypeFromFootprint(footprint,value)),jlcpcbPartNumbers&&(sourceComponentData.supplier_part_numbers={jlcpcb:jlcpcbPartNumbers}),value){let sanitizedValue=value.replace(/,/g,".");switch(ftype){case"simple_resistor":sourceComponentData.resistance=sanitizedValue;break;case"simple_capacitor":sourceComponentData.capacitance=sanitizedValue;break;case"simple_inductor":sourceComponentData.inductance=sanitizedValue;break}}let sourceComponentId=ctx.db.source_component.insert(sourceComponentData).source_component_id,componentId=ctx.db.pcb_component.insert({center:{x:cjPos.x,y:cjPos.y},layer:getComponentLayer(footprint),rotation:-rotation5,width:0,height:0,source_component_id:sourceComponentId}).pcb_component_id;ctx.footprintUuidToComponentId?.set(uuid,componentId),ctx.footprintUuidToSourceComponentId?.set(uuid,sourceComponentId),processPads(ctx,footprint,componentId,kicadPos,rotation5),processFootprintText(ctx,footprint,componentId,kicadPos,rotation5),processFootprintGraphics(ctx,footprint,componentId,kicadPos,rotation5),ctx.stats&&(ctx.stats.components=(ctx.stats.components||0)+1)}function getFootprintReference(footprint){let propertyValue=findFootprintPropertyValue(footprint,"Reference");if(propertyValue)return propertyValue;let textItems=footprint.fpTexts||[],textArray=Array.isArray(textItems)?textItems:[textItems];for(let text of textArray)if(text.type==="reference")return text.text}function getFootprintValue(footprint){let propertyValue=findFootprintPropertyValue(footprint,"Value");if(propertyValue)return propertyValue;let textItems=footprint.fpTexts||[],textArray=Array.isArray(textItems)?textItems:[textItems];for(let text of textArray)if(text.type==="value")return text.text}function getJlcpcbPartNumbers(footprint){return parseSupplierPartNumbers(findFootprintPropertyValue(footprint,["JLCPCB Part #","Supplier Part Number"]))}var CollectFootprintsStage=class extends ConverterStage{constructor(){super(...arguments);__publicField(this,"processedFootprints",new Set)}step(){if(!this.ctx.kicadPcb||!this.ctx.k2cMatPcb)return this.finished=!0,!1;let footprints=this.ctx.kicadPcb.footprints||[],footprintArray=Array.isArray(footprints)?footprints:[footprints];for(let footprint of footprintArray){let uuid=footprint.uuid?.value||footprint.tstamp?.value;uuid&&(this.processedFootprints.has(uuid)||(processFootprint(this.ctx,footprint),this.processedFootprints.add(uuid)))}return this.finished=!0,!1}},FULL_TURN=Math.PI*2;function normalizeToArray(value){return value?Array.isArray(value)?value:[value]:[]}function getLayerNames(layer){return layer?typeof layer=="string"?[layer]:layer.names||[]:[]}function getGraphicLayerNames(graphic){return getLayerNames(graphic?.layer)}function getPcbPoint(point7){return{x:point7?.x??0,y:point7?.y??0}}function getLineStartEnd(line2){return{start:getPcbPoint(line2.start),end:getPcbPoint(line2.end)}}function getArcStartMidEnd(arc2){return{start:getPcbPoint(arc2.start),mid:getPcbPoint(arc2.mid),end:getPcbPoint(arc2.end)}}function getCircleCenterEnd(circle2){return{center:getPcbPoint(circle2.center),end:getPcbPoint(circle2.end)}}function getGraphicArcs(kicadPcb){return normalizeToArray(kicadPcb.graphicArcs)}function getGraphicCircles(kicadPcb){return normalizeToArray(kicadPcb.graphicCircles)}function getGraphicCurves(kicadPcb){return normalizeToArray(kicadPcb.graphicCurves)}function getTopLevelCopperArcs(kicadPcb){return normalizeToArray(kicadPcb.arcs)}function approximateArcPoints(start,mid,end,options){let geometry=getArcGeometry(start,mid,end);if(!geometry)return[start,end];let segmentLength=options?.segmentLength??.25,minSegments=options?.minSegments??8,arcLength2=Math.abs(geometry.radius*geometry.sweepAngle),numSegments=Math.max(2,minSegments,Math.ceil(arcLength2/segmentLength)),points=[];for(let i3=0;i3<=numSegments;i3++){let t52=i3/numSegments,angle=geometry.startAngle+geometry.sweepAngle*t52;points.push({x:geometry.center.x+geometry.radius*Math.cos(angle),y:geometry.center.y+geometry.radius*Math.sin(angle)})}return points}function getCurvePoints(curve){let xyPoints=(curve.points?.points??[]).filter(point7=>point7.token==="xy").map(point7=>getPcbPoint(point7));return xyPoints.length<4?null:{start:xyPoints[0],control1:xyPoints[1],control2:xyPoints[2],end:xyPoints[3]}}function approximateCubicBezierPoints(start,control1,control2,end,options){let segmentLength=options?.segmentLength??.25,minSegments=options?.minSegments??8,controlPolygonLength=getDistance4(start,control1)+getDistance4(control1,control2)+getDistance4(control2,end),numSegments=Math.max(2,minSegments,Math.ceil(controlPolygonLength/segmentLength)),points=[];for(let i3=0;i3<=numSegments;i3++){let t52=i3/numSegments,omt=1-t52;points.push({x:omt**3*start.x+3*omt**2*t52*control1.x+3*omt*t52**2*control2.x+t52**3*end.x,y:omt**3*start.y+3*omt**2*t52*control1.y+3*omt*t52**2*control2.y+t52**3*end.y})}return points}function approximateCirclePoints(center2,end,options){let radius=getDistance4(center2,end);if(radius<=0)return[center2];let segmentLength=options?.segmentLength??.25,minSegments=options?.minSegments??16,circumference=FULL_TURN*radius,numSegments=Math.max(8,minSegments,Math.ceil(circumference/segmentLength)),startAngle=Math.atan2(end.y-center2.y,end.x-center2.x),points=[];for(let i3=0;i3<=numSegments;i3++){let t52=i3/numSegments,angle=startAngle+FULL_TURN*t52;points.push({x:center2.x+radius*Math.cos(angle),y:center2.y+radius*Math.sin(angle)})}return points}function getArcGeometry(start,mid,end){let circle2=calculateArcCenter2(start,mid,end);if(!circle2)return null;let startAngle=Math.atan2(start.y-circle2.center.y,start.x-circle2.center.x),midAngle=Math.atan2(mid.y-circle2.center.y,mid.x-circle2.center.x),endAngle=Math.atan2(end.y-circle2.center.y,end.x-circle2.center.x),sweepAngle=normalizeSignedAngle(endAngle-startAngle),midSweep=normalizeSignedAngle(midAngle-startAngle),isCounterClockwise=sweepAngle>0;return isCounterClockwise&&midSweep>0&&midSweep<sweepAngle||!isCounterClockwise&&midSweep<0&&midSweep>sweepAngle||(sweepAngle=sweepAngle>0?sweepAngle-FULL_TURN:sweepAngle+FULL_TURN),{center:circle2.center,radius:circle2.radius,startAngle,sweepAngle}}function normalizeSignedAngle(angle){for(;angle<=-Math.PI;)angle+=FULL_TURN;for(;angle>Math.PI;)angle-=FULL_TURN;return angle}function calculateArcCenter2(p12,p22,p32){let ax3=p12.x,ay3=p12.y,bx3=p22.x,by3=p22.y,cx3=p32.x,cy3=p32.y,determinant=2*(ax3*(by3-cy3)+bx3*(cy3-ay3)+cx3*(ay3-by3));if(Math.abs(determinant)<1e-10)return null;let ux3=((ax3*ax3+ay3*ay3)*(by3-cy3)+(bx3*bx3+by3*by3)*(cy3-ay3)+(cx3*cx3+cy3*cy3)*(ay3-by3))/determinant,uy3=((ax3*ax3+ay3*ay3)*(cx3-bx3)+(bx3*bx3+by3*by3)*(ax3-cx3)+(cx3*cx3+cy3*cy3)*(bx3-ax3))/determinant;return{center:{x:ux3,y:uy3},radius:Math.sqrt((ax3-ux3)**2+(ay3-uy3)**2)}}function getDistance4(a3,b3){return Math.hypot(b3.x-a3.x,b3.y-a3.y)}var CollectGraphicsStage=class extends ConverterStage{step(){if(!this.ctx.kicadPcb||!this.ctx.k2cMatPcb)return this.finished=!0,!1;let lines=this.ctx.kicadPcb.graphicLines||[],lineArray=Array.isArray(lines)?lines:[lines],arcArray=getGraphicArcs(this.ctx.kicadPcb),circleArray=getGraphicCircles(this.ctx.kicadPcb),curveArray=getGraphicCurves(this.ctx.kicadPcb),edgeCutPrimitives=[];for(let line2 of lineArray){let layerStr=getGraphicLayerNames(line2).join(" ");if(layerStr.includes("Edge.Cuts")){let{start,end}=getLineStartEnd(line2);edgeCutPrimitives.push({type:"line",start,end})}else if(layerStr.includes("SilkS")||layerStr.includes("Fab")||layerStr.includes("CrtYd")){let renderLayer=mapKicadLayerToPcbRenderLayer(line2.layer);renderLayer&&this.createGraphicPath(line2,renderLayer)}}for(let arc2 of arcArray){let layerStr=getGraphicLayerNames(arc2).join(" ");if(layerStr.includes("Edge.Cuts")){let{start,mid,end}=getArcStartMidEnd(arc2);edgeCutPrimitives.push({type:"arc",start,mid,end})}else if(layerStr.includes("SilkS")||layerStr.includes("Fab")||layerStr.includes("CrtYd")){let renderLayer=mapKicadLayerToPcbRenderLayer(arc2.layer);renderLayer&&this.createGraphicArc(arc2,renderLayer)}}for(let circle2 of circleArray){if(!getGraphicLayerNames(circle2).join(" ").includes("Edge.Cuts"))continue;let{center:center2,end}=getCircleCenterEnd(circle2);edgeCutPrimitives.push({type:"circle",center:center2,start:end,end})}for(let curve of curveArray){if(!getGraphicLayerNames(curve).join(" ").includes("Edge.Cuts"))continue;let points=getCurvePoints(curve);points&&edgeCutPrimitives.push({type:"curve",start:points.start,control1:points.control1,control2:points.control2,end:points.end})}edgeCutPrimitives.length>0&&this.createBoardOutline(edgeCutPrimitives);let grRects=this.ctx.kicadPcb.graphicRects||[];for(let rect of grRects)this.processRectangle(rect);let grPolys=this.ctx.kicadPcb.graphicPolys||[],polyArray=Array.isArray(grPolys)?grPolys:[grPolys];for(let poly of polyArray)this.processPolygon(poly);let texts=this.ctx.kicadPcb.graphicTexts||[],textArray=Array.isArray(texts)?texts:[texts];for(let text of textArray){let renderLayer=mapKicadLayerToPcbRenderLayer(text.layer);renderLayer&&this.createGraphicText(text,renderLayer)}return this.finished=!0,!1}createBoardOutline(primitives){if(!this.ctx.k2cMatPcb)return;let orderedSegments=[],remainingSegments=[...primitives];if(remainingSegments.length>0)for(orderedSegments.push(remainingSegments.shift());remainingSegments.length>0;){let lastEnd=orderedSegments[orderedSegments.length-1].end,foundIndex=remainingSegments.findIndex(seg=>this.pointsEqualKicad(seg.start,lastEnd));if(foundIndex===-1&&(foundIndex=remainingSegments.findIndex(seg=>this.pointsEqualKicad(seg.end,lastEnd)),foundIndex!==-1)){let seg=remainingSegments[foundIndex];orderedSegments.push(seg.type==="arc"?{type:"arc",start:seg.end,mid:seg.mid,end:seg.start}:seg.type==="circle"?{type:"circle",center:seg.center,start:seg.end,end:seg.start}:seg.type==="curve"?{type:"curve",start:seg.end,control1:seg.control2,control2:seg.control1,end:seg.start}:{type:"line",start:seg.end,end:seg.start}),remainingSegments.splice(foundIndex,1);continue}foundIndex!==-1?orderedSegments.push(remainingSegments.splice(foundIndex,1)[0]):orderedSegments.push(remainingSegments.shift())}let points=[];for(let segment2 of orderedSegments){let kicadPoints;segment2.type==="arc"?kicadPoints=approximateArcPoints(segment2.start,segment2.mid,segment2.end,{segmentLength:.25,minSegments:16}):segment2.type==="circle"?kicadPoints=approximateCirclePoints(segment2.center,segment2.end,{segmentLength:.25,minSegments:16}):segment2.type==="curve"?kicadPoints=approximateCubicBezierPoints(segment2.start,segment2.control1,segment2.control2,segment2.end,{segmentLength:.25,minSegments:16}):kicadPoints=[segment2.start,segment2.end];for(let kicadPoint of kicadPoints){let point7=applyToPoint(this.ctx.k2cMatPcb,kicadPoint),lastPoint=points[points.length-1];(!lastPoint||!this.pointsEqual(lastPoint,point7))&&points.push(point7)}}let existingBoard=this.ctx.db.pcb_board.list()[0];existingBoard?(existingBoard.outline=points,existingBoard.width=this.calculateWidth(points),existingBoard.height=this.calculateHeight(points)):this.ctx.db.pcb_board.insert({outline:points,width:this.calculateWidth(points),height:this.calculateHeight(points)})}createGraphicPath(line2,renderLayer){if(!this.ctx.k2cMatPcb)return;let{start,end}=getLineStartEnd(line2),startPos=applyToPoint(this.ctx.k2cMatPcb,start),endPos=applyToPoint(this.ctx.k2cMatPcb,end),layer=mapKicadLayerToVisibleLayer(line2.layer),strokeWidth=line2.width||.15;this.insertRouteGraphic({layer,renderLayer,pcbComponentId:"",route:[startPos,endPos],strokeWidth})}createGraphicArc(arc2,renderLayer){if(!this.ctx.k2cMatPcb)return;let{start,mid,end}=getArcStartMidEnd(arc2),route=approximateArcPoints(start,mid,end,{segmentLength:.1,minSegments:8}).map(point7=>applyToPoint(this.ctx.k2cMatPcb,point7)),layer=mapKicadLayerToVisibleLayer(arc2.layer),strokeWidth=arc2.stroke?.width??arc2._sxStroke?._sxWidth?.value??arc2.width??.15;this.insertRouteGraphic({layer,renderLayer,pcbComponentId:"",route,strokeWidth})}insertRouteGraphic(options){let{layer,renderLayer,pcbComponentId,route,strokeWidth}=options;if(renderLayer.endsWith("_silkscreen")){this.ctx.db.pcb_silkscreen_path.insert({pcb_component_id:pcbComponentId,layer,route,stroke_width:strokeWidth});return}if(renderLayer.endsWith("_fabrication_note")){this.ctx.db.pcb_fabrication_note_path.insert({pcb_component_id:pcbComponentId,layer,route,stroke_width:strokeWidth});return}this.ctx.db.pcb_courtyard_outline.insert({pcb_component_id:pcbComponentId,layer,outline:route})}processRectangle(rect){if(!this.ctx.k2cMatPcb)return;let start={x:rect._sxStart?._x??0,y:rect._sxStart?._y??0},end={x:rect._sxEnd?._x??0,y:rect._sxEnd?._y??0},renderLayer=mapKicadLayerToPcbRenderLayer(rect._sxLayer),isFilled=rect._sxFill&&(rect._sxFill.isFilled===!0||String(rect._sxFill).includes("fill yes")),isCopperLayer=renderLayer?.endsWith("_copper"),centerKicad={x:(start.x+end.x)/2,y:(start.y+end.y)/2},widthKicad=Math.abs(end.x-start.x),heightKicad=Math.abs(end.y-start.y),centerCJ=applyToPoint(this.ctx.k2cMatPcb,centerKicad);if(isFilled&&isCopperLayer){let layer2=mapKicadLayerToLayerRef(rect._sxLayer);this.ctx.db.pcb_smtpad.insert({pcb_component_id:"",x:centerCJ.x,y:centerCJ.y,width:widthKicad,height:heightKicad,layer:layer2,shape:"rect",port_hints:[]}),this.ctx.stats&&(this.ctx.stats.pads=(this.ctx.stats.pads||0)+1);return}let layer=mapKicadLayerToVisibleLayer(rect._sxLayer),strokeWidth=rect.stroke?.width??rect._sxStroke?._sxWidth?.value??rect.width??.15;if(renderLayer?.endsWith("_fabrication_note")){this.ctx.db.pcb_fabrication_note_rect.insert({pcb_component_id:"",center:centerCJ,width:widthKicad,height:heightKicad,layer,stroke_width:strokeWidth,is_filled:isFilled,has_stroke:!0});return}renderLayer?.endsWith("_courtyard")&&this.ctx.db.pcb_courtyard_rect.insert({pcb_component_id:"",center:centerCJ,width:widthKicad,height:heightKicad,layer})}createGraphicText(text,renderLayer){if(!this.ctx.k2cMatPcb)return;let at3=text.at||text._sxPosition,pos=applyToPoint(this.ctx.k2cMatPcb,{x:at3?.x??0,y:at3?.y??0}),layer=mapKicadLayerToVisibleLayer(text.layer),fontSize=(text._sxEffects?._sxFont?._sxSize?._height||text.effects?.font?.size?.y||1)*1.5,textValue=text.text||text._text||"",justify=text._sxEffects?._sxJustify||text.effects?.justify,anchorAlignment=mapKicadJustifyToAnchorAlignment(justify);if(renderLayer.endsWith("_silkscreen")){this.ctx.db.pcb_silkscreen_text.insert({pcb_component_id:"",text:textValue,anchor_position:pos,anchor_alignment:anchorAlignment,layer,font_size:fontSize,font:"tscircuit2024"});return}if(renderLayer.endsWith("_fabrication_note")){this.ctx.db.pcb_fabrication_note_text.insert({pcb_component_id:"",text:textValue,anchor_position:pos,anchor_alignment:anchorAlignment,layer,font_size:fontSize,font:"tscircuit2024"});return}renderLayer.endsWith("_copper")&&this.ctx.db.pcb_copper_text.insert({pcb_component_id:"",text:textValue,anchor_position:pos,anchor_alignment:anchorAlignment,layer,font_size:fontSize,font:"tscircuit2024"})}pointsEqual(p12,p22){return Math.abs(p12.x-p22.x)<.001&&Math.abs(p12.y-p22.y)<.001}pointsEqualKicad(p12,p22){return Math.abs(p12.x-p22.x)<.001&&Math.abs(p12.y-p22.y)<.001}calculateWidth(points){if(points.length===0)return 0;let xs3=points.map(p4=>p4.x);return Math.max(...xs3)-Math.min(...xs3)}calculateHeight(points){if(points.length===0)return 0;let ys3=points.map(p4=>p4.y);return Math.max(...ys3)-Math.min(...ys3)}processPolygon(poly){if(!this.ctx.k2cMatPcb)return;let renderLayer=mapKicadLayerToPcbRenderLayer(poly._sxLayer),isFilled=poly._sxFill?.filled===!0,isCopperLayer=renderLayer?.endsWith("_copper");if(!isFilled&&!renderLayer?.endsWith("_courtyard"))return;let ptsData=poly._sxPts?.points||[],points=[];for(let pt3 of ptsData)if(pt3.token==="xy")points.push({x:pt3.x,y:pt3.y});else if(pt3.token==="arc"){let arcPoints=approximateArcPoints({x:pt3._sxStart?._x,y:pt3._sxStart?._y},{x:pt3._sxMid?._x,y:pt3._sxMid?._y},{x:pt3._sxEnd?._x,y:pt3._sxEnd?._y});points.push(...arcPoints)}if(points.length<3)return;let transformedPoints=points.map(pt3=>applyToPoint(this.ctx.k2cMatPcb,pt3));if(isFilled&&isCopperLayer){let layer=mapKicadLayerToLayerRef(poly._sxLayer);this.ctx.db.pcb_smtpad.insert({pcb_component_id:"",shape:"polygon",points:transformedPoints,layer,port_hints:[]}),this.ctx.stats&&(this.ctx.stats.pads=(this.ctx.stats.pads||0)+1);return}if(renderLayer?.endsWith("_courtyard")){let layer=mapKicadLayerToVisibleLayer(poly._sxLayer);this.ctx.db.pcb_courtyard_outline.insert({pcb_component_id:"",layer,outline:transformedPoints})}}};function sanitizeCircuitJsonNetName(rawName,fallbackName){let name=(rawName?.trim()||fallbackName).replace(/\+/g,"_P").replace(/-/g,"_").replace(/[^A-Za-z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"")||fallbackName;return/^\d/.test(name)?`net_${name}`:name}var CollectNetsStage=class extends ConverterStage{step(){if(!this.ctx.kicadPcb||!this.ctx.netNumToName)return this.finished=!0,!1;let nets=this.ctx.kicadPcb.nets||[],netArray=Array.isArray(nets)?nets:[nets],usedNetNames=new Set;for(let net of netArray){let netNum=net._id??net.number??net.ordinal??0,rawNetName=net._name??net.name,sanitizedNetName=sanitizeCircuitJsonNetName(rawNetName,`Net_${netNum}`),netName=usedNetNames.has(sanitizedNetName)?`${sanitizedNetName}_${netNum}`:sanitizedNetName;usedNetNames.add(netName),this.ctx.netNumToName.set(netNum,netName)}return this.ctx.netNumToName.has(0)||this.ctx.netNumToName.set(0,""),this.finished=!0,!1}},CollectSourceTracesStage=class extends ConverterStage{constructor(){super(...arguments);__publicField(this,"processedNets",new Set)}step(){if(!this.ctx.kicadPcb||!this.ctx.netNumToName)return this.finished=!0,!1;let netToPads=new Map,footprints=this.ctx.kicadPcb.footprints||[],footprintArray=Array.isArray(footprints)?footprints:[footprints];for(let footprint of footprintArray)this.processFootprintPads(footprint,netToPads);this.collectNetsFromCopper(netToPads);for(let[netNum,pads]of netToPads.entries())this.processedNets.has(netNum)||(this.ctx.netNumToSourcePortIds?.set(netNum,pads.map(p4=>p4.sourcePortId)),this.createSourceNet(netNum),this.processedNets.add(netNum));return this.finished=!0,!1}collectNetsFromCopper(netToPads){if(!this.ctx.kicadPcb)return;let segments=this.ctx.kicadPcb.segments||[],segmentArray=Array.isArray(segments)?segments:[segments];for(let segment2 of segmentArray){let netNum=this.getSegmentNet(segment2);netNum&&(netToPads.has(netNum)||netToPads.set(netNum,[]))}let arcArray=getTopLevelCopperArcs(this.ctx.kicadPcb);for(let arc2 of arcArray){let netNum=this.getSegmentNet(arc2);netNum&&(netToPads.has(netNum)||netToPads.set(netNum,[]))}}getSegmentNet(segment2){let net=segment2?.net;return net?typeof net=="number"?net:typeof net=="object"?net._id??net.number??net.ordinal??null:null:null}processFootprintPads(footprint,netToPads){let footprintUuid=footprint.uuid?.value||footprint.tstamp?.value;if(!footprintUuid)return;let componentId=this.ctx.footprintUuidToComponentId?.get(footprintUuid);if(!componentId)return;let pads=footprint.fpPads||[],padArray=Array.isArray(pads)?pads:[pads];for(let pad2 of padArray){let padNumber=pad2.number?.toString();if(!padNumber)continue;let netNum=this.getPadNet(pad2);if(netNum==null||netNum===0)continue;let sourcePortId=this.getOrCreateSourcePort(componentId,padNumber,footprint);netToPads.has(netNum)||netToPads.set(netNum,[]),netToPads.get(netNum).push({componentId,padNumber,sourcePortId})}}getPadNet(pad2){let net=pad2._sxNet||pad2.net;return net?typeof net=="number"?net:typeof net=="object"?net._id??net.number??net.ordinal??null:null:null}getOrCreateSourcePort(componentId,padNumber,footprint){let sourcePortId=`${componentId}_port_${padNumber}`;if(!this.ctx.db.source_port.list().find(sp3=>sp3.source_port_id===sourcePortId)){let footprintUuid=footprint.uuid?.value||footprint.tstamp?.value,sourceComponentId=footprintUuid&&this.ctx.footprintUuidToSourceComponentId?this.ctx.footprintUuidToSourceComponentId.get(footprintUuid):void 0;this.ctx.db.source_port.insert({source_port_id:sourcePortId,source_component_id:sourceComponentId||componentId,name:this.getSourcePortName(padNumber),pin_number:this.getSourcePortPinNumber(padNumber)})}return sourcePortId}getSourcePortName(padNumber){return/^\d+$/.test(padNumber)?`pin${Number(padNumber)}`:padNumber}getSourcePortPinNumber(padNumber){return/^\d+$/.test(padNumber)?Number(padNumber):padNumber}createSourceNet(netNum){let netName=this.ctx.netNumToName?.get(netNum)||`Net-${netNum}`,sourceNet=this.ctx.db.source_net.insert({name:netName,member_source_group_ids:[]});this.ctx.netNumToSourceNetId?.set(netNum,sourceNet.source_net_id),this.ctx.stats&&(this.ctx.stats.traces=(this.ctx.stats.traces||0)+1)}},CollectTracesStage=class extends ConverterStage{constructor(){super(...arguments);__publicField(this,"PORT_MATCH_TOLERANCE",.001);__publicField(this,"POINT_KEY_PRECISION",1e6)}step(){if(!this.ctx.kicadPcb||!this.ctx.k2cMatPcb||!this.ctx.netNumToName||!this.ctx.netNumToSourceNetId)return this.finished=!0,!1;let segments=this.ctx.kicadPcb.segments||[],segmentArray=Array.isArray(segments)?segments:[segments],arcArray=getTopLevelCopperArcs(this.ctx.kicadPcb),primitives=[];for(let segment2 of segmentArray){let primitive=this.getTracePrimitiveFromSegment(segment2);primitive&&primitives.push(primitive)}for(let arc2 of arcArray){let primitive=this.getTracePrimitiveFromArc(arc2);primitive&&primitives.push(primitive)}let vias=this.ctx.kicadPcb.vias||[],viaArray=Array.isArray(vias)?vias:[vias];for(let via of viaArray){let primitive=this.getTracePrimitiveFromVia(via);primitive&&primitives.push(primitive)}return this.annotatePrimitivesWithConnectedSourcePorts(primitives),this.createTracesFromPrimitives(primitives),this.finished=!0,!1}getTracePrimitiveFromSegment(segment2){if(!this.ctx.k2cMatPcb)return;let start=segment2.start||{x:0,y:0},end=segment2.end||{x:0,y:0},width=segment2.width||.2,layer=segment2.layer,layerStr=getLayerNames(layer).join(" "),mappedLayer=mapKicadLayerToLayerRef(layerStr),netNum=this.getSegmentNet(segment2),startPoint={x:start.x,y:start.y},endPoint={x:end.x,y:end.y};if(!this.pointsMatch(startPoint,endPoint))return{primitiveType:"wire",start:startPoint,end:endPoint,points:[startPoint,endPoint],width,layer:mappedLayer,netNum}}getTracePrimitiveFromArc(arc2){if(!this.ctx.k2cMatPcb)return;let{start,mid,end}=getArcStartMidEnd(arc2),width=arc2.width??arc2._sxWidth?.value??.2,layerStr=getLayerNames(arc2.layer).join(" "),mappedLayer=mapKicadLayerToLayerRef(layerStr),netNum=this.getSegmentNet(arc2),points=approximateArcPoints(start,mid,end,{segmentLength:Math.max(width,.1),minSegments:8}),startPoint=points[0],endPoint=points[points.length-1];if(!(!startPoint||!endPoint||this.pointsMatch(startPoint,endPoint)))return{primitiveType:"wire",start:startPoint,end:endPoint,points,width,layer:mappedLayer,netNum}}getTracePrimitiveFromVia(via){let netNum=this.getSegmentNet(via);if(netNum===null)return;let at3=via.at||{x:0,y:0},point7={x:at3.x,y:at3.y},viaLayers=via.layers?getCopperSpanLayerRefsFromLayers(via.layers,this.ctx.kicadPcb):[],layers=viaLayers.length>0?viaLayers:getPcbCopperLayerRefs(this.ctx.kicadPcb),fromLayer=layers[0],toLayer=layers[layers.length-1];if(!(!fromLayer||!toLayer||fromLayer===toLayer))return{primitiveType:"via",start:point7,end:point7,points:[point7],fromLayer,toLayer,outerDiameter:via.size||.8,holeDiameter:via.drill||.4,netNum}}createTracesFromPrimitives(primitives){let groupedPrimitives=new Map;for(let primitive of primitives){let key=this.getPrimitiveGroupKey(primitive),group=groupedPrimitives.get(key)??[];group.push(primitive),groupedPrimitives.set(key,group)}for(let group of groupedPrimitives.values())this.createTracesFromPrimitiveGroup(group)}createTracesFromPrimitiveGroup(primitives){let graph=this.createTraceGraph(primitives),visitedEdgeIds=new Set,isTerminal=nodeKey=>this.isTerminalNode(nodeKey,graph);for(let nodeKey of graph.adjacency.keys())if(isTerminal(nodeKey))for(let edgeId of graph.adjacency.get(nodeKey)??[]){if(visitedEdgeIds.has(edgeId))continue;let path=this.walkTracePath(nodeKey,edgeId,graph,visitedEdgeIds);this.insertTracePath(path)}for(let edge of graph.edges){if(visitedEdgeIds.has(edge.id))continue;let path=this.walkTracePath(edge.startKey,edge.id,graph,visitedEdgeIds);this.insertTracePath(path)}}createTraceGraph(primitives){let edges=[],adjacency=new Map;for(let primitive of primitives){let id2=edges.length,startLayer=primitive.primitiveType==="via"?primitive.fromLayer:primitive.layer,endLayer=primitive.primitiveType==="via"?primitive.toLayer:primitive.layer,startKey=this.getTraceGraphNodeKey(primitive.start,startLayer),endKey=this.getTraceGraphNodeKey(primitive.end,endLayer),edge={...primitive,id:id2,startKey,endKey};edges.push(edge);for(let nodeKey of[startKey,endKey]){let edgeIds=adjacency.get(nodeKey)??[];edgeIds.push(id2),adjacency.set(nodeKey,edgeIds)}}return{edges,adjacency}}walkTracePath(startNodeKey,firstEdgeId,graph,visitedEdgeIds){let path=[],currentNodeKey=startNodeKey,edgeId=firstEdgeId;for(;!visitedEdgeIds.has(edgeId);){let edge=graph.edges[edgeId];if(!edge)break;let reversed=edge.endKey===currentNodeKey;if(path.push({edge,reversed}),visitedEdgeIds.add(edgeId),currentNodeKey=reversed?edge.startKey:edge.endKey,this.isTerminalNode(currentNodeKey,graph))break;let nextEdgeId=(graph.adjacency.get(currentNodeKey)??[]).find(candidateEdgeId=>candidateEdgeId!==edgeId&&!visitedEdgeIds.has(candidateEdgeId));if(nextEdgeId===void 0)break;edgeId=nextEdgeId}return path}insertTracePath(path){if(!this.ctx.k2cMatPcb||!this.ctx.netNumToSourceNetId||path.length===0)return;let routePoints=this.getPathRoutePoints(path);if(routePoints.length<2)return;let firstNode=this.getTraceGraphNodeFromKey(this.getOrientedTraceEdgeStartKey(path[0])),lastNode=this.getTraceGraphNodeFromKey(this.getOrientedTraceEdgeEndKey(path[path.length-1])),netNum=path[0].edge.netNum,sourceNetId=netNum!==null?this.ctx.netNumToSourceNetId.get(netNum)??void 0:void 0,startPoint=applyToPoint(this.ctx.k2cMatPcb,firstNode.point),lastPoint=applyToPoint(this.ctx.k2cMatPcb,lastNode.point),startPcbPortId=this.findPortAtPosition(startPoint,firstNode.layer),endPcbPortId=this.findPortAtPosition(lastPoint,lastNode.layer),connectedSourcePortIds=this.getConnectedSourcePortIds([startPcbPortId,endPcbPortId]),traceConnectedSourcePortIds=this.getTraceConnectedSourcePortIds(path),inferredSourcePortIds=this.getSourcePortIdsForTrace({netNum,connectedSourcePortIds,traceConnectedSourcePortIds}),sourceTraceId=sourceNetId?this.createSourceTraceForPath({sourceNetId,connectedSourcePortIds:inferredSourcePortIds,netNum}):void 0,firstWireIndex=routePoints.findIndex(point7=>point7.routeType==="wire"),lastWireIndex=routePoints.findLastIndex(point7=>point7.routeType==="wire");if(firstWireIndex===-1)return;let route=routePoints.map((point7,index)=>point7.routeType==="via"?{route_type:"via",x:point7.x,y:point7.y,from_layer:point7.fromLayer,to_layer:point7.toLayer,...point7.outerDiameter?{outer_diameter:point7.outerDiameter}:{},...point7.holeDiameter?{hole_diameter:point7.holeDiameter}:{}}:{route_type:"wire",x:point7.x,y:point7.y,width:point7.width,layer:point7.layer,...index===firstWireIndex&&startPcbPortId?{start_pcb_port_id:startPcbPortId}:{},...index===lastWireIndex&&endPcbPortId?{end_pcb_port_id:endPcbPortId}:{}});this.ctx.db.pcb_trace.insert({route,source_trace_id:sourceTraceId,pcb_port_id:void 0}),this.ctx.stats&&(this.ctx.stats.traces=(this.ctx.stats.traces||0)+1)}getPathRoutePoints(path){let routePoints=[],lastRawPoint,lastWireLayer;for(let{edge,reversed}of path){if(edge.primitiveType==="via"){let point7=edge.start,transformedPoint=applyToPoint(this.ctx.k2cMatPcb,point7);routePoints.push({routeType:"via",x:transformedPoint.x,y:transformedPoint.y,fromLayer:reversed?edge.toLayer:edge.fromLayer,toLayer:reversed?edge.fromLayer:edge.toLayer,outerDiameter:edge.outerDiameter,holeDiameter:edge.holeDiameter});continue}let edgePoints=reversed?[...edge.points].reverse():edge.points,layer=edge.layer,width=edge.width;for(let point7 of edgePoints){if(lastRawPoint&&lastWireLayer===layer&&this.pointsMatch(lastRawPoint,point7))continue;let transformedPoint=applyToPoint(this.ctx.k2cMatPcb,point7);routePoints.push({routeType:"wire",x:transformedPoint.x,y:transformedPoint.y,width,layer}),lastRawPoint=point7,lastWireLayer=layer}}return routePoints}isTerminalNode(nodeKey,graph){if((graph.adjacency.get(nodeKey)??[]).length!==2)return!0;let{point:point7,layer}=this.getTraceGraphNodeFromKey(nodeKey),transformedPoint=applyToPoint(this.ctx.k2cMatPcb,point7);return!!this.findPortAtPosition(transformedPoint,layer)}getPrimitiveGroupKey(primitive){return`${primitive.netNum??"no-net"}`}getPointKey(point7){let x4=Math.round(point7.x*this.POINT_KEY_PRECISION),y4=Math.round(point7.y*this.POINT_KEY_PRECISION);return`${x4},${y4}`}getPointFromKey(pointKey4){let[x4,y4]=pointKey4.split(",").map(Number);return{x:(x4??0)/this.POINT_KEY_PRECISION,y:(y4??0)/this.POINT_KEY_PRECISION}}getTraceGraphNodeKey(point7,layer){return`${layer}:${this.getPointKey(point7)}`}getTraceGraphNodeFromKey(nodeKey){let[layer,...pointKeyParts]=nodeKey.split(":");return{layer,point:this.getPointFromKey(pointKeyParts.join(":"))}}getOrientedTraceEdgeStartKey({edge,reversed}){return reversed?edge.endKey:edge.startKey}getOrientedTraceEdgeEndKey({edge,reversed}){return reversed?edge.startKey:edge.endKey}pointsMatch(a3,b3){return this.getPointKey(a3)===this.getPointKey(b3)}getPcbTraceNodeKey({netNum,layer,point:point7}){return`${netNum??"no-net"}:${layer}:${this.getPointKey(point7)}`}annotatePrimitivesWithConnectedSourcePorts(primitives){if(!this.ctx.k2cMatPcb||primitives.length===0)return;let nodes=new Map,adjacency=new Map,ensureNode=(netNum,layer,point7)=>{let key=this.getPcbTraceNodeKey({netNum,layer,point:point7});return nodes.has(key)||nodes.set(key,{key,point:point7,layer,netNum}),adjacency.has(key)||adjacency.set(key,new Set),key},connectNodes=(a3,b3)=>{adjacency.get(a3)?.add(b3),adjacency.get(b3)?.add(a3)};for(let primitive of primitives){if(primitive.primitiveType!=="wire")continue;let startKey=ensureNode(primitive.netNum,primitive.layer,primitive.start),endKey=ensureNode(primitive.netNum,primitive.layer,primitive.end);connectNodes(startKey,endKey)}let vias=this.ctx.kicadPcb?.vias||[],viaArray=Array.isArray(vias)?vias:[vias];for(let via of viaArray){let netNum=this.getSegmentNet(via);if(netNum===null)continue;let at3=via.at||{x:0,y:0},point7={x:at3.x,y:at3.y},viaLayers=via.layers?getCopperSpanLayerRefsFromLayers(via.layers,this.ctx.kicadPcb):[],viaNodeKeys=(viaLayers.length>0?viaLayers:getPcbCopperLayerRefs(this.ctx.kicadPcb)).map(layer=>ensureNode(netNum,layer,point7));for(let i3=1;i3<viaNodeKeys.length;i3++)connectNodes(viaNodeKeys[0],viaNodeKeys[i3])}let connectedSourcePortIdsByNodeKey=new Map,visited=new Set;for(let startNodeKey of nodes.keys()){if(visited.has(startNodeKey))continue;let traceNodeKeys=[],traceConnectedSourcePortIds=new Set,stack=[startNodeKey];for(visited.add(startNodeKey);stack.length>0;){let nodeKey=stack.pop(),node=nodes.get(nodeKey);if(!node)continue;traceNodeKeys.push(nodeKey);let transformedPoint=applyToPoint(this.ctx.k2cMatPcb,node.point),pcbPortId=this.findPortAtPosition(transformedPoint,node.layer),sourcePortId=this.getConnectedSourcePortIds([pcbPortId])[0];sourcePortId&&traceConnectedSourcePortIds.add(sourcePortId);for(let neighborNodeKey of adjacency.get(nodeKey)??[])visited.has(neighborNodeKey)||(visited.add(neighborNodeKey),stack.push(neighborNodeKey))}let sourcePortIds=[...traceConnectedSourcePortIds];for(let nodeKey of traceNodeKeys)connectedSourcePortIdsByNodeKey.set(nodeKey,sourcePortIds)}for(let primitive of primitives){if(primitive.primitiveType!=="wire")continue;let nodeKey=this.getPcbTraceNodeKey({netNum:primitive.netNum,layer:primitive.layer,point:primitive.start});primitive.connectedSourcePortIds=connectedSourcePortIdsByNodeKey.get(nodeKey)??[]}}getSegmentNet(segment2){let net=segment2?.net;return net?typeof net=="number"?net:typeof net=="object"?net._id??net.number??net.ordinal??null:null:null}findPortAtPosition(point7,layer){let ports=this.ctx.db.pcb_port.list();for(let port of ports){let layers=port.layers;if(!(layers?.length&&!layers.includes(layer))&&Math.abs((port.x??0)-point7.x)<=this.PORT_MATCH_TOLERANCE&&Math.abs((port.y??0)-point7.y)<=this.PORT_MATCH_TOLERANCE)return port.pcb_port_id}}getConnectedSourcePortIds(pcbPortIds){let connectedSourcePortIds=[];for(let pcbPortId of pcbPortIds){if(!pcbPortId)continue;let sourcePortId=this.ctx.db.pcb_port.get(pcbPortId)?.source_port_id;!sourcePortId||connectedSourcePortIds.includes(sourcePortId)||connectedSourcePortIds.push(sourcePortId)}return connectedSourcePortIds}getSourcePortIdsForTrace({netNum,connectedSourcePortIds,traceConnectedSourcePortIds}){if(netNum===null||connectedSourcePortIds.length>=2)return connectedSourcePortIds;let inferredSourcePortIds=[...connectedSourcePortIds];for(let sourcePortId of traceConnectedSourcePortIds)if(inferredSourcePortIds.includes(sourcePortId)||inferredSourcePortIds.push(sourcePortId),inferredSourcePortIds.length>=2)return inferredSourcePortIds.slice(0,2);let netSourcePortIds=this.ctx.netNumToSourcePortIds?.get(netNum)??[];for(let sourcePortId of netSourcePortIds)if(inferredSourcePortIds.includes(sourcePortId)||inferredSourcePortIds.push(sourcePortId),inferredSourcePortIds.length>=2)return inferredSourcePortIds.slice(0,2);return inferredSourcePortIds}getTraceConnectedSourcePortIds(path){let sourcePortIds=[];for(let{edge}of path)for(let sourcePortId of edge.connectedSourcePortIds??[])sourcePortIds.includes(sourcePortId)||sourcePortIds.push(sourcePortId);return sourcePortIds}createSourceTraceForPath({sourceNetId,connectedSourcePortIds,netNum}){let netName=netNum!==null?this.ctx.netNumToName?.get(netNum)??`Net-${netNum}`:void 0;return this.ctx.db.source_trace.insert({connected_source_port_ids:connectedSourcePortIds,connected_source_net_ids:[sourceNetId],display_name:netName}).source_trace_id}},CollectViasStage=class extends ConverterStage{constructor(){super(...arguments);__publicField(this,"POINT_KEY_PRECISION",1e6)}step(){if(!this.ctx.kicadPcb||!this.ctx.k2cMatPcb||!this.ctx.netNumToName)return this.finished=!0,!1;let vias=this.ctx.kicadPcb.vias||[],viaArray=Array.isArray(vias)?vias:[vias];for(let via of viaArray)this.processVia(via);return this.finished=!0,!1}processVia(via){if(!this.ctx.k2cMatPcb||!this.ctx.netNumToName)return;let at3=via.at||{x:0,y:0},pos=applyToPoint(this.ctx.k2cMatPcb,{x:at3.x,y:at3.y}),size3=via.size||.8,drill=via.drill||.4,mappedLayers=via.layers?getCopperSpanLayerRefsFromLayers(via.layers,this.ctx.kicadPcb):[],layers=mappedLayers.length>0?mappedLayers:getPcbCopperLayerRefs(this.ctx.kicadPcb);if(this.hasMatchingTraceRouteVia(pos,layers)){this.ctx.stats&&(this.ctx.stats.vias=(this.ctx.stats.vias||0)+1);return}this.ctx.db.pcb_via.insert({x:pos.x,y:pos.y,outer_diameter:size3,hole_diameter:drill,layers}),this.ctx.stats&&(this.ctx.stats.vias=(this.ctx.stats.vias||0)+1)}hasMatchingTraceRouteVia(point7,layers){let pointKey4=this.getPointKey(point7),layerSet=new Set(layers);return this.ctx.db.pcb_trace.list().some(trace=>(trace.route??[]).some(routePoint=>routePoint.route_type==="via"&&this.getPointKey(routePoint)===pointKey4&&layerSet.has(routePoint.from_layer)&&layerSet.has(routePoint.to_layer)))}getPointKey(point7){let x4=Math.round(point7.x*this.POINT_KEY_PRECISION),y4=Math.round(point7.y*this.POINT_KEY_PRECISION);return`${x4},${y4}`}},CollectZonesStage=class extends ConverterStage{step(){if(!this.ctx.kicadPcb||!this.ctx.k2cMatPcb||!this.ctx.netNumToName)return this.finished=!0,!1;let zones=this.ctx.kicadPcb.zones||[],zoneArray=Array.isArray(zones)?zones:[zones];for(let zone of zoneArray)this.isZoneFilled(zone)&&this.createCopperPourFromZone(zone);return this.finished=!0,!1}isZoneFilled(zone){if(!zone._rawChildren||!Array.isArray(zone._rawChildren))return!1;let fillEntry=zone._rawChildren.find(child=>Array.isArray(child)&&child[0]==="fill");return fillEntry&&fillEntry[1]==="yes"?!0:zone._rawChildren.some(child=>Array.isArray(child)&&child[0]==="filled_polygon")}createCopperPourFromZone(zone){if(!this.ctx.k2cMatPcb||!this.ctx.netNumToName||!zone._rawChildren||!Array.isArray(zone._rawChildren))return;let zoneData=this.parseZoneData(zone._rawChildren),filledPolygons=this.extractFilledPolygons(zone._rawChildren);if(filledPolygons.length===0){let mainPolygon=this.extractMainPolygon(zone._rawChildren);mainPolygon.length>0&&filledPolygons.push(mainPolygon)}if(filledPolygons.length===0){this.ctx.warnings&&this.ctx.warnings.push(`Zone on layer ${zoneData.layer||"unknown"} has no valid polygon points`);return}let layer=mapKicadLayerToLayerRef(zoneData.layer),netNum=zoneData.net||0,netName=this.ctx.netNumToName.get(netNum)||zoneData.netName||"";for(let polygonPoints of filledPolygons){let transformedPoints=polygonPoints.map(point7=>applyToPoint(this.ctx.k2cMatPcb,{x:point7.x,y:point7.y}));this.ctx.db.pcb_copper_pour.insert({layer,net_name:netName,points:transformedPoints,shape:"polygon"}),this.ctx.stats&&(this.ctx.stats.copper_pours=(this.ctx.stats.copper_pours||0)+1)}}parseZoneData(children){let data={};for(let child of children)if(Array.isArray(child))switch(child[0]){case"net":data.net=child[1];break;case"net_name":data.netName=child[1];break;case"layer":data.layer=child[1];break}return data}extractMainPolygon(children){let polygonEntry=children.find(child=>Array.isArray(child)&&child[0]==="polygon");return polygonEntry?this.extractPointsFromPolygonEntry(polygonEntry):[]}extractFilledPolygons(children){let filledPolygonEntries=children.filter(child=>Array.isArray(child)&&child[0]==="filled_polygon"),polygons=[];for(let entry of filledPolygonEntries){let points=this.extractPointsFromPolygonEntry(entry);points.length>0&&polygons.push(points)}return polygons}extractPointsFromPolygonEntry(polygonEntry){let points=[],ptsEntry=polygonEntry.find(child=>Array.isArray(child)&&child[0]==="pts");if(!ptsEntry)return[];for(let i3=1;i3<ptsEntry.length;i3++){let item=ptsEntry[i3];if(Array.isArray(item)&&item[0]==="xy"&&item.length>=3){let x4=item[1],y4=item[2];typeof x4=="number"&&typeof y4=="number"&&points.push({x:x4,y:y4})}}return points}},InitializePcbContextStage=class extends ConverterStage{step(){if(!this.ctx.kicadPcb)return this.finished=!0,!1;let center2=this.calculateBoardCenter();return this.ctx.k2cMatPcb=compose(scale(1,-1),translate(-center2.x,-center2.y)),this.ctx.netNumToName=new Map,this.ctx.netNumToSourceNetId=new Map,this.ctx.netNumToSourcePortIds=new Map,this.ctx.footprintUuidToComponentId=new Map,this.ctx.footprintUuidToSourceComponentId=new Map,this.finished=!0,!1}calculateBoardCenter(){if(!this.ctx.kicadPcb)return{x:0,y:0};let lines=this.ctx.kicadPcb.graphicLines||[],lineArray=Array.isArray(lines)?lines:[lines],arcArray=getGraphicArcs(this.ctx.kicadPcb),circleArray=getGraphicCircles(this.ctx.kicadPcb),curveArray=getGraphicCurves(this.ctx.kicadPcb),xs3=[],ys3=[];for(let line2 of lineArray){if(!getGraphicLayerNames(line2).join(" ").includes("Edge.Cuts"))continue;let{start,end}=getLineStartEnd(line2);xs3.push(start.x,end.x),ys3.push(start.y,end.y)}for(let arc2 of arcArray){if(!getGraphicLayerNames(arc2).join(" ").includes("Edge.Cuts"))continue;let{start,mid,end}=getArcStartMidEnd(arc2);for(let point7 of approximateArcPoints(start,mid,end,{segmentLength:.25,minSegments:16}))xs3.push(point7.x),ys3.push(point7.y)}for(let circle2 of circleArray){if(!getGraphicLayerNames(circle2).join(" ").includes("Edge.Cuts"))continue;let{center:center2,end}=getCircleCenterEnd(circle2);for(let point7 of approximateCirclePoints(center2,end,{segmentLength:.25,minSegments:16}))xs3.push(point7.x),ys3.push(point7.y)}for(let curve of curveArray){if(!getGraphicLayerNames(curve).join(" ").includes("Edge.Cuts"))continue;let points=getCurvePoints(curve);if(points)for(let point7 of approximateCubicBezierPoints(points.start,points.control1,points.control2,points.end,{segmentLength:.25,minSegments:16}))xs3.push(point7.x),ys3.push(point7.y)}if(xs3.length===0||ys3.length===0)return{x:0,y:0};let minX=Math.min(...xs3),maxX=Math.max(...xs3),minY=Math.min(...ys3),maxY=Math.max(...ys3);return{x:(minX+maxX)/2,y:(minY+maxY)/2}}};function rotationToDirection(rotation5){let normalized=(rotation5%360+360)%360;return normalized>=315||normalized<45?"up":normalized>=45&&normalized<135?"right":normalized>=135&&normalized<225?"down":"left"}function inferSymbolName({libId,reference,rotation:rotation5}){let lower=libId.toLowerCase(),direction2=rotationToDirection(rotation5);if(lower.includes(":r_")||lower.includes(":r")&&reference.startsWith("R"))return`boxresistor_${direction2}`;if(lower.includes(":c_")||lower.includes(":c")&&reference.startsWith("C"))return lower.includes("polarized")||lower.includes("_pol")?`capacitor_${direction2}`:`capacitor_${direction2}`;if(lower.includes(":l_")||lower.includes(":l")&&reference.startsWith("L"))return`inductor_${direction2}`;if(lower.includes(":d_")||lower.includes("diode")||reference.startsWith("D"))return lower.includes("led")?`led_${direction2}`:lower.includes("schottky")?`schottky_diode_${direction2}`:lower.includes("zener")?`zener_diode_${direction2}`:`diode_${direction2}`;if(lower.includes(":q_")||reference.startsWith("Q"))return lower.includes("npn")?`npn_bipolar_transistor_${direction2}`:lower.includes("pnp")?`pnp_bipolar_transistor_${direction2}`:lower.includes("_n_")||lower.includes("nmos")?`n_channel_mosfet_transistor_${direction2}`:lower.includes("_p_")||lower.includes("pmos")?`p_channel_mosfet_transistor_${direction2}`:`npn_bipolar_transistor_${direction2}`;lower.includes("gnd")||lower.includes("ground")||lower.includes("vcc")||lower.includes("vdd")||lower.includes("power")}var CollectLibrarySymbolsStage=class extends ConverterStage{constructor(){super(...arguments);__publicField(this,"processedSymbols",new Set)}step(){if(!this.ctx.kicadSch||!this.ctx.k2cMatSch)return this.finished=!0,!1;let symbols=this.ctx.kicadSch.symbols||[];for(let symbol of symbols){let uuid=symbol.uuid;!uuid||this.processedSymbols.has(uuid)||(this.processSymbol(symbol),this.processedSymbols.add(uuid))}return this.finished=!0,!1}processSymbol(symbol){if(!this.ctx.k2cMatSch)return;let reference=this.getProperty(symbol,"Reference")||"U?",value=this.getProperty(symbol,"Value")||"",libId=symbol.libraryId||"",at3=symbol.at,kicadPos={x:at3?.x??0,y:at3?.y??0},cjPos=applyToPoint(this.ctx.k2cMatSch,kicadPos),rotation5=at3?.angle??0,ftype=this.inferFtype(libId,reference),sourceComponentId=`${libId}_source`;this.ctx.db.source_component.list().find(sc2=>sc2.source_component_id===sourceComponentId)||this.ctx.db.source_component.insert({name:libId||reference,ftype,manufacturer_part_number:value||void 0});let uuid=symbol.uuid;if(!uuid)return;let symbolName=inferSymbolName({libId,reference,rotation:rotation5}),componentId=this.ctx.db.schematic_component.insert({source_component_id:sourceComponentId,center:{x:cjPos.x,y:cjPos.y},size:this.estimateSize(symbol),...symbolName?{symbol_name:symbolName}:{}}).schematic_component_id;this.ctx.symbolUuidToComponentId?.set(uuid,componentId),this.createPorts(symbol,componentId),this.ctx.stats&&(this.ctx.stats.components=(this.ctx.stats.components||0)+1)}getProperty(symbol,propName){return(symbol.properties||[]).find(p4=>p4.key===propName)?.value}inferFtype(libId,reference){let lower=libId.toLowerCase();return lower.includes(":r_")||reference.startsWith("R")?"simple_resistor":lower.includes(":c_")||reference.startsWith("C")?"simple_capacitor":lower.includes(":l_")||reference.startsWith("L")?"simple_inductor":lower.includes(":d_")||reference.startsWith("D")?"simple_diode":lower.includes(":led")||reference.startsWith("LED")?"simple_led":lower.includes(":q_")||reference.startsWith("Q")?"simple_transistor":"simple_chip"}estimateSize(symbol){return{width:1,height:1}}createPorts(symbol,componentId){let libId=symbol.libraryId,libSymbol=this.ctx.kicadSch?.libSymbols?.symbols?.find(ls3=>ls3.libraryId===libId);if(!libSymbol)return;let allPins=[];if(libSymbol.pins&&Array.isArray(libSymbol.pins)&&libSymbol.pins.length>0?allPins.push(...libSymbol.pins):libSymbol.pins&&!Array.isArray(libSymbol.pins)&&allPins.push(libSymbol.pins),libSymbol.subSymbols&&Array.isArray(libSymbol.subSymbols))for(let subSymbol of libSymbol.subSymbols)subSymbol.pins&&Array.isArray(subSymbol.pins)&&subSymbol.pins.length>0?allPins.push(...subSymbol.pins):subSymbol.pins&&!Array.isArray(subSymbol.pins)&&allPins.push(subSymbol.pins);if(allPins.length===0)return;let componentRotation=symbol.at?.angle??0;for(let pin of allPins){let pinAt=pin._sxAt;if(!pinAt)continue;let rotRad=componentRotation*Math.PI/180,cosR=Math.cos(rotRad),sinR=Math.sin(rotRad),rotatedPinPos={x:pinAt.x*cosR-pinAt.y*sinR,y:pinAt.x*sinR+pinAt.y*cosR},scaleFactor=Math.abs(this.ctx.k2cMatSch?.a||1/15),relativePos={x:rotatedPinPos.x*scaleFactor,y:-rotatedPinPos.y*scaleFactor};this.ctx.db.schematic_port.insert({schematic_component_id:componentId,center:relativePos,facing_direction:this.inferPinDirection(pin,componentRotation),pin_number:pin._sxNumber?.value??pin.pinNumber??void 0})}}inferPinDirection(pin,componentRotation){let totalAngle=(pin.at?.angle??0)+componentRotation;return rotationToDirection(totalAngle)}},CollectSchematicTracesStage=class extends ConverterStage{step(){if(!this.ctx.kicadSch||!this.ctx.k2cMatSch)return this.finished=!0,!1;let wires=this.ctx.kicadSch.wires||[],wireArray=Array.isArray(wires)?wires:[wires];for(let wire of wireArray)this.processWire(wire);let junctions=this.ctx.kicadSch.junctions||[],junctionArray=Array.isArray(junctions)?junctions:[junctions];for(let junction of junctionArray)this.processJunction(junction);return this.finished=!0,!1}processWire(wire){if(!this.ctx.k2cMatSch||!wire.pts)return;let pts=Array.isArray(wire.pts.xy)?wire.pts.xy:[wire.pts.xy];if(pts.length<2)return;let edges=[];for(let i3=0;i3<pts.length-1;i3++){let from=applyToPoint(this.ctx.k2cMatSch,{x:pts[i3].x,y:pts[i3].y}),to3=applyToPoint(this.ctx.k2cMatSch,{x:pts[i3+1].x,y:pts[i3+1].y});edges.push({from,to:to3})}this.ctx.db.schematic_trace.insert({edges}),this.ctx.stats&&(this.ctx.stats.traces=(this.ctx.stats.traces||0)+1)}processJunction(junction){if(!this.ctx.k2cMatSch||!junction.at)return;let pos=applyToPoint(this.ctx.k2cMatSch,{x:junction.at.x,y:junction.at.y});this.ctx.db.schematic_trace.insert({edges:[],junctions:[pos]})}},InitializeSchematicContextStage=class extends ConverterStage{step(){if(!this.ctx.kicadSch)return this.finished=!0,!1;let KICAD_CENTER_X=105,KICAD_CENTER_Y=148.5,kicadCenterX=KICAD_CENTER_X,kicadCenterY=KICAD_CENTER_Y,cjCenterX=0,cjCenterY=0;return this.ctx.k2cMatSch=compose(translate(cjCenterX,cjCenterY),scale(1/15,-1/15),translate(-kicadCenterX,-kicadCenterY)),this.ctx.symbolUuidToComponentId=new Map,this.ctx.warnings=this.ctx.warnings||[],this.ctx.stats=this.ctx.stats||{},this.finished=!0,!1}},KicadToCircuitJsonConverter=class{constructor(){__publicField(this,"fsMap",{});__publicField(this,"ctx");__publicField(this,"currentStageIndex",0);__publicField(this,"pipeline")}get currentStage(){return this.pipeline?.[this.currentStageIndex]}addFile(filePath,content){this.fsMap[filePath]=content}_findFileWithExtension(extension){let filesWithExtension=Object.keys(this.fsMap).filter(key=>key.endsWith(extension));if(filesWithExtension.length>1)throw new Error(`Expected 0 or 1 file with extension ${extension}, got ${filesWithExtension.length}. Files: ${filesWithExtension.join(", ")}`);return filesWithExtension[0]??null}initializePipeline(){let pcbFile=this._findFileWithExtension(".kicad_pcb"),schFile=this._findFileWithExtension(".kicad_sch");this.ctx={db:cju_default([]),kicadPcb:pcbFile?parseKicadPcb(this.fsMap[pcbFile]):void 0,kicadSch:schFile?parseKicadSch(this.fsMap[schFile]):void 0,warnings:[],stats:{}},this.pipeline=[],this.ctx.kicadSch&&this.pipeline.push(new InitializeSchematicContextStage(this.ctx),new CollectLibrarySymbolsStage(this.ctx),new CollectSchematicTracesStage(this.ctx)),this.ctx.kicadPcb&&this.pipeline.push(new InitializePcbContextStage(this.ctx),new CollectNetsStage(this.ctx),new CollectFootprintsStage(this.ctx),new CollectSourceTracesStage(this.ctx),new CollectTracesStage(this.ctx),new CollectViasStage(this.ctx),new CollectZonesStage(this.ctx),new CollectGraphicsStage(this.ctx))}step(){return this.pipeline||this.initializePipeline(),this.currentStage?((!this.currentStage.step()||this.currentStage.finished)&&this.currentStageIndex++,this.currentStageIndex<(this.pipeline?.length||0)):!1}runUntilFinished(){this.pipeline||this.initializePipeline();for(let stage of this.pipeline||[])stage.runUntilFinished()}getOutput(){this.ctx||(this.initializePipeline(),this.runUntilFinished());let elements=[],tableNames=["source_component","source_port","source_net","source_trace","schematic_component","schematic_port","schematic_trace","schematic_net_label","pcb_component","pcb_port","pcb_smtpad","pcb_plated_hole","pcb_hole","pcb_trace","pcb_via","pcb_copper_pour","pcb_board","pcb_copper_text","pcb_silkscreen_text","pcb_silkscreen_path","pcb_fabrication_note_text","pcb_fabrication_note_path","pcb_fabrication_note_rect","pcb_courtyard_rect","pcb_courtyard_outline","pcb_courtyard_circle"];for(let tableName of tableNames){let table=this.ctx.db[tableName];if(table&&typeof table.list=="function"){let items=table.list();items&&Array.isArray(items)&&elements.push(...items)}}return elements}getOutputString(){return JSON.stringify(this.getOutput(),null,2)}getWarnings(){return this.ctx?.warnings||[]}getStats(){return this.ctx?.stats||{}}};var React=__toESM(require_react(),1),KICAD_FOOTPRINT_CACHE_URL="https://kicad-mod-cache.tscircuit.com",ngspiceEngineCache=null,toJlcpcbSupplierPartNumber=partNumber=>/^\d+$/.test(partNumber)?`C${partNumber}`:/^c\d+$/i.test(partNumber)?`C${partNumber.slice(1)}`:partNumber,loadKicadPcbStaticFile=async fileContent=>{let kicadPcbContent=typeof fileContent=="string"?fileContent:new TextDecoder().decode(fileContent);if(kicadPcbContent==="__STATIC_ASSET__"||kicadPcbContent.startsWith("blob:"))throw new Error(".kicad_pcb imports require local file contents. Static asset URLs are not supported.");let converter=new KicadToCircuitJsonConverter;converter.addFile("imported.kicad_pcb",kicadPcbContent),converter.runUntilFinished();let circuitJson=converter.getOutput(),boardContentCircuitJson=circuitJson.filter(elm=>elm.type!=="pcb_board");return{__esModule:!0,default:circuitJson,Board:props=>React.createElement("board",{...props,circuitJson}),boardContentCircuitJson,circuitJson}},getPlatformConfig=(overrides={},options={})=>{let partsEngine2=overrides.partsEngine??jlcPartsEngine;return!overrides.partsEngine&&options.easyEdaProxyConfig&&(partsEngine2=new JlcPcbPartsEngine({platformFetch:overrides.platformFetch,easyEdaProxyConfig:options.easyEdaProxyConfig})),{localCacheEngine:overrides.localCacheEngine,partsEngine:partsEngine2,autorouterMap:{krt:{createAutorouter:createKiCadRoutingToolsAutorouter({gridStep:.1,clearance:.2,maxIterations:3e5})},...overrides.autorouterMap},spiceEngineMap:{ngspice:{simulate:async spice=>{if(!ngspiceEngineCache){let createNgspiceSpiceEngine=await dynamicallyLoadDependencyWithCdnBackup("@tscircuit/ngspice-spice-engine").catch(error2=>{throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.",{cause:error2})});createNgspiceSpiceEngine&&(ngspiceEngineCache=await createNgspiceSpiceEngine({pspiceCompatibility:!0}))}if(!ngspiceEngineCache)throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.");return ngspiceEngineCache.simulate(spice)}}},footprintLibraryMap:{kicad:async footprintName=>{let baseUrl=`${KICAD_FOOTPRINT_CACHE_URL}/${footprintName}`,circuitJsonUrl=`${baseUrl}.circuit.json`,res2=await fetch(circuitJsonUrl);if(!res2.ok){let bodyPreview=(await res2.text()).slice(0,200);throw new Error(`Failed to load KiCad footprint "${footprintName}" from ${circuitJsonUrl} (HTTP ${res2.status}). ${bodyPreview}`)}let raw;try{raw=await res2.json()}catch{throw new Error(`Failed to parse KiCad footprint JSON for "${footprintName}" from ${circuitJsonUrl}`)}let filtered=Array.isArray(raw)?raw.filter(el3=>el3?.type==="pcb_silkscreen_text"?el3?.text==="REF**":!0):[raw],wrlUrl=`${baseUrl}.wrl`,stepUrl=`${baseUrl}.step`;return{footprintCircuitJson:filtered,cadModel:{wrlUrl,stepUrl,modelUnitToMmScale:2.54}}},jlcpcb:async partNumber=>{if(!partsEngine2.fetchPartCircuitJson)throw new Error("Configured parts engine does not support fetchPartCircuitJson, required for jlcpcb footprints.");let supplierPartNumber=toJlcpcbSupplierPartNumber(partNumber),footprintCircuitJson=await partsEngine2.fetchPartCircuitJson({supplierPartNumber,platformFetch:overrides.platformFetch});if(!Array.isArray(footprintCircuitJson))throw new Error(`Failed to load JLCPCB footprint "${supplierPartNumber}" from parts engine.`);return{footprintCircuitJson,cadModel:extractCadModelFromCircuitJson2(footprintCircuitJson)}}},footprintFileParserMap:{kicad_mod:{loadFromUrl:async url2=>{let kicadContent=await fetch(url2).then(res2=>res2.text()),kicadJson=await parseKicadModToCircuitJson(kicadContent);return{footprintCircuitJson:Array.isArray(kicadJson)?kicadJson:[kicadJson]}}}},staticFileLoaderMap:{kicad_pcb:loadKicadPcbStaticFile,...overrides.staticFileLoaderMap}}};var tslib_es6_exports={};__export(tslib_es6_exports,{__addDisposableResource:()=>__addDisposableResource,__assign:()=>__assign,__asyncDelegator:()=>__asyncDelegator,__asyncGenerator:()=>__asyncGenerator,__asyncValues:()=>__asyncValues,__await:()=>__await,__awaiter:()=>__awaiter,__classPrivateFieldGet:()=>__classPrivateFieldGet,__classPrivateFieldIn:()=>__classPrivateFieldIn,__classPrivateFieldSet:()=>__classPrivateFieldSet,__createBinding:()=>__createBinding,__decorate:()=>__decorate,__disposeResources:()=>__disposeResources,__esDecorate:()=>__esDecorate,__exportStar:()=>__exportStar,__extends:()=>__extends,__generator:()=>__generator,__importDefault:()=>__importDefault,__importStar:()=>__importStar,__makeTemplateObject:()=>__makeTemplateObject,__metadata:()=>__metadata,__param:()=>__param,__propKey:()=>__propKey,__read:()=>__read,__rest:()=>__rest,__rewriteRelativeImportExtension:()=>__rewriteRelativeImportExtension,__runInitializers:()=>__runInitializers,__setFunctionName:()=>__setFunctionName,__spread:()=>__spread,__spreadArray:()=>__spreadArray,__spreadArrays:()=>__spreadArrays,__values:()=>__values,default:()=>tslib_es6_default});var extendStatics=function(d4,b3){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d5,b4){d5.__proto__=b4}||function(d5,b4){for(var p4 in b4)Object.prototype.hasOwnProperty.call(b4,p4)&&(d5[p4]=b4[p4])},extendStatics(d4,b3)};function __extends(d4,b3){if(typeof b3!="function"&&b3!==null)throw new TypeError("Class extends value "+String(b3)+" is not a constructor or null");extendStatics(d4,b3);function __2(){this.constructor=d4}d4.prototype=b3===null?Object.create(b3):(__2.prototype=b3.prototype,new __2)}var __assign=function(){return __assign=Object.assign||function(t52){for(var s3,i3=1,n4=arguments.length;i3<n4;i3++){s3=arguments[i3];for(var p4 in s3)Object.prototype.hasOwnProperty.call(s3,p4)&&(t52[p4]=s3[p4])}return t52},__assign.apply(this,arguments)};function __rest(s3,e5){var t52={};for(var p4 in s3)Object.prototype.hasOwnProperty.call(s3,p4)&&e5.indexOf(p4)<0&&(t52[p4]=s3[p4]);if(s3!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i3=0,p4=Object.getOwnPropertySymbols(s3);i3<p4.length;i3++)e5.indexOf(p4[i3])<0&&Object.prototype.propertyIsEnumerable.call(s3,p4[i3])&&(t52[p4[i3]]=s3[p4[i3]]);return t52}function __decorate(decorators,target,key,desc){var c4=arguments.length,r5=c4<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d4;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r5=Reflect.decorate(decorators,target,key,desc);else for(var i3=decorators.length-1;i3>=0;i3--)(d4=decorators[i3])&&(r5=(c4<3?d4(r5):c4>3?d4(target,key,r5):d4(target,key))||r5);return c4>3&&r5&&Object.defineProperty(target,key,r5),r5}function __param(paramIndex,decorator){return function(target,key){decorator(target,key,paramIndex)}}function __esDecorate(ctor,descriptorIn,decorators,contextIn,initializers,extraInitializers){function accept(f3){if(f3!==void 0&&typeof f3!="function")throw new TypeError("Function expected");return f3}for(var kind=contextIn.kind,key=kind==="getter"?"get":kind==="setter"?"set":"value",target=!descriptorIn&&ctor?contextIn.static?ctor:ctor.prototype:null,descriptor=descriptorIn||(target?Object.getOwnPropertyDescriptor(target,contextIn.name):{}),_4,done=!1,i3=decorators.length-1;i3>=0;i3--){var context={};for(var p4 in contextIn)context[p4]=p4==="access"?{}:contextIn[p4];for(var p4 in contextIn.access)context.access[p4]=contextIn.access[p4];context.addInitializer=function(f3){if(done)throw new TypeError("Cannot add initializers after decoration has completed");extraInitializers.push(accept(f3||null))};var result=(0,decorators[i3])(kind==="accessor"?{get:descriptor.get,set:descriptor.set}:descriptor[key],context);if(kind==="accessor"){if(result===void 0)continue;if(result===null||typeof result!="object")throw new TypeError("Object expected");(_4=accept(result.get))&&(descriptor.get=_4),(_4=accept(result.set))&&(descriptor.set=_4),(_4=accept(result.init))&&initializers.unshift(_4)}else(_4=accept(result))&&(kind==="field"?initializers.unshift(_4):descriptor[key]=_4)}target&&Object.defineProperty(target,contextIn.name,descriptor),done=!0}function __runInitializers(thisArg,initializers,value){for(var useValue=arguments.length>2,i3=0;i3<initializers.length;i3++)value=useValue?initializers[i3].call(thisArg,value):initializers[i3].call(thisArg);return useValue?value:void 0}function __propKey(x4){return typeof x4=="symbol"?x4:"".concat(x4)}function __setFunctionName(f3,name,prefix){return typeof name=="symbol"&&(name=name.description?"[".concat(name.description,"]"):""),Object.defineProperty(f3,"name",{configurable:!0,value:prefix?"".concat(prefix," ",name):name})}function __metadata(metadataKey,metadataValue){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(metadataKey,metadataValue)}function __awaiter(thisArg,_arguments,P4,generator){function adopt(value){return value instanceof P4?value:new P4(function(resolve){resolve(value)})}return new(P4||(P4=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e5){reject(e5)}}function rejected(value){try{step(generator.throw(value))}catch(e5){reject(e5)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})}function __generator(thisArg,body){var _4={label:0,sent:function(){if(t52[0]&1)throw t52[1];return t52[1]},trys:[],ops:[]},f3,y4,t52,g6=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return g6.next=verb(0),g6.throw=verb(1),g6.return=verb(2),typeof Symbol=="function"&&(g6[Symbol.iterator]=function(){return this}),g6;function verb(n4){return function(v4){return step([n4,v4])}}function step(op3){if(f3)throw new TypeError("Generator is already executing.");for(;g6&&(g6=0,op3[0]&&(_4=0)),_4;)try{if(f3=1,y4&&(t52=op3[0]&2?y4.return:op3[0]?y4.throw||((t52=y4.return)&&t52.call(y4),0):y4.next)&&!(t52=t52.call(y4,op3[1])).done)return t52;switch(y4=0,t52&&(op3=[op3[0]&2,t52.value]),op3[0]){case 0:case 1:t52=op3;break;case 4:return _4.label++,{value:op3[1],done:!1};case 5:_4.label++,y4=op3[1],op3=[0];continue;case 7:op3=_4.ops.pop(),_4.trys.pop();continue;default:if(t52=_4.trys,!(t52=t52.length>0&&t52[t52.length-1])&&(op3[0]===6||op3[0]===2)){_4=0;continue}if(op3[0]===3&&(!t52||op3[1]>t52[0]&&op3[1]<t52[3])){_4.label=op3[1];break}if(op3[0]===6&&_4.label<t52[1]){_4.label=t52[1],t52=op3;break}if(t52&&_4.label<t52[2]){_4.label=t52[2],_4.ops.push(op3);break}t52[2]&&_4.ops.pop(),_4.trys.pop();continue}op3=body.call(thisArg,_4)}catch(e5){op3=[6,e5],y4=0}finally{f3=t52=0}if(op3[0]&5)throw op3[1];return{value:op3[0]?op3[1]:void 0,done:!0}}}var __createBinding=Object.create?(function(o4,m4,k4,k22){k22===void 0&&(k22=k4);var desc=Object.getOwnPropertyDescriptor(m4,k4);(!desc||("get"in desc?!m4.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m4[k4]}}),Object.defineProperty(o4,k22,desc)}):(function(o4,m4,k4,k22){k22===void 0&&(k22=k4),o4[k22]=m4[k4]});function __exportStar(m4,o4){for(var p4 in m4)p4!=="default"&&!Object.prototype.hasOwnProperty.call(o4,p4)&&__createBinding(o4,m4,p4)}function __values(o4){var s3=typeof Symbol=="function"&&Symbol.iterator,m4=s3&&o4[s3],i3=0;if(m4)return m4.call(o4);if(o4&&typeof o4.length=="number")return{next:function(){return o4&&i3>=o4.length&&(o4=void 0),{value:o4&&o4[i3++],done:!o4}}};throw new TypeError(s3?"Object is not iterable.":"Symbol.iterator is not defined.")}function __read(o4,n4){var m4=typeof Symbol=="function"&&o4[Symbol.iterator];if(!m4)return o4;var i3=m4.call(o4),r5,ar3=[],e5;try{for(;(n4===void 0||n4-- >0)&&!(r5=i3.next()).done;)ar3.push(r5.value)}catch(error2){e5={error:error2}}finally{try{r5&&!r5.done&&(m4=i3.return)&&m4.call(i3)}finally{if(e5)throw e5.error}}return ar3}function __spread(){for(var ar3=[],i3=0;i3<arguments.length;i3++)ar3=ar3.concat(__read(arguments[i3]));return ar3}function __spreadArrays(){for(var s3=0,i3=0,il3=arguments.length;i3<il3;i3++)s3+=arguments[i3].length;for(var r5=Array(s3),k4=0,i3=0;i3<il3;i3++)for(var a3=arguments[i3],j4=0,jl3=a3.length;j4<jl3;j4++,k4++)r5[k4]=a3[j4];return r5}function __spreadArray(to3,from,pack2){if(pack2||arguments.length===2)for(var i3=0,l4=from.length,ar3;i3<l4;i3++)(ar3||!(i3 in from))&&(ar3||(ar3=Array.prototype.slice.call(from,0,i3)),ar3[i3]=from[i3]);return to3.concat(ar3||Array.prototype.slice.call(from))}function __await(v4){return this instanceof __await?(this.v=v4,this):new __await(v4)}function __asyncGenerator(thisArg,_arguments,generator){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var g6=generator.apply(thisArg,_arguments||[]),i3,q4=[];return i3=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",awaitReturn),i3[Symbol.asyncIterator]=function(){return this},i3;function awaitReturn(f3){return function(v4){return Promise.resolve(v4).then(f3,reject)}}function verb(n4,f3){g6[n4]&&(i3[n4]=function(v4){return new Promise(function(a3,b3){q4.push([n4,v4,a3,b3])>1||resume(n4,v4)})},f3&&(i3[n4]=f3(i3[n4])))}function resume(n4,v4){try{step(g6[n4](v4))}catch(e5){settle(q4[0][3],e5)}}function step(r5){r5.value instanceof __await?Promise.resolve(r5.value.v).then(fulfill,reject):settle(q4[0][2],r5)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f3,v4){f3(v4),q4.shift(),q4.length&&resume(q4[0][0],q4[0][1])}}function __asyncDelegator(o4){var i3,p4;return i3={},verb("next"),verb("throw",function(e5){throw e5}),verb("return"),i3[Symbol.iterator]=function(){return this},i3;function verb(n4,f3){i3[n4]=o4[n4]?function(v4){return(p4=!p4)?{value:__await(o4[n4](v4)),done:!1}:f3?f3(v4):v4}:f3}}function __asyncValues(o4){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var m4=o4[Symbol.asyncIterator],i3;return m4?m4.call(o4):(o4=typeof __values=="function"?__values(o4):o4[Symbol.iterator](),i3={},verb("next"),verb("throw"),verb("return"),i3[Symbol.asyncIterator]=function(){return this},i3);function verb(n4){i3[n4]=o4[n4]&&function(v4){return new Promise(function(resolve,reject){v4=o4[n4](v4),settle(resolve,reject,v4.done,v4.value)})}}function settle(resolve,reject,d4,v4){Promise.resolve(v4).then(function(v5){resolve({value:v5,done:d4})},reject)}}function __makeTemplateObject(cooked,raw){return Object.defineProperty?Object.defineProperty(cooked,"raw",{value:raw}):cooked.raw=raw,cooked}var __setModuleDefault=Object.create?(function(o4,v4){Object.defineProperty(o4,"default",{enumerable:!0,value:v4})}):function(o4,v4){o4.default=v4},ownKeys=function(o4){return ownKeys=Object.getOwnPropertyNames||function(o6){var ar3=[];for(var k4 in o6)Object.prototype.hasOwnProperty.call(o6,k4)&&(ar3[ar3.length]=k4);return ar3},ownKeys(o4)};function __importStar(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k4=ownKeys(mod),i3=0;i3<k4.length;i3++)k4[i3]!=="default"&&__createBinding(result,mod,k4[i3]);return __setModuleDefault(result,mod),result}function __importDefault(mod){return mod&&mod.__esModule?mod:{default:mod}}function __classPrivateFieldGet(receiver,state2,kind,f3){if(kind==="a"&&!f3)throw new TypeError("Private accessor was defined without a getter");if(typeof state2=="function"?receiver!==state2||!f3:!state2.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f3:kind==="a"?f3.call(receiver):f3?f3.value:state2.get(receiver)}function __classPrivateFieldSet(receiver,state2,value,kind,f3){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f3)throw new TypeError("Private accessor was defined without a setter");if(typeof state2=="function"?receiver!==state2||!f3:!state2.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f3.call(receiver,value):f3?f3.value=value:state2.set(receiver,value),value}function __classPrivateFieldIn(state2,receiver){if(receiver===null||typeof receiver!="object"&&typeof receiver!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof state2=="function"?receiver===state2:state2.has(receiver)}function __addDisposableResource(env,value,async){if(value!=null){if(typeof value!="object"&&typeof value!="function")throw new TypeError("Object expected.");var dispose,inner;if(async){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose],async&&(inner=dispose)}if(typeof dispose!="function")throw new TypeError("Object not disposable.");inner&&(dispose=function(){try{inner.call(this)}catch(e5){return Promise.reject(e5)}}),env.stack.push({value,dispose,async})}else async&&env.stack.push({async:!0});return value}var _SuppressedError=typeof SuppressedError=="function"?SuppressedError:function(error2,suppressed,message){var e5=new Error(message);return e5.name="SuppressedError",e5.error=error2,e5.suppressed=suppressed,e5};function __disposeResources(env){function fail(e5){env.error=env.hasError?new _SuppressedError(e5,env.error,"An error was suppressed during disposal."):e5,env.hasError=!0}var r5,s3=0;function next2(){for(;r5=env.stack.pop();)try{if(!r5.async&&s3===1)return s3=0,env.stack.push(r5),Promise.resolve().then(next2);if(r5.dispose){var result=r5.dispose.call(r5.value);if(r5.async)return s3|=2,Promise.resolve(result).then(next2,function(e5){return fail(e5),next2()})}else s3|=1}catch(e5){fail(e5)}if(s3===1)return env.hasError?Promise.reject(env.error):Promise.resolve();if(env.hasError)throw env.error}return next2()}function __rewriteRelativeImportExtension(path,preserveJsx){return typeof path=="string"&&/^\.\.?\//.test(path)?path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m4,tsx,d4,ext,cm3){return tsx?preserveJsx?".jsx":".js":d4&&(!ext||!cm3)?m4:d4+ext+"."+cm3.toLowerCase()+"js"}):path}var tslib_es6_default={__extends,__assign,__rest,__decorate,__param,__esDecorate,__runInitializers,__propKey,__setFunctionName,__metadata,__awaiter,__generator,__createBinding,__exportStar,__values,__read,__spread,__spreadArrays,__spreadArray,__await,__asyncGenerator,__asyncDelegator,__asyncValues,__makeTemplateObject,__importStar,__importDefault,__classPrivateFieldGet,__classPrivateFieldSet,__classPrivateFieldIn,__addDisposableResource,__disposeResources,__rewriteRelativeImportExtension};var import_debug23=__toESM(require_browser(),1),debug13=(0,import_debug23.default)("tsci:eval:execution-context");function createExecutionContext(webWorkerConfiguration,opts={}){globalThis.React=React3;let basePlatform=opts.platform||getPlatformConfig({},{easyEdaProxyConfig:webWorkerConfiguration.easyEdaProxyConfig}),platform=opts.projectConfig?{...basePlatform,...opts.projectConfig}:basePlatform;platform.partsEngineDisabled&&(platform.partsEngine=void 0);let circuit=new RootCircuit({platform});opts.name&&(circuit.name=opts.name),opts.debugNamespace&&circuit.enableDebug(opts.debugNamespace);let logs=[];return{fsMap:{},entrypoint:"",logger:{info:message=>{logs.push({msg:message})},getLogs:()=>logs,stringifyLogs:()=>logs.map(log=>log.msg).join(`
|
|
801
801
|
`)},preSuppliedImports:{"@tscircuit/core":dist_exports4,tscircuit:dist_exports4,"@tscircuit/math-utils":dist_exports2,"@tscircuit/mm":dist_exports5,react:React3,"react/jsx-runtime":ReactJsxRuntime,debug:import_debug23.default,tslib:tslib_es6_exports,"@tscircuit/props":{}},circuit,tsConfig:null,importStack:[],currentlyImporting:new Set,...webWorkerConfiguration}}function normalizeFilePath(filePath){let normFilePath=filePath;return normFilePath=normFilePath.replace(/\\/g,"/"),normFilePath=normFilePath.trim(),normFilePath.startsWith("./")&&(normFilePath=normFilePath.slice(2)),normFilePath.startsWith("/")&&(normFilePath=normFilePath.slice(1)),normFilePath}function normalizeFsMap(fsMap){let normalizedFsMap={};for(let[fsPath,fileContent]of Object.entries(fsMap))normalizedFsMap[normalizeFilePath(fsPath)]=fileContent;return normalizedFsMap}function dirname(path){if(!path)return".";let cleanPath=path.replace(/\\/g,"/").replace(/\/+$/,"");return cleanPath.indexOf("/")===-1?".":cleanPath.substring(0,cleanPath.lastIndexOf("/"))||"/"}function resolveRelativePath(importPath,cwd){if(importPath.startsWith("../")){let parentDir=dirname(cwd);return resolveRelativePath(importPath.slice(3),parentDir)}return importPath.startsWith("./")?resolveRelativePath(importPath.slice(2),cwd):importPath.startsWith("/")?importPath.slice(1):`${cwd}/${importPath}`}function getTsConfig(fsMapOrAllFilePaths){if(Array.isArray(fsMapOrAllFilePaths))return null;let tsconfigContent=fsMapOrAllFilePaths["tsconfig.json"];if(!tsconfigContent)return null;try{let sanitizedContent=tsconfigContent.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,"");return JSON.parse(sanitizedContent)}catch(e5){throw new Error(`Failed to parse tsconfig.json: ${e5.message}`)}}function resolveWithTsconfigPaths(opts){let{importPath,normalizedFilePathMap,extensions,tsConfig,tsconfigDir}=opts,paths=tsConfig?.compilerOptions?.paths;if(!paths)return null;let baseUrl=tsConfig?.compilerOptions?.baseUrl||".",tryResolveCandidate=candidate=>{let normalizedCandidate=normalizeFilePath(candidate);if(normalizedFilePathMap.has(normalizedCandidate))return normalizedFilePathMap.get(normalizedCandidate);for(let ext of extensions){let withExt=`${normalizedCandidate}.${ext}`;if(normalizedFilePathMap.has(withExt))return normalizedFilePathMap.get(withExt)}return null};for(let[alias,targets]of Object.entries(paths))if(alias.includes("*")){let[prefix,suffix]=alias.split("*");if(!importPath.startsWith(prefix)||!importPath.endsWith(suffix||""))continue;let starMatch=importPath.slice(prefix.length,importPath.length-(suffix?suffix.length:0));for(let target of targets){let replaced=target.replace("*",starMatch),candidate=baseUrl&&!replaced.startsWith("./")&&!replaced.startsWith("/")?`${baseUrl}/${replaced}`:replaced,resolved=tryResolveCandidate(candidate);if(resolved)return resolved}}else{if(importPath!==alias)continue;for(let target of targets){let candidate=baseUrl&&!target.startsWith("./")&&!target.startsWith("/")?`${baseUrl}/${target}`:target,resolved=tryResolveCandidate(candidate);if(resolved)return resolved}}let resolvedPathFromBaseUrl=resolveWithBaseUrl({importPath,normalizedFilePathMap,extensions,tsConfig,tsconfigDir});return resolvedPathFromBaseUrl||null}function resolveWithBaseUrl(opts){let{importPath,normalizedFilePathMap,extensions,tsConfig,tsconfigDir}=opts,baseUrl=tsConfig?.compilerOptions?.baseUrl;if(!baseUrl)return null;let filePathToResolve=`${tsconfigDir||"."}/${baseUrl}/${importPath}`;filePathToResolve=filePathToResolve.replace(/\/+/g,"/"),filePathToResolve=filePathToResolve.replace(/\/\.\//g,"/");let normalizedFilePath=normalizeFilePath(filePathToResolve);if(normalizedFilePathMap.has(normalizedFilePath))return normalizedFilePathMap.get(normalizedFilePath);for(let ext of extensions){let withExt=`${normalizedFilePath}.${ext}`;if(normalizedFilePathMap.has(withExt))return normalizedFilePathMap.get(withExt)}return null}function matchesTsconfigPathPattern(importPath,tsConfig){let paths=tsConfig?.compilerOptions?.paths;if(!paths)return!1;for(let[alias]of Object.entries(paths))if(alias.includes("*")){let[prefix,suffix]=alias.split("*");if(importPath.startsWith(prefix)&&importPath.endsWith(suffix||""))return!0}else if(importPath===alias)return!0;return!1}var FILE_EXTENSIONS=["tsx","ts","json","js","jsx","obj","gltf","glb","stl","step","stp"],resolveFilePath=(unknownFilePath,fsMapOrAllFilePaths,cwd,opts={})=>{let tsConfig=opts.tsConfig??null,isRelativeImport=unknownFilePath.startsWith("./")||unknownFilePath.startsWith("../"),hasBaseUrl=!!tsConfig?.compilerOptions?.baseUrl,resolvedPath=cwd&&(isRelativeImport||!hasBaseUrl)?resolveRelativePath(unknownFilePath,cwd):unknownFilePath,filePaths=new Set(Array.isArray(fsMapOrAllFilePaths)?fsMapOrAllFilePaths:Object.keys(fsMapOrAllFilePaths));if(filePaths.has(resolvedPath))return resolvedPath;let normalizedFilePathMap=new Map;for(let filePath of filePaths)normalizedFilePathMap.set(normalizeFilePath(filePath),filePath);let normalizedResolvedPath=normalizeFilePath(resolvedPath);if(isRelativeImport||!hasBaseUrl){if(normalizedFilePathMap.has(normalizedResolvedPath))return normalizedFilePathMap.get(normalizedResolvedPath);for(let ext of FILE_EXTENSIONS){let possibleFilePath=`${normalizedResolvedPath}.${ext}`;if(normalizedFilePathMap.has(possibleFilePath))return normalizedFilePathMap.get(possibleFilePath)}}if(!isRelativeImport){let resolvedPathFromPaths=resolveWithTsconfigPaths({importPath:unknownFilePath,normalizedFilePathMap,extensions:FILE_EXTENSIONS,tsConfig,tsconfigDir:opts.tsconfigDir});if(resolvedPathFromPaths)return resolvedPathFromPaths;let resolvedPathFromBaseUrl=resolveWithBaseUrl({importPath:unknownFilePath,normalizedFilePathMap,extensions:FILE_EXTENSIONS,tsConfig,tsconfigDir:opts.tsconfigDir});if(resolvedPathFromBaseUrl)return resolvedPathFromBaseUrl}if(!isRelativeImport&&!hasBaseUrl){let normalizedUnknownFilePath=normalizeFilePath(unknownFilePath);if(normalizedFilePathMap.has(normalizedUnknownFilePath))return normalizedFilePathMap.get(normalizedUnknownFilePath);for(let ext of FILE_EXTENSIONS){let possibleFilePath=`${normalizedUnknownFilePath}.${ext}`;if(normalizedFilePathMap.has(possibleFilePath))return normalizedFilePathMap.get(possibleFilePath)}}return null},resolveFilePathOrThrow=(unknownFilePath,fsMapOrAllFilePaths,cwd,opts={})=>{let resolvedFilePath=resolveFilePath(unknownFilePath,fsMapOrAllFilePaths,cwd,opts);if(!resolvedFilePath)throw new Error(`File not found "${unknownFilePath}", available paths:
|
|
802
802
|
|
|
803
803
|
${Object.keys(fsMapOrAllFilePaths).join(", ")}`);return resolvedFilePath};var stripComments=code=>{let out="",i3=0,inSingle=!1,inDouble=!1,inTemplate=!1;for(;i3<code.length;){let ch3=code[i3],next2=code[i3+1];if(!inDouble&&!inTemplate&&ch3==="'"&&code[i3-1]!=="\\"){inSingle=!inSingle,out+=ch3,i3++;continue}if(!inSingle&&!inTemplate&&ch3==='"'&&code[i3-1]!=="\\"){inDouble=!inDouble,out+=ch3,i3++;continue}if(!inSingle&&!inDouble&&ch3==="`"&&code[i3-1]!=="\\"){inTemplate=!inTemplate,out+=ch3,i3++;continue}if(!inSingle&&!inDouble&&!inTemplate){if(ch3==="/"&&next2==="/"){for(out+=" ",i3+=2;i3<code.length&&code[i3]!==`
|